(self["webpackChunkproject"] = self["webpackChunkproject"] || []).push([[792],{

/***/ 7312:
/*!***************************************!*\
  !*** ./src/app/app-routing.module.ts ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppRoutingModule: () => (/* binding */ AppRoutingModule)
/* harmony export */ });
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/router */ 4947);
/* harmony import */ var _privacy_policy_privacy_policy_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./privacy-policy/privacy-policy.component */ 3054);
/* harmony import */ var _shared_authentication_guards_auth_guard__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shared/authentication/guards/auth.guard */ 7579);
/* harmony import */ var _shared_data_guards_data_guard__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shared/data/guards/data.guard */ 3545);
/* harmony import */ var _shared_authentication_guards_logged_out_guard__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shared/authentication/guards/logged-out.guard */ 2014);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/core */ 4380);

/* Components */

/* Guards */





const routes = [{
  path: 'documents',
  loadChildren: () => __webpack_require__.e(/*! import() */ 577).then(__webpack_require__.bind(__webpack_require__, /*! ./documents/documents.module */ 1577)).then(m => m.DocumentModule)
}, {
  path: 'documents/:signerKey',
  loadChildren: () => __webpack_require__.e(/*! import() */ 577).then(__webpack_require__.bind(__webpack_require__, /*! ./documents/documents.module */ 1577)).then(m => m.DocumentModule)
}, {
  path: 'privacy-policy',
  component: _privacy_policy_privacy_policy_component__WEBPACK_IMPORTED_MODULE_0__.PrivacyPolicyComponent
}, {
  path: 'login',
  loadChildren: () => __webpack_require__.e(/*! import() */ 163).then(__webpack_require__.bind(__webpack_require__, /*! ./authentication/authentication.module */ 1163)).then(m => m.AuthenticationModule),
  canActivate: [_shared_authentication_guards_logged_out_guard__WEBPACK_IMPORTED_MODULE_3__.LoggedOutGuard]
}, {
  path: 'sync/:encodedPath',
  loadChildren: () => __webpack_require__.e(/*! import() */ 59).then(__webpack_require__.bind(__webpack_require__, /*! ./data/data.module */ 7059)).then(m => m.DataModule),
  canActivate: [_shared_authentication_guards_auth_guard__WEBPACK_IMPORTED_MODULE_1__.AuthGuard]
}, {
  path: '',
  loadChildren: () => __webpack_require__.e(/*! import() */ 9).then(__webpack_require__.bind(__webpack_require__, /*! ./main/main.module */ 1009)).then(m => m.MainModule),
  canActivate: [_shared_data_guards_data_guard__WEBPACK_IMPORTED_MODULE_2__.DataGuard]
}];
let AppRoutingModule = /*#__PURE__*/(() => {
  class AppRoutingModule {
    static #_ = (() => this.ɵfac = function AppRoutingModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppRoutingModule)();
    })();
    static #_2 = (() => this.ɵmod = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵdefineNgModule"]({
      type: AppRoutingModule
    }))();
    static #_3 = (() => this.ɵinj = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵdefineInjector"]({
      imports: [_angular_router__WEBPACK_IMPORTED_MODULE_5__.RouterModule.forRoot(routes), _angular_router__WEBPACK_IMPORTED_MODULE_5__.RouterModule]
    }))();
  }
  return AppRoutingModule;
})();
(function () {
  (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵsetNgModuleScope"](AppRoutingModule, {
    imports: [_angular_router__WEBPACK_IMPORTED_MODULE_5__.RouterModule],
    exports: [_angular_router__WEBPACK_IMPORTED_MODULE_5__.RouterModule]
  });
})();

/***/ }),

/***/ 7054:
/*!**********************************!*\
  !*** ./src/app/app.component.ts ***!
  \**********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppComponent: () => (/* binding */ AppComponent)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _shared_system_services_app_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shared/system/services/app.service */ 6763);
/* harmony import */ var _shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shared/authentication/services/auth-ref.service */ 4387);
/* harmony import */ var _shared_authentication_services_auth_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./shared/authentication/services/auth.service */ 1619);
/* harmony import */ var _shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shared/ui/services/ui.service */ 345);
/* harmony import */ var _shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./shared/documents/services/document.service */ 3040);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _shared_ui_components_loader_loader_component__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./shared/ui/components/loader/loader.component */ 5086);
/* harmony import */ var _shared_documents_components_signature_pad_signature_pad_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./shared/documents/components/signature-pad/signature-pad.component */ 4812);
/* harmony import */ var _shared_documents_components_initial_pad_initial_pad_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./shared/documents/components/initial-pad/initial-pad.component */ 1400);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @angular/router */ 4947);













function AppComponent_ng_container_0_main_1_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "main", 12);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](1, "router-outlet");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
  }
}
function AppComponent_ng_container_0_aside_2_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "aside", 13)(1, "div", 8);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](2, "loader", 14);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵclassProp"]("closing", ctx_r0.closing);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("fill", true);
  }
}
function AppComponent_ng_container_0_h2_6_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "h2");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](1);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtextInterpolate1"](" ", ctx_r0.promptHeader, " ");
  }
}
function AppComponent_ng_container_0_p_7_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "p");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](1);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtextInterpolate1"](" ", ctx_r0.promptDescription, " ");
  }
}
function AppComponent_ng_container_0_button_9_Template(rf, ctx) {
  if (rf & 1) {
    const _r2 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "button", 15);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵlistener"]("click", function AppComponent_ng_container_0_button_9_Template_button_click_0_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵrestoreView"](_r2);
      const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
      return _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵresetView"](ctx_r0.cancelPrompt());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](1, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtextInterpolate"](ctx_r0.promptCancelLabel);
  }
}
function AppComponent_ng_container_0_button_10_Template(rf, ctx) {
  if (rf & 1) {
    const _r3 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "button", 16);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵlistener"]("click", function AppComponent_ng_container_0_button_10_Template_button_click_0_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵrestoreView"](_r3);
      const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
      return _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵresetView"](ctx_r0.confirmPrompt());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](1, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtextInterpolate"](ctx_r0.promptConfirmLabel);
  }
}
function AppComponent_ng_container_0_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementContainerStart"](0);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](1, AppComponent_ng_container_0_main_1_Template, 2, 0, "main", 5)(2, AppComponent_ng_container_0_aside_2_Template, 3, 3, "aside", 6);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](3, "aside", 7);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](4, "div", 2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](5, "div", 8);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](6, AppComponent_ng_container_0_h2_6_Template, 2, 1, "h2", 0)(7, AppComponent_ng_container_0_p_7_Template, 2, 1, "p", 0);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](8, "div", 9);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](9, AppComponent_ng_container_0_button_9_Template, 3, 1, "button", 10)(10, AppComponent_ng_container_0_button_10_Template, 3, 1, "button", 11);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]()()();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementContainerEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", !ctx_r0.authenticating);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx_r0.authenticating);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵclassProp"]("active", ctx_r0.showPrompt);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx_r0.promptHeader != null);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx_r0.promptDescription != null);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx_r0.promptCancelLabel != null);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx_r0.promptConfirmLabel != null);
  }
}
function AppComponent_signature_pad_3_Template(rf, ctx) {
  if (rf & 1) {
    const _r4 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "signature-pad", 17);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵlistener"]("close", function AppComponent_signature_pad_3_Template_signature_pad_close_0_listener($event) {
      _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵrestoreView"](_r4);
      const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵresetView"](ctx_r0.closeSignature($event));
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("fieldId", ctx_r0.signingFieldId)("signer", ctx_r0.signer);
  }
}
function AppComponent_initial_pad_6_Template(rf, ctx) {
  if (rf & 1) {
    const _r5 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](0, "initial-pad", 17);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵlistener"]("close", function AppComponent_initial_pad_6_Template_initial_pad_close_0_listener($event) {
      _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵrestoreView"](_r5);
      const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵresetView"](ctx_r0.closeInitials($event));
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("fieldId", ctx_r0.initialingFieldId)("signer", ctx_r0.initialer);
  }
}
function AppComponent_ng_container_7_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementContainerStart"](0);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](1, "aside", 18);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](2, "loader", 14);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](3, "h2");
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](4);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]()();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementContainerEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("fill", true);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtextInterpolate"](ctx_r0.updatingLabel);
  }
}
let AppComponent = /*#__PURE__*/(() => {
  class AppComponent {
    constructor(appService, authRefService, authService, uiService, documentsService) {
      this.appService = appService;
      this.authRefService = authRefService;
      this.authService = authService;
      this.uiService = uiService;
      this.documentsService = documentsService;
      // #region Version
      this.checkingForUpdate = true;
      this.updatingApp = false;
      this.updatingLabel = "Updating";
      this.authenticating = false;
      this.closing = false;
    }
    updateLabel() {
      this.updateTimer = window.setTimeout(() => {
        switch (this.updatingLabel) {
          case "Updating":
            this.updatingLabel = "Updating.";
            break;
          case "Updating.":
            this.updatingLabel = "Updating..";
            break;
          case "Updating..":
            this.updatingLabel = "Updating...";
            break;
          case "Updating...":
            this.updatingLabel = "Updating";
            break;
        }
        this.updateLabel();
      }, 500);
    }
    checkForUpdate() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (_capacitor_core__WEBPACK_IMPORTED_MODULE_1__.Capacitor.isNativePlatform()) {
          const update = yield _this.appService.checkForUpdate();
          if (update != null) {
            _this.updatingApp = true;
            _this.checkingForUpdate = false;
            setTimeout(() => {
              _this.updateLabel();
            }, 500);
            const updated = yield _this.appService.downloadAndApplyUpdate(update);
            if (!updated) {
              window.clearTimeout(_this.updateTimer);
              _this.updatingApp = false;
            }
          } else {
            _this.checkingForUpdate = false;
          }
        } else {
          _this.checkingForUpdate = false;
        }
      })();
    }
    watchAuthentication() {
      clearTimeout(this.authTimer);
      clearTimeout(this.closeTimer);
      const initialTimer = setTimeout(() => {
        this.authenticating = false;
      }, 32);
      const start = new Date().getTime();
      this.authSubscription = this.authRefService.authenticating.subscribe({
        next: authenticating => {
          if (!authenticating) {
            const now = new Date().getTime();
            const delta = now - start;
            if (delta <= 64) {
              // 4 frames
              clearTimeout(initialTimer);
              this.closing = false;
              this.authenticating = false;
            } else {
              this.closeTimer = window.setTimeout(() => {
                this.closing = true;
              }, 2500);
              this.authTimer = window.setTimeout(() => {
                this.closing = false;
                this.authenticating = false;
              }, 3500);
            }
          } else {
            this.authenticating = true;
          }
        }
      });
    }
    initAuthentication() {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        _this2.watchAuthentication();
        _this2.authService.initFlow();
      })();
    }
    // #endregion
    // #region Prompts
    get showPrompt() {
      return this.uiService.showPrompt;
    }
    get promptHeader() {
      return this.uiService.promptHeader;
    }
    get promptDescription() {
      return this.uiService.promptDescription;
    }
    get promptConfirmLabel() {
      return this.uiService.promptConfirmLabel;
    }
    get promptCancelLabel() {
      return this.uiService.promptCancelLabel;
    }
    confirmPrompt() {
      this.uiService.confirmPrompt();
    }
    cancelPrompt() {
      this.uiService.cancelPrompt();
    }
    // #endregion
    // #region Initialing
    get initialer() {
      return this.documentsService.initialer;
    }
    get initialingFieldId() {
      return this.documentsService.initialingFieldId;
    }
    get initialing() {
      return this.documentsService.initialing;
    }
    closeInitials(signature) {
      this.documentsService.closeInitials(signature);
    }
    // #endregion
    // #region Signing
    get signer() {
      return this.documentsService.signer;
    }
    get signingFieldId() {
      return this.documentsService.signingFieldId;
    }
    get signing() {
      return this.documentsService.signing;
    }
    closeSignature(signature) {
      this.documentsService.closeSignature(signature);
    }
    // #endregion
    // #region Bootstrapping
    get initialized() {
      return !this.checkingForUpdate && !this.updatingApp;
    }
    // #endregion
    ngOnInit() {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const requestedRoute = window.location.pathname;
        if (requestedRoute.indexOf("/documents") == 0) {
          _this3.checkingForUpdate = false;
          _this3.updatingApp = false;
          _this3.authenticating = false;
        } else {
          _this3.initAuthentication();
          yield _this3.checkForUpdate();
        }
      })();
    }
    static #_ = (() => this.ɵfac = function AppComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdirectiveInject"](_shared_system_services_app_service__WEBPACK_IMPORTED_MODULE_2__.AppService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdirectiveInject"](_shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_3__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdirectiveInject"](_shared_authentication_services_auth_service__WEBPACK_IMPORTED_MODULE_4__.AuthService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdirectiveInject"](_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_5__.UiService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdirectiveInject"](_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_6__.DocumentService));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdefineComponent"]({
      type: AppComponent,
      selectors: [["app-root"]],
      standalone: false,
      decls: 9,
      vars: 8,
      consts: [[4, "ngIf"], [1, "signature-pad"], [1, "bg"], [3, "fieldId", "signer", "close", 4, "ngIf"], [1, "initial-pad"], ["id", "appComponent", 4, "ngIf"], ["id", "appLoader", 3, "closing", 4, "ngIf"], ["id", "prompt"], [1, "content"], [1, "controls"], ["class", "control alternate", 3, "click", 4, "ngIf"], ["class", "control success", 3, "click", 4, "ngIf"], ["id", "appComponent"], ["id", "appLoader"], [1, "active", 3, "fill"], [1, "control", "alternate", 3, "click"], [1, "control", "success", 3, "click"], [3, "close", "fieldId", "signer"], ["id", "appUpdater"]],
      template: function AppComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](0, AppComponent_ng_container_0_Template, 11, 8, "ng-container", 0);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](1, "div", 1);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](2, "div", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](3, AppComponent_signature_pad_3_Template, 1, 2, "signature-pad", 3);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementStart"](4, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelement"](5, "div", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](6, AppComponent_initial_pad_6_Template, 1, 2, "initial-pad", 3);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtemplate"](7, AppComponent_ng_container_7_Template, 5, 2, "ng-container", 0);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵtext"](8, " 110");
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx.initialized);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵclassProp"]("active", ctx.signing);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx.signing);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵclassProp"]("active", ctx.initialing);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"](2);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx.initialing);
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵadvance"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵproperty"]("ngIf", ctx.updatingApp);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_11__.NgIf, _shared_ui_components_loader_loader_component__WEBPACK_IMPORTED_MODULE_7__.LoaderComponent, _shared_documents_components_signature_pad_signature_pad_component__WEBPACK_IMPORTED_MODULE_8__.SignaturePadComponent, _shared_documents_components_initial_pad_initial_pad_component__WEBPACK_IMPORTED_MODULE_9__.InitialPadComponent, _angular_router__WEBPACK_IMPORTED_MODULE_12__.RouterOutlet],
      styles: ["@keyframes _ngcontent-%COMP%_loadIn {\n  0% {\n    opacity: 0;\n  }\n  100% {\n    opacity: 1;\n  }\n}\n@keyframes _ngcontent-%COMP%_loadOut {\n  0% {\n    opacity: 1;\n    transform: scale(1);\n  }\n  100% {\n    opacity: 0;\n    transform: scale(0.8);\n  }\n}\n#appComponent[_ngcontent-%COMP%] {\n  animation-name: _ngcontent-%COMP%_loadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: linear;\n  animation-duration: 1s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n\n#appUpdater[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n}\n#appUpdater[_ngcontent-%COMP%]    > loader[_ngcontent-%COMP%] {\n  display: block;\n  position: relative;\n  width: 14vw;\n  height: 14vw;\n  --fillSpeed: 2s;\n}\n#appUpdater[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 100%;\n  left: 2.5vw;\n  margin-top: 2vw;\n  text-align: left;\n  color: var(--color1);\n  font-size: 2.4vw;\n  font-weight: var(--ltweight);\n  white-space: nowrap;\n}\n\n#prompt[_ngcontent-%COMP%] {\n  pointer-events: none;\n  z-index: 10000;\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  opacity: 0;\n  -webkit-backdrop-filter: blur(0.5vw);\n  -moz-backdrop-filter: blur(0.5vw);\n  -o-backdrop-filter: blur(0.5vw);\n  backdrop-filter: blur(0.5vw);\n  transition: opacity 0.2s linear;\n}\n#prompt[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  z-index: 10000;\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: var(--color2);\n  opacity: 0;\n  transition: opacity 0.2s linear;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 10001;\n  background-color: var(--color2);\n  border-radius: 1vw;\n  overflow: hidden;\n  opacity: 0;\n  min-width: 25vw;\n  max-width: 50vw;\n  transform: translate(-50%, -50%) scale(0.8);\n  transition: opacity 0.2s, transform 0.2s;\n  box-shadow: 0 0.2vw 1vw rgba(var(--black-raw), 0.1);\n  padding: 1vw;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > h2[_ngcontent-%COMP%] {\n  font-size: 1.8vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n  text-align: center;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]   p[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  font-size: 1.6vw;\n  line-height: 1.1;\n  color: var(--colorAlt4);\n  font-weight: var(--stdweight);\n  text-align: center;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  margin-top: 2vw;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  position: relative;\n  margin-left: 1vw;\n  padding: 0.8vw 2vw;\n  border-radius: 1vw;\n  cursor: pointer;\n  margin-left: 1vw;\n  display: flex;\n  align-items: center;\n  background-color: var(--color3);\n  border: 0.1vw transparent solid;\n  transition: background-color 0.1s linear;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.2vw;\n  color: var(--color2);\n  font-weight: var(--strong);\n  line-height: 1;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.alternate[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt1);\n  border-color: var(--color1);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.alternate[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color1);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.success[_ngcontent-%COMP%] {\n  background-color: var(--success);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active {\n  background-color: var(--color3Alt4);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active.success {\n  background-color: var(--successAlt4);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active.alternate {\n  background-color: var(--color2Alt2);\n}\n#prompt[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n#prompt.active[_ngcontent-%COMP%] {\n  opacity: 1;\n  pointer-events: initial;\n}\n#prompt.active[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  opacity: 0.8;\n}\n#prompt.active[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%] {\n  transform: translate(-50%, -50%) scale(1);\n  opacity: 1;\n}\n\n.signature-pad[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 1;\n  background-color: rgba(var(--color1-raw), 0.7);\n  -webkit-backdrop-filter: blur(0.25vw);\n  -moz-backdrop-filter: blur(0.25vw);\n  -o-backdrop-filter: blur(0.25vw);\n  backdrop-filter: blur(0.25vw);\n  opacity: 0;\n  transition: opacity 0.2s linear;\n  pointer-events: none;\n  z-index: var(--sideNav-layer)1;\n}\n.signature-pad[_ngcontent-%COMP%]   signature-pad[_ngcontent-%COMP%] {\n  display: block;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 2;\n  width: 75vw;\n  z-index: var(--sideNav-layer)2;\n}\n.signature-pad.active[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  opacity: 1;\n  pointer-events: initial;\n}\n\n.initial-pad[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 1;\n  background-color: rgba(var(--color1-raw), 0.7);\n  -webkit-backdrop-filter: blur(0.25vw);\n  -moz-backdrop-filter: blur(0.25vw);\n  -o-backdrop-filter: blur(0.25vw);\n  backdrop-filter: blur(0.25vw);\n  opacity: 0;\n  transition: opacity 0.2s linear;\n  pointer-events: none;\n  z-index: var(--sideNav-layer)1;\n}\n.initial-pad[_ngcontent-%COMP%]   initial-pad[_ngcontent-%COMP%] {\n  display: block;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 2;\n  width: 50vw;\n  z-index: var(--sideNav-layer)2;\n}\n.initial-pad.active[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  opacity: 1;\n  pointer-events: initial;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return AppComponent;
})();

/***/ }),

/***/ 3009:
/*!*******************************!*\
  !*** ./src/app/app.module.ts ***!
  \*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppModule: () => (/* binding */ AppModule),
/* harmony export */   HammerConfig: () => (/* binding */ HammerConfig),
/* harmony export */   storageFactory: () => (/* binding */ storageFactory)
/* harmony export */ });
/* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @angular/platform-browser */ 4604);
/* harmony import */ var _angular_platform_browser_animations__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! @angular/platform-browser/animations */ 5251);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _app_routing_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./app-routing.module */ 7312);
/* harmony import */ var _shared_ui_ui_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shared/ui/ui.module */ 663);
/* harmony import */ var angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! angular-oauth2-oidc */ 2888);
/* harmony import */ var _app_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app.component */ 7054);
/* harmony import */ var _privacy_policy_privacy_policy_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./privacy-policy/privacy-policy.component */ 3054);
/* harmony import */ var _shared_system_services_app_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./shared/system/services/app.service */ 6763);
/* harmony import */ var _shared_authentication_services_auth_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shared/authentication/services/auth.service */ 1619);
/* harmony import */ var _shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./shared/authentication/services/auth-ref.service */ 4387);
/* harmony import */ var _shared_system_services_system_service__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./shared/system/services/system.service */ 1901);
/* harmony import */ var _shared_data_services_storage_service__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./shared/data/services/storage.service */ 1490);
/* harmony import */ var _shared_data_services_db_service__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./shared/data/services/db.service */ 1235);
/* harmony import */ var _shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./shared/system/services/api.service */ 1160);
/* harmony import */ var _shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./shared/ui/services/ui.service */ 345);
/* harmony import */ var _shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./shared/documents/services/document.service */ 3040);
/* harmony import */ var _shared_authentication_interceptors_token_interceptor__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./shared/authentication/interceptors/token.interceptor */ 6402);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _shared_documents_documents_module__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./shared/documents/documents.module */ 3749);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @angular/core */ 4380);



/* Modules */



/* Components */


/* Services */









/* Interceptors */

/* Pipes */




let HammerConfig = /*#__PURE__*/(() => {
  class HammerConfig extends _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.HammerGestureConfig {
    constructor() {
      super(...arguments);
      this.overrides = {
        swipe: {
          enable: false
        },
        press: {
          time: 72
        }
      };
    }
    static #_ = (() => this.ɵfac = /*@__PURE__*/(() => {
      let ɵHammerConfig_BaseFactory;
      return function HammerConfig_Factory(__ngFactoryType__) {
        return (ɵHammerConfig_BaseFactory || (ɵHammerConfig_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_16__["ɵɵgetInheritedFactory"](HammerConfig)))(__ngFactoryType__ || HammerConfig);
      };
    })())();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_16__["ɵɵdefineInjectable"]({
      token: HammerConfig,
      factory: HammerConfig.ɵfac
    }))();
  }
  return HammerConfig;
})();
let AppModule = /*#__PURE__*/(() => {
  class AppModule {
    static #_ = (() => this.ɵfac = function AppModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppModule)();
    })();
    static #_2 = (() => this.ɵmod = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_16__["ɵɵdefineNgModule"]({
      type: AppModule,
      bootstrap: [_app_component__WEBPACK_IMPORTED_MODULE_2__.AppComponent]
    }))();
    static #_3 = (() => this.ɵinj = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_16__["ɵɵdefineInjector"]({
      providers: [{
        provide: _angular_common_http__WEBPACK_IMPORTED_MODULE_17__.HTTP_INTERCEPTORS,
        useClass: _shared_authentication_interceptors_token_interceptor__WEBPACK_IMPORTED_MODULE_13__.TokenInterceptor,
        multi: true
      }, {
        provide: _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.HAMMER_GESTURE_CONFIG,
        useClass: HammerConfig
      }, _shared_system_services_app_service__WEBPACK_IMPORTED_MODULE_4__.AppService, _shared_system_services_system_service__WEBPACK_IMPORTED_MODULE_7__.SystemService, _shared_data_services_storage_service__WEBPACK_IMPORTED_MODULE_8__.StorageService, _shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_12__.DocumentService, _shared_data_services_db_service__WEBPACK_IMPORTED_MODULE_9__.DbService, _shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_10__.ApiService, _shared_authentication_services_auth_service__WEBPACK_IMPORTED_MODULE_5__.AuthService, _shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_6__.AuthRefService, _shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_11__.UiService, _angular_common__WEBPACK_IMPORTED_MODULE_18__.DatePipe, _angular_common__WEBPACK_IMPORTED_MODULE_18__.CurrencyPipe, {
        provide: angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_19__.OAuthStorage,
        useFactory: storageFactory
      }, (0,_angular_common_http__WEBPACK_IMPORTED_MODULE_17__.provideHttpClient)((0,_angular_common_http__WEBPACK_IMPORTED_MODULE_17__.withInterceptorsFromDi)())],
      imports: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.BrowserModule, _shared_ui_ui_module__WEBPACK_IMPORTED_MODULE_1__.UiModule, _angular_platform_browser_animations__WEBPACK_IMPORTED_MODULE_20__.BrowserAnimationsModule, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.HammerModule, _shared_documents_documents_module__WEBPACK_IMPORTED_MODULE_14__.SharedDocumentsModule, _app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule, angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_19__.OAuthModule.forRoot()]
    }))();
  }
  return AppModule;
})();
(function () {
  (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_16__["ɵɵsetNgModuleScope"](AppModule, {
    declarations: [_app_component__WEBPACK_IMPORTED_MODULE_2__.AppComponent, _privacy_policy_privacy_policy_component__WEBPACK_IMPORTED_MODULE_3__.PrivacyPolicyComponent],
    imports: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.BrowserModule, _shared_ui_ui_module__WEBPACK_IMPORTED_MODULE_1__.UiModule, _angular_platform_browser_animations__WEBPACK_IMPORTED_MODULE_20__.BrowserAnimationsModule, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.HammerModule, _shared_documents_documents_module__WEBPACK_IMPORTED_MODULE_14__.SharedDocumentsModule, _app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule, angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_19__.OAuthModule]
  });
})();
function storageFactory() {
  return localStorage;
}

/***/ }),

/***/ 3054:
/*!************************************************************!*\
  !*** ./src/app/privacy-policy/privacy-policy.component.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   PrivacyPolicyComponent: () => (/* binding */ PrivacyPolicyComponent)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../shared/authentication/services/auth-ref.service */ 4387);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/router */ 4947);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/common */ 6216);




function PrivacyPolicyComponent_button_251_Template(rf, ctx) {
  if (rf & 1) {
    const _r2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](0, "button", 16);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function PrivacyPolicyComponent_button_251_Template_button_click_0_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r2);
      const ctx_r2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx_r2.goHome());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](1, "span", 8);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](2, "i", 17);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](3, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](4, " Dashboard ");
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
  }
}
let PrivacyPolicyComponent = /*#__PURE__*/(() => {
  class PrivacyPolicyComponent {
    constructor(authRefService, router) {
      this.authRefService = authRefService;
      this.router = router;
      // #region Authentication
      this.authenticated = false;
      // #endregion
      // #region Side Nav
      this.sideNavActive = false;
    }
    watchAuth() {
      this.authSubscription = this.authRefService.authenticated.subscribe({
        next: authenticated => {
          this.authenticated = authenticated;
        }
      });
    }
    toggleSideNav() {
      this.sideNavActive = !this.sideNavActive;
    }
    closeSideNav() {
      this.sideNavActive = false;
    }
    get showHomeNav() {
      return this.authenticated;
    }
    goHome() {
      this.router.navigate(['/']);
    }
    // #endregion
    // #region Bootstrapping
    init() {
      this.watchAuth();
    }
    // #endregion
    ngOnInit() {
      this.init();
    }
    ngOnDestroy() {
      this.authSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function PrivacyPolicyComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PrivacyPolicyComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_shared_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_router__WEBPACK_IMPORTED_MODULE_2__.Router));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineComponent"]({
      type: PrivacyPolicyComponent,
      selectors: [["ng-component"]],
      standalone: false,
      decls: 257,
      vars: 5,
      consts: [["sideNavControlElm", ""], ["id", "privacyPolicy"], [1, "logo"], ["src", "/assets/images/logo.svg"], [1, "document"], ["id", "sideNav"], [1, "bg", 3, "click"], [1, "control", 3, "click"], [1, "icon"], [1, "bars"], [1, "bar"], [1, "island"], [1, "routes"], ["class", "route", 3, "click", 4, "ngIf"], ["href", "https://repipe.com/", "target", "_blank", 1, "route"], [1, "fa-duotone", "fa-link"], [1, "route", 3, "click"], [1, "fa-duotone", "fa-solid", "fa-calendar"]],
      template: function PrivacyPolicyComponent_Template(rf, ctx) {
        if (rf & 1) {
          const _r1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetCurrentView"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](0, "section", 1)(1, "header")(2, "div", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](3, "img", 3);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](4, "div", 4)(5, "h1");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](6, "\"Repipe\" Application");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](7, "h1");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](8, "Privacy Policy");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](9, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](10, "Effective Date: September 8, 2025");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](11, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](12, "Last Updated: September 8, 2025");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](13, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](14, "1. Introduction");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](15, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](16, "National Renovations LLC (\"we,\" \"our,\" or \"us\") respects your privacy and is committed to protecting your personal information. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our mobile application Repipe (the \"App\").");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](17, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](18, "2. Information We Collect");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](19, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](20, "2.1 Personal Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](21, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](22, "We may collect the following types of personal information:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](23, "ul")(24, "li")(25, "strong");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](26, "From Repipe Consultants:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](27, "ul")(28, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](29, "Name, email address, and phone number");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](30, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](31, "Professional credentials and company affiliation");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](32, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](33, "Profile photos");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](34, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](35, "Device identifiers and technical information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](36, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](37, "App interaction patterns and feature usage analytics");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](38, "li")(39, "strong");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](40, "From Homeowners:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](41, "ul")(42, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](43, "Name, email address, and phone number");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](44, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](45, "Property address and location information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](46, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](47, "Communication preferences");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](48, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](49, "2.2 Property and Project Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](50, "ul")(51, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](52, "Property diagrams and measurements");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](53, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](54, "Photos of plumbing systems and property areas");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](55, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](56, "Estimate details and pricing information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](57, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](58, "Project notes and specifications");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](59, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](60, "Communication history between consultants and homeowners");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](61, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](62, "2.3 Location Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](63, "ul")(64, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](65, "Precise location data when using mapping features");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](66, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](67, "Property locations for service estimates");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](68, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](69, "GPS coordinates for navigation purposes");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](70, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](71, "2.4 Communication Data");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](72, "ul")(73, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](74, "Messages sent through the in-app messaging system");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](75, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](76, "Call logs and communication history");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](77, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](78, "File attachments and shared documents");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](79, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](80, "2.5 Technical Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](81, "ul")(82, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](83, "Device type, operating system, and version");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](84, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](85, "App usage analytics and performance data");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](86, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](87, "IP address and network information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](88, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](89, "Crash reports and error logs");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](90, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](91, "3. How We Use Your Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](92, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](93, "We use the collected information for the following purposes:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](94, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](95, "3.1 Service Delivery");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](96, "ul")(97, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](98, "Facilitate communication between consultants and homeowners");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](99, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](100, "Create and store property diagrams and estimates");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](101, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](102, "Schedule appointments and manage projects");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](103, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](104, "Provide customer support");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](105, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](106, "3.2 App Functionality");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](107, "ul")(108, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](109, "Enable location-based services and navigation");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](110, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](111, "Synchronize data across devices");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](112, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](113, "Maintain user accounts and preferences");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](114, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](115, "Process payments and billing");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](116, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](117, "3.3 Business Operations");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](118, "ul")(119, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](120, "Improve app performance and user experience");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](121, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](122, "Analyze usage patterns and trends");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](123, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](124, "Ensure security and prevent fraud");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](125, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](126, "Comply with legal obligations");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](127, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](128, "4. Information Sharing and Disclosure");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](129, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](130, "4.1 Service Providers");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](131, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](132, "We may share information with trusted third-party service providers who assist us in:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](133, "ul")(134, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](135, "Cloud storage and data hosting");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](136, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](137, "Payment processing");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](138, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](139, "Analytics and app performance monitoring");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](140, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](141, "4.2 Business Partners");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](142, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](143, "Information may be shared between consultants and homeowners as necessary for service delivery.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](144, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](145, "4.3 Legal Requirements");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](146, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](147, "We may disclose information when required by law or to:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](148, "ul")(149, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](150, "Comply with legal processes");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](151, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](152, "Protect our rights and property");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](153, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](154, "Ensure user safety and security");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](155, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](156, "Prevent fraud or illegal activities");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](157, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](158, "4.4 Business Transfers");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](159, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](160, "In the event of a merger, acquisition, or sale of assets, user information may be transferred as part of the transaction.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](161, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](162, "5. Data Security");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](163, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](164, "We implement appropriate technical and organizational measures to protect your information, including:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](165, "ul")(166, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](167, "Encryption of data in transit and at rest");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](168, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](169, "Secure authentication protocols");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](170, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](171, "Regular security assessments");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](172, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](173, "Limited access controls");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](174, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](175, "Secure data centers and hosting environments");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](176, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](177, "6. Data Retention");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](178, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](179, "We retain your information for as long as necessary to:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](180, "ul")(181, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](182, "Provide our services");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](183, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](184, "Comply with legal obligations");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](185, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](186, "Resolve disputes");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](187, "li");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](188, "Enforce our agreements");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](189, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](190, "7. Your Rights and Choices");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](191, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](192, "7.1 Access and Correction");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](193, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](194, "You may request access to or correction of your personal information by contacting us at it@repipespecialists.com.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](195, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](196, "7.2 Data Deletion");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](197, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](198, "You may request deletion of your account and associated data, subject to legal retention requirements.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](199, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](200, "7.3 Communication Preferences");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](201, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](202, "You can opt out of promotional communications while still receiving service-related messages.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](203, "h3");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](204, "7.4 Location Services");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](205, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](206, "You can disable location services through your device settings, though this may limit app functionality.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](207, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](208, "8. Children's Privacy");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](209, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](210, "Our App is not intended for children under 13 years of age. We do not knowingly collect personal information from children under 13. If we become aware that we have collected such information, we will take steps to delete it promptly.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](211, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](212, "9. App Access Restrictions");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](213, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](214, "This App is restricted to authorized repipe consultants and employees of National Renovations, LLC. Access is granted only to verified personnel who have been properly onboarded and trained. Unauthorized use of this App is prohibited.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](215, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](216, "10. International Data Transfers");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](217, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](218, "Your information may be transferred to and processed in countries other than your country of residence. We ensure appropriate safeguards are in place for such transfers in accordance with applicable laws.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](219, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](220, "11. Third-Party Services");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](221, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](222, "Our App may contain links to or integrate with third-party services. This Privacy Policy does not apply to those services, and we encourage you to review their privacy policies.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](223, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](224, "12. Updates to This Policy");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](225, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](226, "We may update this Privacy Policy periodically to reflect changes in our practices or applicable laws. We will notify users of material changes through the App or other appropriate means.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](227, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](228, "13. Contact Information");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](229, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](230, "If you have questions about this Privacy Policy or our privacy practices, please contact us:");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](231, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](232, "Email: it@repipespecialists.com");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](233, "h2");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](234, "14. Consent");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](235, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](236, "By using our App, you consent to the collection, use, and disclosure of your information as described in this Privacy Policy.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](237, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](238, "This Privacy Policy was last updated on September 8, 2025 and is effective as of September 8, 2025.");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](239, "nav", 5)(240, "div", 6);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function PrivacyPolicyComponent_Template_div_click_240_listener() {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.closeSideNav());
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](241, "button", 7, 0);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function PrivacyPolicyComponent_Template_button_click_241_listener() {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.toggleSideNav());
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](243, "span", 8)(244, "span", 9);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](245, "span", 10)(246, "span", 10)(247, "span", 10);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](248, "aside", 5)(249, "div", 11)(250, "div", 12);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtemplate"](251, PrivacyPolicyComponent_button_251_Template, 5, 0, "button", 13);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](252, "a", 14)(253, "span", 8);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](254, "i", 15);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](255, "label");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](256, " Repipe Home Page ");
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]()()()()()();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"](239);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵclassProp"]("active", ctx.sideNavActive);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"](9);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵclassProp"]("active", ctx.sideNavActive);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"](3);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵproperty"]("ngIf", ctx.showHomeNav);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_3__.NgIf],
      styles: ["#privacyPolicy[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  overflow-x: hidden;\n  padding: 5vw;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > header[_ngcontent-%COMP%]    > .logo[_ngcontent-%COMP%] {\n  text-align: center;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > header[_ngcontent-%COMP%]    > .logo[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  width: 30vw;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%] {\n  margin-top: 3vw;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   *[_ngcontent-%COMP%] {\n  font-family: \"Times New Roman\", Times, serif;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   h1[_ngcontent-%COMP%] {\n  text-align: center;\n  font-size: 4vw;\n  font-weight: var(--strongest);\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  margin-top: 2vw;\n  font-size: 3vw;\n  font-weight: var(--stronger);\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n  margin-top: 0.5vw;\n  font-size: 2.6vw;\n  font-weight: var(--strong);\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   p[_ngcontent-%COMP%] {\n  margin: 1vw 0;\n  font-size: 1.8vw;\n  font-weight: var(--stdweight);\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   ul[_ngcontent-%COMP%] {\n  margin: 1vw 0;\n  list-style-type: disc;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   ul[_ngcontent-%COMP%]   li[_ngcontent-%COMP%] {\n  font-size: 1.8vw;\n  font-weight: var(--stdweight);\n  margin-top: 0.5vw;\n}\n#privacyPolicy[_ngcontent-%COMP%]    > .document[_ngcontent-%COMP%]   ul[_ngcontent-%COMP%]   li[_ngcontent-%COMP%]:first-child {\n  margin-top: 0;\n}\n\n#sideNav[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: calc(var(--sideNav-layer) - 1);\n  background-color: rgba(var(--color1-raw), 0.7);\n  -webkit-backdrop-filter: blur(0.25vw);\n  -moz-backdrop-filter: blur(0.25vw);\n  -o-backdrop-filter: blur(0.25vw);\n  backdrop-filter: blur(0.25vw);\n  opacity: 0;\n  transition: opacity 0.2s linear;\n  pointer-events: none;\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  position: fixed;\n  z-index: calc(var(--sideNav-layer) + 1);\n  top: calc(0.5vw + var(--systemOffset-top));\n  left: 0.5vw;\n  cursor: pointer;\n  transition: transform 0.2s var(--easeInOutQuad);\n  transform: translateX(0) translateY(0);\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%] {\n  display: block;\n  height: 3.5vw;\n  width: 3.5vw;\n  position: relative;\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]:before {\n  content: \"\";\n  display: block;\n  border-radius: 100%;\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: transparent;\n  z-index: 0;\n  transition: border-radius 0.2s var(--easeInOutQuad), background-color 0.2s var(--easeInOutQuad);\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 1;\n  transform-origin: top center;\n  transition: transform 0.1s var(--easeInOutQuad);\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%] {\n  display: block;\n  width: 1.6vw;\n  height: 0.22vw;\n  background-color: var(--color1);\n  border-radius: 999px;\n  margin-top: 0.3vw;\n  opacity: 1;\n  transition: transform 0.2s var(--easeInOutQuad), opacity 0.2s var(--easeInOutQuad);\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:nth-child(1) {\n  transform-origin: top left;\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:nth-child(3) {\n  transform-origin: bottom left;\n}\n#sideNav[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:first-child {\n  margin-top: 0;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%] {\n  position: fixed;\n  z-index: var(--sideNav-layer);\n  top: calc(1.5vw + var(--systemOffset-top));\n  left: 2vw;\n  background-color: var(--color2);\n  padding: 3vw 0 1vw;\n  border-radius: 999px;\n  transition: transform 0.2s var(--easeInOutQuad);\n  transform: scale(0);\n  transform-origin: top left;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%] {\n  display: flex;\n  padding: 1vw;\n  display: flex;\n  flex-direction: column;\n  align-items: flex-start;\n  border-top: 0.1vw var(--color2Alt2) solid;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%] {\n  cursor: pointer;\n  position: relative;\n  margin-top: 1vw;\n  display: flex;\n  width: 100%;\n  align-items: center;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%] {\n  display: block;\n  position: relative;\n  height: 4.2vw;\n  width: 4.2vw;\n  background-color: var(--color2);\n  border-radius: 100%;\n  transition: border-color 0.2s, background-color 0.2s;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  color: var(--color1Alt1);\n  font-size: 2vw;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 100%;\n  margin-left: 2vw;\n  font-size: 1.4vw;\n  font-weight: var(--strong);\n  color: var(--color2);\n  white-space: nowrap;\n  display: block;\n  transform: scale(0) translateY(-50%);\n  transform-origin: left center;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route.active[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%] {\n  background-color: rgba(var(--color3-raw), 0.2);\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route.active[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > i[_ngcontent-%COMP%] {\n  color: var(--color3Alt1);\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%]:first-child {\n  margin-top: 0;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]:first-child {\n  border-top: none;\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav.active[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%] {\n  transform: scale(1);\n}\n#sideNav[_ngcontent-%COMP%]   #sideNav.active[_ngcontent-%COMP%]    > .island[_ngcontent-%COMP%]    > .routes[_ngcontent-%COMP%]    > .route[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  transform: scale(1) translateY(-50%);\n  transition: transform 0.5s 0.3s;\n}\n#sideNav.active[_ngcontent-%COMP%]    > .bg[_ngcontent-%COMP%] {\n  opacity: 1;\n  pointer-events: initial;\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  transform: translateX(2.75vw) translateY(1vw);\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]:before {\n  background-color: var(--color2);\n  border-bottom-left-radius: 0;\n  border-bottom-right-radius: 0;\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%] {\n  transform: translate(-50%, -50%) translateX(25%);\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:nth-child(1) {\n  transform: rotate(45deg);\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:nth-child(2) {\n  opacity: 0;\n}\n#sideNav.active[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > .icon[_ngcontent-%COMP%]    > .bars[_ngcontent-%COMP%]    > .bar[_ngcontent-%COMP%]:nth-child(3) {\n  transform: rotate(-45deg);\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return PrivacyPolicyComponent;
})();

/***/ }),

/***/ 2846:
/*!****************************************************!*\
  !*** ./src/app/shared/addresses/models/address.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Address: () => (/* binding */ Address)
/* harmony export */ });
class Address {
  get friendlyAddress() {
    let streetAddress = this.streetAddress1;
    if (this.streetAddress2 != null) {
      streetAddress += ` ${this.streetAddress2}`;
    }
    return `${streetAddress}, ${this.city}, ${this.regionIso3166}, ${this.postalCode}`;
  }
  get mappingAddress() {
    return `${this.streetAddress1}, ${this.city}, ${this.regionIso3166}, ${this.postalCode}`;
  }
  constructor() {}
}

/***/ }),

/***/ 8723:
/*!***********************************************************!*\
  !*** ./src/app/shared/appointments/models/appointment.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Appointment: () => (/* binding */ Appointment),
/* harmony export */   AppointmentDocument: () => (/* binding */ AppointmentDocument),
/* harmony export */   AppointmentDocumentResponseContent: () => (/* binding */ AppointmentDocumentResponseContent),
/* harmony export */   AppointmentEventSubType: () => (/* binding */ AppointmentEventSubType),
/* harmony export */   AppointmentEventType: () => (/* binding */ AppointmentEventType),
/* harmony export */   AppointmentFixture: () => (/* binding */ AppointmentFixture),
/* harmony export */   AppointmentPricingState: () => (/* binding */ AppointmentPricingState),
/* harmony export */   AppointmentPropertyEntity: () => (/* binding */ AppointmentPropertyEntity),
/* harmony export */   AppointmentShop: () => (/* binding */ AppointmentShop),
/* harmony export */   AppointmentStatus: () => (/* binding */ AppointmentStatus),
/* harmony export */   AppointmentViewingStatus: () => (/* binding */ AppointmentViewingStatus),
/* harmony export */   AvailableFixtures: () => (/* binding */ AvailableFixtures),
/* harmony export */   FixtureSection: () => (/* binding */ FixtureSection),
/* harmony export */   ManagedAppointmentSummary: () => (/* binding */ ManagedAppointmentSummary),
/* harmony export */   NoteAudience: () => (/* binding */ NoteAudience),
/* harmony export */   PublicAppointmentPayment: () => (/* binding */ PublicAppointmentPayment),
/* harmony export */   PublicAppointmentPrice: () => (/* binding */ PublicAppointmentPrice)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var _properties_models_property__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../properties/models/property */ 1750);
/* harmony import */ var _rendering__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rendering */ 3114);
/* harmony import */ var _fixtures_models_fixture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../fixtures/models/fixture */ 1735);
/* harmony import */ var _pricing__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pricing */ 3300);
/* harmony import */ var _entities_models_attributes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../entities/models/attributes */ 7720);
/* harmony import */ var _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../entities/models/rules */ 822);
/* harmony import */ var _promotions_models_promotion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../promotions/models/promotion */ 8083);
/* harmony import */ var _payments_models_payment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../payments/models/payment */ 1083);
/* harmony import */ var _documents_models_document__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../documents/models/document */ 735);
/* harmony import */ var _documents_models_content__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../documents/models/content */ 5477);
/* harmony import */ var _helpers_methods_methods__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../helpers/methods/methods */ 2853);
/* harmony import */ var _needs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./needs */ 6467);













class ManagedAppointmentSummary {
  constructor() {
    this.id = "";
    this.status = AppointmentStatus.Open;
    this.lastUpdated_Utc = new Date();
    /* Local */
    this.reverting = false;
  }
}
class Appointment {
  constructor() {
    this.id = "";
    this.accepted = false;
    this.opportunityTypes = [];
    this.opportunityPlumbingIssues = [];
    this.isEmergency = false;
    this.status = AppointmentStatus.Open;
    this.customerNeeds = {};
    this.payments = [];
    this.lenders = [];
    this.availablePromotions = [];
    this.availableFixtures = [];
    this.availableEntities = [];
    this.availableSkus = [];
    this.availablePaymentSettings = [];
    this.availableDocuments = [];
    this.availableDispositionStatuses = [];
    this.availablePresentationContent = [];
    this.availableShops = [];
    this.documents = [];
    this.created_Utc = new Date();
    this.lastUpdated_Utc = new Date();
    /* Local */
    this.reverting = false;
    this.accepting = false;
    this.changed$ = new rxjs__WEBPACK_IMPORTED_MODULE_12__.Subject();
    this.priceChanged$ = new rxjs__WEBPACK_IMPORTED_MODULE_12__.Subject();
    this.available = true;
    this.submittingEstimate = false;
    // #region Progression
    this.checkInCompleted = false;
    this.summaryCompleted = false;
    this.needsCompleted = false;
    this.pricingCompleted = false;
    this.inspectionCompleted = false;
    this.presentationCompleted = false;
    this.jobSummaryCompleted = false;
    this.documentsCompleted = false;
    // #endregion
    // #region Customer Needs
    this.questions = [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("How did you hear about Repipe Specialists?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Radio", "radio"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("TV", "tv"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Internet", "internet"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Direct Mail", "directmail"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Referral Shop", "referralshop"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Facebook / Instagram", "social"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")]), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("What was the primary reason you called us out today?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Old Pipes", "oldpipes"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Leaks", "leaks"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Water shut off", "watershutoff"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Low pressure", "lowpressure"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Rusty Water", "rustywater"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Insurance related", "insurance"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Polybutylene pipes", "polybutylene"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")]), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("What other problems are you having with your current plumbing system?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Hot water takes a long time to come out", "hotwater"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Old water heater", "oldwaterheater"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Drains", "drains"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")]), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("How much do you know about the repipe process?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("None", "none"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("It's been fully explained", "explained"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Some knowledge", "some"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")]), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("What is important to you when hiring a company to repipe your home?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Good Reviews", "reviews"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Good rating with the BBB", "bbb"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Fair price point", "price"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Backs their warranty", "warranty"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Many years in business", "yearsinbusiness"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("An all-inclusive job start to finish -- including patching", "allinclusive"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")]), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedQuestion("Have you had any plumbers out to talk about your repipe?", [new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Yes", "yes"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("No", "no"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("You're the first one", "first"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Have had a couple of bids", "couplebids"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Not Applicable", "na"), new _needs__WEBPACK_IMPORTED_MODULE_11__.CustomerNeedPossibleAnswer("Other", "other")])];
    // #endregion
    // #region Documents
    this.documentsValidForEstimate = false;
    // #endregion
    // #region Payments
    this.paymentsValidForEstimate = false;
  }
  get hasPlumbingIssues() {
    return this.opportunityPlumbingIssues.length > 0;
  }
  checkSummaryProgression() {
    this.summaryCompleted = true;
  }
  checkCheckInProgression() {
    if (this.property?.photo?.fileName != null || this.property?.photo_B64 != null) {
      this.checkInCompleted = true;
    } else {
      this.checkInCompleted = false;
    }
  }
  checkNeedsProgression() {
    let missingQuestion = false;
    for (var i = 0, len = this.questions.length; i < len; i++) {
      const question = this.questions[i];
      const answeredQuestion = this.customerNeeds[question.question];
      if (answeredQuestion == null || answeredQuestion.length <= 0) {
        missingQuestion = true;
        break;
      }
    }
    this.needsCompleted = !missingQuestion;
  }
  inspectionProgressionFixtureCheck(entities) {
    let foundFixture = false;
    for (var i = 0, len = entities.length; i < len; i++) {
      const entity = entities[i];
      const validFixture = entity.fixtures.find(x => x.valid);
      if (validFixture != null) {
        foundFixture = true;
        break;
      } else if (!foundFixture) {
        foundFixture = this.inspectionProgressionFixtureCheck(entity.entities);
      }
    }
    return foundFixture;
  }
  checkInspectionProgression() {
    let hasAtLeastOneFixture = false;
    if (this.property?.entity != null) {
      hasAtLeastOneFixture = this.inspectionProgressionFixtureCheck(this.property.entity.entities);
    }
    this.inspectionCompleted = hasAtLeastOneFixture && (this.property?.entity?.valid ?? false);
  }
  checkPresentationProgression() {
    this.presentationCompleted = this.inspectionCompleted;
  }
  checkJobSummaryProgression() {
    this.jobSummaryCompleted = this.presentationCompleted;
  }
  checkPricingProgression() {
    this.pricingCompleted = this.price?.finalPrice != null && this.price.finalPrice > 0;
  }
  checkDocumentsProgression() {
    let missingDocument = this.documents.length <= 0;
    for (var i = 0, len = this.documents.length; i < len; i++) {
      const document = this.documents[i];
      if (document.executedDocument?.fileName == null && document.executedDocument_B64 == null) {
        missingDocument = true;
        break;
      }
    }
    this.documentsCompleted = !missingDocument;
  }
  checkProgression() {
    this.checkSummaryProgression();
    this.checkCheckInProgression();
    this.checkNeedsProgression();
    this.checkInspectionProgression();
    this.checkPresentationProgression();
    this.checkJobSummaryProgression();
    this.checkPricingProgression();
    this.checkDocumentsProgression();
  }
  checkDocumentValidity() {
    let hasMissingDocument = false;
    for (var i = 0, len = this.documents.length; i < len; i++) {
      const document = this.documents[i];
      if (document.content != null) {
        if ((document.content.includes("signature") || document.content.includes("initial")) && document.signatures.length <= 0) {
          hasMissingDocument = true;
          break;
        }
      }
    }
    this.documentsValidForEstimate = !hasMissingDocument;
  }
  doesDocumentRuleApply(rule, matches, entities = undefined) {
    if (entities != null) {
      for (var i = 0, len = entities.length; i < len; i++) {
        const entity = entities[i];
        const entityMatches = this.checkIfCriteriaMatched(entity, rule);
        matches.push(...entityMatches);
        if (matches.length == rule.criteria.length) {
          return true;
        } else {
          for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
            const fixture = entity.fixtures[j];
            const fixtureMatches = this.checkIfCriteriaMatched(fixture, rule);
            matches.push(...fixtureMatches);
            if (matches.length == rule.criteria.length) {
              return true;
            }
          }
          return this.doesDocumentRuleApply(rule, matches, entity.entities);
        }
      }
    } else {
      if (this.job != null) {
        const jobMatches = this.checkIfCriteriaMatched(this.job, rule);
        matches.push(...jobMatches);
        if (matches.length == rule.criteria.length) {
          return true;
        }
      }
      if (this.property?.entity != null) {
        const propertyMatches = this.checkIfCriteriaMatched(this.property.entity, rule);
        matches.push(...propertyMatches);
        if (matches.length == rule.criteria.length) {
          return true;
        } else {
          for (var j = 0, jlen = this.property.entity.fixtures.length; j < jlen; j++) {
            const fixture = this.property.entity.fixtures[j];
            const fixtureMatches = this.checkIfCriteriaMatched(fixture, rule);
            matches.push(...fixtureMatches);
            if (matches.length == rule.criteria.length) {
              return true;
            }
          }
          return this.doesDocumentRuleApply(rule, matches, this.property.entity.entities);
        }
      }
    }
    return false;
  }
  checkIfDocumentApplies(document) {
    const matchingRules = [];
    for (var i = 0, len = document.rules.length; i < len; i++) {
      const rule = document.rules[i];
      const ruleMatches = this.doesDocumentRuleApply(rule, []);
      if (ruleMatches) {
        matchingRules.push(rule);
      }
    }
    if (matchingRules.length == document.rules.length) {
      return true;
    } else {
      return false;
    }
  }
  applyDocument(document) {
    const existingDoc = this.documents.find(x => x.id == document.id);
    if (existingDoc == null) {
      const apptDoc = new AppointmentDocument(document.id, document.name, document.customerFacing, document.shopFacing, document.standalone, document.dynamic, document.alwaysShow, document.mapping, document.displayOrder, document.content);
      this.documents.push(apptDoc);
    } else {
      existingDoc.content = document.content;
      existingDoc.mapping = document.mapping;
    }
  }
  removeDocument(document) {
    let existingIndex = this.documents.findIndex(x => x.id == document.id);
    if (existingIndex <= -1) {
      existingIndex = this.documents.findIndex(x => x.name == document.name);
    }
    if (existingIndex > -1) {
      this.documents.splice(existingIndex, 1);
    }
  }
  checkDocuments() {
    if (this.property?.entity != null && this.price?.finalPrice != null) {
      /* Shim to account for duplicate documents */
      const documents = [];
      this.documents.forEach(document => {
        const existingDoc = documents.find(x => x.id == document.id);
        if (existingDoc == null) {
          documents.push(document);
        }
      });
      this.documents = documents;
      const existingAddenda = this.documents.find(x => x.name == "Scope of Work Acknowledgments");
      let addenda = new AppointmentDocument((0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_10__.generateId)(), "Scope of Work Acknowledgments", true, true, false, true, true, undefined, 999, "<p>{{logo}}</p><p>{{document.name}}</p>{{timestamp}}");
      if (existingAddenda != null) {
        addenda = existingAddenda;
      }
      for (var i = 0, len = this.availableDocuments.length; i < len; i++) {
        const document = this.availableDocuments[i];
        const applies = this.checkIfDocumentApplies(document);
        if (applies) {
          if (document.standalone) {
            this.applyDocument(document);
          } else {
            const existingAddendum = addenda.documents.find(x => x.id == document.id);
            if (existingAddendum == null) {
              const addendum = new AppointmentDocument(document.id, document.name, document.customerFacing, document.shopFacing, false, document.dynamic, document.alwaysShow, document.mapping, addenda.documents.length, document.content);
              addenda.documents.push(addendum);
            }
          }
        } else {
          this.removeDocument(document);
        }
      }
      if (existingAddenda == null && addenda.documents.length > 0) {
        this.applyDocument(addenda);
      } else {
        this.removeDocument(addenda);
      }
    } else {
      this.documents = [];
    }
  }
  // #endregion
  // #region Entities
  flattenEntity(entity, flattened) {
    flattened.push(...entity.entities);
    entity.entities.forEach(childEntity => [flattened.push(...this.flattenEntity(childEntity, flattened))]);
    return flattened;
  }
  findParent(entityId) {
    if (this.property?.entity != null) {
      const flattened = this.flattenEntity(this.property.entity, [this.property.entity]);
      for (var i = 0, len = flattened.length; i < len; i++) {
        const entity = flattened[i];
        for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
          const fixture = entity.fixtures[j];
          if (fixture.id == entityId) {
            return entity;
          }
        }
        for (var j = 0, jlen = entity.entities.length; j < jlen; j++) {
          const childEntity = entity.entities[j];
          if (childEntity.id == entityId) {
            return entity;
          }
        }
      }
    }
    return undefined;
  }
  // #endregion
  // #region Fixtures
  getFixtureCountByName(name, entities = [], count = 0, attributesToMatch = []) {
    entities.forEach(entity => {
      entity.fixtures.forEach(f => {
        const fixtureName = f.name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
        if (fixtureName == name) {
          if (attributesToMatch.length > 0) {
            let matchCount = 0;
            f.attributes.forEach(attribute => {
              const attributeName = attribute.name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
              const attributeValue = attribute.values[0]?.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
              attributesToMatch.forEach(attributeToMatch => {
                const matchingName = attributeToMatch.name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
                const matchingValue = attributeToMatch.value.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
                if (attributeName == matchingName && attributeValue == matchingValue) {
                  matchCount = matchCount + 1;
                }
              });
            });
            if (matchCount == attributesToMatch.length) {
              count = count + 1;
            }
          } else {
            count = count + 1;
          }
        }
      });
      count = this.getFixtureCountByName(name, entity.entities, count, attributesToMatch);
    });
    return count;
  }
  getFixtureCount(type, entities = [], count = 0) {
    entities.forEach(entity => {
      entity.fixtures.forEach(f => {
        if (f.imageSrc_Base64 == type) {
          count = count + 1;
        }
      });
      count = this.getFixtureCount(type, entity.entities, count);
    });
    return count;
  }
  renumberFixturesByType(type, entities = [], count = 1) {
    entities.forEach(entity => {
      entity.fixtures.forEach(f => {
        if (f.imageSrc_Base64 == type) {
          f.number = count;
          count = count + 1;
        }
      });
      count = this.renumberFixturesByType(type, entity.entities, count);
    });
    return count;
  }
  renumberFixtures() {
    this.availableFixtures.forEach(fc => {
      fc.fixtures.forEach(af => {
        this.renumberFixturesByType(af.imageSrc_Base64, this.property?.entity?.entities);
      });
    });
  }
  // #endregion
  // #region Rooms
  getRoomTypeCount(type, entities = [], roomCount = 0) {
    entities.forEach(e => {
      if (e.type == _properties_models_property__WEBPACK_IMPORTED_MODULE_0__.PropertyEntityType.Room && e.name != null) {
        const name = e.name.toLowerCase();
        if (name == type) {
          roomCount = roomCount + 1;
        }
      } else {
        roomCount = this.getRoomTypeCount(type, e.entities, roomCount);
      }
    });
    return roomCount;
  }
  renumberRoomsByType(type, entities = [], roomCount = 0) {
    entities.forEach(e => {
      if (e.type == _properties_models_property__WEBPACK_IMPORTED_MODULE_0__.PropertyEntityType.Room && e.name != null) {
        const name = e.name.toLowerCase();
        if (name == type) {
          roomCount = roomCount + 1;
          e.number = roomCount;
        }
      } else {
        roomCount = this.renumberRoomsByType(type, e.entities, roomCount);
      }
    });
    return roomCount;
  }
  renumberRooms() {
    this.renumberRoomsByType("bathroom", this.property?.entity?.entities);
  }
  checkPaymentsValidity() {
    this.paymentsValidForEstimate = true;
    if (this.payments.length <= 0) {
      this.paymentsValidForEstimate = false;
    }
    if (this.paymentSetting != null) {
      for (var i = 0, len = this.paymentSetting.details.length; i < len; i++) {
        const detail = this.paymentSetting.details[i];
        if (detail.amount < detail.minimumAmount || detail.maximumAmount != null && detail.amount > detail.maximumAmount || detail.amount == undefined) {
          this.paymentsValidForEstimate = false;
        }
        for (var i = 0, len = this.lenders.length; i < len; i++) {
          const lender = this.lenders[i];
          if (lender.amountFinanced == null || lender.amountFinanced <= 0) {
            this.paymentsValidForEstimate = false;
          }
          const matchedLender = detail.lenderAmounts.find(x => x.name == lender.name);
          if (matchedLender != null && matchedLender.amount == undefined) {
            this.paymentsValidForEstimate = false;
          } else if (matchedLender == null) {
            this.paymentsValidForEstimate = false;
          }
        }
      }
      for (var i = 0, len = this.payments.length; i < len; i++) {
        const payment = this.payments[i];
        if (payment.amount <= 0) {
          this.paymentsValidForEstimate = false;
        }
      }
    } else {
      this.paymentsValidForEstimate = false;
    }
  }
  // #endregion
  // #region Payment Details
  setPaymentSetting(setting) {
    if (this.price?.finalPrice != null) {
      const setDetails = [];
      for (var i = 0, len = setting.details.length; i < len; i++) {
        const detail = setting.details[i];
        let amount = this.price.finalPrice * (detail.defaultPercent / 100);
        if (detail.maximumAmount != null && amount > detail.maximumAmount) {
          amount = detail.maximumAmount;
        }
        if (detail.minimumAmount != null && amount < detail.minimumAmount) {
          amount = detail.minimumAmount;
        }
        const setDetail = new _payments_models_payment__WEBPACK_IMPORTED_MODULE_7__.PaymentDetail(detail, amount);
        setDetails.push(setDetail);
      }
      const setMethods = [];
      for (var i = 0, len = setting.methods.length; i < len; i++) {
        const method = setting.methods[i];
        const setMethod = Object.assign(new _payments_models_payment__WEBPACK_IMPORTED_MODULE_7__.PaymentMethod(), method);
        setMethods.push(setMethod);
      }
      const setSetting = Object.assign(new _payments_models_payment__WEBPACK_IMPORTED_MODULE_7__.PaymentSetting(), setting);
      setSetting.details = setDetails;
      setSetting.methods = setMethods;
      this.paymentSetting = setSetting;
    }
  }
  checkPaymentSetting() {
    if (this.price?.finalPrice != null) {
      let matchedSetting;
      paymentLoop: for (var i = 0, len = this.availablePaymentSettings.length; i < len; i++) {
        const setting = this.availablePaymentSettings[i];
        if (setting.skuTrigger != null) {
          for (var j = 0, jlen = this.price.details.length; j < jlen; j++) {
            const detail = this.price.details[j];
            const matchingSku = detail.lineItems.find(x => x.skuId == setting.skuTrigger);
            if (matchingSku != null) {
              this.setPaymentSetting(setting);
              matchedSetting = setting;
              break paymentLoop;
            }
          }
        }
      }
      if (matchedSetting == null) {
        matchedSetting = this.availablePaymentSettings.find(x => x.skuTrigger == null);
        if (matchedSetting != null) {
          this.setPaymentSetting(matchedSetting);
        }
      }
    }
  }
  // #endregion
  // #region Pricing
  parseReferenceQuantity(entityId, rule, attributes) {
    const regex = /\[([^\.]+)\.([^\]]*)\](-?\d+)/;
    const match = rule.result.match(regex);
    if (match != null) {
      const referenceId = entityId;
      const refAttribute = match[2];
      let quantity = 0;
      const attribute = attributes.find(x => x.name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase() == refAttribute);
      if (attribute != null) {
        const attrQuantity = Number.parseInt(attribute.values[0]);
        if (match[3] != null) {
          const refQuantity = Number.parseInt(match[3]);
          quantity = attrQuantity + refQuantity;
        } else {
          quantity = attrQuantity;
        }
      }
      const parsedQuantity = {
        referenceId: referenceId,
        attribute: refAttribute,
        quantity: quantity
      };
      return parsedQuantity;
    }
    return null;
  }
  getMatchingEntityAttribute(entity, attributeId) {
    for (var i = 0, len = entity.attributes.length; i < len; i++) {
      const attribute = entity.attributes[i];
      if (attribute.id == attributeId) {
        return attribute;
      }
    }
    const parent = this.findParent(entity.id);
    if (parent != null) {
      const attribute = this.getMatchingEntityAttribute(parent, attributeId);
      if (attribute != null) {
        return attribute;
      }
    } else if (this.job != null) {
      for (var i = 0, len = this.job.attributes.length; i < len; i++) {
        const attribute = this.job.attributes[i];
        if (attribute.id == attributeId) {
          return attribute;
        }
      }
    }
    return undefined;
  }
  checkIfCriteriaMatched(entity, rule) {
    var matches = [];
    for (var i = 0, len = rule.criteria.length; i < len; i++) {
      const criteria = rule.criteria[i];
      switch (criteria.triggerType) {
        case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityCriteriaTriggerType.Attribute:
          {
            let matchingAttribute = this.getMatchingEntityAttribute(entity, criteria.trigger);
            if (matchingAttribute != null) {
              for (var j = 0, jlen = matchingAttribute.values.length; j < jlen; j++) {
                const value = matchingAttribute.values[j];
                let localValue = value.toLowerCase();
                if (value == "true") {
                  localValue = "yes";
                } else if (value == "false") {
                  localValue = "no";
                }
                const possibleValues = [];
                criteria.possibleValues.forEach(value => {
                  possibleValues.push(value.toLowerCase());
                });
                switch (criteria.type) {
                  case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleCriteriaType.Exact:
                    {
                      if (possibleValues.includes(localValue)) {
                        matches.push(`Value: ${localValue} on Attribute: ${matchingAttribute.name}`);
                      }
                    }
                    break;
                  case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleCriteriaType.GreaterThanOrEqual:
                    {
                      var relValue = criteria.possibleValues[0];
                      var attrValue = localValue;
                      if (relValue != null) {
                        var relValueNum = parseInt(relValue);
                        var attrValueNum = parseInt(attrValue);
                        if (attrValueNum >= relValueNum) {
                          matches.push(`Value: ${attrValueNum} is greater than or equal to ${relValueNum} on Attribute: ${matchingAttribute.name}`);
                        }
                      }
                    }
                    break;
                  case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleCriteriaType.GreaterThan:
                    {
                      var relValue = criteria.possibleValues[0];
                      var attrValue = localValue;
                      if (relValue != null) {
                        var relValueNum = parseInt(relValue);
                        var attrValueNum = parseInt(attrValue);
                        if (attrValueNum > relValueNum) {
                          matches.push(`Value: ${attrValueNum} is greater than ${relValueNum} on Attribute: ${matchingAttribute.name}`);
                        }
                      }
                    }
                    break;
                  case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleCriteriaType.LessThanOrEqual:
                    {
                      var relValue = criteria.possibleValues[0];
                      var attrValue = localValue;
                      if (relValue != null) {
                        var relValueNum = parseInt(relValue);
                        var attrValueNum = parseInt(attrValue);
                        if (attrValueNum <= relValueNum) {
                          matches.push(`Value: ${attrValueNum} is less than or equal to ${relValueNum} on Attribute: ${matchingAttribute.name}`);
                        }
                      }
                    }
                    break;
                  case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleCriteriaType.LessThan:
                    {
                      var relValue = criteria.possibleValues[0];
                      var attrValue = localValue;
                      if (relValue != null) {
                        var relValueNum = parseInt(relValue);
                        var attrValueNum = parseInt(attrValue);
                        if (attrValueNum <= relValueNum) {
                          matches.push(`Value: ${attrValueNum} is less than ${relValueNum} on Attribute: ${matchingAttribute.name}`);
                        }
                      }
                    }
                    break;
                }
              }
            }
          }
          break;
        case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityCriteriaTriggerType.ParentRestriction:
          {
            const parent = this.findParent(entity.id);
            if (parent?.entityId == criteria.trigger) {
              matches.push(`Parent Entity is ${parent.type}`);
            }
          }
          break;
      }
      if (criteria.triggerType == "Attribute") {}
    }
    return matches;
  }
  calcPricingForFixture(baseFixture, fixture, details, customPrices = []) {
    for (var i = 0, len = baseFixture.rules.length; i < len; i++) {
      const rule = baseFixture.rules[i];
      var matches = [];
      var entityMatches = this.checkIfCriteriaMatched(fixture, rule);
      if (entityMatches.length == rule.criteria.length) {
        matches.push(...entityMatches);
      }
      if (matches.length > 0) {
        const sku = this.availableSkus.find(x => x.id == rule.skuId);
        if (sku != null) {
          const skuPrice = customPrices.find(x => x.skuId == sku.id)?.price ?? sku.price;
          const lineItem = {
            skuId: sku.id,
            skuCategory: sku.category,
            name: sku.name,
            customerFacing: sku.customerFacing,
            isAttachment: sku.isAttachment,
            description: "",
            price: skuPrice,
            quantity: 0
          };
          switch (rule.resultType) {
            case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleResultType.Quantity:
              {
                lineItem.quantity = parseInt(rule.result);
              }
              break;
            case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleResultType.ReferenceQuantity:
              {
                const parsedQuantity = this.parseReferenceQuantity(fixture.id, rule, fixture.attributes);
                if (parsedQuantity != null) {
                  lineItem.quantity = parsedQuantity.quantity;
                }
              }
              break;
          }
          var detail = {
            ruleId: rule.id,
            matches: matches,
            lineItems: [lineItem],
            result: ""
          };
          details.push(detail);
        }
      }
    }
  }
  calcPricingForFixtures(fixtures, details, customPrices = []) {
    for (var i = 0, len = fixtures.length; i < len; i++) {
      const fixture = fixtures[i];
      let baseFixture = undefined;
      for (var j = 0, jlen = this.availableFixtures.length; j < jlen; j++) {
        const fc = this.availableFixtures[j];
        for (var k = 0, klen = fc.fixtures.length; k < klen; k++) {
          const fcFixture = fc.fixtures[k];
          if (fcFixture.entityId == fixture.entityId) {
            baseFixture = fcFixture;
            break;
          }
        }
      }
      if (baseFixture != null) {
        this.calcPricingForFixture(baseFixture, fixture, details, customPrices);
      }
    }
  }
  calcPricingForEntity(baseEntity, entity, details, customPrices = []) {
    for (var i = 0, len = baseEntity.rules.length; i < len; i++) {
      const rule = baseEntity.rules[i];
      var matches = [];
      var entityMatches = this.checkIfCriteriaMatched(entity, rule);
      if (entityMatches.length == rule.criteria.length) {
        matches.push(...entityMatches);
      }
      if (matches.length > 0) {
        const sku = this.availableSkus.find(x => x.id == rule.skuId);
        if (sku != null) {
          const skuPrice = customPrices.find(x => x.skuId == sku.id)?.price ?? sku.price;
          const lineItem = {
            skuId: sku.id,
            skuCategory: sku.category,
            name: sku.name,
            customerFacing: sku.customerFacing,
            isAttachment: sku.isAttachment,
            description: "",
            price: skuPrice,
            quantity: 0
          };
          switch (rule.resultType) {
            case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleResultType.Quantity:
              {
                lineItem.quantity = parseInt(rule.result);
              }
              break;
            case _entities_models_rules__WEBPACK_IMPORTED_MODULE_5__.EntityRuleResultType.ReferenceQuantity:
              {
                const parsedQuantity = this.parseReferenceQuantity(entity.id, rule, entity.attributes);
                if (parsedQuantity != null) {
                  lineItem.quantity = parsedQuantity.quantity;
                }
              }
              break;
          }
          var detail = {
            ruleId: rule.id,
            matches: matches,
            lineItems: [lineItem],
            result: ""
          };
          details.push(detail);
        }
      }
    }
    this.calcPricingForFixtures(entity.fixtures, details, customPrices);
    this.calcPricingForEntities(details, entity.entities, customPrices);
  }
  calcPricingForEntities(details, entities = undefined, customPrices = []) {
    if (entities != null) {
      for (var i = 0, len = entities.length; i < len; i++) {
        const entity = entities[i];
        let baseEntity = undefined;
        this.availableEntities.forEach(ec => {
          for (var j = 0, jlen = ec.entities.length; j < jlen; j++) {
            const ecEntity = ec.entities[j];
            if (ecEntity.type == entity.type) {
              baseEntity = ecEntity;
              break;
            }
          }
        });
        if (baseEntity != null) {
          this.calcPricingForEntity(baseEntity, entity, details, customPrices);
        }
      }
    } else {
      if (this.job != null) {
        let baseEntity = undefined;
        for (var i = 0, len = this.availableEntities.length; i < len; i++) {
          const ec = this.availableEntities[i];
          for (var j = 0, jlen = ec.entities.length; j < jlen; j++) {
            const ecEntity = ec.entities[j];
            if (ecEntity.type == this.job.type) {
              baseEntity = ecEntity;
              break;
            }
          }
        }
        if (baseEntity != null) {
          this.calcPricingForEntity(baseEntity, this.job, details, customPrices);
        }
      }
      if (this.property?.entity != null) {
        let baseEntity = undefined;
        for (var i = 0, len = this.availableEntities.length; i < len; i++) {
          const ec = this.availableEntities[i];
          for (var j = 0, jlen = ec.entities.length; j < jlen; j++) {
            const ecEntity = ec.entities[j];
            if (ecEntity.type == this.property.entity.type) {
              baseEntity = ecEntity;
              break;
            }
          }
        }
        if (baseEntity != null) {
          this.calcPricingForEntity(baseEntity, this.property.entity, details, customPrices);
        }
      }
    }
  }
  calcAblPrice(parPrice) {
    let ablPrice = parPrice * .6;
    if (ablPrice <= 0) {
      ablPrice = 0;
    }
    return ablPrice;
  }
  calcTargetPrice(parPrice) {
    return parPrice + parPrice * .4;
  }
  calcParPrice(customItems, details) {
    let parPrice = 0;
    customItems.forEach(item => {
      if (item.price != null) {
        parPrice = parPrice + item.price;
      }
    });
    details.forEach(detail => {
      detail.lineItems.forEach(lineItem => {
        parPrice = parPrice + lineItem.price * lineItem.quantity;
      });
    });
    if (parPrice <= 0) {
      parPrice = 0;
    }
    return parPrice;
  }
  calcPromotionalPrice(retailPrice) {
    let promotionalPrice = retailPrice;
    const appliedPromotions = this.price?.appliedPromotions ?? [];
    appliedPromotions.forEach(promotion => {
      if (promotion.discount != null) {
        switch (promotion.type) {
          case _promotions_models_promotion__WEBPACK_IMPORTED_MODULE_6__.PromotionType.Amount:
            {
              promotion.appliedDiscount = promotion.discount;
            }
            break;
          case _promotions_models_promotion__WEBPACK_IMPORTED_MODULE_6__.PromotionType.Percent:
            {
              promotion.appliedDiscount = promotionalPrice * (promotion.discount / 100);
            }
            break;
        }
      } else {
        promotion.appliedDiscount = 0;
      }
      if (promotion.appliedDiscount != null) {
        promotionalPrice = promotionalPrice - promotion.appliedDiscount;
      }
    });
    return promotionalPrice;
  }
  calcFinalPrice(targetPromoPrice) {
    return targetPromoPrice;
  }
  calcPricing() {
    const details = [];
    const considerations = [];
    this.price?.customItems.forEach(item => {
      considerations.push(item);
    });
    const customPrices = [];
    if (this.price != null) {
      for (var i = 0, len = this.price.details.length; i < len; i++) {
        const detail = this.price.details[i];
        for (var j = 0, jlen = detail.lineItems.length; j < jlen; j++) {
          const lineItem = detail.lineItems[j];
          if (lineItem.skuCategory == "CUSTOM") {
            customPrices.push({
              skuId: lineItem.skuId,
              price: lineItem.price
            });
          }
        }
      }
    }
    this.calcPricingForEntities(details, undefined, customPrices);
    const mergedDetails = [];
    details.forEach(detail => {
      const lineItem = detail.lineItems[0];
      if (lineItem != null) {
        const existingDetail = mergedDetails.find(x => x.lineItems[0]?.skuId == lineItem.skuId);
        if (existingDetail != null) {
          const existingLineItem = existingDetail.lineItems[0];
          existingLineItem.quantity = existingLineItem.quantity + lineItem.quantity;
        } else {
          mergedDetails.push(detail);
        }
      }
    });
    const parPrice = this.calcParPrice(considerations, details);
    const ablPrice = this.calcAblPrice(parPrice);
    const targetPrice = this.calcTargetPrice(parPrice);
    const targetPromoPrice = this.calcPromotionalPrice(targetPrice);
    let finalPrice = this.price?.finalPrice;
    if (targetPromoPrice != this.price?.targetPromoPrice) {
      finalPrice = this.calcFinalPrice(targetPromoPrice);
    }
    this.price = new _pricing__WEBPACK_IMPORTED_MODULE_3__.AppointmentPrice(mergedDetails, this.price?.customItems, this.price?.appliedPromotions, this.price?.usingCustomPrice, this.price?.managerApproved, finalPrice, targetPrice, ablPrice, parPrice, targetPromoPrice);
    this.priceChanged$.next();
  }
  // #endregion
  // #region Attributes
  updateMappedDefaultValues(attribute, parentEntity) {
    switch (attribute.defaultValue) {
      case '[entity.type=room].[attribute.roomtype=bathroom].{{count}}':
        {
          const roomCount = this.getRoomTypeCount("bathroom", parentEntity?.entities);
          attribute.values = [`${roomCount}`];
        }
        break;
      case '[entity.type=hosebibb].[attribute.detached=no].[attribute.keepactive=ifpossible].{{count}}':
        {
          const attributesToMatch = [{
            name: "detached",
            value: "false"
          }, {
            name: "keepactive",
            value: "ifpossible"
          }];
          const fixtureCount = this.getFixtureCountByName("hosebibb", parentEntity?.entities, 0, attributesToMatch);
          attribute.values = [`${fixtureCount}`];
        }
        break;
    }
  }
  updateAttributes(entities = undefined) {
    if (entities != null) {
      entities.forEach(e => {
        e.attributes.forEach(a => {
          this.updateMappedDefaultValues(a, e);
        });
        this.updateAttributes(e.entities);
      });
    } else if (this?.property?.entity != null) {
      this.property.entity.attributes.forEach(attribute => {
        if (this.property?.entity != null) {
          this.updateMappedDefaultValues(attribute, this.property.entity);
        }
      });
      this.property.entity.entities.forEach(e => {
        e.attributes.forEach(a => {
          this.updateMappedDefaultValues(a, e);
        });
        this.updateAttributes(e.entities);
      });
    }
  }
  findAttributes(entity, id, entities = undefined, attributes = []) {
    if (entities != null) {
      for (var i = 0, len = entities.length; i < len; i++) {
        const entity = entities[i];
        for (var j = 0, jlen = entity.attributes.length; j < jlen; j++) {
          const attribute = entity.attributes[j];
          if (attribute.id == id) {
            attributes.push(attribute);
          }
        }
        for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
          const fixture = entity.fixtures[j];
          for (var k = 0, klen = fixture.attributes.length; k < klen; k++) {
            const attribute = fixture.attributes[k];
            if (attribute.id == id) {
              attributes.push(attribute);
            }
          }
        }
        this.findAttributes(entity, id, entity.entities, attributes);
      }
    } else {
      for (var i = 0, len = entity.attributes.length; i < len; i++) {
        const attribute = entity.attributes[i];
        if (attribute.id == id) {
          attributes.push(attribute);
        }
      }
      for (var i = 0, len = entity.fixtures.length; i < len; i++) {
        const fixture = entity.fixtures[i];
        for (var j = 0, jlen = fixture.attributes.length; j < jlen; j++) {
          const attribute = fixture.attributes[j];
          if (attribute.id == id) {
            attributes.push(attribute);
          }
        }
      }
      this.findAttributes(entity, id, entity.entities, attributes);
    }
    return attributes;
  }
  getAvailableEntities() {
    const entities = [];
    this.availableEntities.forEach(category => {
      category.entities.forEach(e => {
        entities.push(e);
      });
    });
    return entities;
  }
  getAvailableFixtures() {
    const fixtures = [];
    this.availableFixtures.forEach(category => {
      category.fixtures.forEach(f => {
        fixtures.push(f);
      });
    });
    return fixtures;
  }
  getBaseRules(entity, attributeId) {
    const availableEntities = this.getAvailableEntities();
    for (var i = 0, len = availableEntities.length; i < len; i++) {
      const availEntity = availableEntities[i];
      const attribute = availEntity.attributes.find(x => x.id == attributeId);
      if (attribute != null) {
        return attribute.rules;
      }
    }
    const availableFixtures = this.getAvailableFixtures();
    for (var i = 0, len = availableFixtures.length; i < len; i++) {
      const availFixture = availableFixtures[i];
      if (availFixture.entityId == entity.entityId) {
        const attribute = availFixture.attributes.find(x => x.id == attributeId);
        if (attribute != null) {
          return attribute.rules;
        }
      }
    }
    return [];
  }
  processAttributeRules(entities = undefined) {
    if (entities != null) {
      entities.forEach(entity => {
        if (entity.attributes.length > 0) {
          const targetAttributes = [];
          entity.attributes.forEach(attribute => {
            this.processRulesForAttribute(attribute);
          });
        }
        entity.fixtures.forEach(fixture => {
          const targetAttributes = [];
          fixture.attributes.forEach(attribute => {
            this.processRulesForAttribute(attribute);
          });
        });
        this.processAttributeRules(entity.entities);
      });
    } else if (this?.property?.entity != null) {
      this.property.entity.attributes.forEach(attribute => {
        this.processRulesForAttribute(attribute);
      });
      this.processAttributeRules(this.property.entity.entities);
    }
  }
  processRulesForAttribute(attribute) {
    if (attribute.appliedRules != null) {
      let shouldDisable = false;
      let shouldHide = false;
      let newValue;
      attribute.appliedRules.forEach(rule => {
        if (rule.shouldDisable) {
          shouldDisable = true;
          shouldHide = true;
        }
        if (rule.targetValue != null) {
          newValue = rule.targetValue;
        }
      });
      if (shouldDisable) {
        attribute.disabled = true;
        attribute.values = [];
      } else {
        attribute.disabled = false;
      }
      if (shouldHide) {
        attribute.hiddenByRule = true;
      } else {
        attribute.hiddenByRule = false;
      }
      if (newValue != null) {
        attribute.values = [newValue];
      }
    }
  }
  applyAttributeRules(entities = undefined) {
    if (entities != null) {
      entities.forEach(entity => {
        if (entity.attributes.length > 0) {
          const targetAttributes = [];
          entity.attributes.forEach(attribute => {
            this.applyRulesForAttribute(entity, attribute, targetAttributes);
          });
        }
        entity.fixtures.forEach(fixture => {
          const targetAttributes = [];
          fixture.attributes.forEach(attribute => {
            this.applyRulesForAttribute(fixture, attribute, targetAttributes);
          });
        });
        this.applyAttributeRules(entity.entities);
      });
    } else if (this?.property?.entity != null) {
      const targetAttributes = [];
      this.property.entity.attributes.forEach(attribute => {
        this.applyRulesForAttribute(this.property.entity, attribute, targetAttributes);
      });
      if (this.job != null) {
        this.job.attributes.forEach(attribute => {
          this.applyRulesForAttribute(this.job, attribute, targetAttributes);
        });
      }
      this.applyAttributeRules(this.property.entity.entities);
      this.processAttributeRules();
    }
  }
  applyRulesForAttribute(entity, attribute, targetAttributes) {
    const rules = this.getBaseRules(entity, attribute.id);
    for (var i = 0, len = rules.length; i < len; i++) {
      const rule = rules[i];
      let targetAttributes = [];
      if (entity instanceof AppointmentPropertyEntity) {
        targetAttributes = this.findAttributes(entity, rule.targetAttributeId);
      } else {
        entity.attributes.forEach(attribute => {
          if (attribute.id == rule.targetAttributeId) {
            targetAttributes.push(attribute);
          }
        });
      }
      let triggerValue = rule.triggerValue.toLocaleLowerCase();
      if (attribute.type == _entities_models_attributes__WEBPACK_IMPORTED_MODULE_4__.EntityAttributeType.Boolean) {
        if (triggerValue.toLocaleLowerCase() == 'yes') {
          triggerValue = 'true';
        } else {
          triggerValue = 'false';
        }
      }
      targetAttributes.forEach(targetAttribute => {
        const sanitizedValues = [];
        attribute.values.forEach(value => {
          sanitizedValues.push(value.toLocaleLowerCase());
        });
        if (targetAttribute.appliedRules == null) {
          targetAttribute.appliedRules = [];
        }
        if (sanitizedValues.includes(triggerValue)) {
          const ruleIndex = targetAttribute.appliedRules.findIndex(x => x.id == rule.id);
          if (ruleIndex < 0) {
            targetAttribute.appliedRules.push(rule);
          }
        } else {
          const ruleIndex = targetAttribute.appliedRules.findIndex(x => x.id == rule.id);
          if (ruleIndex > -1) {
            targetAttribute.appliedRules.splice(ruleIndex, 1);
          }
        }
      });
    }
  }
  // #endregion
  toJSON() {
    return {
      id: this.id,
      accepted: this.accepted,
      accepted_Utc: this.accepted_Utc,
      assignedTo: this.assignedTo,
      assigned_Utc: this.assigned_Utc,
      customer: this.customer,
      property: this.property,
      opportunityNotes: this.opportunityNotes,
      opportunityTypes: this.opportunityTypes,
      opportunityPlumbingIssues: this.opportunityPlumbingIssues,
      opportunityCouponCode: this.opportunityCouponCode,
      isEmergency: this.isEmergency,
      status: this.status,
      statusDescription: this.statusDescription,
      customerNeeds: this.customerNeeds,
      payments: this.payments,
      paymentSetting: this.paymentSetting,
      lenders: this.lenders,
      price: this.price,
      dispositionStatus: this.dispositionStatus,
      documents: this.documents,
      shop: this.shop,
      scheduled_Utc: this.scheduled_Utc,
      created_Utc: this.created_Utc,
      lastUpdated_Utc: this.lastUpdated_Utc
    };
  }
}
var AppointmentPricingState = /*#__PURE__*/function (AppointmentPricingState) {
  AppointmentPricingState["Internal"] = "Internal";
  AppointmentPricingState["External"] = "External";
  AppointmentPricingState["Documents"] = "Documents";
  return AppointmentPricingState;
}(AppointmentPricingState || {});
var AppointmentEventType = /*#__PURE__*/function (AppointmentEventType) {
  AppointmentEventType["Generic"] = "Generic";
  AppointmentEventType["Open"] = "Open";
  AppointmentEventType["Close"] = "Close";
  AppointmentEventType["Create"] = "Create";
  AppointmentEventType["Accept"] = "Accept";
  AppointmentEventType["Schedule"] = "Schedule";
  AppointmentEventType["Status"] = "Status";
  AppointmentEventType["ViewingStatus"] = "ViewingStatus";
  AppointmentEventType["Property"] = "Property";
  AppointmentEventType["Structure"] = "Structure";
  AppointmentEventType["Floor"] = "Floor";
  AppointmentEventType["Room"] = "Room";
  AppointmentEventType["Fixture"] = "Fixture";
  AppointmentEventType["CheckIn"] = "CheckIn";
  AppointmentEventType["Needs"] = "Needs";
  AppointmentEventType["Pricing"] = "Pricing";
  return AppointmentEventType;
}(AppointmentEventType || {});
var AppointmentEventSubType = /*#__PURE__*/function (AppointmentEventSubType) {
  AppointmentEventSubType["Added"] = "Added";
  AppointmentEventSubType["Removed"] = "Removed";
  AppointmentEventSubType["Changed"] = "Changed";
  AppointmentEventSubType["Started"] = "Started";
  AppointmentEventSubType["Completed"] = "Completed";
  return AppointmentEventSubType;
}(AppointmentEventSubType || {});
var AppointmentStatus = /*#__PURE__*/function (AppointmentStatus) {
  AppointmentStatus["Open"] = "Open";
  AppointmentStatus["Canceled"] = "Canceled";
  AppointmentStatus["InProgress"] = "InProgress";
  AppointmentStatus["PendingSubmission"] = "PendingSubmission";
  AppointmentStatus["Submitted"] = "Submitted";
  AppointmentStatus["Dispositioned"] = "Dispositioned";
  AppointmentStatus["Sold"] = "Sold";
  return AppointmentStatus;
}(AppointmentStatus || {});
var AppointmentViewingStatus = /*#__PURE__*/function (AppointmentViewingStatus) {
  AppointmentViewingStatus["CheckIn"] = "CheckIn";
  AppointmentViewingStatus["Summary"] = "Summary";
  AppointmentViewingStatus["DetailedSummary"] = "DetailedSummary";
  AppointmentViewingStatus["Needs"] = "Needs";
  AppointmentViewingStatus["Diagram"] = "Diagram";
  AppointmentViewingStatus["Presentation"] = "Presentation";
  AppointmentViewingStatus["Completion"] = "Completion";
  AppointmentViewingStatus["Inspection"] = "Inspection";
  AppointmentViewingStatus["Documents"] = "Documents";
  AppointmentViewingStatus["JobSummary"] = "JobSummary";
  AppointmentViewingStatus["Pricing"] = "Pricing";
  return AppointmentViewingStatus;
}(AppointmentViewingStatus || {});
class AvailableFixtures {
  constructor() {
    this.sections = [];
  }
}
class FixtureSection {
  constructor() {
    this.name = "";
    this.fixtures = [];
    /* Local */
    this.active = false;
  }
}
class AppointmentDocument extends _documents_models_document__WEBPACK_IMPORTED_MODULE_8__.Document {
  constructor(id, name, customerFacing, shopFacing, standalone, dynamic, alwaysShow, mapping, displayOrder = 0, content = undefined, signers = [], rules = [], documents = [], signatures = [], userContent = [], lastUpdated_Utc = undefined, created_Utc = undefined, executedDocument = undefined, executedDocument_B64 = undefined, executedHash = undefined, generatedContent = undefined, originalHash = undefined) {
    super(id, name, customerFacing, shopFacing, standalone, dynamic, alwaysShow, mapping, displayOrder, content, signers, rules, documents, signatures, userContent, executedDocument, executedDocument_B64, executedHash, lastUpdated_Utc, created_Utc);
    this.documents = [];
    this.generatedContent = generatedContent;
    this.documents = documents;
    this.originalHash = originalHash;
  }
}
var NoteAudience = /*#__PURE__*/function (NoteAudience) {
  NoteAudience["Customer"] = "Customer";
  NoteAudience["Shop"] = "Shop";
  return NoteAudience;
}(NoteAudience || {});
class AppointmentPropertyEntity extends _properties_models_property__WEBPACK_IMPORTED_MODULE_0__.PropertyEntity {
  get hasInvalidAttributes() {
    const invalidAttribute = this.attributes.find(x => !x.valid);
    return invalidAttribute != null;
  }
  get hasInvalidEntities() {
    const invalidEntity = this.entities.find(x => !x.valid);
    return invalidEntity != null;
  }
  get hasInvalidFixtures() {
    const invalidFixture = this.fixtures.find(x => !x.valid);
    return invalidFixture != null;
  }
  get valid() {
    const photosCount = this.photos.length + this.photos_B64.length;
    if (this.hasInvalidAttributes || this.hasInvalidFixtures || this.hasInvalidEntities || this.type == _properties_models_property__WEBPACK_IMPORTED_MODULE_0__.PropertyEntityType.Room && photosCount == 0) {
      return false;
    }
    return true;
  }
  constructor(id, entityId, type, name, number, attributes = [], fixtures = [], renderDimensions, metafields, rules, photos = [], photos_B64 = [], render, render_B64, notes) {
    super(id, entityId, type, name, attributes, fixtures);
    this.appointmentId = "";
    this.entities = [];
    this.fixtures = [];
    this.metafields = {};
    this.photos = [];
    this.photos_B64 = [];
    /* Local */
    this.number = 1;
    this.resizing = false;
    this.moving = false;
    this.active = false; /* Selected */
    this.renderDimensions = new _rendering__WEBPACK_IMPORTED_MODULE_1__.RenderDimensions(renderDimensions.x, renderDimensions.y, renderDimensions.width, renderDimensions.height, renderDimensions.rotation);
    this.metafields = metafields;
    this.rules = rules;
    this.photos = photos;
    this.photos_B64 = photos_B64;
    this.render = render;
    this.render_B64 = render_B64;
    this.notes = notes;
    this.number = number;
  }
  toJSON() {
    return {
      id: this.id,
      entityId: this.entityId,
      type: this.type,
      name: this.name,
      attributes: this.attributes,
      entities: this.entities,
      fixtures: this.fixtures,
      rules: this.rules,
      notes: this.notes,
      renderDimensions: this.renderDimensions,
      metafields: this.metafields,
      photos: this.photos,
      photos_B64: this.photos_B64,
      render: this.render,
      render_B64: this.render_B64,
      number: this.number
    };
  }
}
class AppointmentFixture extends _fixtures_models_fixture__WEBPACK_IMPORTED_MODULE_2__.Fixture {
  get hasInvalidAttributes() {
    const invalidAttribute = this.attributes.find(x => !x.valid);
    return invalidAttribute != null;
  }
  get valid() {
    const photosCount = this.photos.length + this.photos_B64.length;
    if (this.hasInvalidAttributes || photosCount == 0) {
      return false;
    }
    return true;
  }
  constructor(id, entityId, name, imageSrc_Base64, number, attributes = [], renderDimensions, photos = [], photos_B64 = [], notes) {
    super(id, entityId, name, imageSrc_Base64, attributes);
    this.photos = [];
    this.photos_B64 = [];
    /* Local */
    this.number = 1;
    this.rotating = false;
    this.resizing = false;
    this.moving = false;
    this.renderDimensions = new _rendering__WEBPACK_IMPORTED_MODULE_1__.RenderDimensions(renderDimensions.x, renderDimensions.y, renderDimensions.width, renderDimensions.height, renderDimensions.rotation);
    this.photos_B64 = photos_B64;
    this.photos = photos;
    this.notes = notes;
    this.number = number;
  }
  toJSON() {
    return {
      id: this.id,
      entityId: this.entityId,
      name: this.name,
      imageSrc_Base64: this.imageSrc_Base64,
      attributes: this.attributes,
      rules: this.rules,
      notes: this.notes,
      renderDimensions: this.renderDimensions,
      photos: this.photos,
      photos_B64: this.photos_B64,
      number: this.number
    };
  }
}
class AppointmentDocumentResponseContent extends _documents_models_content__WEBPACK_IMPORTED_MODULE_9__.DocumentResponseContent {
  constructor() {
    super(...arguments);
    this.documents = [];
    this.payments = [];
    this.completed = false;
  }
}
class PublicAppointmentPrice {
  constructor() {
    this.details = [];
    this.customItems = [];
    this.price = 0;
  }
}
class PublicAppointmentPayment {
  constructor() {
    this.amount = 0;
    this.description = "";
  }
}
class AppointmentShop {
  constructor(installDate_Utc, shop) {
    this.preferredInstallDate_Utc = installDate_Utc;
    this.preferredShop = shop;
  }
}

/***/ }),

/***/ 6467:
/*!*****************************************************!*\
  !*** ./src/app/shared/appointments/models/needs.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CustomerNeedPossibleAnswer: () => (/* binding */ CustomerNeedPossibleAnswer),
/* harmony export */   CustomerNeedQuestion: () => (/* binding */ CustomerNeedQuestion)
/* harmony export */ });
class CustomerNeedQuestion {
  constructor(question, possibleAnswers) {
    this.possibleAnswers = [];
    this.answers = [];
    this.storing = false;
    this.question = question;
    this.possibleAnswers = possibleAnswers;
  }
}
class CustomerNeedPossibleAnswer {
  constructor(title, answer) {
    this.title = title;
    this.answer = answer;
  }
}

/***/ }),

/***/ 3300:
/*!*******************************************************!*\
  !*** ./src/app/shared/appointments/models/pricing.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppointmentPrice: () => (/* binding */ AppointmentPrice),
/* harmony export */   AppointmentPriceDetail: () => (/* binding */ AppointmentPriceDetail),
/* harmony export */   LineItem: () => (/* binding */ LineItem)
/* harmony export */ });
class AppointmentPrice {
  constructor(details, customDetails, appliedPromotions = [], usingCustomPrice = false, managerApproved = false, finalPrice = 0, targetPrice = 0, ablPrice = 0, parPrice = 0, targetPromoPrice = 0) {
    this.iso4217 = "USD";
    this.parPrice = 0;
    this.targetPrice = 0;
    this.targetPromoPrice = 0;
    this.ablPrice = 0;
    this.finalPrice = 0;
    this.usingCustomPrice = false;
    this.managerApproved = false;
    this.appliedPromotions = [];
    this.details = details;
    this.appliedPromotions = appliedPromotions;
    this.usingCustomPrice = usingCustomPrice;
    this.managerApproved = managerApproved;
    this.customItems = customDetails ?? [];
    this.finalPrice = finalPrice;
    this.targetPrice = targetPrice;
    this.ablPrice = ablPrice;
    this.parPrice = parPrice;
    this.targetPromoPrice = targetPromoPrice;
  }
}
class AppointmentPriceDetail {
  constructor() {
    this.ruleId = "";
    this.lineItems = [];
    this.matches = [];
    this.result = "";
  }
}
class LineItem {
  constructor() {
    this.skuId = "";
    this.skuCategory = "";
    this.customerFacing = true;
    this.isAttachment = false;
    this.name = "";
    this.description = "";
    this.price = 0;
    this.quantity = 0;
  }
}

/***/ }),

/***/ 3114:
/*!*********************************************************!*\
  !*** ./src/app/shared/appointments/models/rendering.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   RenderDimensions: () => (/* binding */ RenderDimensions)
/* harmony export */ });
class RenderDimensions {
  get transform() {
    return `translate3d(${this.x}px,${this.y}px,0)`;
  }
  get widthCss() {
    return `${this.width}px`;
  }
  get heightCss() {
    return `${this.height}px`;
  }
  constructor(x, y, width, height, rotation) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.rotation = rotation;
  }
}

/***/ }),

/***/ 1303:
/*!*****************************************************************************!*\
  !*** ./src/app/shared/appointments/services/appointment-mapping.service.ts ***!
  \*****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppointmentMappingService: () => (/* binding */ AppointmentMappingService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! src/app/shared/appointments/models/appointment */ 8723);
/* harmony import */ var src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/app/shared/properties/models/property */ 1750);
/* harmony import */ var src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! src/app/shared/addresses/models/address */ 2846);
/* harmony import */ var src_app_shared_entities_models_attributes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! src/app/shared/entities/models/attributes */ 7720);
/* harmony import */ var _content_models_binary__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../content/models/binary */ 4768);
/* harmony import */ var _models_pricing__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../models/pricing */ 3300);
/* harmony import */ var _helpers_methods_methods__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../helpers/methods/methods */ 2853);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/core */ 4380);

/* Models */








/* Services */
let AppointmentMappingService = /*#__PURE__*/(() => {
  class AppointmentMappingService {
    constructor() {}
    // #region Mapping
    mapAppointment(appointmentJson) {
      const parsedAppointment = JSON.parse(appointmentJson);
      const appointment = Object.assign(new src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_0__.Appointment(), parsedAppointment);
      if (appointment.scheduled_Utc != null) {
        appointment.scheduled_Utc = new Date(appointment.scheduled_Utc);
      }
      if (appointment.property != null) {
        const property = Object.assign(new src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_1__.Property(), appointment.property);
        if (property.photo != null) {
          property.photo = new _content_models_binary__WEBPACK_IMPORTED_MODULE_4__.ContentBinary(property.photo);
        }
        if (property.address != null) {
          const address = Object.assign(new src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_2__.Address(), appointment.property.address);
          property.address = address;
        }
        if (property.entity != null) {
          property.entity = this.mapPropertyEntity(property.entity, appointment);
        }
        appointment.property = property;
        appointment.changed$ = new rxjs__WEBPACK_IMPORTED_MODULE_7__.Subject();
        appointment.priceChanged$ = new rxjs__WEBPACK_IMPORTED_MODULE_7__.Subject();
      }
      if (appointment.job != null) {
        appointment.job = this.mapPropertyEntity(appointment.job, appointment);
      }
      if (appointment.price != null) {
        appointment.price = this.mapAppointmentPrice(appointment.price, appointment);
      }
      appointment.documents = this.mapAppointmentDocuments(appointment);
      appointment.checkPaymentsValidity();
      appointment.checkDocumentValidity();
      appointment.checkProgression();
      return appointment;
    }
    mapAppointmentDocuments(appointment) {
      const documents = [];
      appointment.documents.forEach(document => {
        const existingDoc = documents.find(x => x.id == document.id);
        if (existingDoc == null) {
          const mappedDocument = new src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_0__.AppointmentDocument(document.id, document.name, document.customerFacing, document.shopFacing, document.standalone, document.dynamic, document.alwaysShow, document.mapping, document.displayOrder, document.content, document.signers, document.rules, document.documents, document.signatures, document.userContent, document.lastUpdated_Utc, document.created_Utc, document.executedDocument, document.executedDocument_B64, document.executedHash, document.generatedContent, document.originalHash);
          if (mappedDocument.dynamic) {
            mappedDocument.hash = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_6__.hashString)(mappedDocument.content ?? "");
          } else {
            mappedDocument.hash = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_6__.hashString)(JSON.stringify(mappedDocument.mapping));
          }
          if (mappedDocument.name == "Scope of Work Acknowledgments") {
            mappedDocument.hash = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_6__.hashString)(JSON.stringify(mappedDocument.documents));
          }
          documents.push(mappedDocument);
        }
      });
      return documents;
    }
    mapAppointmentPrice(price, appointment) {
      const mappedPrice = new _models_pricing__WEBPACK_IMPORTED_MODULE_5__.AppointmentPrice(price.details, price.customItems, price.appliedPromotions, price.usingCustomPrice, price.managerApproved, price.finalPrice, price.targetPrice, price.ablPrice, price.parPrice, price.targetPromoPrice);
      return mappedPrice;
    }
    mapPropertyEntity(entity, appointment) {
      const mappedEntity = new src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_0__.AppointmentPropertyEntity(entity.id, entity.entityId, entity.type, entity.name, entity.number, entity.attributes, entity.fixtures, entity.renderDimensions, entity.metafields, entity.rules, entity.photos, entity.photos_B64, entity.render, entity.render_B64, entity.notes);
      const mappedEntities = [];
      for (var i = 0, len = entity.entities.length; i < len; i++) {
        const childEntity = entity.entities[i];
        const mappedChildEntity = this.mapPropertyEntity(childEntity, appointment);
        mappedEntities.push(mappedChildEntity);
      }
      mappedEntity.entities = mappedEntities;
      const mappedFixtures = this.mapFixtures(entity.fixtures, appointment);
      const mappedAttributes = this.mapAttributes(entity.attributes, appointment);
      mappedEntity.fixtures = mappedFixtures;
      mappedEntity.attributes = mappedAttributes;
      const photos = [];
      mappedEntity.photos.forEach(photo => {
        photo = new _content_models_binary__WEBPACK_IMPORTED_MODULE_4__.ContentBinary(photo);
        photos.push(photo);
      });
      mappedEntity.photos = photos;
      if (mappedEntity.render != null) {
        mappedEntity.render = new _content_models_binary__WEBPACK_IMPORTED_MODULE_4__.ContentBinary(mappedEntity.render);
      }
      return mappedEntity;
    }
    mapFixture(fixture, appointment) {
      const mappedFixture = new src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_0__.AppointmentFixture(fixture.id, fixture.entityId, fixture.name, fixture.imageSrc_Base64, fixture.number, fixture.attributes, fixture.renderDimensions, fixture.photos, fixture.photos_B64, fixture.notes);
      mappedFixture.attributes = this.mapAttributes(fixture.attributes, appointment);
      const photos = [];
      mappedFixture.photos.forEach(photo => {
        photo = new _content_models_binary__WEBPACK_IMPORTED_MODULE_4__.ContentBinary(photo);
        photos.push(photo);
      });
      mappedFixture.photos = photos;
      return mappedFixture;
    }
    mapFixtures(fixtures, appointment) {
      const mappedFixtures = [];
      fixtures.forEach(fixture => {
        const mappedFixture = this.mapFixture(fixture, appointment);
        mappedFixtures.push(mappedFixture);
      });
      return mappedFixtures;
    }
    mapAttributes(attributes, appointment) {
      const mappedAttributes = [];
      if (attributes != null) {
        attributes.forEach(attribute => {
          const mappedAttribute = new src_app_shared_entities_models_attributes__WEBPACK_IMPORTED_MODULE_3__.EntityAttribute(attribute.id, attribute.name, attribute.customerFacing, attribute.possibleValues, attribute.type, attribute.displayOrder, attribute.defaultValue, attribute.hidden, attribute.rules, attribute.values, attribute.functionName);
          mappedAttributes.push(mappedAttribute);
        });
      }
      return mappedAttributes;
    }
    // #endregion
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function AppointmentMappingService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppointmentMappingService)();
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_8__["ɵɵdefineInjectable"]({
      token: AppointmentMappingService,
      factory: AppointmentMappingService.ɵfac,
      providedIn: 'root'
    }))();
  }
  return AppointmentMappingService;
})();

/***/ }),

/***/ 3990:
/*!*************************************************************!*\
  !*** ./src/app/shared/authentication/config/auth.config.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AuthProvider: () => (/* binding */ AuthProvider),
/* harmony export */   RepipeAuthConfig: () => (/* binding */ RepipeAuthConfig),
/* harmony export */   RepipeTokenResponse: () => (/* binding */ RepipeTokenResponse),
/* harmony export */   msFlowConfig: () => (/* binding */ msFlowConfig)
/* harmony export */ });
/* harmony import */ var angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular-oauth2-oidc */ 2888);

const msFlowConfig = {
  issuer: 'https://login.microsoftonline.com/10079819-db1a-4413-9782-48b92ca5125f/v2.0',
  redirectUri: window.location.origin,
  originalNativeUri: "repipe://localhost",
  nativeRedirectUri: 'msauth.com.repipe.Home://auth',
  clientId: 'c04f2cb4-7b85-4eb3-917b-fad4c3dc1a79',
  responseType: 'code',
  useSilentRefresh: true,
  silentRefreshTimeout: 5000,
  scope: 'openid profile email api://c04f2cb4-7b85-4eb3-917b-fad4c3dc1a79/access offline_access',
  showDebugInformation: false,
  strictDiscoveryDocumentValidation: false
};
var AuthProvider = /*#__PURE__*/function (AuthProvider) {
  AuthProvider["Microsoft"] = "Microsoft";
  AuthProvider["Email"] = "Email";
  return AuthProvider;
}(AuthProvider || {});
class RepipeTokenResponse {
  constructor() {
    this.userId = "";
    this.accessToken = "";
    this.idToken = "";
    this.refreshToken = "";
    this.expiresAt = new Date();
  }
}
class RepipeAuthConfig extends angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_0__.AuthConfig {
  constructor() {
    super(...arguments);
    this.nativeRedirectUri = "";
    this.originalNativeUri = "";
  }
}

/***/ }),

/***/ 7579:
/*!************************************************************!*\
  !*** ./src/app/shared/authentication/guards/auth.guard.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AuthGuard: () => (/* binding */ AuthGuard)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 6634);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../services/auth-ref.service */ 4387);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/router */ 4947);




let AuthGuard = /*#__PURE__*/(() => {
  class AuthGuard {
    constructor(authRefService, router) {
      this.authRefService = authRefService;
      this.router = router;
    }
    canActivate(next, state) {
      return this.authRefService.authenticated.pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_1__.map)(authenticated => {
        if (authenticated) {
          return true;
        } else {
          return this.router.parseUrl('/login');
        }
      }));
    }
    static #_ = (() => this.ɵfac = function AuthGuard_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AuthGuard)(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_router__WEBPACK_IMPORTED_MODULE_3__.Router));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({
      token: AuthGuard,
      factory: AuthGuard.ɵfac,
      providedIn: 'root'
    }))();
  }
  return AuthGuard;
})();

/***/ }),

/***/ 2014:
/*!******************************************************************!*\
  !*** ./src/app/shared/authentication/guards/logged-out.guard.ts ***!
  \******************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   LoggedOutGuard: () => (/* binding */ LoggedOutGuard)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 2921);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../services/auth-ref.service */ 4387);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/router */ 4947);




let LoggedOutGuard = /*#__PURE__*/(() => {
  class LoggedOutGuard {
    constructor(authRefService, router) {
      this.authRefService = authRefService;
      this.router = router;
    }
    canActivate(next, state) {
      return new rxjs__WEBPACK_IMPORTED_MODULE_1__.Observable(o => {
        this.authRefService.authenticating.subscribe({
          next: authenticating => {
            if (!authenticating) {
              const isAuthenticated = this.authRefService.authenticated.getValue();
              if (isAuthenticated) {
                const route = this.router.parseUrl('/');
                o.next(route);
                o.complete();
              } else {
                o.next(true);
                o.complete();
              }
            }
          }
        });
      });
    }
    static #_ = (() => this.ɵfac = function LoggedOutGuard_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || LoggedOutGuard)(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_router__WEBPACK_IMPORTED_MODULE_3__.Router));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({
      token: LoggedOutGuard,
      factory: LoggedOutGuard.ɵfac,
      providedIn: 'root'
    }))();
  }
  return LoggedOutGuard;
})();

/***/ }),

/***/ 6402:
/*!*************************************************************************!*\
  !*** ./src/app/shared/authentication/interceptors/token.interceptor.ts ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   TokenInterceptor: () => (/* binding */ TokenInterceptor)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 4484);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs */ 1969);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs */ 9754);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs */ 3471);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 6634);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../services/auth-ref.service */ 4387);
/* harmony import */ var _system_services_api_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../system/services/api.service */ 1160);




let TokenInterceptor = /*#__PURE__*/(() => {
  class TokenInterceptor {
    constructor(authRefService, apiService) {
      this.authRefService = authRefService;
      this.apiService = apiService;
      this.apiUrl = apiService.apiUrl;
    }
    processApiRequest(url, request, next) {
      // Queue up requests and wait for authentication to finish before sending API request.
      return this.authRefService.authenticating.pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_2__.filter)(authenticating => !authenticating), (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.take)(1), (0,rxjs__WEBPACK_IMPORTED_MODULE_4__.exhaustMap)(() => {
        return this.processAuthenticatedRequest(url, request, next);
      }));
    }
    processAuthenticatedRequest(url, request, next) {
      const accessToken = this.authRefService.accessToken;
      if (accessToken != null) {
        const headers = {
          'Accept-Language': 'en-US',
          Authorization: `Bearer ${accessToken}`
        };
        request = request.clone({
          setHeaders: headers,
          url: url
        });
        return next.handle(request);
      } else {
        return rxjs__WEBPACK_IMPORTED_MODULE_5__.EMPTY;
      }
    }
    intercept(request, next) {
      let apiUrl;
      const isAuthenticatingRequest = request.url.includes("{{authApi}}");
      const isAuthenticatedRequest = request.url.includes("{{api}}");
      apiUrl = request.url.replace("{{api}}", this.apiUrl).replace("{{authApi}}", this.apiUrl).replace("{{openApi}}", this.apiUrl);
      if (isAuthenticatedRequest) {
        return this.processApiRequest(apiUrl, request, next);
      } else if (isAuthenticatingRequest) {
        return this.processAuthenticatedRequest(apiUrl, request, next);
      } else {
        request = request.clone({
          url: apiUrl
        });
        return next.handle(request).pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_6__.map)(event => {
          return event;
        }));
      }
    }
    static #_ = (() => this.ɵfac = function TokenInterceptor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || TokenInterceptor)(_angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵinject"](_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_0__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵinject"](_system_services_api_service__WEBPACK_IMPORTED_MODULE_1__.ApiService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵdefineInjectable"]({
      token: TokenInterceptor,
      factory: TokenInterceptor.ɵfac
    }))();
  }
  return TokenInterceptor;
})();

/***/ }),

/***/ 4387:
/*!********************************************************************!*\
  !*** ./src/app/shared/authentication/services/auth-ref.service.ts ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AuthRefService: () => (/* binding */ AuthRefService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 4997);
/* harmony import */ var jwt_decode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jwt-decode */ 4003);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/common/http */ 8143);




let AuthRefService = /*#__PURE__*/(() => {
  class AuthRefService {
    constructor(http) {
      this.http = http;
      // #endregion
      // #region User
      this.user = new rxjs__WEBPACK_IMPORTED_MODULE_1__.BehaviorSubject(null);
      // #endregion
      // #region Authentication
      this.authenticated = new rxjs__WEBPACK_IMPORTED_MODULE_1__.BehaviorSubject(false);
      this.authenticating = new rxjs__WEBPACK_IMPORTED_MODULE_1__.BehaviorSubject(true);
    }
    setAccessToken(token) {
      this.accessToken = token;
    }
    setIdToken(token) {
      if (token != null) {
        const parsedToken = (0,jwt_decode__WEBPACK_IMPORTED_MODULE_0__.jwtDecode)(token);
        this.idToken = parsedToken;
      } else {
        this.idToken = undefined;
      }
    }
    setRefreshToken(token) {
      this.refreshToken = token;
    }
    setUser(user) {
      this.user.next(user);
    }
    getUser() {
      const url = `{{authApi}}/users/me`;
      return this.http.get(url).pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_2__.tap)(user => {
        localStorage.setItem("uid", user.id);
        this.user.next(user);
      }));
    }
    setAuthenticated(authenticated) {
      this.authenticated.next(authenticated);
    }
    setAuthenticating(authenticating) {
      this.authenticating.next(authenticating);
    }
    // #endregion
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function AuthRefService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AuthRefService)(_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_4__.HttpClient));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdefineInjectable"]({
      token: AuthRefService,
      factory: AuthRefService.ɵfac,
      providedIn: 'root'
    }))();
  }
  return AuthRefService;
})();

/***/ }),

/***/ 1619:
/*!****************************************************************!*\
  !*** ./src/app/shared/authentication/services/auth.service.ts ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AuthService: () => (/* binding */ AuthService)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var angular_oauth2_oidc_jwks__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! angular-oauth2-oidc-jwks */ 9643);
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _capacitor_browser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @capacitor/browser */ 333);
/* harmony import */ var _capacitor_app__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @capacitor/app */ 6627);
/* harmony import */ var _config_auth_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config/auth.config */ 3990);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @angular/router */ 4947);
/* harmony import */ var _auth_ref_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./auth-ref.service */ 4387);
/* harmony import */ var angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! angular-oauth2-oidc */ 2888);
/* harmony import */ var _data_services_db_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../data/services/db.service */ 1235);
/* harmony import */ var _data_services_storage_service__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../data/services/storage.service */ 1490);













let AuthService = /*#__PURE__*/(() => {
  class AuthService {
    constructor(http, router, refService, oAuthService, dbService, storageService) {
      this.http = http;
      this.router = router;
      this.refService = refService;
      this.oAuthService = oAuthService;
      this.dbService = dbService;
      this.storageService = storageService;
      // #endregion
      // #region Flow
      this.initiatingFlow = false;
      // #endregion
      // #region Bootstrapping
      this.isNative = _capacitor_core__WEBPACK_IMPORTED_MODULE_1__.Capacitor.isNativePlatform();
      this.initiatingFlow = location.search.indexOf("code") > -1;
      _capacitor_app__WEBPACK_IMPORTED_MODULE_3__.App.addListener('appUrlOpen', data => {
        this.nativeAuthenticate(data.url);
      });
      if (!this.initiatingFlow) {
        this.initAuthState();
      }
    }
    get user() {
      return this.refService.user;
    }
    initUser() {
      var _this = this;
      this.refService.getUser().subscribe({
        next: user => {
          this.dbService.storeUser(user);
          this.refService.setAuthenticated(true);
          this.refService.setAuthenticating(false);
        },
        error: function () {
          var _ref = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
            const userId = localStorage.getItem("uid");
            if (userId != null) {
              _this.dbService.getUser(userId).then(/*#__PURE__*/function () {
                var _ref2 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (user) {
                  if (user != null) {
                    _this.refService.setUser(user);
                    _this.refService.setAuthenticated(true);
                    _this.refService.setAuthenticating(false);
                  } else {
                    yield _this.logoutApp();
                  }
                });
                return function (_x) {
                  return _ref2.apply(this, arguments);
                };
              }()).catch(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
                yield _this.logoutApp();
              }));
            } else {
              yield _this.logoutApp();
            }
          });
          return function error() {
            return _ref.apply(this, arguments);
          };
        }()
      });
    }
    get accessToken() {
      return this.refService.accessToken;
    }
    get idToken() {
      return this.refService.idToken;
    }
    get refreshToken() {
      return this.refService.refreshToken;
    }
    startTokenRefresh() {
      var _this2 = this;
      this.stopTokenRefresh();
      const checkInterval = 60 * 1000;
      this.refreshInterval = window.setInterval(() => {
        const expiresAt = this.oAuthService.getAccessTokenExpiration();
        const now = Date.now();
        const bufferTime = 5 * 60 * 1000;
        if (expiresAt && expiresAt - now < bufferTime) {
          this.oAuthService.refreshToken().catch(/*#__PURE__*/function () {
            var _ref4 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (e) {
              yield _this2.logoutApp();
            });
            return function (_x2) {
              return _ref4.apply(this, arguments);
            };
          }());
        }
      }, checkInterval);
    }
    stopTokenRefresh() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
      }
    }
    logoutApp() {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        _this3.refService.setAuthenticated(false);
        _this3.userSubscription?.unsubscribe();
        _this3.refService.setUser(null);
        _this3.refService.setAccessToken(undefined);
        _this3.refService.setIdToken(undefined);
        _this3.refService.setRefreshToken(undefined);
        _this3.oAuthService.stopAutomaticRefresh();
        localStorage.clear();
        yield _this3.storageService.clear();
        // this.router.navigate(['/login']);
        // this.oAuthService.logOut();
      })();
    }
    login() {
      this.initiatingFlow = true;
      this.loginWithMicrosoft();
    }
    checkEmailAuthenticationSupport() {
      const url = "{{openApi}}/users/authenticate/email/support";
      return this.http.get(url);
    }
    loginWithEmail(emailAddress, password) {
      const url = "{{openApi}}/users/authenticate/email";
      const headers = {
        "Content-Type": "application/json"
      };
      const request = {
        emailAddress: emailAddress,
        password: password
      };
      this.http.post(url, JSON.stringify(request), {
        headers: headers
      }).subscribe({
        next: response => {
          this.finalizeAuthentication(true, _config_auth_config__WEBPACK_IMPORTED_MODULE_4__.AuthProvider.Email, response.token);
        },
        error: () => {
          this.finalizeAuthentication(false);
        }
      });
    }
    initFlow() {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const currentProvider = yield localStorage.getItem('authProvider');
        if (currentProvider != null) {
          switch (currentProvider) {
            case "Microsoft":
              _this4.loginWithMicrosoft();
              break;
          }
        }
      })();
    }
    loginWithMicrosoft() {
      localStorage.setItem("authProvider", "Microsoft");
      this.authenticate(_config_auth_config__WEBPACK_IMPORTED_MODULE_4__.AuthProvider.Microsoft, _config_auth_config__WEBPACK_IMPORTED_MODULE_4__.msFlowConfig);
    }
    finalizeAuthentication(authorized = false, provider = undefined, token = undefined) {
      if (authorized) {
        if (provider == _config_auth_config__WEBPACK_IMPORTED_MODULE_4__.AuthProvider.Email && token != null) {
          this.refService.setAccessToken(token);
        } else {
          const accessToken = this.oAuthService.getAccessToken();
          this.refService.setAccessToken(accessToken);
          const idToken = this.oAuthService.getIdToken();
          this.refService.setIdToken(idToken);
          const refreshToken = this.oAuthService.getRefreshToken();
          this.refService.setRefreshToken(refreshToken);
          this.startTokenRefresh();
        }
        if (provider != undefined) {
          localStorage.setItem("authProvider", provider);
        } else {
          localStorage.removeItem("authProvider");
        }
        this.initUser();
      } else {
        this.logoutApp().then(() => {
          this.refService.setAuthenticating(false);
        });
      }
    }
    nativeAuthenticate(url) {
      var _this5 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const currentProviderString = yield localStorage.getItem('authProvider');
        const currentProvider = currentProviderString != null ? _config_auth_config__WEBPACK_IMPORTED_MODULE_4__.AuthProvider[currentProviderString] : undefined;
        _capacitor_browser__WEBPACK_IMPORTED_MODULE_2__.Browser.close();
        if (currentProviderString != null) {
          const urlParams = new URLSearchParams(url.split('?')[1] || '');
          const code = urlParams.get('code');
          const state = urlParams.get('state');
          const sessionState = urlParams.get('session_state') || '';
          if (code != null && state != null) {
            const newQueryString = `code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}&session_state=${encodeURIComponent(sessionState)}`;
            window.history.pushState({}, '', `${window.location.pathname}?${newQueryString}`);
            _this5.oAuthService.tryLogin().then(() => {
              _this5.finalizeAuthentication(true, currentProvider);
            }).catch(() => {
              _this5.finalizeAuthentication(false, currentProvider);
            });
          } else {
            _this5.finalizeAuthentication(false, currentProvider);
          }
        }
      })();
    }
    authenticate(provider, config) {
      if (this.isNative) {
        config.redirectUri = config.nativeRedirectUri;
        config.openUri = url => {
          const customAuthUrl = url.replace(config.nativeRedirectUri, config.originalNativeUri);
          _capacitor_browser__WEBPACK_IMPORTED_MODULE_2__.Browser.open({
            url: customAuthUrl
          });
        };
      }
      this.oAuthService.configure(config);
      this.oAuthService.tokenValidationHandler = new angular_oauth2_oidc_jwks__WEBPACK_IMPORTED_MODULE_8__.JwksValidationHandler();
      this.oAuthService.events.subscribe(event => {
        if (event.type === 'token_received') {
          if (this.oAuthService.hasValidAccessToken()) {
            this.finalizeAuthentication(true, provider);
          } else {
            this.finalizeAuthentication(false, provider);
          }
        }
      });
      if (this.initiatingFlow) {
        this.oAuthService.loadDiscoveryDocumentAndLogin().catch(e => {
          this.finalizeAuthentication(false, provider);
        });
      } else {
        this.oAuthService.loadDiscoveryDocument().then(() => {
          this.oAuthService.refreshToken().catch(e => {
            this.finalizeAuthentication(false, provider);
          });
        }).catch(e => {
          this.finalizeAuthentication(false, provider);
        });
      }
    }
    initAuthState() {
      var _this6 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const expiration = yield localStorage.getItem('expires_at');
        if (expiration == null) {
          _this6.finalizeAuthentication(false);
        } else {
          _this6.finalizeAuthentication(true);
        }
      })();
    }
    // #endregion
    ngOnDestroy() {
      this.userSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function AuthService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AuthService)(_angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_10__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_angular_router__WEBPACK_IMPORTED_MODULE_11__.Router), _angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_auth_ref_service__WEBPACK_IMPORTED_MODULE_5__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_12__.OAuthService), _angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_data_services_db_service__WEBPACK_IMPORTED_MODULE_6__.DbService), _angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_data_services_storage_service__WEBPACK_IMPORTED_MODULE_7__.StorageService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵdefineInjectable"]({
      token: AuthService,
      factory: AuthService.ɵfac,
      providedIn: 'root'
    }))();
  }
  return AuthService;
})();

/***/ }),

/***/ 904:
/*!**************************************************************************!*\
  !*** ./src/app/shared/contact-information/models/contact-information.ts ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ContactInformation: () => (/* binding */ ContactInformation),
/* harmony export */   ContactInformationType: () => (/* binding */ ContactInformationType)
/* harmony export */ });
class ContactInformation {
  constructor() {
    this.id = "";
    this.isPrimary = false;
    this.enableNotifications = false;
    this.value = "";
  }
}
var ContactInformationType = /*#__PURE__*/function (ContactInformationType) {
  ContactInformationType["Email"] = "Email";
  ContactInformationType["Phone"] = "Phone";
  ContactInformationType["CellPhone"] = "CellPhone";
  ContactInformationType["HomePhone"] = "HomePhone";
  ContactInformationType["WorkPhone"] = "WorkPhone";
  return ContactInformationType;
}(ContactInformationType || {});

/***/ }),

/***/ 4768:
/*!*************************************************!*\
  !*** ./src/app/shared/content/models/binary.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ContentBinary: () => (/* binding */ ContentBinary)
/* harmony export */ });
class ContentBinary {
  get src() {
    return `https://api.repipe.cloud/i/${this.b64Src()}`;
  }
  b64Src() {
    const base64 = btoa(this.fileName);
    return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  }
  constructor(binary) {
    this.id = "";
    this.name = "";
    this.fileName = "";
    this.mimeType = "";
    this.sizeInBytes = 0;
    this.id = binary.id;
    this.name = binary.name;
    this.fileName = binary.fileName;
    this.mimeType = binary.mimeType;
    this.width = binary.width;
    this.height = binary.height;
    this.sizeInBytes = binary.sizeInBytes;
  }
}

/***/ }),

/***/ 3545:
/*!**************************************************!*\
  !*** ./src/app/shared/data/guards/data.guard.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DataGuard: () => (/* binding */ DataGuard)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 6634);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _services_db_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../services/db.service */ 1235);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/router */ 4947);




let DataGuard = /*#__PURE__*/(() => {
  class DataGuard {
    constructor(dbService, router) {
      this.dbService = dbService;
      this.router = router;
    }
    canActivate(next, state) {
      return this.dbService.dataRetrieved.pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_1__.map)(retrieved => {
        if (retrieved) {
          return true;
        } else {
          const path = encodeURIComponent(window.location.pathname);
          return this.router.parseUrl(`/sync/${path}`);
        }
      }));
    }
    static #_ = (() => this.ɵfac = function DataGuard_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DataGuard)(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_services_db_service__WEBPACK_IMPORTED_MODULE_0__.DbService), _angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_router__WEBPACK_IMPORTED_MODULE_3__.Router));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({
      token: DataGuard,
      factory: DataGuard.ɵfac,
      providedIn: 'root'
    }))();
  }
  return DataGuard;
})();

/***/ }),

/***/ 4886:
/*!********************************************!*\
  !*** ./src/app/shared/data/models/data.ts ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DataRetrievalResult: () => (/* binding */ DataRetrievalResult),
/* harmony export */   DataSyncResult: () => (/* binding */ DataSyncResult),
/* harmony export */   DataSyncState: () => (/* binding */ DataSyncState),
/* harmony export */   DataSyncType: () => (/* binding */ DataSyncType),
/* harmony export */   DataToSync: () => (/* binding */ DataToSync),
/* harmony export */   StoreDataRequest: () => (/* binding */ StoreDataRequest)
/* harmony export */ });
class DataToSync {
  constructor() {
    this.key = "";
    this.retries = 0;
  }
}
class DataSyncResult {
  get timestamp() {
    if (this.timestampStr != null) {
      return new Date(this.timestampStr);
    }
    return undefined;
  }
  constructor(type) {
    this.state = DataSyncState.NotSynced;
    this.type = type;
  }
}
var DataSyncState = /*#__PURE__*/function (DataSyncState) {
  DataSyncState["NotSynced"] = "NotSynced";
  DataSyncState["Success"] = "Success";
  DataSyncState["Error"] = "Error";
  return DataSyncState;
}(DataSyncState || {});
var DataSyncType = /*#__PURE__*/function (DataSyncType) {
  DataSyncType["Appointments"] = "Appointments";
  DataSyncType["TeamAppointments"] = "TeamAppointments";
  DataSyncType["Customers"] = "Customers";
  DataSyncType["Reminders"] = "Reminders";
  DataSyncType["Users"] = "Users";
  DataSyncType["SalesWeekCommissionEstimates"] = "SalesWeekCommissionEstimates";
  return DataSyncType;
}(DataSyncType || {});
class StoreDataRequest {
  constructor() {
    this.data = [];
  }
}
class DataRetrievalResult {
  constructor(result, data) {
    this.result = result;
    this.data = data;
  }
}

/***/ }),

/***/ 1235:
/*!****************************************************!*\
  !*** ./src/app/shared/data/services/db.service.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DbService: () => (/* binding */ DbService)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rxjs */ 2921);
/* harmony import */ var _models_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../models/data */ 4886);
/* harmony import */ var _helpers_models_responses__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../helpers/models/responses */ 5561);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _appointments_services_appointment_mapping_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../appointments/services/appointment-mapping.service */ 1303);
/* harmony import */ var _authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../authentication/services/auth-ref.service */ 4387);
/* harmony import */ var _system_services_api_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../system/services/api.service */ 1160);
/* harmony import */ var _storage_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./storage.service */ 1490);


/* Models */








let DbService = /*#__PURE__*/(() => {
  class DbService {
    constructor(http, apptMappingService, authRefService, apiService, storageService) {
      this.http = http;
      this.apptMappingService = apptMappingService;
      this.authRefService = authRefService;
      this.apiService = apiService;
      this.storageService = storageService;
      this.retrievalFrequencyInMs = 2000;
      this.storageFrequencyInMs = 2000;
      this.bufferInMs = 0;
      // #endregion
      // #region UI
      this.managingSync = false;
      this.online = false;
      this.authenticated = false;
      // #endregion
      // #region Users
      this.retrievingUser = false;
      this.storingUser = false;
      this.userRetrievalPercentage = 0;
      // #endregion
      // #region Sales Week Commission Estimates
      this.retrievingCommissionEstimates = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      this.commissionEstimatesRetrieved = new rxjs__WEBPACK_IMPORTED_MODULE_8__.Subject();
      // #endregion
      // #region Reminders
      this.retrievingReminders = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      this.remindersRetrieved = new rxjs__WEBPACK_IMPORTED_MODULE_8__.Subject();
      this.storingReminders = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      // #endregion
      // #region Team Appointments
      this.retrievingTeamAppointments = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      this.teamAppointmentsRetrieved = new rxjs__WEBPACK_IMPORTED_MODULE_8__.Subject();
      // #endregion
      // #region Appointments
      this.retrievingAppointments = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      this.appointmentsRetrieved = new rxjs__WEBPACK_IMPORTED_MODULE_8__.Subject();
      this.storingAppointments = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      this.appointmentsBeingStored = [];
      // #endregion
      // #region Retrieval
      this.dataRetrieved = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      // #endregion
      // #region Storage
      this.storingData = false;
      this.dataStored = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
      // #endregion
      // #region Syncing
      this.syncEnabled = true;
      this.syncDelayInMs = 5000;
      this.syncing = new rxjs__WEBPACK_IMPORTED_MODULE_7__.BehaviorSubject(false);
    }
    // #region Boostrapping
    init() {
      this.watchAuth();
      this.watchOnlineStatus();
    }
    manageSync() {
      this.managingSync = true;
    }
    stopManagingSync() {
      this.managingSync = false;
    }
    watchOnlineStatus() {
      this.onlineSubscription = this.apiService.online.subscribe({
        next: online => {
          if (this.online && !online) {
            this.stopSyncing();
          }
          if (!this.online && online) {
            this.initSyncing();
          }
          this.online = online;
        }
      });
    }
    watchAuth() {
      this.authSubscription = this.authRefService.authenticated.subscribe({
        next: authenticated => {
          if (!this.authenticated && authenticated) {
            this.initSyncing();
          } else if (!authenticated) {
            this.stopSyncing();
          }
          this.authenticated = authenticated;
        }
      });
    }
    get activeUser() {
      return this.authRefService.user;
    }
    getUser(id) {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this.storageService.getItem(`Users_${id}`);
      })();
    }
    deleteUser(id) {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this2.storageService.deleteItem(`Users_${id}`);
      })();
    }
    retrieveActiveUser() {
      this.retrievingUser = true;
      return new Promise((res, rej) => {
        if (this.authenticated) {
          let url = `{{authApi}}/users/me`;
          this.userRetrievalPercentage = 0;
          this.http.get(url).subscribe({
            next: user => {
              this.userRetrievalPercentage = 100;
              this.retrievingUser = false;
              this.storeUser(user);
              this.authRefService.setUser(user);
              res(true);
            },
            error: e => {
              this.userRetrievalPercentage = 100;
              this.retrievingUser = false;
              res(false);
            }
          });
        } else {
          rej(false);
        }
      });
    }
    storeUser(user) {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        let key = `Users_${user.id}`;
        _this3.storageService.deleteItem(key);
        yield _this3.storageService.storeItem(key, user);
        return key;
      })();
    }
    getLastCommissionEstimateRetrieval() {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this4.getSyncState(`RetrievalToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.SalesWeekCommissionEstimates}`);
      })();
    }
    getCommissioneEstimatesForActiveUser() {
      const activeUser = this.activeUser.getValue();
      return this.storageService.getItems(`Commissions_SalesWeek_Estimates_${activeUser?.id}`);
    }
    scheduleCommissionEstimatesRetrieval(retrievalFrequencyInMs = this.retrievalFrequencyInMs) {
      var _this5 = this;
      window.clearTimeout(this.commissionEstimatesTimer);
      this.commissionEstimatesTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const now = new Date();
        let sinceInMs = null;
        if (_this5.lastCommissionEstimatesRetrieval != null) {
          sinceInMs = now.getTime() - _this5.lastCommissionEstimatesRetrieval.getTime() + _this5.bufferInMs; // Buffer to allow for sever operations
        }
        yield _this5.retrieveCommissionEstimates(sinceInMs);
      }), retrievalFrequencyInMs);
    }
    retrieveCommissionEstimates(sinceInMs) {
      var _this6 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref2 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const retrievingCommissionEstimates = _this6.retrievingCommissionEstimates.getValue();
            if (!retrievingCommissionEstimates) {
              _this6.retrievingCommissionEstimates.next(true);
              const localEstimates = yield _this6.getCommissioneEstimatesForActiveUser();
              if (localEstimates.length == 0) {
                sinceInMs = null;
              }
              _this6.retrieveData(sinceInMs, _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.SalesWeekCommissionEstimates, `{{api}}/reporting/commissions/sales-week/estimates/latest`).then(response => {
                response.data.forEach(week => {
                  _this6.localStoreCommissionEstimate(week);
                });
                _this6.commissionEstimatesRetrieved.next(response.data);
                _this6.lastCommissionEstimatesRetrieval = response.result.timestamp;
                _this6.retrievingCommissionEstimates.next(false);
                _this6.scheduleCommissionEstimatesRetrieval();
                res();
              }).catch(response => {
                _this6.lastCommissionEstimatesRetrieval = new Date();
                _this6.retrievingCommissionEstimates.next(false);
                _this6.scheduleCommissionEstimatesRetrieval();
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x, _x2) {
            return _ref2.apply(this, arguments);
          };
        }());
      })();
    }
    localStoreCommissionEstimate(week) {
      var _this7 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const activeUser = _this7.activeUser.getValue();
        let key = `Commissions_SalesWeek_Estimates_${activeUser?.id}_${week.weekId}`;
        _this7.storageService.deleteItem(key);
        yield _this7.storageService.storeItem(key, week);
        return key;
      })();
    }
    getRemindersForActiveUser() {
      const activeUser = this.activeUser.getValue();
      return this.storageService.getItems(`Reminders_${activeUser?.id}`);
    }
    getLastReminderRetrieval() {
      var _this8 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this8.getSyncState(`RetrievalToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Reminders}`);
      })();
    }
    scheduleReminderRetrieval(retrievalFrequencyInMs = this.retrievalFrequencyInMs) {
      var _this9 = this;
      window.clearTimeout(this.reminderRetrievalTimer);
      this.reminderRetrievalTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const now = new Date();
        let sinceInMs = null;
        if (_this9.lastReminderRetrieval != null) {
          sinceInMs = now.getTime() - _this9.lastReminderRetrieval.getTime() + _this9.bufferInMs; // Buffer to allow for sever operations
        }
        yield _this9.retrieveReminders(sinceInMs);
      }), retrievalFrequencyInMs);
    }
    retrieveReminders(sinceInMs) {
      var _this10 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref4 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const retrievingReminders = _this10.retrievingReminders.getValue();
            if (!retrievingReminders) {
              _this10.retrievingReminders.next(true);
              const localReminders = yield _this10.getRemindersForActiveUser();
              if (localReminders.length == 0) {
                sinceInMs = null;
              }
              _this10.retrieveData(sinceInMs, _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Reminders, `{{api}}/reminders/latest`).then(response => {
                response.data.forEach(reminder => {
                  const localReminder = localReminders.find(x => x.id == reminder.id);
                  if (localReminder == null) {
                    _this10.localStoreReminder(reminder);
                  } else {
                    const remoteDate = new Date(reminder.lastUpdated_Utc).toISOString();
                    const localDate = localReminder.lastUpdated_Utc.toISOString();
                    if (remoteDate >= localDate) {
                      _this10.localStoreReminder(reminder);
                    }
                  }
                });
                _this10.remindersRetrieved.next(response.data);
                _this10.lastReminderRetrieval = response.result.timestamp;
                _this10.retrievingReminders.next(false);
                _this10.scheduleReminderRetrieval();
                res();
              }).catch(response => {
                _this10.lastReminderRetrieval = new Date();
                _this10.retrievingReminders.next(false);
                _this10.scheduleReminderRetrieval();
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x3, _x4) {
            return _ref4.apply(this, arguments);
          };
        }());
      })();
    }
    getLastReminderStorage() {
      var _this11 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this11.getSyncState(`StorageToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Reminders}`);
      })();
    }
    scheduleReminderStorage(storageFrequencyInMs = this.storageFrequencyInMs) {
      var _this12 = this;
      window.clearTimeout(this.reminderStorageTimer);
      this.reminderStorageTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this12.storeReminders();
      }), storageFrequencyInMs);
    }
    storeReminders() {
      var _this13 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref6 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const storingReminders = _this13.storingReminders.getValue();
            if (!storingReminders) {
              _this13.storingReminders.next(true);
              _this13.storeData(_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Reminders, "Reminders", "Reminders", `{{api}}/reminders/store`).then(result => {
                _this13.lastReminderStorage = result.timestamp;
                _this13.scheduleReminderStorage();
                _this13.storingReminders.next(false);
                res();
              }).catch(result => {
                _this13.lastReminderStorage = new Date();
                _this13.scheduleReminderStorage();
                _this13.storingReminders.next(false);
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x5, _x6) {
            return _ref6.apply(this, arguments);
          };
        }());
      })();
    }
    localStoreReminder(reminder) {
      var _this14 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        reminder.lastUpdated_Utc = _this14.getUtcDate();
        const activeUser = _this14.activeUser.getValue();
        let key = `Reminders_${reminder.recipient?.id}_${reminder.id}`;
        _this14.storageService.deleteItem(key);
        yield _this14.storageService.storeItem(key, reminder);
        return key;
      })();
    }
    deleteReminder(id, userId = undefined) {
      var _this15 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (userId == null) {
          const activeUser = _this15.activeUser.getValue();
          userId = activeUser?.id;
        }
        yield _this15.storageService.deleteItem(`Reminders_${userId}_${id}`);
      })();
    }
    storeReminder(reminder) {
      var _this16 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (reminder.recipient != null && reminder.creator != null && reminder.id != null) {
          yield _this16.localStoreReminder(reminder);
          const syncKey = `Reminders_${reminder.id}`;
          _this16.markEntityForSync(syncKey, reminder.id);
        }
      })();
    }
    getLastTeamAppointmentsRetrieval() {
      var _this17 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this17.getSyncState(`RetrievalToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.TeamAppointments}`);
      })();
    }
    scheduleTeamAppointmentsRetrieval(retrievalFrequencyInMs = this.retrievalFrequencyInMs) {
      var _this18 = this;
      window.clearTimeout(this.teamAppointmentsRetrievalTimer);
      this.teamAppointmentsRetrievalTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const now = new Date();
        let sinceInMs = null;
        if (_this18.lastTeamAppointmentsRetrieval != null) {
          sinceInMs = now.getTime() - _this18.lastTeamAppointmentsRetrieval.getTime() + _this18.bufferInMs; // Buffer to allow for sever operations
        }
        yield _this18.retrieveTeamAppointments(sinceInMs);
      }), retrievalFrequencyInMs);
    }
    retrieveTeamAppointments(sinceInMs) {
      var _this19 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref8 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const retrievingTeamAppointments = _this19.retrievingTeamAppointments.getValue();
            if (!retrievingTeamAppointments) {
              _this19.retrievingTeamAppointments.next(true);
              const localAppointments = yield _this19.getAppointments();
              if (localAppointments.length == 0) {
                sinceInMs = null;
              }
              _this19.retrieveData(sinceInMs, _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.TeamAppointments, `{{api}}/appointments/team/latest`).then(response => {
                response.data.forEach(appointment => {
                  const localAppointment = localAppointments.find(x => x.id == appointment.id);
                  if (localAppointment == null) {
                    _this19.localStoreAppointment(appointment);
                  } else {
                    const remoteDate = new Date(appointment.lastUpdated_Utc).toISOString();
                    const localDate = localAppointment.lastUpdated_Utc.toISOString();
                    if (remoteDate >= localDate) {
                      _this19.localStoreAppointment(appointment);
                    }
                  }
                });
                _this19.teamAppointmentsRetrieved.next(response.data);
                _this19.lastTeamAppointmentsRetrieval = response.result.timestamp;
                _this19.retrievingTeamAppointments.next(false);
                _this19.scheduleTeamAppointmentsRetrieval();
                res();
              }).catch(response => {
                _this19.lastTeamAppointmentsRetrieval = new Date();
                _this19.retrievingTeamAppointments.next(false);
                _this19.scheduleTeamAppointmentsRetrieval();
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x7, _x8) {
            return _ref8.apply(this, arguments);
          };
        }());
      })();
    }
    getLastAppointmentsRetrieval() {
      var _this20 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this20.getSyncState(`RetrievalToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Appointments}`);
      })();
    }
    scheduleAppointmentsRetrieval(retrievalFrequencyInMs = this.retrievalFrequencyInMs) {
      var _this21 = this;
      window.clearTimeout(this.appointmentsRetrievalTimer);
      this.appointmentsRetrievalTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const now = new Date();
        let sinceInMs = null;
        if (_this21.lastAppointmentsRetrieval != null) {
          sinceInMs = now.getTime() - _this21.lastAppointmentsRetrieval.getTime() + _this21.bufferInMs; // Buffer to allow for sever operations
        }
        yield _this21.retrieveAppointments(sinceInMs);
      }), retrievalFrequencyInMs);
    }
    retrieveAppointments(sinceInMs) {
      var _this22 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref10 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const retrievingAppointments = _this22.retrievingAppointments.getValue();
            if (!retrievingAppointments) {
              _this22.retrievingAppointments.next(true);
              const localAppointments = yield _this22.getAppointmentsForActiveUser();
              if (localAppointments.length == 0) {
                sinceInMs = null;
              }
              _this22.retrieveData(sinceInMs, _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Appointments, `{{api}}/appointments/latest`).then(response => {
                response.data.forEach(appointment => {
                  const localAppointment = localAppointments.find(x => x.id == appointment.id);
                  if (localAppointment == null) {
                    _this22.localStoreAppointment(appointment);
                  } else {
                    // Testing
                    _this22.localStoreAppointment(appointment);
                  }
                });
                _this22.appointmentsRetrieved.next(response.data);
                _this22.lastAppointmentsRetrieval = response.result.timestamp;
                _this22.retrievingAppointments.next(false);
                _this22.scheduleAppointmentsRetrieval();
                res();
              }).catch(response => {
                _this22.lastAppointmentsRetrieval = new Date();
                _this22.retrievingAppointments.next(false);
                _this22.scheduleAppointmentsRetrieval();
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x9, _x10) {
            return _ref10.apply(this, arguments);
          };
        }());
      })();
    }
    getAppointmentsForUser(userId) {
      return this.storageService.getItems(`Appointments_${userId}`);
    }
    getAppointments() {
      return this.storageService.getItems(`Appointments_`);
    }
    getAppointmentsForActiveUser() {
      const activeUser = this.activeUser.getValue();
      return this.storageService.getItems(`Appointments_${activeUser?.id}`);
    }
    getAppointmentForActiveUser(id) {
      return new rxjs__WEBPACK_IMPORTED_MODULE_9__.Observable(o => {
        const activeUser = this.activeUser.getValue();
        this.storageService.getItems(`Appointments_${activeUser?.id}`).then(appointments => {
          for (var i = 0, len = appointments.length; i < len; i++) {
            const appointment = appointments[i];
            if (appointment.id == id) {
              o.next(appointment);
              o.complete();
              break;
            }
          }
          o.next(undefined);
          o.complete();
        }).catch(() => {
          o.error();
        });
      });
    }
    isAppointmentBeingStored(id) {
      return this.appointmentsBeingStored.indexOf(id) > -1;
    }
    unmarkAppointmentBeingStored(id) {
      const index = this.appointmentsBeingStored.findIndex(x => x == id);
      this.appointmentsBeingStored.splice(index, 1);
    }
    getLastAppointmentsStorage() {
      var _this23 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this23.getSyncState(`StorageToSync_${_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Appointments}`);
      })();
    }
    scheduleAppointmentsStorage(storageFrequencyInMs = this.storageFrequencyInMs) {
      var _this24 = this;
      window.clearTimeout(this.appointmentsStorageTimer);
      this.appointmentsStorageTimer = window.setTimeout(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this24.storeAppointments();
      }), storageFrequencyInMs);
    }
    storeAppointments() {
      var _this25 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref12 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const storingAppointments = _this25.storingAppointments.getValue();
            if (!storingAppointments) {
              _this25.storingAppointments.next(true);
              _this25.storeData(_models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncType.Appointments, "Appointments", "Appointments", `{{api}}/appointments/store`).then(result => {
                _this25.lastAppointmentsRetrieval = result.timestamp;
                _this25.scheduleAppointmentsStorage();
                _this25.storingAppointments.next(false);
                res();
              }).catch(result => {
                _this25.lastAppointmentsRetrieval = new Date();
                _this25.scheduleAppointmentsStorage();
                _this25.storingAppointments.next(false);
                rej();
              });
            } else {
              res();
            }
          });
          return function (_x11, _x12) {
            return _ref12.apply(this, arguments);
          };
        }());
      })();
    }
    localStoreAppointment(appointment) {
      var _this26 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        appointment.lastUpdated_Utc = _this26.getUtcDate();
        let key = `Appointments_${appointment.assignedTo?.id}_${appointment.id}`;
        _this26.storageService.deleteItem(key);
        yield _this26.storageService.storeItem(key, appointment);
        return key;
      })();
    }
    deleteAppointment(id, userId = undefined) {
      var _this27 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (userId == null) {
          const activeUser = _this27.activeUser.getValue();
          userId = activeUser?.id;
        }
        yield _this27.storageService.deleteItem(`Appointments_${userId}_${id}`);
      })();
    }
    storeAppointment(appointment) {
      var _this28 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this28.localStoreAppointment(appointment);
        const syncKey = `Appointments_${appointment.id}`;
        _this28.markEntityForSync(syncKey, appointment.id);
      })();
    }
    retrieveData(sinceInMs, type, url) {
      var _this29 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref13 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const result = new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncResult(type);
            if (_this29.syncEnabled) {
              _this29.updateSyncStatus();
              if (sinceInMs != null) {
                url = `${url}/${sinceInMs}`;
              }
              _this29.http.get(url).subscribe({
                next: data => {
                  const now = new Date();
                  result.timestampStr = now.toISOString();
                  result.message = "Successful.";
                  result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.Success;
                  _this29.storeSyncState(`RetrievalToSync_${type}`, result).then(() => {
                    _this29.updateSyncStatus();
                    res(new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataRetrievalResult(result, data));
                  });
                },
                error: () => {
                  const now = new Date();
                  result.timestampStr = now.toISOString();
                  result.message = `Failed to retrieve ${type}(s).`;
                  result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.Error;
                  _this29.storeSyncState(`RetrievalToSync_${type}`, result).then(() => {
                    _this29.updateSyncStatus();
                    rej(new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataRetrievalResult(result, []));
                  });
                }
              });
            } else {
              const now = new Date();
              result.timestampStr = now.toISOString();
              result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.NotSynced;
              result.message = `${type} retrieval already in progress.`;
              res(new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataRetrievalResult(result, []));
            }
          });
          return function (_x13, _x14) {
            return _ref13.apply(this, arguments);
          };
        }());
      })();
    }
    storeData(type, dataPrefix, dataToSyncStr, url) {
      var _this30 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref14 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            const result = new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncResult(type);
            if (_this30.syncEnabled) {
              _this30.updateSyncStatus();
              const result = new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncResult(type);
              const activeUser = _this30.activeUser.getValue();
              const datas = yield _this30.storageService.getItems(dataPrefix);
              const dataToSyncRef = yield _this30.storageService.getItems(`DataToSync_${activeUser?.id}_${dataToSyncStr}`);
              const dataToSync = [];
              for (var i = 0, len = dataToSyncRef.length; i < len; i++) {
                const ref = dataToSyncRef[i];
                const data = datas.find(x => x.id == ref.key);
                if (data != null) {
                  dataToSync.push(data);
                }
              }
              if (dataToSync.length > 0) {
                const headers = {
                  "Content-Type": "application/json"
                };
                const request = {
                  data: dataToSync
                };
                _this30.http.post(url, JSON.stringify(request), {
                  headers: headers
                }).subscribe({
                  next: response => {
                    if (response.state == _helpers_models_responses__WEBPACK_IMPORTED_MODULE_2__.GeneralResponseState.Successful) {
                      dataToSync.forEach(/*#__PURE__*/function () {
                        var _ref15 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (data) {
                          yield _this30.removeEntityForSync(`${dataPrefix}_${data.id}`);
                        });
                        return function (_x17) {
                          return _ref15.apply(this, arguments);
                        };
                      }());
                      const now = new Date();
                      result.timestampStr = now.toISOString();
                      result.message = "Successful.";
                      result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.Success;
                      _this30.storeSyncState(`StorageToSync_${type}`, result).then(() => {
                        _this30.updateSyncStatus();
                        res(result);
                      });
                    } else {
                      const now = new Date();
                      result.timestampStr = now.toISOString();
                      result.message = response.message;
                      result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.Error;
                      _this30.storeSyncState(`StorageToSync_${type}`, result).then(() => {
                        _this30.updateSyncStatus();
                        rej(result);
                      });
                    }
                  },
                  error: () => {
                    const now = new Date();
                    result.timestampStr = now.toISOString();
                    result.message = `Server failure.`;
                    result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.Error;
                    _this30.storeSyncState(`StorageToSync_${type}`, result).then(() => {
                      rej(result);
                    });
                  }
                });
              } else {
                const now = new Date();
                result.timestampStr = now.toISOString();
                result.message = `Has no data to sync.`;
                result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.NotSynced;
                _this30.updateSyncStatus();
                res(result);
              }
            } else {
              const now = new Date();
              result.timestampStr = now.toISOString();
              result.state = _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncState.NotSynced;
              result.message = `Storage already in progress.`;
              res(result);
            }
          });
          return function (_x15, _x16) {
            return _ref14.apply(this, arguments);
          };
        }());
      })();
    }
    updateSyncStatus() {
      const storingReminders = this.storingReminders.getValue();
      const storingAppointments = this.storingAppointments.getValue();
      const syncing = storingReminders || storingAppointments;
      this.syncing.next(syncing);
    }
    initSyncing() {
      var _this31 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        _this31.syncEnabled = true;
        yield _this31.scheduleCommissionEstimatesRetrieval();
        yield _this31.scheduleReminderRetrieval();
        yield _this31.scheduleReminderStorage();
        yield _this31.scheduleAppointmentsRetrieval();
        yield _this31.scheduleAppointmentsStorage();
        const activeUser = _this31.activeUser.getValue();
        if (activeUser?.isManager) {
          _this31.scheduleTeamAppointmentsRetrieval();
        }
      })();
    }
    stopSyncing() {
      this.syncEnabled = false;
    }
    getSyncState(key) {
      var _this32 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const activeUser = _this32.activeUser.getValue();
        if (activeUser != null) {
          key = `SyncState_${activeUser.id}_${key}`;
          const result = yield _this32.storageService.getItem(key);
          if (result?.type != null) {
            const mappedResult = Object.assign(new _models_data__WEBPACK_IMPORTED_MODULE_1__.DataSyncResult(result.type), result);
            return mappedResult;
          }
        }
        return null;
      })();
    }
    storeSyncState(key, result) {
      var _this33 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const activeUser = _this33.activeUser.getValue();
        if (activeUser != null) {
          key = `SyncState_${activeUser.id}_${key}`;
          yield _this33.storageService.storeItem(key, result);
        }
      })();
    }
    removeEntityForSync(storageKey) {
      var _this34 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const activeUser = _this34.activeUser.getValue();
        if (activeUser != null) {
          const key = `DataToSync_${activeUser?.id}_${storageKey}`;
          yield _this34.storageService.deleteItem(key);
        }
      })();
    }
    markEntityForSync(storageKey, referenceKey) {
      var _this35 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const entity = {
          key: referenceKey,
          retries: 0,
          synced_Utc: undefined
        };
        const activeUser = _this35.activeUser.getValue();
        if (activeUser != null) {
          const key = `DataToSync_${activeUser?.id}_${storageKey}`;
          yield _this35.storageService.storeItem(key, entity);
        }
      })();
    }
    reset() {
      this.storageService.clear();
    }
    // #endregion
    // #region Helpers
    getUtcDate() {
      return new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate(), new Date().getUTCHours(), new Date().getUTCMinutes(), new Date().getUTCSeconds(), new Date().getUTCMilliseconds()));
    }
    // #endregion
    ngOnDestroy() {
      this.onlineSubscription?.unsubscribe();
      this.authSubscription?.unsubscribe();
      window.clearTimeout(this.syncTimer);
    }
    static #_ = (() => this.ɵfac = function DbService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DbService)(_angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_11__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵinject"](_appointments_services_appointment_mapping_service__WEBPACK_IMPORTED_MODULE_3__.AppointmentMappingService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵinject"](_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_4__.AuthRefService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵinject"](_system_services_api_service__WEBPACK_IMPORTED_MODULE_5__.ApiService), _angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵinject"](_storage_service__WEBPACK_IMPORTED_MODULE_6__.StorageService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_10__["ɵɵdefineInjectable"]({
      token: DbService,
      factory: DbService.ɵfac
    }))();
  }
  return DbService;
})();

/***/ }),

/***/ 1490:
/*!*********************************************************!*\
  !*** ./src/app/shared/data/services/storage.service.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   StorageService: () => (/* binding */ StorageService)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var src_environments_environment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/environments/environment */ 1618);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 4380);



let StorageService = /*#__PURE__*/(() => {
  class StorageService {
    constructor() {
      this.dbName = 'repipeDb';
      this.storeName = 'repipeStore';
      this.db = null;
      this.initializeDb();
      this.initVersion();
    }
    // #region Bootstrapping
    initializeDb() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          _this.db = yield _this.openDb();
        } catch (error) {
          console.error('Failed to initialize database:', error);
          throw new Error('Database initialization failed');
        }
      })();
    }
    openDb() {
      return new Promise((resolve, reject) => {
        const request = indexedDB.open(this.dbName, 1);
        request.onupgradeneeded = event => {
          const db = event.target.result;
          db.createObjectStore(this.storeName);
        };
        request.onsuccess = event => {
          resolve(event.target.result);
        };
        request.onerror = () => reject(new Error('Failed to open IndexedDB'));
      });
    }
    ensureDb() {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (!_this2.db) {
          _this2.db = yield _this2.openDb();
        }
        return _this2.db;
      })();
    }
    initVersion() {
      const currentVersion = src_environments_environment__WEBPACK_IMPORTED_MODULE_1__.environment.APP_VERSION.toString();
      const previousVersion = localStorage.getItem('db_v');
      if (previousVersion !== currentVersion) {
        this.clear().then(() => {
          localStorage.setItem('db_v', currentVersion);
          this.version = currentVersion;
        }).catch(error => {
          console.error('Failed to clear database during version update:', error);
        });
      } else {
        localStorage.setItem('db_v', currentVersion);
        this.version = currentVersion;
      }
    }
    // #endregion
    // #region Retrieval
    getRawItem(key) {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const db = yield _this3.ensureDb();
        return new Promise((resolve, reject) => {
          const transaction = db.transaction(_this3.storeName, 'readonly');
          const store = transaction.objectStore(_this3.storeName);
          const request = store.get(key);
          request.onsuccess = () => resolve(request.result ?? null);
          request.onerror = () => reject(new Error(`Failed to get ${key}`));
        });
      })();
    }
    getItem(key) {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const value = yield _this4.getRawItem(key);
        if (value === null) return null;
        try {
          return JSON.parse(value);
        } catch {
          return value; // Fallback for non-JSON strings
        }
      })();
    }
    getItems(prefix) {
      var _this5 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const db = yield _this5.ensureDb();
        return new Promise((resolve, reject) => {
          const results = [];
          const transaction = db.transaction(_this5.storeName, 'readonly');
          const store = transaction.objectStore(_this5.storeName);
          const request = store.openCursor();
          request.onsuccess = event => {
            const cursor = event.target.result;
            if (cursor) {
              const key = cursor.key;
              if (key.startsWith(prefix)) {
                let value;
                try {
                  value = JSON.parse(cursor.value);
                } catch {
                  value = cursor.value; // Fallback for non-JSON strings
                }
                results.push(value);
              }
              cursor.continue();
            } else {
              resolve(results);
            }
          };
          request.onerror = () => reject(new Error(`Failed to retrieve items with prefix ${prefix}`));
        });
      })();
    }
    // #endregion
    // #region Storage
    storeItem(key, data) {
      var _this6 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const storableData = _this6.deepClone(data);
        const db = yield _this6.ensureDb();
        return new Promise((resolve, reject) => {
          const transaction = db.transaction(_this6.storeName, 'readwrite');
          const store = transaction.objectStore(_this6.storeName);
          const request = store.put(storableData, key);
          request.onsuccess = () => resolve();
          request.onerror = () => reject(new Error(`Failed to store ${key}`));
        });
      })();
    }
    // #endregion
    // #region Deletion
    deleteItem(key) {
      var _this7 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const db = yield _this7.ensureDb();
        return new Promise((resolve, reject) => {
          const transaction = db.transaction(_this7.storeName, 'readwrite');
          const store = transaction.objectStore(_this7.storeName);
          const request = store.delete(key);
          request.onsuccess = () => resolve();
          request.onerror = () => reject(new Error(`Failed to delete ${key}`));
        });
      })();
    }
    clear() {
      var _this8 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const db = yield _this8.ensureDb();
        return new Promise((resolve, reject) => {
          const transaction = db.transaction(_this8.storeName, 'readwrite');
          const store = transaction.objectStore(_this8.storeName);
          const request = store.clear();
          request.onsuccess = () => resolve();
          request.onerror = () => reject(new Error('Failed to clear store'));
        });
      })();
    }
    // #endregion
    // #region Helpers
    deepClone(obj, seen = new WeakMap()) {
      if (obj === null || typeof obj !== 'object') {
        return obj;
      }
      if (Array.isArray(obj) && obj.every(item => typeof item !== 'object' && typeof item !== 'function')) {
        return [...obj];
      }
      if (seen.has(obj)) {
        const rawObj = obj;
        if (rawObj._finalizers == null && rawObj.observers == null) {
          return seen.get(obj);
        } else {
          return undefined;
        }
      }
      if (obj instanceof Date) {
        return new Date(obj.getTime());
      }
      if (obj instanceof Map) {
        const clone = new Map();
        seen.set(obj, clone);
        obj.forEach((value, key) => {
          if (typeof value !== 'function') {
            clone.set(this.deepClone(key, seen), this.deepClone(value, seen));
          }
        });
        return clone;
      }
      if (obj instanceof Set) {
        const clone = new Set();
        seen.set(obj, clone);
        obj.forEach(value => {
          if (typeof value !== 'function') {
            clone.add(this.deepClone(value, seen));
          }
        });
        return clone;
      }
      if (Array.isArray(obj)) {
        const clone = [];
        seen.set(obj, clone);
        for (let i = 0; i < obj.length; i++) {
          if (typeof obj[i] !== 'function') {
            clone[i] = this.deepClone(obj[i], seen);
          }
        }
        return clone;
      }
      const clone = {};
      seen.set(obj, clone);
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          const value = obj[key];
          if (typeof value !== 'function') {
            clone[key] = this.deepClone(value, seen);
          }
        }
      }
      return clone;
    }
    // #endregion
    closeDb() {
      if (this.db) {
        this.db.close();
        this.db = null;
      }
    }
    static #_ = (() => this.ɵfac = function StorageService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || StorageService)();
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({
      token: StorageService,
      factory: StorageService.ɵfac
    }))();
  }
  return StorageService;
})();

/***/ }),

/***/ 6488:
/*!****************************************************************************************************!*\
  !*** ./src/app/shared/documents/components/appointment-document/appointment-document.component.ts ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppointmentDocumentComponent: () => (/* binding */ AppointmentDocumentComponent)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/app/shared/appointments/models/appointment */ 8723);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var src_app_shared_documents_models_document__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! src/app/shared/documents/models/document */ 735);
/* harmony import */ var src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! src/app/shared/properties/models/property */ 1750);
/* harmony import */ var src_app_shared_contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! src/app/shared/contact-information/models/contact-information */ 904);
/* harmony import */ var src_app_shared_content_models_binary__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! src/app/shared/content/models/binary */ 4768);
/* harmony import */ var src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! src/app/shared/addresses/models/address */ 2846);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! src/app/shared/helpers/methods/methods */ 2853);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! src/app/shared/ui/services/ui.service */ 345);
/* harmony import */ var src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! src/app/shared/documents/services/document.service */ 3040);
/* harmony import */ var src_app_shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! src/app/shared/system/services/api.service */ 1160);
/* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @angular/platform-browser */ 4604);
/* harmony import */ var _ui_components_loader_loader_component__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../../ui/components/loader/loader.component */ 5086);








/* Pipes */









const _c0 = ["viewerElm"];
const _c1 = ["staticElm"];
const _c2 = ["componentElm"];
function AppointmentDocumentComponent_div_0_loader_1_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelement"](0, "loader", 7);
  }
  if (rf & 2) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("fill", true);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_4_div_1_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelement"](0, "div", 10);
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵnextContext"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("innerHtml", ctx_r0.documentContent, _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵsanitizeHtml"]);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_4_div_2_div_2_div_3_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelement"](0, "div", 17);
  }
  if (rf & 2) {
    const field_r2 = ctx.$implicit;
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵstyleProp"]("left", field_r2.displayX)("top", field_r2.displayY)("width", field_r2.displayWidth)("height", field_r2.displayHeight);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("innerHTML", field_r2.contentHtml, _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵsanitizeHtml"]);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_4_div_2_div_2_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementStart"](0, "div", 13);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelement"](1, "img", 14);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementStart"](2, "div", 15);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](3, AppointmentDocumentComponent_div_0_ng_container_4_div_2_div_2_div_3_Template, 1, 9, "div", 16);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const page_r3 = ctx.$implicit;
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("src", page_r3.binary == null ? null : page_r3.binary.src, _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵsanitizeUrl"]);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngForOf", page_r3.fields);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_4_div_2_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementStart"](0, "div", 11, 1);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](2, AppointmentDocumentComponent_div_0_ng_container_4_div_2_div_2_Template, 4, 2, "div", 12);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵnextContext"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngForOf", ctx_r0.activePages);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_4_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementContainerStart"](0);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](1, AppointmentDocumentComponent_div_0_ng_container_4_div_1_Template, 1, 1, "div", 8)(2, AppointmentDocumentComponent_div_0_ng_container_4_div_2_Template, 3, 1, "div", 9);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementContainerEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", ctx_r0.isDynamic);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", !ctx_r0.isDynamic);
  }
}
function AppointmentDocumentComponent_div_0_ng_container_5_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementContainerStart"](0);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelement"](1, "img", 14);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementContainerEnd"]();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("src", ctx_r0.executedDocument, _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵsanitizeUrl"]);
  }
}
function AppointmentDocumentComponent_div_0_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementStart"](0, "div", 3);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](1, AppointmentDocumentComponent_div_0_loader_1_Template, 1, 1, "loader", 4);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementStart"](2, "div", 5, 0);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](4, AppointmentDocumentComponent_div_0_ng_container_4_Template, 3, 2, "ng-container", 6)(5, AppointmentDocumentComponent_div_0_ng_container_5_Template, 2, 1, "ng-container", 6);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", !ctx_r0.isDynamic);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", !ctx_r0.renderExecutedDocument);
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", ctx_r0.renderExecutedDocument);
  }
}
let AppointmentDocumentComponent = /*#__PURE__*/(() => {
  class AppointmentDocumentComponent {
    constructor(uiService, documentService, apiService, currencyPipe, sanitizer) {
      this.uiService = uiService;
      this.documentService = documentService;
      this.apiService = apiService;
      this.currencyPipe = currencyPipe;
      this.sanitizer = sanitizer;
      this.activePages = [];
      // #endregion
      // #region User Content
      this.userContentValid = false;
      this.initialCount = 0;
      // #endregion
      // #region Signatures
      this.signatureCount = 0;
      this.signaturesValid = false;
      this.renderExecutedDocument = false;
      this.changed$ = new rxjs__WEBPACK_IMPORTED_MODULE_13__.Subject();
    }
    replaceJobId(content) {
      if (this.appointmentContent != null) {
        const labelRegex = /{{appointment.jobid.label}}/gi;
        const labelReplacement = `Estimate #`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.jobid}}/gi;
        const replacement = `${this.appointmentContent.jobId}`;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    get documents() {
      return this.appointmentContent?.documents ?? [];
    }
    get isDynamic() {
      if (this.document != null && this.document.dynamic && this.document.content != null) {
        return true;
      }
      return false;
    }
    calcStaticRatio(pageWidth) {
      const staticElm = this.staticElm?.nativeElement;
      if (staticElm != null) {
        const width = staticElm.offsetWidth;
        return width / pageWidth;
      }
      return 1;
    }
    initMapping(document) {
      setTimeout(() => {
        if (document.mapping != null) {
          const mappedPages = [];
          for (var i = 0, len = document.mapping.pages.length; i < len; i++) {
            const page = document.mapping.pages[i];
            if (page.binary != null) {
              const binary = new src_app_shared_content_models_binary__WEBPACK_IMPORTED_MODULE_5__.ContentBinary(page.binary);
              const ratio = binary.width != null ? this.calcStaticRatio(binary.width) : 1;
              const mappedFields = [];
              page.fields.forEach(field => {
                const mappedField = new src_app_shared_documents_models_document__WEBPACK_IMPORTED_MODULE_2__.DocumentFieldMapping(field, ratio);
                if (field.fieldId == null || field.content == null) {
                  if (mappedField.id != null) {
                    mappedField.content = this.replaceVariables(document, mappedField.id);
                  }
                  if (mappedField.content != null) {
                    mappedField.fieldId = mappedField.content.match(/field='([0-9a-f-]{36})'/)?.[1] ?? undefined;
                  }
                }
                if (mappedField.content != null) {
                  mappedField.contentHtml = this.sanitizer.bypassSecurityTrustHtml(mappedField.content);
                }
                mappedFields.push(mappedField);
              });
              const mappedPage = {
                fields: mappedFields,
                binary: binary
              };
              mappedPages.push(mappedPage);
            }
          }
          this.activePages = mappedPages;
          document.mapping.pages = mappedPages;
          setTimeout(() => {
            this.initSignatureElms();
            this.initIntialElms();
          }, 0);
        }
      }, 0);
    }
    // #endregion
    // #region Additional Considerations
    replaceAdditionalConsiderations(content) {
      if (this.price != null && this.price.customItems.length > 0) {
        let markup = `
                <h3>Additional Considerations to Scope:</h3>
                <table class='additional-considerations'>
                <thead>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Quantity</th>
                </thead>
                <tbody>`;
        this.price.customItems.forEach(item => {
          markup = markup + `<tr class='consideration'>
                        <td>${item.name}</td>
                        <td>${item.description}</td>
                        <td>${item.quantity}</td>
                    </tr>`;
        });
        markup = markup + "</tbody></table>";
        const acRegex = /{{price.customItems.customer}}/gi;
        content = content.replace(acRegex, markup);
      } else {
        const acRegex = /{{price.customItems.customer}}/gi;
        content = content.replace(acRegex, '');
      }
      return content;
    }
    // #endregion
    // #region Entity Details
    renderEntityDetailAttribute(entity, index, onlyCustomerFacing = false, parentEntity = null) {
      const customerFacingAttribute = entity.attributes.find(x => x.customerFacing);
      if (!onlyCustomerFacing && entity.attributes.length > 0 || onlyCustomerFacing && customerFacingAttribute != null) {
        let markup = "";
        if (entity.type == src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Unit) {
          markup = markup + "<tr class='spacer'><td></td></tr>";
        }
        if (parentEntity != null && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Property) {
          if (entity.type == src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
            markup = markup + `<tr class='type ${entity.type}'>
                        <td>
                        <span class='parent'>${parentEntity.name}</span>
                        <span class='entity'>${entity.name} ${entity.number} Details</span>
                        </td>
                        </tr>`;
          } else {
            markup = markup + `<tr class='type ${entity.type}'>
                        <td>
                        <span class='parent'>${parentEntity.name}</span>
                        <span class='entity'>${entity.name} Details</span>
                        </td>
                        </tr>`;
          }
        } else if (entity.type == src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
          markup = markup + `<tr class='type ${entity.type}'>
                    <td>
                    <span class='entity'>${entity.name} ${entity.number} Details</span>
                    </td>
                    </tr>`;
        } else {
          markup = markup + `<tr class='type ${entity.type}'>
                    <td>
                    <span class='entity'>${entity.name} Details</span>
                    </td>
                    </tr>`;
        }
        markup = markup + "<tr class='details'><td>";
        markup = markup + "<span class='attributes'>";
        entity.attributes.forEach(attribute => {
          if ((!onlyCustomerFacing || attribute.customerFacing) && attribute.values.length > 0) {
            markup = markup + `<span class='attribute'>
                        <span class='name'>${attribute.name}</span>`;
            attribute.values.forEach(value => {
              const sanitizedValue = value.toLowerCase();
              switch (sanitizedValue) {
                case "false":
                  value = "No";
                  break;
                case "true":
                  value = "Yes";
                  break;
              }
              markup = markup + `<span class='value'>${value}</span>`;
            });
            markup = markup + "</span>";
          }
        });
        markup = markup + "</span>";
        if (entity.fixtures.length > 0) {
          markup = markup + "<span class='fixtures'>";
          for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
            const fixture = entity.fixtures[j];
            markup = markup + `<span class='fixture'><span class='name'>${fixture.name} -</span>`;
            fixture.attributes.forEach(attribute => {
              if ((!onlyCustomerFacing || attribute.customerFacing) && attribute.values.length > 0) {
                markup = markup + `<span class='attribute'>
                                <span class='name'>${attribute.name}</span>`;
                attribute.values.forEach(value => {
                  markup = markup + `<span class='value'>${value}</span>`;
                });
                markup = markup + "</span></span>";
              }
            });
          }
          markup = markup + "</span>";
        }
        markup = markup + "</td></tr>";
        return markup;
      }
      return "";
    }
    getEntityDetailsAttributes(entity = null, entities = [], parentEntity = null, onlyCustomerFacing = false, index = 1) {
      let entityNotes = "";
      if (entity != null) {
        let note = this.renderEntityDetailAttribute(entity, index, onlyCustomerFacing, parentEntity);
        note = note + this.getEntityDetailsAttributes(null, entity.entities, entity, onlyCustomerFacing, index + 1);
        entityNotes = entityNotes + note;
      } else {
        for (var i = 0, len = entities.length; i < len; i++) {
          const childEntity = entities[i];
          let note = this.renderEntityDetailAttribute(childEntity, index, onlyCustomerFacing, parentEntity);
          index = index + 1;
          note = note + this.getEntityDetailsAttributes(null, childEntity.entities, childEntity, onlyCustomerFacing, index);
          entityNotes = entityNotes + note;
        }
      }
      return entityNotes;
    }
    replaceEntityDetails(matchText, content, onlyCustomerFacing = false) {
      if (this.appointmentContent?.property?.entity != null) {
        let markup = `<table class="entity-details">`;
        markup = markup + this.getEntityDetailsAttributes(this.appointmentContent.job, [], null, onlyCustomerFacing, 1);
        markup = markup + this.getEntityDetailsAttributes(this.appointmentContent.property.entity, [], null, onlyCustomerFacing, 1) + "</table>";
        const regex = new RegExp(matchText, 'g');
        const replacement = markup;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Attributes
    renderAttribute(entity, index, onlyCustomerFacing = false, parentEntity = null) {
      const customerFacingAttribute = entity.attributes.find(x => x.customerFacing);
      if (!onlyCustomerFacing && entity.attributes.length > 0 || onlyCustomerFacing && customerFacingAttribute != null) {
        let markup = "";
        if (parentEntity != null) {
          if (parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Property && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Structure && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Floor) {
            markup = `<div class='inspection-attribute'>
                        <h3>${parentEntity.name} ${parentEntity.number}</h3>
                        <h4>${entity.name} ${entity.number} Details</h4>`;
          } else {
            markup = `<div class='inspection-attribute'>
                        <h3>${parentEntity.name}</h3>
                        <h4>${entity.name} Details</h4>`;
          }
        } else {
          markup = `<div class='inspection-attribute'>
                    <h3>${entity.name} Details</h3>`;
        }
        entity.attributes.forEach(attribute => {
          if (!onlyCustomerFacing || attribute.customerFacing) {
            markup = markup + `<div class='attribute'>
                        <label>${attribute.name}</label>`;
            attribute.values.forEach(value => {
              markup = markup + `<span class='value'>${value}</span>`;
            });
            markup = markup + "</div>";
          }
        });
        markup = markup + "</div>";
        return markup;
      }
      return "";
    }
    getAttributes(entity = null, entities = [], parentEntity = null, onlyCustomerFacing = false, index = 1) {
      let entityNotes = "";
      if (entity != null) {
        let note = this.renderAttribute(entity, index, onlyCustomerFacing, parentEntity);
        note = note + this.getAttributes(null, entity.entities, entity, onlyCustomerFacing, index + 1);
        entityNotes = entityNotes + note;
      } else {
        for (var i = 0, len = entities.length; i < len; i++) {
          const childEntity = entities[i];
          if (childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Structure && childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
            let note = this.renderAttribute(childEntity, index, onlyCustomerFacing, parentEntity);
            index = index + 1;
            for (var j = 0, jlen = childEntity.fixtures.length; j < jlen; j++) {
              const fixture = childEntity.fixtures[j];
              note = note + this.renderAttribute(fixture, index, onlyCustomerFacing, childEntity);
            }
            note = note + this.getAttributes(null, childEntity.entities, childEntity, onlyCustomerFacing, index);
            entityNotes = entityNotes + note;
          } else if (childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
            index = index + 1;
            const note = this.getAttributes(null, childEntity.entities, childEntity, onlyCustomerFacing, index);
            entityNotes = entityNotes + note;
          }
        }
      }
      return entityNotes;
    }
    replaceAttributes(matchText, content, onlyCustomerFacing = false) {
      if (this.appointmentContent?.property?.entity != null) {
        let attributes = `<div class='inspection-attributes'>
                <div class='attributes'>`;
        attributes = attributes + this.getAttributes(this.appointmentContent.property.entity, [], null, onlyCustomerFacing, 1) + "</div></div>";
        const regex = new RegExp(matchText, 'g');
        const replacement = attributes;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Photos
    renderPhoto(entity, index, parentEntity = null) {
      if (entity.photos_B64.length > 0 || entity.photos.length > 0) {
        let diagram = "";
        if (parentEntity != null) {
          if (parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Property && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Structure && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Floor) {
            diagram = `<div class='inspection-photos'>
                        <h3>${parentEntity.name} ${parentEntity.number}</h3>
                        <h4>${entity.name} ${entity.number}</h4>
                        <div class='images'>`;
          } else {
            diagram = `<div class='inspection-photos'>
                        <h3>${parentEntity.name}</h3>
                        <h4>${entity.name} Photos</h4>
                        <div class='images'>`;
          }
        } else {
          diagram = `<div class='inspection-photos'>
                    <h3>${entity.name}</h3>`;
        }
        entity.photos.forEach(photo => {
          const mappedPhoto = new src_app_shared_content_models_binary__WEBPACK_IMPORTED_MODULE_5__.ContentBinary(photo);
          diagram = diagram + `<div class='image'><img src='${mappedPhoto.src}' /></div>`;
        });
        entity.photos_B64.forEach(photo => {
          diagram = diagram + `<div class='image'><img src='${photo}' /></div>`;
        });
        diagram = diagram + "</div></div>";
        return diagram;
      }
      return "";
    }
    renderPhotos(entity = null, entities = [], parentEntity = null, index = 1) {
      let entityNotes = "";
      if (entity != null) {
        let note = this.renderPhoto(entity, index, parentEntity);
        note = note + this.renderPhotos(null, entity.entities, entity, index + 1);
        entityNotes = entityNotes + note;
      } else {
        for (var i = 0, len = entities.length; i < len; i++) {
          const childEntity = entities[i];
          let note = this.renderPhoto(childEntity, index, parentEntity);
          index = index + 1;
          for (var j = 0, jlen = childEntity.fixtures.length; j < jlen; j++) {
            const fixture = childEntity.fixtures[j];
            note = note + this.renderPhoto(fixture, index, childEntity);
          }
          note = note + this.renderPhotos(null, childEntity.entities, childEntity, index);
          entityNotes = entityNotes + note;
        }
      }
      return entityNotes;
    }
    replacePhotos(matchText, content) {
      if (this.appointmentContent?.property?.entity != null) {
        let photos = `<div class='inspection-photos'>
                <h2>Property Photos</h2>
                <div class='photos'>`;
        photos = photos + this.renderPhotos(this.appointmentContent.property.entity, [], null, 1) + "</div></div>";
        const regex = new RegExp(matchText, 'g');
        const replacement = photos;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Diagrams
    renderDiagram(entity, index, parentEntity = null) {
      if (entity.render_B64 != null) {
        let diagram = "";
        if (parentEntity != null) {
          if (parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Property && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Structure && parentEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Floor) {
            diagram = `<div class='inspection-diagram'>
                        <h3>${parentEntity.name} ${parentEntity.number}</h3>
                        <h4>${entity.name} ${entity.number} Details</h4>
                        <div class='image'><img src='${entity.render_B64}' /></div>`;
          } else {
            diagram = `<div class='inspection-diagram'>
                        <h3>${parentEntity.name}</h3>
                        <h4>${entity.name} Diagram</h4>
                        <div class='image'><img src='${entity.render_B64}' /></div>`;
          }
        } else {
          diagram = `<div class='inspection-diagram'>
                    <h3>${entity.name}</h3>
                    <div class='image'><img src='${entity.render_B64}' /></div>`;
        }
        diagram = diagram + "</div>";
        return diagram;
      }
      return "";
    }
    getDiagrams(entity = null, entities = [], parentEntity = null, index = 1) {
      let entityNotes = "";
      if (entity != null) {
        let note = this.renderDiagram(entity, index, parentEntity);
        note = note + this.getDiagrams(null, entity.entities, entity, index + 1);
        entityNotes = entityNotes + note;
      } else {
        for (var i = 0, len = entities.length; i < len; i++) {
          const childEntity = entities[i];
          if (childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Structure && childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
            let note = this.renderDiagram(childEntity, index, parentEntity);
            index = index + 1;
            note = note + this.getDiagrams(null, childEntity.entities, childEntity, index);
            entityNotes = entityNotes + note;
          } else if (childEntity.type != src_app_shared_properties_models_property__WEBPACK_IMPORTED_MODULE_3__.PropertyEntityType.Room) {
            index = index + 1;
            const note = this.getDiagrams(null, childEntity.entities, childEntity, index);
            entityNotes = entityNotes + note;
          }
        }
      }
      return entityNotes;
    }
    replaceDiagrams(matchText, content) {
      if (this.appointmentContent?.property?.entity != null) {
        let diagrams = `<div class='inspection-diagrams'>
                <h2>Property Diagrams</h2>
                <div class='diagrams'>`;
        diagrams = diagrams + this.getDiagrams(this.appointmentContent.property.entity, [], null, 1) + "</div></div>";
        const regex = new RegExp(matchText, 'g');
        const replacement = diagrams;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Notes
    renderNote(precursor = "", entity, index, type) {
      switch (type) {
        case "customer":
          {
            const customerNote = entity.notes[src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_1__.NoteAudience.Customer];
            if (customerNote != null) {
              if (this.document?.customerFacing) {
                return `<div class='customer-note'>
                        <label>${index}) ${precursor}${entity.name} Note</label>
                        <span class='value'>${entity.notes[src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_1__.NoteAudience.Customer]}</span>
                        </div>
                        {{initial.customer.mandatory}}`;
              } else {
                return `<div class='customer-note'>
                        <label>${index}) ${precursor}${entity.name} Note</label>
                        <span class='value'>${entity.notes[src_app_shared_appointments_models_appointment__WEBPACK_IMPORTED_MODULE_1__.NoteAudience.Customer]}</span>
                        </div>`;
              }
            }
          }
          break;
      }
      return "";
    }
    getNotes(entity = null, entities = [], index = 1, type) {
      let entityNotes = "";
      if (entity != null) {
        let note = this.renderNote("", entity, index, type);
        for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
          const fixture = entity.fixtures[j];
          index = index + 1;
          note = note + this.renderNote(`${entity.name} `, fixture, index, type);
        }
        note = note + this.getNotes(null, entity.entities, index + 1, type);
        entityNotes = entityNotes + note;
      } else {
        for (var i = 0, len = entities.length; i < len; i++) {
          const entity = entities[i];
          let note = this.renderNote("", entity, index, type);
          index = index + 1;
          for (var j = 0, jlen = entity.fixtures.length; j < jlen; j++) {
            const fixture = entity.fixtures[j];
            note = note + this.renderNote(`${entity.name} `, fixture, index, type);
            index = index + 1;
          }
          note = note + this.getNotes(null, entity.entities, index, type);
          entityNotes = entityNotes + note;
        }
      }
      return entityNotes;
    }
    replaceNotes(matchText, content, type) {
      if (this.appointmentContent?.property?.entity != null) {
        const notes = this.getNotes(this.appointmentContent.property.entity, [], 1, type);
        const regex = new RegExp(matchText, 'g');
        let replacement = notes;
        if (replacement == "") {
          if (this.document?.customerFacing) {
            replacement = "<p>No additional notes indicated.</p>{{initial.customer.mandatory}}";
          }
        }
        content = content.replace(regex, replacement);
      }
      return content;
    }
    generateCheckboxHtml(signer, mandatory = false) {
      let replacement = "";
      switch (signer) {
        case "customer":
          {
            const customerName = `${this.customer?.firstName} ${this.customer?.lastName}`;
            if (mandatory) {
              replacement = `<div signer='${customerName}' class='checkbox mandatory customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                            <i class="fa-regular fa-square unchecked"></i>
                            <i class="fa-regular fa-square-check checked"></i>
                            <label>Signatory: ${customerName}</label>
                        </div>`;
            } else {
              replacement = `<div signer='${customerName}' class='checkbox optional customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                            <i class="fa-regular fa-square unchecked"></i>
                            <i class="fa-regular fa-square-check checked"></i>
                            <label>Signatory: ${customerName}</label>
                        </div>`;
            }
          }
          break;
        case "consultant":
          {
            if (mandatory) {
              replacement = `<div signer='${this.consultant?.fullName}' class='checkbox mandatory customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                            <i class="fa-regular fa-square unchecked"></i>
                            <i class="fa-regular fa-square-check checked"></i>
                            <label>Signatory: Repipe Consultant</label>
                        </div>`;
            } else {
              replacement = `<div signer='${this.consultant?.fullName}' class='checkbox optional customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                            <i class="fa-regular fa-square unchecked"></i>
                            <i class="fa-regular fa-square-check checked"></i>
                            <label>Signatory: Repipe Consultant</label>
                        </div>`;
            }
          }
          break;
      }
      return replacement;
    }
    replaceCheckboxes(matchText, content, signer, mandatory = false) {
      const pattern = new RegExp(matchText, 'g');
      let match;
      while ((match = pattern.exec(content)) !== null) {
        const replacement = this.generateCheckboxHtml(signer, mandatory);
        content = content.replace(match[0], replacement);
      }
      return content;
    }
    generateTextboxHtml(signer, mandatory) {
      let replacement = "";
      switch (signer) {
        case "customer":
          {
            const customerName = `${this.customer?.firstName} ${this.customer?.lastName}`;
            if (mandatory) {
              replacement = `<div signer='${customerName}' class='input mandatory customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <textarea maxlength='100' rows='3' required='true'></textarea>
                        <label>Signatory: ${customerName}</label>
                        </div>`;
            } else {
              replacement = `<div signer='${customerName}' class='input optional customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <textbox maxlength='100' rows='3' required='false'></textarea>
                        <label>Signatory: ${customerName}</label>
                    </div>`;
            }
          }
          break;
        case "consultant":
          {
            if (mandatory) {
              replacement = `<div signer='${this.consultant?.fullName}' class='input mandatory consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <textarea maxlength='100' rows='3' required='true'></textarea>
                        <label>Signatory: Repipe Consultant</label>
                        </div>`;
            } else {
              replacement = `<div signer='${this.consultant?.fullName}' class='input optional consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <textarea maxlength='100' rows='3' required='false'></textarea>
                        <label>Signatory: Repipe Consultant</label>
                    </div>`;
            }
          }
          break;
      }
      return replacement;
    }
    replaceTextbox(matchText, content, signer, mandatory = false) {
      const pattern = new RegExp(matchText, 'g');
      let match;
      while ((match = pattern.exec(content)) !== null) {
        const replacement = this.generateTextboxHtml(signer, mandatory);
        content = content.replace(match[0], replacement);
      }
      return content;
    }
    initInputElms() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null) {
        const checkboxElms = viewerElm.querySelectorAll(`.checkbox`);
        checkboxElms.forEach(checkboxElm => {
          checkboxElm.addEventListener('click', () => {
            const signer = checkboxElm.getAttribute('signer');
            const fieldId = checkboxElm.getAttribute('field');
            if (signer != null && fieldId != null && this.document != null) {
              const checked = checkboxElm.classList.contains("checked");
              const checkboxContent = this.documentService.initUserContent(signer, fieldId, this.document.id);
              if (checked) {
                checkboxElm.classList.remove("checked");
                checkboxContent.content = "false";
                if (checkboxElm.classList.contains("mandatory")) {
                  checkboxElm.classList.remove("valid");
                }
              } else {
                checkboxElm.classList.add("checked");
                checkboxElm.classList.add("valid");
                checkboxContent.content = "true";
              }
              this.storeUserContent(checkboxContent);
            }
          });
        });
        const inputElms = viewerElm.querySelectorAll('.input');
        inputElms.forEach(inputElm => {
          const input = inputElm.querySelector("input,textarea");
          if (input != null) {
            input.addEventListener("input", () => {
              const signer = inputElm.getAttribute('signer');
              const fieldId = inputElm.getAttribute('field');
              if (signer != null && fieldId != null && this.document != null) {
                const inputContent = this.documentService.initUserContent(signer, fieldId, this.document.id);
                inputContent.content = input.value;
                if (input.value.length > 0) {
                  inputElm.classList.add("valid");
                } else {
                  inputElm.classList.remove("valid");
                }
                this.storeUserContent(inputContent);
              }
            });
          }
        });
      }
    }
    storeUserContent(userContent) {
      if (this.document != null) {
        const existingIndex = this.document.userContent.findIndex(x => x.fieldId == userContent.fieldId);
        if (existingIndex > 0) {
          this.document.userContent[existingIndex] = userContent;
        } else {
          this.document.userContent.push(userContent);
        }
        this.changed$.next();
      }
    }
    restoreUserContent() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (this.document != null && viewerElm != null) {
        const missingContent = [];
        for (var i = 0, len = this.document.userContent.length; i < len; i++) {
          const userContent = this.document.userContent[i];
          const fieldElm = viewerElm.querySelector(`[field="${userContent.fieldId}"]`);
          let missing = fieldElm == null;
          if (fieldElm != null) {
            if (fieldElm.classList.contains("checkbox")) {
              if (userContent.content == "true") {
                fieldElm.classList.add("checked");
                fieldElm.classList.add("valid");
              } else {
                fieldElm.classList.remove("checked");
                if (fieldElm.classList.contains("mandatory")) {
                  fieldElm.classList.remove("valid");
                }
              }
            } else if (fieldElm.classList.contains("input")) {
              const input = fieldElm.querySelector("input,textarea");
              if (input != null) {
                input.value = userContent.content ?? "";
                if (input.value.length > 0) {
                  fieldElm.classList.add("valid");
                }
              }
            }
            fieldElm.classList.add('valid');
          }
          if (missing) {
            missingContent.push(i);
          }
        }
        missingContent.forEach(i => {
          if (this.document != null) {
            this.document.userContent = this.document.userContent.splice(i, 1);
            this.changed$.next();
          }
        });
        this.setDocumentValidity();
      }
    }
    validateUserContent() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null) {
        let valid = true;
        const checkboxElms = viewerElm.querySelectorAll(`.checkbox`);
        checkboxElms.forEach(elm => {
          if (elm.classList.contains("mandatory") && !elm.classList.contains("valid")) {
            valid = false;
          }
        });
        const inputElms = viewerElm.querySelectorAll(`.input`);
        inputElms.forEach(elm => {
          if (elm.classList.contains("mandatory") && !elm.classList.contains("valid")) {
            valid = false;
          }
        });
        this.userContentValid = valid;
      }
    }
    watchInitials() {
      this.initialSubscription = this.documentService.initials.subscribe({
        next: update => {
          if (update.signature?.signature_B64 != null && update.signer != null) {
            this.renderInitials(update.signature, update.signer);
          }
        }
      });
    }
    storeSignerInitials(signer, initials_B64) {
      signer.initials_B64 = initials_B64;
    }
    renderInitials(initials, signer) {
      const viewerElm = this.viewerElm?.nativeElement;
      if (initials?.signature_B64 != null && viewerElm != null) {
        this.storeSignerInitials(signer, initials.signature_B64);
        this.storeSignature(initials);
        const fieldElm = viewerElm.querySelector(`.initials[field='${initials.fieldId}']`);
        const renderElm = fieldElm?.querySelector('.render');
        if (fieldElm != null && renderElm != null) {
          const html = `
                    <canvas width='4' height='3'></canvas>
                    <img src='${initials.signature_B64}' />
                    <div class='hash'>
                        ${initials.hash_SHA256}
                    </div>
                    <div class='timestamp'>
                        ${initials.timeStamp_Utc}
                    </div>
                `;
          renderElm.innerHTML = html;
          fieldElm.classList.add('valid');
        }
      }
      this.setDocumentValidity();
    }
    startInitialing(fieldId = null, name = null) {
      const signer = this.document?.signers.find(x => x.fullName == name);
      if (signer != null && fieldId != null) {
        this.documentService.startInitialing(signer, fieldId);
      }
    }
    generateInitialHtml(signer, mandatory) {
      let replacement = "";
      switch (signer) {
        case "customer":
          {
            const customerName = `${this.customer?.firstName} ${this.customer?.lastName}`;
            if (mandatory) {
              replacement = `<div signer='${customerName}' class='initials mandatory customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='4' height='3'></canvas>
                        </div>
                        <label>Signatory: ${customerName}</label>
                        </div>`;
            } else {
              replacement = `<div signer='${customerName}' class='initials optional customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='4' height='3'></canvas>
                        </div>
                        <label>Signatory: ${customerName}</label>
                        </div>`;
            }
          }
          break;
        case "consultant":
          {
            if (mandatory) {
              replacement = `<div signer='${this.consultant?.fullName}' class='initials mandatory consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='4' height='3'></canvas>
                        </div>
                        <label>Signatory: Repipe Consultant</label>
                        </div>`;
            } else {
              replacement = `<div signer='${this.consultant?.fullName}' class='initials optional consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='4' height='3'></canvas>
                        </div>
                        <label>Signatory: Repipe Consultant</label>
                        </div>`;
            }
          }
          break;
      }
      return replacement;
    }
    replaceInitials(matchText, content, signer, mandatory = false) {
      const pattern = new RegExp(matchText, 'g');
      let match;
      while ((match = pattern.exec(content)) !== null) {
        const replacement = this.generateInitialHtml(signer, mandatory);
        content = content.replace(match[0], replacement);
      }
      return content;
    }
    initIntialElms() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null) {
        const initialElms = viewerElm.querySelectorAll(`.initials`);
        this.initialCount = initialElms.length;
        initialElms.forEach(initialElm => {
          const signer = initialElm.getAttribute('signer');
          if (this.appointmentContent?.recipient == null || this.appointmentContent.recipient.fullName == signer) {
            const renderElm = initialElm.querySelector('.render');
            if (renderElm != null) {
              renderElm.addEventListener('click', () => {
                const signer = initialElm.getAttribute('signer');
                const fieldId = initialElm.getAttribute('field');
                this.startInitialing(fieldId, signer);
              });
            }
          } else {
            initialElm.classList.add('disabled');
          }
        });
      }
    }
    watchSignatures() {
      this.signatureSubscription = this.documentService.signature.subscribe({
        next: update => {
          if (update.signature?.signature_B64 != null && update.signer != null) {
            this.renderSignature(update.signature, update.signer);
          }
        }
      });
    }
    storeSignerSignature(signer, signature_B64) {
      signer.signature_B64 = signature_B64;
    }
    renderSignature(signature, signer) {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null && signature.signature_B64 != null) {
        this.storeSignerSignature(signer, signature.signature_B64);
        this.storeSignature(signature);
        const signatureElm = viewerElm.querySelector(`.signature[field='${signature.fieldId}']`);
        const renderElm = signatureElm?.querySelector(".render");
        if (signatureElm != null && renderElm != null) {
          const html = `
                    <canvas width='16' height='6'></canvas>
                    <img src='${signature.signature_B64}' />
                    <div class='hash'>
                        ${signature.hash_SHA256}
                    </div>
                    <div class='timestamp'>
                        ${signature.timeStamp_Utc}
                    </div>
                `;
          renderElm.innerHTML = html;
          signatureElm.classList.add('valid');
        }
      }
      this.setDocumentValidity();
    }
    startSigning(fieldId = null, name) {
      const signer = this.document?.signers.find(x => x.fullName == name);
      if (signer != null && fieldId != null) {
        this.documentService.startSigning(signer, fieldId);
      }
    }
    generateSignatureHtml(signer, mandatory) {
      let replacement = "";
      switch (signer) {
        case "customer":
          {
            const customerName = `${this.customer?.firstName} ${this.customer?.lastName}`;
            if (mandatory) {
              replacement = `<div signer='${customerName}' class='signature mandatory customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='2' height='1'></canvas>
                        </div>
                        <label>Signatory: ${customerName}</label>
                        </div>`;
            } else {
              replacement = `<div signer='${customerName}' class='signature optional customer' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='2' height='1'></canvas>
                        </div>
                        <label>Signatory: ${customerName}</label>
                        </div>`;
            }
          }
          break;
        case "consultant":
          {
            if (mandatory) {
              replacement = `<div signer='${this.consultant?.fullName}' class='signature mandatory consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='2' height='1'></canvas>
                        </div>
                        <label>Signatory: Repipe Consultant</label>
                        </div>`;
            } else {
              replacement = `<div signer='${this.consultant?.fullName}' class='signature optional consultant' field='${(0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.generateId)()}'>
                        <div class='render'>
                            <canvas width='2' height='1'></canvas>
                        </div>
                        <label>Signatory: Repipe Consultant</label>
                        </div>`;
            }
          }
          break;
      }
      return replacement;
    }
    replaceSignature(matchText, content, signer, mandatory = false) {
      const pattern = new RegExp(matchText, 'g');
      let match;
      let counter = 1;
      while ((match = pattern.exec(content)) !== null) {
        const replacement = this.generateSignatureHtml(signer, mandatory);
        content = content.replace(match[0], replacement);
      }
      return content;
    }
    initSignatureElms() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null) {
        const signatureElms = viewerElm.querySelectorAll(`.signature`);
        this.signatureCount = signatureElms.length;
        signatureElms.forEach(signatureElm => {
          const signer = signatureElm.getAttribute('signer');
          if (this.appointmentContent?.recipient == null || this.appointmentContent.recipient.fullName == signer) {
            const renderElm = signatureElm.querySelector('.render');
            if (renderElm != null) {
              renderElm.addEventListener('click', () => {
                const name = signatureElm.getAttribute('signer');
                const fieldId = signatureElm.getAttribute('field');
                this.startSigning(fieldId, name);
              });
            }
          } else {
            signatureElm.classList.add('disabled');
          }
        });
      }
    }
    restoreSignatures() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (this.document != null && viewerElm != null) {
        const missingSignatures = [];
        for (var i = 0, len = this.document.signatures.length; i < len; i++) {
          const signature = this.document.signatures[i];
          const fieldElm = viewerElm.querySelector(`[field="${signature.fieldId}"]`);
          const renderElm = fieldElm?.querySelector('.render');
          if (fieldElm != null && renderElm != null) {
            let html = "";
            if (fieldElm.classList.contains("initials")) {
              html = `
                            <canvas width='4' height='3'></canvas>
                            <img src='${signature.signature_B64}' />
                            <div class='hash'>
                                ${signature.hash_SHA256}
                            </div>
                            <div class='timestamp'>
                                ${signature.timeStamp_Utc}
                            </div>
                        `;
            } else {
              html = `
                            <canvas width='16' height='6'></canvas>
                            <img src='${signature.signature_B64}' />
                            <div class='hash'>
                                ${signature.hash_SHA256}
                            </div>
                            <div class='timestamp'>
                                ${signature.timeStamp_Utc}
                            </div>
                        `;
            }
            renderElm.innerHTML = html;
            fieldElm.classList.add('valid');
          } else {
            missingSignatures.push(i);
          }
        }
        missingSignatures.forEach(i => {
          if (this.document != null) {
            this.document.signatures = this.document.signatures.splice(i, 1);
            this.changed$.next();
          }
        });
        this.setDocumentValidity();
      }
    }
    storeSignature(signature) {
      if (this.document != null) {
        const existingSignatureIndex = this.document.signatures.findIndex(x => x.fieldId == signature.fieldId);
        if (existingSignatureIndex > 0) {
          this.document.signatures[existingSignatureIndex] = signature;
        } else {
          this.document.signatures.push(signature);
        }
        this.changed$.next();
      }
    }
    validateSignatures() {
      const viewerElm = this.viewerElm?.nativeElement;
      if (viewerElm != null) {
        let valid = true;
        const signatureElms = viewerElm.querySelectorAll('.signature,.initials');
        signatureElms.forEach(elm => {
          if (elm.classList.contains("mandatory") && !elm.classList.contains("valid")) {
            valid = false;
          }
        });
        this.signaturesValid = valid;
      }
    }
    // #endregion
    // #region Headers
    replaceHeaders(content) {
      content = this.replaceH1(content);
      content = this.replaceH2(content);
      content = this.replaceH3(content);
      content = this.replaceH4(content);
      content = this.replaceH5(content);
      return content;
    }
    replaceH1(content) {
      const openH2Regex = /(&lt;h1&gt;)/gi;
      const closeH2Regex = /(&lt;\/h1&gt;)/gi;
      content = content.replace(openH2Regex, '<h1>');
      content = content.replace(closeH2Regex, '</h1>');
      return content;
    }
    replaceH2(content) {
      const openH2Regex = /(&lt;h2&gt;)/gi;
      const closeH2Regex = /(&lt;\/h2&gt;)/gi;
      content = content.replace(openH2Regex, '<h2>');
      content = content.replace(closeH2Regex, '</h2>');
      return content;
    }
    replaceH3(content) {
      const openH2Regex = /(&lt;h3&gt;)/gi;
      const closeH2Regex = /(&lt;\/h3&gt;)/gi;
      content = content.replace(openH2Regex, '<h3>');
      content = content.replace(closeH2Regex, '</h3>');
      return content;
    }
    replaceH4(content) {
      const openH2Regex = /(&lt;h4&gt;)/gi;
      const closeH2Regex = /(&lt;\/h4&gt;)/gi;
      content = content.replace(openH2Regex, '<h4>');
      content = content.replace(closeH2Regex, '</h4>');
      return content;
    }
    replaceH5(content) {
      const openH2Regex = /(&lt;h5&gt;)/gi;
      const closeH2Regex = /(&lt;\/h5&gt;)/gi;
      content = content.replace(openH2Regex, '<h5>');
      content = content.replace(closeH2Regex, '</h5>');
      return content;
    }
    // #endregion
    // #region Text Styling
    replaceTextTags(content) {
      const openH2Regex = /(&lt;strong&gt;)/gi;
      const closeH2Regex = /(&lt;\/strong&gt;)/gi;
      content = content.replace(openH2Regex, '<strong>');
      content = content.replace(closeH2Regex, '</strong>');
      return content;
    }
    replaceTextSizes(content) {
      const applyClassToParent = (variable, size) => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(`<div>${content}</div>`, 'text/html');
        const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);
        let nodesToProcess = [];
        while (walker.nextNode()) {
          const node = walker.currentNode;
          if (node.nodeValue?.includes(variable)) {
            nodesToProcess.push(node);
          }
        }
        nodesToProcess.forEach(node => {
          node.nodeValue = node.nodeValue?.replace(/\[\[fontSize\.large\]\]/gi, '') ?? null;
          const parent = node.parentElement;
          const grandParent = parent?.parentElement; // Account for generated p tags
          if (grandParent) {
            const existingClass = grandParent.getAttribute('class') || '';
            grandParent.setAttribute('class', existingClass ? `${existingClass} font-${size}` : `font-${size}`);
            parent.remove();
          }
        });
        return doc.body.innerHTML;
      };
      content = applyClassToParent("[[fontSize.small]]", "small");
      content = applyClassToParent("[[fontSize.medium]]", "medium");
      content = applyClassToParent("[[fontSize.large]]", "large");
      return content;
    }
    // #endregion
    // #region Horizontal Rows
    replaceHr(content) {
      const hrRegex = /{{hr}}/gi;
      content = content.replace(hrRegex, '<hr />');
      return content;
    }
    // #endregion
    // #region Labels
    replaceLabels(content) {
      const labelRegex = /(&lt;label&gt;)/gi;
      content = content.replace(labelRegex, '<label>');
      const endLabelRegex = /(&lt;\/label&gt;)/gi;
      content = content.replace(endLabelRegex, '</label>');
      return content;
    }
    // #endregion
    // #region Lists
    replaceLists(content) {
      content = this.replaceListVariables(content);
      const startRegex = /\[\[startList\]\]/gi;
      const startReplacement = `<div class='list'>`;
      const endRegex = /\[\[endList\]\]/gi;
      const endReplacement = `</div>`;
      content = content.replace(startRegex, startReplacement);
      return content.replace(endRegex, endReplacement);
    }
    replaceListVariables(content) {
      const tableRegex = /\[\[startList\]\]([\s\S]*?)\[\[endList\]\]/;
      const match = content.match(tableRegex);
      if (match != null && match[1] != null) {
        const tableContent = this.removeEmptyTags(match[1]);
        const replacedContent = tableContent.replace(/\{\{(.*?)\}\}/g, (match, variable) => {
          return `<div class='list-item'>{{${variable}}}</div>`;
        });
        return content.replace(tableRegex, `[[startList]]${replacedContent}[[endList]]`);
      }
      return content;
    }
    // #endregion
    // #region Rows
    replaceRows(content) {
      const startRegex = /\[\[startRow\]\]/gi;
      const startReplacement = `<div class='row'>`;
      const endRegex = /\[\[endRow\]\]/gi;
      const endReplacement = `</div>`;
      content = content.replace(startRegex, startReplacement);
      return content.replace(endRegex, endReplacement);
    }
    // #endregion
    // #region Alignment
    replaceAlignment(content) {
      if (content.includes("startAlign.right")) {
        const startRegex = /\[\[startAlign.right\]\]/gi;
        const startReplacement = `<div class='align-right'>`;
        content = content.replace(startRegex, startReplacement);
        const endRegex = /\[\[endAlign.right\]\]/gi;
        const endReplacement = `</div>`;
        content = content.replace(endRegex, endReplacement);
      }
      if (content.includes("startAlign.left")) {
        const startRegex = /\[\[startAlign.left\]\]/gi;
        const startReplacement = `<div class='align-left'>`;
        content = content.replace(startRegex, startReplacement);
        const endRegex = /\[\[endAlign.left\]\]/gi;
        const endReplacement = `</div>`;
        content = content.replace(endRegex, endReplacement);
      }
      if (content.includes("startAlign.centered")) {
        const startRegex = /\[\[startAlign.center\]\]/gi;
        const startReplacement = `<div class='align-center'>`;
        content = content.replace(startRegex, startReplacement);
        const endRegex = /\[\[endAlign.center\]\]/gi;
        const endReplacement = `</div>`;
        content = content.replace(endRegex, endReplacement);
      }
      if (content.includes("startAlign.justified")) {
        const startRegex = /\[\[startAlign.justify\]\]/gi;
        const startReplacement = `<div class='align-justify'>`;
        content = content.replace(startRegex, startReplacement);
        const endRegex = /\[\[endAlign.justify\]\]/gi;
        const endReplacement = `</div>`;
        content = content.replace(endRegex, endReplacement);
      }
      return content;
    }
    // #endregion
    // #region Blocks
    replaceBlocks(content) {
      const startRegex = /\[\[startBlock\]\]/gi;
      const startReplacement = `<div class='block'>`;
      const endRegex = /\[\[endBlock\]\]/gi;
      const endReplacement = `</div>`;
      content = content.replace(startRegex, startReplacement);
      return content.replace(endRegex, endReplacement);
    }
    // #endregion
    // #region Tables
    replaceTables(content) {
      content = this.replaceTableVariables(content);
      const startRegex = /\[\[startTable\]\]/gi;
      const startReplacement = `<table class='standard'><tbody>`;
      const endRegex = /\[\[endTable\]\]/gi;
      const endReplacement = `</tbody></table>`;
      content = content.replace(startRegex, startReplacement);
      return content.replace(endRegex, endReplacement);
    }
    replaceTableVariables(content) {
      const tableRegex = /\[\[startTable\]\]([\s\S]*?)\[\[endTable\]\]/g;
      const matches = Array.from(content.matchAll(tableRegex)).map(match => match[1]);
      for (var i = 0, len = matches.length; i < len; i++) {
        const match = matches[i];
        const replacedContent = match.replace(/\{\{(.*?)\}\}/gi, (m, variable) => {
          if (variable.indexOf('initial') < 0 && variable.indexOf('signature') < 0) {
            return `<tr><td class='label'>{{${variable}.label}}</td><td>{{${variable}}}</td></td>`;
          }
          return `{{${variable}}}`;
        });
        content = content.replace(match, replacedContent);
      }
      return content;
    }
    // #endregion
    // #region Payments
    get payments() {
      return this.appointmentContent?.payments ?? [];
    }
    replacePayments(content) {
      const firstPayment = this.payments[0];
      if (firstPayment != null) {
        const labelRegex = /{{appointment.payments.first.amount.label}}/gi;
        const labelReplacement = `${firstPayment.description}`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.first.amount}}/gi;
        const amount = this.currencyPipe.transform(firstPayment.amount, 'USD', 'symbol', '1.2-2') || '';
        const replacement = `${amount}`;
        content = content.replace(regex, replacement);
      } else {
        const labelRegex = /{{appointment.payments.first.amount.label}}/gi;
        const labelReplacement = ``;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.first.amount}}/gi;
        const replacement = ``;
        content = content.replace(regex, replacement);
      }
      const secondPayment = this.payments[1];
      if (secondPayment != null) {
        const labelRegex = /{{appointment.payments.second.amount.label}}/gi;
        const labelReplacement = `${secondPayment.description}`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.second.amount}}/gi;
        const amount = this.currencyPipe.transform(secondPayment.amount, 'USD', 'symbol', '1.2-2') || '';
        const replacement = `${amount}`;
        content = content.replace(regex, replacement);
      } else {
        const labelRegex = /{{appointment.payments.second.amount.label}}/gi;
        const labelReplacement = ``;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.second.amount}}/gi;
        const replacement = ``;
        content = content.replace(regex, replacement);
      }
      const thirdPayment = this.payments[2];
      if (thirdPayment != null) {
        const labelRegex = /{{appointment.payments.third.amount.label}}/gi;
        const labelReplacement = `${thirdPayment.description}`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.third.amount}}/gi;
        const amount = this.currencyPipe.transform(thirdPayment.amount, 'USD', 'symbol', '1.2-2') || '';
        const replacement = `${amount}`;
        content = content.replace(regex, replacement);
      } else {
        const labelRegex = /{{appointment.payments.third.amount.label}}/gi;
        const labelReplacement = ``;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.third.amount}}/gi;
        const replacement = ``;
        content = content.replace(regex, replacement);
      }
      const fourthPayment = this.payments[4];
      if (fourthPayment != null) {
        const labelRegex = /{{appointment.payments.fourth.amount.label}}/gi;
        const labelReplacement = `${fourthPayment.description}`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.fourth.amount}}/gi;
        const amount = this.currencyPipe.transform(fourthPayment.amount, 'USD', 'symbol', '1.2-2') || '';
        const replacement = `${amount}`;
        content = content.replace(regex, replacement);
      } else {
        const labelRegex = /{{appointment.payments.fourth.amount.label}}/gi;
        const labelReplacement = ``;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{appointment.payments.fourth.amount}}/gi;
        const replacement = ``;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Pricing
    get price() {
      return this.appointmentContent?.price;
    }
    replaceFinalPrice(content) {
      const labelRegex = /{{appointment.price.final.label}}/gi;
      const labelReplacement = `Contract Price`;
      content = content.replace(labelRegex, labelReplacement);
      const priceRegex = /{{appointment.price.final}}/gi;
      if (this.price != null) {
        const price = this.currencyPipe.transform(this.price.price, 'USD', 'symbol', '1.2-2') || '';
        content = content.replace(priceRegex, `${price}`);
      } else {
        content = content.replace(priceRegex, ``);
      }
      return content;
    }
    // #endregion   
    // #region Customer
    get customer() {
      return this.appointmentContent?.customer;
    }
    get email() {
      if (this.customer != null) {
        for (var i = 0, len = this.customer.contactInformation.length; i < len; i++) {
          const contactInfo = this.customer.contactInformation[i];
          if (contactInfo.type == src_app_shared_contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.Email) {
            return contactInfo.value;
          }
        }
      }
      return "";
    }
    get cellPhone() {
      if (this.customer != null) {
        for (var i = 0, len = this.customer.contactInformation.length; i < len; i++) {
          const contactInfo = this.customer.contactInformation[i];
          if (contactInfo.type == src_app_shared_contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.CellPhone) {
            return contactInfo.value;
          }
        }
      }
      return "";
    }
    get homePhone() {
      if (this.customer != null) {
        for (var i = 0, len = this.customer.contactInformation.length; i < len; i++) {
          const contactInfo = this.customer.contactInformation[i];
          if (contactInfo.type == src_app_shared_contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.HomePhone) {
            return contactInfo.value;
          }
        }
      }
      return "";
    }
    replaceCustomerName(content) {
      if (this.customer != null) {
        const labelRegex = /{{customer.name.label}}/gi;
        const labelReplacement = `Customer Name`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{customer.name}}/gi;
        const replacement = `${this.customer.firstName} ${this.customer.lastName}`;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    replaceCustomerEmail(content) {
      if (this.customer != null) {
        const labelRegex = /{{customer.email.label}}/gi;
        const labelReplacement = `Customer E-Mail`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{customer.email}}/gi;
        const replacement = this.email;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    replaceCustomerPhone(content) {
      if (this.customer != null) {
        const cellLabelRegex = /{{customer.phone.cell.label}}/gi;
        const cellLabelReplacement = `Customer Cell Phone`;
        content = content.replace(cellLabelRegex, cellLabelReplacement);
        const cellRegex = /{{customer.phone.cell}}/gi;
        const cellReplacement = this.cellPhone;
        content = content.replace(cellRegex, cellReplacement);
        const homeLabelRegex = /{{customer.phone.home.label}}/gi;
        const homeLabelReplacement = `Customer Home Phone`;
        content = content.replace(homeLabelRegex, homeLabelReplacement);
        const homeRegex = /{{customer.phone.home}}/gi;
        const homeReplacement = this.homePhone;
        content = content.replace(homeRegex, homeReplacement);
        const workLabelRegex = /{{customer.phone.work.label}}/gi;
        const workLabelReplacement = `Customer Work Phone`;
        content = content.replace(workLabelRegex, workLabelReplacement);
        const workRegex = /{{customer.phone.work}}/gi;
        const workReplacement = this.homePhone;
        content = content.replace(workRegex, workReplacement);
      }
      return content;
    }
    // #endregion
    // #region Consultant
    get consultant() {
      return this.appointmentContent?.consultant;
    }
    replaceConsultantName(content) {
      if (this.consultant != null) {
        const labelRegex = /{{consultant.name.label}}/gi;
        const labelReplacement = `Consultant Name`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{consultant.name}}/gi;
        const replacement = `${this.consultant.firstName} ${this.consultant.lastName}`;
        content = content.replace(regex, replacement);
      }
      return content;
    }
    replaceConsultantPhone(content) {
      if (this.consultant != null) {
        const labelRegex = /{{consultant.phone.label}}/gi;
        const labelReplacement = `Consultant Phone`;
        content = content.replace(labelRegex, labelReplacement);
        if (this.consultant.phone != null) {
          const regex = /{{consultant.phone}}/gi;
          const replacement = `${this.consultant.phone}`;
          content = content.replace(regex, replacement);
        } else {
          const regex = /{{consultant.phone}}/gi;
          content = content.replace(regex, "");
        }
      }
      return content;
    }
    replaceConsultantEmail(content) {
      if (this.consultant != null) {
        const labelRegex = /{{consultant.email.label}}/gi;
        const labelReplacement = `Consultant E-mail`;
        content = content.replace(labelRegex, labelReplacement);
        if (this.consultant.emailAddress) {
          const regex = /{{consultant.email}}/gi;
          const replacement = `${this.consultant.emailAddress}`;
          content = content.replace(regex, replacement);
        } else {
          const regex = /{{consultant.email}}/gi;
          content = content.replace(regex, "");
        }
      }
      return content;
    }
    // #endregion
    // #region Property
    get property() {
      return this.appointmentContent?.property;
    }
    get address() {
      if (this.property?.address != null) {
        return Object.assign(new src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_6__.Address(), this.property.address);
      }
      return undefined;
    }
    get billingAddress() {
      if (this.property?.address != null) {
        return Object.assign(new src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_6__.Address(), this.property.billingAddress);
      }
      return undefined;
    }
    get mailingAddress() {
      if (this.property?.address != null) {
        return Object.assign(new src_app_shared_addresses_models_address__WEBPACK_IMPORTED_MODULE_6__.Address(), this.property.mailingAddress);
      }
      return undefined;
    }
    replaceAddresses(content) {
      if (this.property?.address != null) {
        const labelRegex = /{{property.address.label}}/gi;
        const labelReplacement = `Property Address`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{property.address}}/gi;
        const replacement = this.address?.friendlyAddress ?? "";
        content = content.replace(regex, replacement);
      }
      if (this.property?.billingAddress != null) {
        const labelRegex = /{{property.billingaddress.label}}/gi;
        const labelReplacement = `Billing Address`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{property.billingaddress}}/gi;
        const replacement = this.billingAddress?.friendlyAddress ?? "";
        content = content.replace(regex, replacement);
      }
      if (this.property?.mailingAddress != null) {
        const labelRegex = /{{property.mailingaddress.label}}/gi;
        const labelReplacement = `Mailing Address`;
        content = content.replace(labelRegex, labelReplacement);
        const regex = /{{property.mailingaddress}}/gi;
        const replacement = this.mailingAddress?.friendlyAddress ?? "";
        content = content.replace(regex, replacement);
      }
      return content;
    }
    // #endregion
    // #region Content
    replaceLogo(content) {
      const regex = /{{logo}}/gi;
      const replacement = '<div class="logo"><img src="/assets/images/logo.svg" /></div>';
      return content.replace(regex, replacement);
    }
    replaceDocumentName(name, content) {
      const regex = /{{document.name}}/gi;
      const replacement = `<h2>${name}</h2>`;
      return content.replace(regex, replacement);
    }
    replaceCustomerDocumentsReceived(content) {
      const regex = /{{customer.documentsReceived}}/gi;
      let replacement = "<span class='note'>Documents received by Customer: ";
      for (var i = 0, len = this.documents.length; i < len; i++) {
        const document = this.documents[i];
        if (document.customerFacing) {
          if (i == 0) {
            replacement = replacement + `${document.name}`;
          } else {
            replacement = replacement + `, ${document.name}`;
          }
        }
      }
      replacement = replacement + "</span>";
      return content.replace(regex, replacement);
    }
    replaceAppointmentDates(content) {
      if (this.appointmentContent?.scheduled_Utc != null) {
        const labelRegex = /{{appointment.date.scheduled.label}}/gi;
        const labelReplacement = `Estimate Date`;
        content = content.replace(labelRegex, labelReplacement);
        const scheduledRegex = /{{appointment.date.scheduled}}/gi;
        const scheduledDate = new Date(this.appointmentContent.scheduled_Utc);
        const scheduledDateStr = `${scheduledDate.getUTCFullYear()}-${String(scheduledDate.getUTCMonth() + 1).padStart(2, '0')}-${String(scheduledDate.getUTCDate()).padStart(2, '0')} at ${String(scheduledDate.getUTCHours()).padStart(2, '0')}:${String(scheduledDate.getUTCMinutes()).padStart(2, '0')}:${String(scheduledDate.getUTCSeconds()).padStart(2, '0')} UTC`;
        content = content.replace(scheduledRegex, scheduledDateStr);
      }
      return content;
    }
    replaceTimestamp(content) {
      const labelRegex = /{{timestamp.label}}/gi;
      const labelReplacement = `Date`;
      content = content.replace(labelRegex, labelReplacement);
      const now = new Date();
      const utcDate = new Date(now.toISOString());
      const year = utcDate.getUTCFullYear();
      const month = String(utcDate.getUTCMonth() + 1).padStart(2, '0');
      const day = String(utcDate.getUTCDate()).padStart(2, '0');
      const hours = String(utcDate.getUTCHours()).padStart(2, '0');
      const minutes = String(utcDate.getUTCMinutes()).padStart(2, '0');
      const seconds = String(utcDate.getUTCSeconds()).padStart(2, '0');
      const tsRegex = /{{timestamp}}/gi;
      const tsReplacement = `${year}-${month}-${day} at ${hours}:${minutes}:${seconds} UTC`;
      content = content.replace(tsRegex, tsReplacement);
      const tsdRegex = /{{timestamp.date}}/gi;
      const tsdreplacement = `${day}`;
      content = content.replace(tsdRegex, tsdreplacement);
      const tsmRegex = /{{timestamp.month}}/gi;
      const tsmReplacement = `${month}`;
      content = content.replace(tsmRegex, tsmReplacement);
      const tsyRegex = /{{timestamp.year}}/gi;
      const tsyReplacement = `${year}`;
      content = content.replace(tsyRegex, tsyReplacement);
      return content;
    }
    replaceVariables(document, content) {
      const regex = /\{\{(.*?)\}\}/gi;
      const variables = [];
      let match;
      while ((match = regex.exec(content)) !== null) {
        variables.push(match[0]);
      }
      variables.forEach(variable => {
        if (variable.indexOf("customer.phone") > -1) {
          content = this.replaceCustomerPhone(content);
        }
        const sanitizedVariable = variable.toLowerCase();
        switch (sanitizedVariable) {
          case "{{logo}}":
            {
              content = this.replaceLogo(content);
            }
            break;
          case "{{document.name}}":
            {
              content = this.replaceDocumentName(document.name, content);
            }
            break;
          case "{{inspection.diagrams}}":
            {
              content = this.replaceDiagrams("{{inspection.diagrams}}", content);
            }
            break;
          case "{{inspection.photos}}":
            {
              content = this.replacePhotos("{{inspection.photos}}", content);
            }
            break;
          case "{{inspection.attributes}}":
            {
              content = this.replaceAttributes("{{inspection.attributes}}", content, false);
            }
            break;
          case "{{inspection.attributes.customer}}":
            {
              content = this.replaceAttributes("{{inspection.attributes.customer}}", content, true);
            }
            break;
          case "{{entity.details.label}}":
            {
              content = content.replaceAll("{{entity.details.label}}", "Property Details");
            }
            break;
          case "{{entity.details}}":
            {
              content = this.replaceEntityDetails("{{entity.details}}", content, false);
            }
            break;
          case "{{entity.details.shop}}":
            {
              content = this.replaceEntityDetails("{{entity.details.shop}}", content, false);
            }
            break;
          case "{{entity.details.customer}}":
            {
              content = this.replaceEntityDetails("{{entity.details.customer}}", content, true);
            }
            break;
          case "{{customer.name}}":
            {
              content = this.replaceCustomerName(content);
            }
            break;
          case "{{checkbox.customer.optional}}":
            {
              content = this.replaceCheckboxes("{{checkbox.customer.optional}}", content, 'customer', false);
            }
            break;
          case "{{checkbox.customer.mandatory}}":
            {
              content = this.replaceCheckboxes("{{checkbox.customer.mandatory}}", content, 'customer', true);
            }
            break;
          case "{{checkbox.consultant.optional}}":
            {
              content = this.replaceCheckboxes("{{checkbox.consultant.optional}}", content, 'consultant', false);
            }
            break;
          case "{{checkbox.consultant.mandatory}}":
            {
              content = this.replaceCheckboxes("{{checkbox.consultant.mandatory}}", content, 'consultant', true);
            }
            break;
          case "{{checkbox.consultant.mandatory}}":
            {
              content = this.replaceCheckboxes("{{checkbox.consultant.mandatory}}", content, 'consultant', true);
            }
            break;
          case "{{textbox.consultant.optional}}":
            {
              content = this.replaceTextbox("{{textbox.consultant.optional}}", content, 'consultant', false);
            }
            break;
          case "{{textbox.consultant.mandatory}}":
            {
              content = this.replaceTextbox("{{textbox.consultant.mandatory}}", content, 'consultant', true);
            }
            break;
          case "{{textbox.customer.optional}}":
            {
              content = this.replaceTextbox("{{textbox.customer.optional}}", content, 'customer', false);
            }
            break;
          case "{{textbox.customer.optional}}":
            {
              content = this.replaceTextbox("{{textbox.customer.mandatory}}", content, 'customer', true);
            }
            break;
          case "{{customer.email}}":
            {
              content = this.replaceCustomerEmail(content);
            }
            break;
          case "{{appointment.price.final}}":
            {
              content = this.replaceFinalPrice(content);
            }
            break;
          case "{{property.address}}":
            {
              content = this.replaceAddresses(content);
            }
            break;
          case "{{property.billingaddress}}":
            {
              content = this.replaceAddresses(content);
            }
            break;
          case "{{property.mailingaddress}}":
            {
              content = this.replaceAddresses(content);
            }
            break;
          case "{{consultant.name}}":
            {
              content = this.replaceConsultantName(content);
            }
            break;
          case "{{consultant.phone}}":
            {
              content = this.replaceConsultantPhone(content);
            }
            break;
          case "{{consultant.email}}":
            {
              content = this.replaceConsultantEmail(content);
            }
            break;
          case "{{appointment.jobid}}":
            {
              content = this.replaceJobId(content);
            }
            break;
          case "{{timestamp}}":
            {
              content = this.replaceTimestamp(content);
            }
            break;
          case "{{customer.documentsreceived}}":
            {
              content = this.replaceCustomerDocumentsReceived(content);
            }
            break;
          case "{{inspection.customernotes}}":
            {
              content = this.replaceNotes(variable, content, "customer");
            }
            break;
          case "{{signature.consultant.mandatory}}":
            {
              content = this.replaceSignature(variable, content, 'consultant', true);
            }
            break;
          case "{{signature.consultant.optional}}":
            {
              content = this.replaceSignature(variable, content, 'consultant', false);
            }
            break;
          case "{{initial.consultant.mandatory}}":
            {
              content = this.replaceInitials(variable, content, 'consultant', true);
            }
            break;
          case "{{initial.consultant.optional}}":
            {
              content = this.replaceInitials(variable, content, 'consultant', false);
            }
            break;
          case "{{signature.customer.mandatory}}":
            {
              content = this.replaceSignature(variable, content, 'customer', true);
            }
            break;
          case "{{signature.customer.optional}}":
            {
              content = this.replaceSignature(variable, content, 'customer', false);
            }
            break;
          case "{{initial.customer.mandatory}}":
            {
              content = this.replaceInitials(variable, content, 'customer', true);
            }
            break;
          case "{{initial.customer.optional}}":
            {
              content = this.replaceInitials(variable, content, 'customer', false);
            }
            break;
        }
      });
      return content;
    }
    removeEmptyTags(content) {
      const regex = /<\/?p>/gi;
      return content.replace(regex, '');
    }
    removeEmptyLines(content) {
      const pRegex = /<p>\s*(<[^>]+>[\s\S]*?)<\/p>|<p>\s*<\/p>/gi;
      content = content.replace(pRegex, (match, innerContent) => innerContent || '');
      const bRegex = /<br\s*\/?>(\s*(?=<[^>]+>))/gi;
      content = content.replace(bRegex, '');
      return content;
    }
    replaceParagraphs(content) {
      const pRegex = /<p>/gi;
      content = content.replace(pRegex, '<div class="paragraph">');
      const pCloseRegex = /<\/p>/gi;
      content = content.replace(pCloseRegex, '</div>');
      return content;
    }
    generateContent(document) {
      if (document.content != null) {
        let generatedContent = this.replaceLabels(document.content);
        generatedContent = this.replaceH2(generatedContent);
        generatedContent = this.replaceHr(generatedContent);
        generatedContent = this.replaceAlignment(generatedContent);
        generatedContent = this.replaceBlocks(generatedContent);
        generatedContent = this.replaceTables(generatedContent);
        generatedContent = this.replaceLists(generatedContent);
        generatedContent = this.replaceRows(generatedContent);
        generatedContent = this.replaceVariables(document, generatedContent);
        generatedContent = this.replaceVariables(document, generatedContent); // Shim to catch dynamically added variables
        generatedContent = this.replaceAppointmentDates(generatedContent);
        generatedContent = this.replacePayments(generatedContent);
        generatedContent = this.replaceAdditionalConsiderations(generatedContent);
        generatedContent = this.replaceHeaders(generatedContent);
        generatedContent = this.removeEmptyLines(generatedContent);
        generatedContent = this.replaceParagraphs(generatedContent);
        generatedContent = this.replaceTextTags(generatedContent);
        generatedContent = this.replaceTextSizes(generatedContent);
        generatedContent = generatedContent.replace(`<div class="paragraph">&nbsp;</div>`, "");
        return generatedContent;
      }
      return "";
    }
    processContent(document) {
      if (document.generatedContent != null && document.originalHash != null && document.originalHash == document.hash && !document.generatedContent.includes("{{")) {
        this.documentContent = this.sanitizer.bypassSecurityTrustHtml(document.generatedContent);
      } else if (document.content != null || document.documents != null && document.documents.length > 0) {
        let generatedContent = this.generateContent(document);
        if (document.documents != null) {
          for (var i = 0, len = document.documents.length; i < len; i++) {
            const childDoc = document.documents[i];
            generatedContent = generatedContent + this.generateContent(childDoc);
          }
        }
        this.documentContent = this.sanitizer.bypassSecurityTrustHtml(generatedContent);
        document.generatedContent = generatedContent;
        document.originalHash = document.hash;
      }
      setTimeout(() => {
        this.initSignatureElms();
        this.initIntialElms();
        this.initInputElms();
      }, 0);
      this.changed$.next();
    }
    get executedDocument() {
      return this.document?.executedDocument?.src ?? this.document?.executedDocument_B64 ?? "";
    }
    setDocumentValidity() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (_this.document != null) {
          _this.validateSignatures();
          _this.validateUserContent();
          if (_this.signaturesValid && _this.userContentValid) {
            yield _this.finalizeDocument();
          } else {
            _this.document.executedDocument_B64 = undefined;
            _this.changed$.next();
          }
        }
      })();
    }
    finalizeDocument() {
      setTimeout(() => {
        if (this.document != null) {
          this.document.executedHash == (0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.hashString)(JSON.stringify(this.document));
          // const viewerElm = this.viewerElm?.nativeElement;
          // if (viewerElm != null) {
          //     toPng(viewerElm, {
          //         quality: 1,
          //         pixelRatio: 1,
          //         backgroundColor: '#fff'
          //     }).then((b64) => {
          //         if (this.document != null) {
          //             this.document.executedDocument_B64 = b64;
          //             this.document.executedHash = hashString(b64);
          //             this.changed$.next();
          //         }
          //     }).catch((e) => {
          //         console.log(e);
          //     })
          // }
        }
      }, 0);
    }
    initDocument() {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (_this2.document != null) {
          if (_this2.document.executedDocument?.fileName == null || _this2.document.executedDocument_B64 == null) {
            if (_this2.document.dynamic) {
              _this2.processContent(_this2.document);
            } else if (_this2.document.mapping != null) {
              _this2.initMapping(_this2.document);
            }
            setTimeout(() => {
              _this2.watchSignatures();
              _this2.watchInitials();
              setTimeout(() => {
                _this2.restoreSignatures();
                _this2.restoreUserContent();
                _this2.setDocumentValidity();
              }, 16);
              _this2.finalizeDocument();
            }, 32);
            _this2.document.executedHash == (0,src_app_shared_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_7__.hashString)(JSON.stringify(_this2.document));
          } else {
            _this2.changed$.next();
          }
        }
      })();
    }
    init() {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this3.initDocument();
      })();
    }
    // #endregion
    ngOnInit() {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        yield _this4.init();
      })();
    }
    ngOnDestroy() {
      this.initialSubscription?.unsubscribe();
      this.signatureSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function AppointmentDocumentComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppointmentDocumentComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdirectiveInject"](src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_8__.UiService), _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdirectiveInject"](src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_9__.DocumentService), _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdirectiveInject"](src_app_shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_10__.ApiService), _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdirectiveInject"](_angular_common__WEBPACK_IMPORTED_MODULE_14__.CurrencyPipe), _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdirectiveInject"](_angular_platform_browser__WEBPACK_IMPORTED_MODULE_15__.DomSanitizer));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵdefineComponent"]({
      type: AppointmentDocumentComponent,
      selectors: [["appointment-document"]],
      viewQuery: function AppointmentDocumentComponent_Query(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵviewQuery"](_c0, 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵviewQuery"](_c1, 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵviewQuery"](_c2, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵloadQuery"]()) && (ctx.viewerElm = _t.first);
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵloadQuery"]()) && (ctx.staticElm = _t.first);
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵloadQuery"]()) && (ctx.componentElm = _t.first);
        }
      },
      inputs: {
        appointmentContent: "appointmentContent",
        document: "document"
      },
      outputs: {
        changed$: "changed"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵProvidersFeature"]([_angular_common__WEBPACK_IMPORTED_MODULE_14__.CurrencyPipe])],
      decls: 1,
      vars: 1,
      consts: [["viewerElm", ""], ["staticElm", ""], ["class", "document", 4, "ngIf"], [1, "document"], [3, "fill", 4, "ngIf"], [1, "content"], [4, "ngIf"], [3, "fill"], ["class", "dynamic-content", 3, "innerHtml", 4, "ngIf"], ["class", "static-content", 4, "ngIf"], [1, "dynamic-content", 3, "innerHtml"], [1, "static-content"], ["class", "page", 4, "ngFor", "ngForOf"], [1, "page"], [3, "src"], [1, "fields"], ["class", "field", 3, "left", "top", "width", "height", "innerHTML", 4, "ngFor", "ngForOf"], [1, "field", 3, "innerHTML"]],
      template: function AppointmentDocumentComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵtemplate"](0, AppointmentDocumentComponent_div_0_Template, 6, 3, "div", 2);
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_12__["ɵɵproperty"]("ngIf", ctx.document != null);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_14__.NgForOf, _angular_common__WEBPACK_IMPORTED_MODULE_14__.NgIf, _ui_components_loader_loader_component__WEBPACK_IMPORTED_MODULE_11__.LoaderComponent],
      styles: [".document[_ngcontent-%COMP%]    > loader[_ngcontent-%COMP%] {\n  display: block;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 0;\n  width: 14vw;\n  height: 14vw;\n  --fillSpeed: 2s;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%] {\n  position: relative;\n  z-index: 1;\n  font-size: 20px;\n  font-family: \"Times New Roman\", Times, serif;\n  font-weight: var(--strong);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]     *:not(i) {\n  font-family: \"Times New Roman\", Times, serif !important;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%] {\n  padding: 20px;\n  background-color: var(--color2);\n  min-height: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .logo {\n  width: 300px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .logo img {\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .paragraph {\n  margin-top: 20px;\n  position: relative;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     hr {\n  margin: 20px 0;\n  height: 3px;\n  box-shadow: none;\n  border: none;\n  background-color: var(--color1Alt3);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     h2 {\n  font-size: 36px;\n  color: var(--color1);\n  font-weight: var(--stronger);\n  margin: 5px 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     h3 {\n  font-size: 28px;\n  color: var(--color1);\n  font-weight: var(--stronger);\n  margin: 5px 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-small {\n  font-size: 20px;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-small * {\n  font-size: 20px !important;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-medium {\n  font-size: 28px;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-medium * {\n  font-size: 28px !important;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-large {\n  font-size: 36px;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .font-large * {\n  font-size: 36px !important;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .note {\n  font-size: 1.4vw;\n  color: var(--color1Alt4);\n  font-weight: var(--stdweight);\n  font-style: italic;\n  margin: 1ch 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     {\n  margin: 1ch 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .row {\n  display: flex;\n  align-items: flex-start;\n  justify-content: space-between;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .block {\n  display: block;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .customer-note {\n  position: relative;\n  padding-right: 5vw;\n  min-height: 5vw;\n  margin: 1ch 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .customer-note > label {\n  display: block;\n  line-height: 1;\n  font-size: 1.2vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .customer-note > .value {\n  display: block;\n  line-height: 1;\n  margin-top: 1ch;\n  font-size: 1.2vw;\n  font-weight: var(--stdweight);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams {\n  margin-top: 2vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > h2 {\n  font-size: 2.2vw;\n  font-weight: var(--stronger);\n  color: var(--color1);\n  margin-bottom: 1vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams {\n  margin-top: 0.5vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram {\n  margin-top: 2vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram > h3 {\n  font-size: 1.2vw;\n  font-weight: var(--stdweight);\n  text-transform: uppercase;\n  color: var(--color1Alt3);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram > h4 {\n  font-size: 1.8vw;\n  font-weight: var(--strong);\n  color: var(--color1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram > .image {\n  margin-top: 0.5vw;\n  border: 0.5vw var(--color4Alt4) solid;\n  border-radius: 2vw;\n  overflow: hidden;\n  font-size: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram > .image img {\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-diagrams > .diagrams > .inspection-diagram:first-child {\n  margin-top: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos {\n  margin-top: 2vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > h3 {\n  font-size: 1.2vw;\n  font-weight: var(--stdweight);\n  text-transform: uppercase;\n  color: var(--color1Alt3);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > h4 {\n  font-size: 1.8vw;\n  font-weight: var(--strong);\n  color: var(--color1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > .images {\n  margin-top: 0.5vw;\n  display: flex;\n  flex-wrap: wrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > .images > .image {\n  width: calc(50% - 1vw);\n  margin-left: 2vw;\n  border: 0.5vw var(--color5Alt4) solid;\n  border-radius: 2vw;\n  overflow: hidden;\n  font-size: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > .images > .image img {\n  width: 100%;\n  height: 100%;\n  -webkit-object-fit: cover;\n  -moz-object-fit: cover;\n  -o-background-size: cover;\n  object-fit: cover;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos > .images > .image:nth-child(odd) {\n  margin-left: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .inspection-photos:first-child {\n  margin-top: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .list {\n  position: relative;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .list > .list-item {\n  position: relative;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .spacer {\n  clear: both;\n  margin-top: 50px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials {\n  position: relative;\n  display: flex;\n  width: 100%;\n  justify-content: flex-end;\n  margin-bottom: 50px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render {\n  position: relative;\n  border: 2px var(--color1) dotted;\n  border-radius: 0.5vw;\n  padding: 5px;\n  cursor: pointer;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render canvas, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render canvas {\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render img, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render img {\n  position: absolute;\n  height: 100%;\n  width: 100%;\n  top: 0;\n  left: 0;\n  -webkit-object-fit: contain;\n  -moz-object-fit: contain;\n  -o-background-size: contain;\n  object-fit: contain;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render .hash, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render .hash {\n  -ms-text-overflow: ellipsis;\n  text-overflow: ellipsis;\n  display: block;\n  white-space: nowrap;\n  overflow: hidden;\n  position: absolute;\n  top: calc(100% + 19px);\n  left: auto;\n  right: 0;\n  bottom: auto;\n  font-size: 7px;\n  color: var(--color1Alt1);\n  font-weight: var(--stdweight);\n  line-height: 1;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render .timestamp, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render .timestamp {\n  position: absolute;\n  top: calc(100% + 29px);\n  left: auto;\n  right: 0;\n  bottom: auto;\n  font-size: 7px;\n  color: var(--color1Alt1);\n  font-weight: var(--stdweight);\n  line-height: 1;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > label, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > label {\n  text-align: right;\n  display: block;\n  font-size: 14px;\n  color: var(--color1Alt3);\n  font-weight: var(--stdweight);\n  white-space: nowrap;\n  position: absolute;\n  right: 0;\n  top: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature.mandatory > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials.mandatory > .render {\n  background-color: rgba(var(--yellow-raw), 0.2);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature.valid > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials.valid > .render {\n  background-color: rgba(var(--success-raw), 0.1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature.disabled, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials.disabled {\n  pointer-events: none;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature.disabled > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials.disabled > .render {\n  background-color: var(--color2) !important;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .signature > .render {\n  width: 250px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .initials > .render {\n  width: 60px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-left {\n  text-align: left;\n  display: flex;\n  justify-content: flex-start;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-left > .block {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-start;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-left * {\n  text-align: initial;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-right {\n  text-align: right;\n  display: flex;\n  justify-content: flex-end;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-right > .block {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-right * {\n  text-align: initial;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-center {\n  text-align: center;\n  display: flex;\n  justify-content: center;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-center > .block {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-center * {\n  text-align: initial;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-justify {\n  text-align: justify;\n  display: flex;\n  justify-content: flex-start;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-justify > .block {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-start;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .align-justify * {\n  text-align: initial;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard {\n  table-layout: auto;\n  max-width: 100%;\n  margin: 10px 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr {\n  border-top: 0.2vw var(--color1Alt1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr td {\n  font-size: 1.2vw;\n  color: var(--color1);\n  font-family: \"Times New Roman\", Times, serif;\n  font-weight: var(--strong);\n  border-left: 0.2vw var(--color1Alt1) solid;\n  padding: 0.25vw 0.5vw;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr td.label {\n  background-color: var(--color3Alt3);\n  color: var(--color2);\n  font-weight: var(--stronger);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr td:first-child {\n  border-left-color: var(--color1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr td:last-child {\n  border-right: 0.2vw var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr:first-child {\n  border-top-color: var(--color1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr:last-child {\n  border-bottom: 0.2vw var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.standard tbody tr:nth-child(odd) {\n  background-color: var(--color2Alt1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details {\n  table-layout: fixed;\n  width: 100%;\n  margin: 10px 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type {\n  border-top: 2px var(--color1) solid;\n  border-bottom: 2px var(--color1) solid;\n  background-color: var(--color2Alt2);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type > td {\n  padding: 3px 5px 5px;\n  border-left: 2px var(--color1) solid;\n  border-right: 2px var(--color1) solid;\n  border-bottom: 2px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type > td > .parent {\n  font-size: 20px;\n  color: var(--color1Alt2);\n  font-weight: var(--mdweight);\n  text-transform: uppercase;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type > td > .entity {\n  font-size: 20px;\n  color: var(--color1);\n  text-transform: uppercase;\n  font-weight: var(--strongest);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type.Structure {\n  background-color: rgba(var(--color4-raw), 0.25);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type.Structure > .type {\n  background-color: var(--color4);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type.Floor {\n  background-color: rgba(var(--color4Alt4-raw), 0.5);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.type.Room {\n  background-color: rgba(var(--color3Alt1-raw), 0.5);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details {\n  background-color: var(--color2);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td {\n  padding: 10px 5px;\n  border-left: 2px var(--color1) solid;\n  border-right: 2px var(--color1) solid;\n  border-bottom: 2px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute {\n  display: inline-block;\n  vertical-align: bottom;\n  margin-right: 10px;\n  padding-right: 10px;\n  border-right: 2px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute > .name, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute > .value {\n  display: inline-block;\n  vertical-align: bottom;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute > .name {\n  font-size: 20px;\n  color: var(--color1);\n  font-weight: var(--stdweight);\n  text-transform: uppercase;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute > .value {\n  margin-left: 5px;\n  font-size: 24px;\n  color: var(--color1);\n  font-weight: var(--strongest);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td .attribute:last-child {\n  border-right: none;\n  margin-right: 0;\n  padding-right: 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td > .attributes {\n  display: block;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td > .fixtures {\n  display: block;\n  margin-top: 10px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td > .fixtures > .fixture {\n  display: block;\n  margin-top: 10px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.details > td > .fixtures > .fixture > .name {\n  display: inline-block;\n  vertical-align: bottom;\n  margin-right: 5px;\n  font-size: 20px;\n  color: var(--color1);\n  font-weight: var(--strongest);\n  text-transform: uppercase;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.spacer {\n  border: none;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.entity-details > tbody > tr.spacer > td {\n  padding: 20px 0;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations {\n  table-layout: fixed;\n  width: 100%;\n  border: 2px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations > thead {\n  background-color: var(--color2Alt2);\n  border-bottom: 2px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations > thead th {\n  padding: 5px;\n  text-align: left;\n  font-size: 20px;\n  text-transform: uppercase;\n  color: var(--color1);\n  font-weight: var(--stronger);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations > tbody > tr {\n  border-bottom: 1px var(--color1) solid;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations > tbody > tr td {\n  padding: 5px;\n  font-size: 20px;\n  color: var(--color1);\n  font-weight: var(--stdweight);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     table.additional-considerations > tbody > tr:nth-child(even) {\n  background-color: var(--color2Alt1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .checkbox {\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .checkbox i {\n  font-size: 36px;\n  margin-right: 10px;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .checkbox i.checked {\n  display: none;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .checkbox.checked i.checked {\n  display: block;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .checkbox.checked i.unchecked {\n  display: none;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .input textarea {\n  display: block;\n  width: 400px;\n  max-width: 100%;\n  font-size: 24px;\n  font-weight: var(--stdweight);\n  padding: 10px;\n  border: 2px var(--color1) solid;\n  border-radius: 5px;\n  resize: none;\n  transition: border-color 0.2s linear;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .dynamic-content[_ngcontent-%COMP%]     .input:focus-within textarea {\n  border-color: var(--color3);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%] {\n  position: relative;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%] {\n  position: absolute;\n  z-index: 1;\n  font-size: 1.2vw;\n  color: var(--color3);\n  font-weight: var(--strong);\n  white-space: nowrap;\n  display: flex;\n  align-items: flex-end;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials {\n  position: absolute;\n  left: 0;\n  top: 0;\n  height: 100%;\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > .render {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  border: 2px var(--color1) dotted;\n  border-radius: 0.5vw;\n  padding: 5px;\n  cursor: pointer;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > .render canvas, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > .render canvas {\n  width: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > .render img, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > .render img {\n  position: absolute;\n  height: 100%;\n  width: 100%;\n  top: 0;\n  left: 0;\n  -webkit-object-fit: contain;\n  -moz-object-fit: contain;\n  -o-background-size: contain;\n  object-fit: contain;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > .render .hash, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > .render .hash {\n  -ms-text-overflow: ellipsis;\n  text-overflow: ellipsis;\n  display: block;\n  white-space: nowrap;\n  overflow: hidden;\n  position: absolute;\n  top: calc(100% + 19px);\n  left: auto;\n  right: 0;\n  bottom: auto;\n  font-size: 7px;\n  color: var(--color1Alt1);\n  font-weight: var(--stdweight);\n  line-height: 1;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > .render .timestamp, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > .render .timestamp {\n  position: absolute;\n  top: calc(100% + 29px);\n  left: auto;\n  right: 0;\n  bottom: auto;\n  font-size: 7px;\n  color: var(--color1Alt1);\n  font-weight: var(--stdweight);\n  line-height: 1;\n  white-space: nowrap;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature > label, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials > label {\n  text-align: right;\n  display: block;\n  font-size: 14px;\n  color: var(--color1Alt3);\n  font-weight: var(--stdweight);\n  white-space: nowrap;\n  position: absolute;\n  right: 0;\n  top: 100%;\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature.mandatory > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials.mandatory > .render {\n  background-color: rgba(var(--yellow-raw), 0.2);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .signature.valid > .render, \n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .static-content[_ngcontent-%COMP%]   .page[_ngcontent-%COMP%]   .fields[_ngcontent-%COMP%]   .field[_ngcontent-%COMP%]     .initials.valid > .render {\n  background-color: rgba(var(--success-raw), 0.1);\n}\n.document[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > img[_ngcontent-%COMP%] {\n  width: 100%;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return AppointmentDocumentComponent;
})();

/***/ }),

/***/ 3528:
/*!**************************************************************************!*\
  !*** ./src/app/shared/documents/components/consent/consent.component.ts ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ConsentComponent: () => (/* binding */ ConsentComponent)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! src/app/shared/ui/services/ui.service */ 345);
/* harmony import */ var src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/app/shared/documents/services/document.service */ 3040);




let ConsentComponent = /*#__PURE__*/(() => {
  class ConsentComponent {
    constructor(uiService, documentService) {
      this.uiService = uiService;
      this.documentService = documentService;
      // #region Consent
      this.consenters = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
      this.currentConsenters = [];
      // #endregion
      // #region Bootstrapping
      this.close = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
    }
    watchConsenters() {
      this.consenterSubscription = this.consenters.subscribe({
        next: consenters => {
          this.initConsenters(consenters);
        }
      });
    }
    continue() {
      if (this.activeConsenter != null) {
        this.activeConsenter.consent = this.documentService.initConsent(this.activeConsenter.fullName);
        const unconsented = this.findUnconsented();
        if (unconsented == null) {
          this.closeView();
        } else {
          this.setActiveConsenter(unconsented);
        }
      }
    }
    toggleConsent() {
      if (this.activeConsenter != null) {
        this.activeConsenter.consented = !this.activeConsenter.consented;
      }
    }
    findUnconsented() {
      return this.currentConsenters.find(x => x.consent == null);
    }
    setActiveConsenter(consenter) {
      this.activeConsenter = consenter;
    }
    initConsenters(consenters) {
      this.currentConsenters = consenters;
      const unconsented = this.findUnconsented();
      if (unconsented == null) {
        this.closeView();
      } else {
        this.setActiveConsenter(unconsented);
      }
    }
    closeView() {
      const unconsented = this.currentConsenters.find(x => x.consent == null);
      if (unconsented == null) {
        this.close.next(this.currentConsenters);
      }
    }
    init() {
      this.watchConsenters();
    }
    // #endregion
    ngOnInit() {
      this.init();
    }
    ngOnDestroy() {
      this.consenterSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function ConsentComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ConsentComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdirectiveInject"](src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_0__.UiService), _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdirectiveInject"](src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_1__.DocumentService));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdefineComponent"]({
      type: ConsentComponent,
      selectors: [["signing-consent"]],
      inputs: {
        consenters: "consenters"
      },
      outputs: {
        close: "close"
      },
      standalone: false,
      decls: 19,
      vars: 4,
      consts: [["id", "consent"], [1, "logo"], ["src", "/assets/images/logo.svg"], [1, "content"], [1, "input-wrap", 3, "click"], [1, "checkbox"], [1, "fa-regular", "fa-square", "unchecked"], [1, "fa-regular", "fa-square-check", "checked"], [1, "consenter"], [1, "controls"], [1, "control", 3, "click", "disabled"]],
      template: function ConsentComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](0, "section", 0)(1, "div", 1);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelement"](2, "img", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](3, "div", 3)(4, "p");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtext"](5, " By agreeing to use electronic records and signatures, I acknowledge that my electronic signature is legally enforceable and has the same legal effect as a handwritten signature in all applicable transactions, as permitted under the Electronic Signatures in Global and National Commerce Act (E-SIGN) and the Uniform Electronic Transactions Act (UETA). ");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](6, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵlistener"]("click", function ConsentComponent_Template_div_click_6_listener() {
            return ctx.toggleConsent();
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](7, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelement"](8, "i", 6)(9, "i", 7);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](10, "label");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtext"](11, " I, ");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](12, "span", 8);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtext"](13);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtext"](14, ", agree to use electronic records and signatures. ");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](15, "div", 9)(16, "button", 10);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵlistener"]("click", function ConsentComponent_Template_button_click_16_listener() {
            return ctx.continue();
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementStart"](17, "label");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtext"](18, "Continue");
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵelementEnd"]()()()();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵadvance"](6);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵclassProp"]("checked", ctx.activeConsenter == null ? null : ctx.activeConsenter.consented);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵadvance"](7);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵtextInterpolate"](ctx.activeConsenter == null ? null : ctx.activeConsenter.fullName);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵadvance"](3);
          _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵproperty"]("disabled", !(ctx.activeConsenter == null ? null : ctx.activeConsenter.consented));
        }
      },
      styles: ["#consent[_ngcontent-%COMP%] {\n  padding: 2vw;\n}\n#consent[_ngcontent-%COMP%]    > .logo[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  height: 10vh;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%] {\n  margin-top: 2vw;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > p[_ngcontent-%COMP%] {\n  font-size: 1.4vw;\n  color: var(--color1);\n  font-weight: var(--stdweight);\n  font-family: \"Times New Roman\", Times, serif;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > p[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  text-decoration: underline;\n  font-weight: var(--strong);\n  cursor: pointer;\n  font-family: \"Times New Roman\", Times, serif;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap[_ngcontent-%COMP%] {\n  margin-top: 2vw;\n  display: flex;\n  align-items: center;\n  cursor: pointer;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap[_ngcontent-%COMP%]    > .checkbox[_ngcontent-%COMP%]    > i[_ngcontent-%COMP%] {\n  font-size: 2.4vw;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap[_ngcontent-%COMP%]    > .checkbox[_ngcontent-%COMP%]    > i.checked[_ngcontent-%COMP%] {\n  display: none;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  margin-left: 1vw;\n  font-size: 1.4vw;\n  color: var(--color1);\n  font-family: \"Times New Roman\", Times, serif;\n  font-weight: var(--strong);\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%]    > .consenter[_ngcontent-%COMP%] {\n  font-family: \"Times New Roman\", Times, serif;\n  font-weight: var(--strongest);\n  text-transform: uppercase;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap.checked[_ngcontent-%COMP%]    > .checkbox[_ngcontent-%COMP%]    > i.checked[_ngcontent-%COMP%] {\n  display: block;\n}\n#consent[_ngcontent-%COMP%]    > .content[_ngcontent-%COMP%]    > .input-wrap.checked[_ngcontent-%COMP%]    > .checkbox[_ngcontent-%COMP%]    > i.unchecked[_ngcontent-%COMP%] {\n  display: none;\n}\n#consent[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  margin-top: 2vw;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n#consent[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  position: relative;\n  margin-left: 1vw;\n  padding: 0.8vw 2vw;\n  border-radius: 1vw;\n  cursor: pointer;\n  margin-left: 1vw;\n  display: flex;\n  align-items: center;\n  background-color: var(--success);\n  border: 0.1vw transparent solid;\n  transition: background-color 0.1s linear;\n}\n#consent[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.2vw;\n  color: var(--color2);\n  font-weight: var(--strong);\n  line-height: 1;\n}\n#consent[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n#consent[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return ConsentComponent;
})();

/***/ }),

/***/ 1400:
/*!**********************************************************************************!*\
  !*** ./src/app/shared/documents/components/initial-pad/initial-pad.component.ts ***!
  \**********************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   InitialPadComponent: () => (/* binding */ InitialPadComponent)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var signature_pad__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! signature_pad */ 287);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var src_app_shared_system_services_system_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! src/app/shared/system/services/system.service */ 1901);
/* harmony import */ var src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! src/app/shared/ui/services/ui.service */ 345);
/* harmony import */ var src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! src/app/shared/documents/services/document.service */ 3040);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/common */ 6216);








const _c0 = ["initialPadElm"];
const _c1 = ["componentElm"];
function InitialPadComponent_div_0_h3_5_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "h3");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](1, " Signatory: ");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](2, "span", 13);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtextInterpolate"](ctx_r1.name);
  }
}
function InitialPadComponent_div_0_div_13_Template(rf, ctx) {
  if (rf & 1) {
    const _r3 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](1, "canvas", 14, 0);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](3, "div", 10)(4, "button", 11);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function InitialPadComponent_div_0_div_13_Template_button_click_4_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r3);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.clearInitials());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](5, "i", 15);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()();
  }
}
function InitialPadComponent_div_0_div_14_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 16);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](1, "canvas", 17)(2, "img", 18);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵpropertyInterpolate"]("width", ctx_r1.padWidth);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵpropertyInterpolate"]("height", ctx_r1.padHeight);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("src", ctx_r1.signer == null ? null : ctx_r1.signer.initials_B64, _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵsanitizeUrl"]);
  }
}
function InitialPadComponent_div_0_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 2)(1, "div", 3)(2, "header")(3, "h2");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](4, "Initial Here");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](5, InitialPadComponent_div_0_h3_5_Template, 4, 1, "h3", 4);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](6, "div", 5)(7, "button", 6);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function InitialPadComponent_div_0_Template_button_click_7_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.drawInitials());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](8, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](9, "Sign New Initials");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](10, "button", 7);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function InitialPadComponent_div_0_Template_button_click_10_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.useInitials());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](11, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](12, "Use My Initials");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](13, InitialPadComponent_div_0_div_13_Template, 6, 0, "div", 8)(14, InitialPadComponent_div_0_div_14_Template, 3, 3, "div", 9);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](15, "div", 10)(16, "button", 11);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function InitialPadComponent_div_0_Template_button_click_16_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.closeView());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](17, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](18, "Cancel");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](19, "button", 12);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function InitialPadComponent_div_0_Template_button_click_19_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.save());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](20, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](21, "Save Initials");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()()();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](5);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx_r1.name != null);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵclassProp"]("drawing", ctx_r1.drawingNew)("using", !ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](4);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("disabled", (ctx_r1.signer == null ? null : ctx_r1.signer.initials_B64) == null);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", !ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](5);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("disabled", !ctx_r1.canSaveSignature);
  }
}
let InitialPadComponent = /*#__PURE__*/(() => {
  class InitialPadComponent {
    constructor(systemService, uiService, documentService) {
      this.systemService = systemService;
      this.uiService = uiService;
      this.documentService = documentService;
      this.canSaveSignature = false;
      this.drawingNew = true;
      this.padWidth = 1200;
      this.padHeight = 900;
      // #endregion
      // #region Document
      this.fieldId = null;
      this.close = new rxjs__WEBPACK_IMPORTED_MODULE_6__.Subject();
      this.initialized = false;
    }
    clearInitials() {
      if (this.initialPad != null) {
        this.initialPad.clear();
        this.canSaveSignature = false;
      }
    }
    drawInitials() {
      this.drawingNew = true;
      this.initPad();
    }
    useInitials() {
      this.drawingNew = false;
      this.canSaveSignature = this.signer?.initials_B64 != null;
    }
    resizeInitials() {
      const initialPadElm = this.initialPadElm?.nativeElement;
      if (this.initialPad != null && initialPadElm != null) {
        const ratio = Math.max(window.devicePixelRatio || 1, 1);
        this.padWidth = initialPadElm.offsetWidth * ratio;
        this.padHeight = initialPadElm.offsetHeight * ratio;
        initialPadElm.width = this.padWidth;
        initialPadElm.height = this.padHeight;
        initialPadElm.getContext("2d")?.scale(ratio, ratio);
        this.clearInitials();
      }
    }
    initPad() {
      setTimeout(() => {
        const initialPadElm = this.initialPadElm?.nativeElement;
        if (initialPadElm != null) {
          this.initialPad = new signature_pad__WEBPACK_IMPORTED_MODULE_1__["default"](initialPadElm, {
            minWidth: 1.5,
            maxWidth: 4,
            penColor: "rgb(0,0,0)"
          });
          this.initialPad.addEventListener('endStroke', () => {
            this.timestamp = new Date();
            this.canSaveSignature = true;
          });
          this.resizeInitials();
        }
      }, 0);
    }
    initInitials() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            if (_this.fieldId != null && _this.signer != null) {
              _this.initials = yield _this.documentService.initSignature(_this.name, _this.fieldId);
              res();
            } else {
              res();
            }
          });
          return function (_x, _x2) {
            return _ref.apply(this, arguments);
          };
        }());
      })();
    }
    exportInitials() {
      if (this.initialPad != null) {
        return this.initialPad.toDataURL("image/svg+xml");
      }
      return undefined;
    }
    updateDocumentInitials() {
      if (this.initials != null) {
        if (this.drawingNew) {
          const signature_B64 = this.exportInitials();
          this.initials.signature_B64 = signature_B64;
        } else if (this.signer?.initials_B64 != null) {
          this.initials.signature_B64 = this.signer.initials_B64;
        }
        this.initials = this.documentService.signSignature(this.initials);
      }
    }
    get name() {
      return this.signer?.fullName;
    }
    reset() {
      this.clearInitials();
      this.timestamp = undefined;
      this.canSaveSignature = false;
      if (this.signer?.initials_B64 != null) {
        this.drawingNew = false;
        this.canSaveSignature = true;
      }
    }
    closeView() {
      this.reset();
      this.close.next(undefined);
    }
    save() {
      if (this.drawingNew) {
        const signature_B64 = this.exportInitials();
        if (signature_B64 != null) {
          this.updateDocumentInitials();
          this.close.next(this.initials);
        } else {
          this.close.next(undefined);
        }
      } else if (this.signer?.initials_B64 != null) {
        this.updateDocumentInitials();
        this.close.next(this.initials);
      } else {
        this.close.next(undefined);
      }
    }
    init() {
      this.reset();
      this.initInitials().then(() => {
        this.initialized = true;
        this.initPad();
      });
    }
    // #endregion
    ngOnInit() {
      this.init();
    }
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function InitialPadComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || InitialPadComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_system_services_system_service__WEBPACK_IMPORTED_MODULE_2__.SystemService), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_3__.UiService), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_4__.DocumentService));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineComponent"]({
      type: InitialPadComponent,
      selectors: [["initial-pad"]],
      viewQuery: function InitialPadComponent_Query(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵviewQuery"](_c0, 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵviewQuery"](_c1, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵloadQuery"]()) && (ctx.initialPadElm = _t.first);
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵloadQuery"]()) && (ctx.componentElm = _t.first);
        }
      },
      inputs: {
        fieldId: "fieldId",
        signer: "signer"
      },
      outputs: {
        close: "close"
      },
      standalone: false,
      decls: 1,
      vars: 1,
      consts: [["initialPadElm", ""], ["class", "initial-pad", 4, "ngIf"], [1, "initial-pad"], [1, "pad"], [4, "ngIf"], [1, "tabs"], [1, "tab", "drawing", 3, "click"], [1, "tab", "using", 3, "click", "disabled"], ["class", "pad", 4, "ngIf"], ["class", "using", 4, "ngIf"], [1, "controls"], [1, "control", 3, "click"], [1, "control", "success", 3, "click", "disabled"], [1, "value"], ["id", "initialPad", "width", "1200", "height", "900"], [1, "fa-solid", "fa-eraser"], [1, "using"], [3, "width", "height"], [3, "src"]],
      template: function InitialPadComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](0, InitialPadComponent_div_0_Template, 22, 9, "div", 1);
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx.initialized);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_7__.NgIf],
      styles: [".initial-pad[_ngcontent-%COMP%] {\n  position: relative;\n  background-color: var(--color2);\n  border-radius: 1vw;\n  padding: 1vw;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   header[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  font-size: 1.4vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   header[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n  font-size: 1vw;\n  text-transform: uppercase;\n  color: var(--color1Alt1);\n  font-weight: var(--strong);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  display: flex;\n  background-color: var(--color2Alt3);\n  border-radius: 999px;\n  padding: 0.5vw;\n  position: relative;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]:before {\n  content: \"\";\n  position: absolute;\n  top: 0.5vw;\n  left: 0.5vw;\n  right: auto;\n  bottom: 0.5vw;\n  width: calc(50% - 0.5vw);\n  background-color: var(--color2);\n  border-radius: 999px;\n  transition: transform 0.25s linear;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%] {\n  width: calc(50% - 0.5vw);\n  margin-left: 1vw;\n  cursor: pointer;\n  padding: 0.5vw;\n  text-align: center;\n  position: relative;\n  z-index: 1;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.4vw;\n  color: var(--color1Alt3);\n  font-weight: var(--strong);\n  transition: color 0.2s linear;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.drawing[_ngcontent-%COMP%]:before {\n  transform: translateX(0);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.drawing[_ngcontent-%COMP%]    > .drawing[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color1);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.using[_ngcontent-%COMP%]:before {\n  transform: translateX(100%);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.using[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color1);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  border: 0.1vw var(--color2Alt2) solid;\n  border-radius: 0.5vw;\n  overflow: hidden;\n  position: relative;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   canvas[_ngcontent-%COMP%] {\n  width: 100%;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0.5vw;\n  right: 0.5vw;\n  border-radius: 100%;\n  padding: 0.25vw;\n  background-color: var(--color2Alt3);\n  display: flex;\n  align-items: center;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  height: 2vw;\n  width: 2vw;\n  border-radius: 100%;\n  position: relative;\n  background-color: var(--color2);\n  transition: background-color 0.1s linear;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > i[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  font-size: 1.2vw;\n  color: var(--color1);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active {\n  background-color: var(--color2Alt1);\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  border: 0.1vw var(--color2Alt2) solid;\n  border-radius: 0.5vw;\n  overflow: hidden;\n  position: relative;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]   canvas[_ngcontent-%COMP%] {\n  width: 100%;\n}\n.initial-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  height: 100%;\n  width: 100%;\n  -webkit-object-fit: contain;\n  -moz-object-fit: contain;\n  -o-background-size: contain;\n  object-fit: contain;\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  display: flex;\n  align-items: center;\n  justify-content: flex-end;\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  margin-left: 0.5vw;\n  padding: 0.8vw 2vw;\n  border-radius: 999px;\n  cursor: pointer;\n  margin-left: 1vw;\n  display: flex;\n  align-items: center;\n  background-color: var(--color2Alt4);\n  border: 0.1vw transparent solid;\n  transition: background-color 0.1s linear;\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.2vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n  line-height: 1;\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.success[_ngcontent-%COMP%] {\n  background-color: var(--success);\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.success[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color2);\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active {\n  background-color: var(--color2Alt4);\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active.success {\n  background-color: var(--successAlt4);\n}\n.initial-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return InitialPadComponent;
})();

/***/ }),

/***/ 4812:
/*!**************************************************************************************!*\
  !*** ./src/app/shared/documents/components/signature-pad/signature-pad.component.ts ***!
  \**************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SignaturePadComponent: () => (/* binding */ SignaturePadComponent)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var signature_pad__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! signature_pad */ 287);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var src_app_shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! src/app/shared/system/services/api.service */ 1160);
/* harmony import */ var src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! src/app/shared/ui/services/ui.service */ 345);
/* harmony import */ var src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! src/app/shared/documents/services/document.service */ 3040);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/common */ 6216);








const _c0 = ["signaturePadElm"];
const _c1 = ["componentElm"];
function SignaturePadComponent_div_0_h3_5_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "h3");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](1, " Signatory: ");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](2, "span", 13);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtextInterpolate"](ctx_r1.name);
  }
}
function SignaturePadComponent_div_0_div_13_Template(rf, ctx) {
  if (rf & 1) {
    const _r3 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](1, "canvas", 14, 0);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](3, "div", 10)(4, "button", 11);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function SignaturePadComponent_div_0_div_13_Template_button_click_4_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r3);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.clearSignature());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](5, "i", 15);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()();
  }
}
function SignaturePadComponent_div_0_div_14_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 16);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelement"](1, "canvas", 17)(2, "img", 18);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"](2);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵpropertyInterpolate"]("width", ctx_r1.padWidth);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵpropertyInterpolate"]("height", ctx_r1.padHeight);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("src", ctx_r1.signer == null ? null : ctx_r1.signer.signature_B64, _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵsanitizeUrl"]);
  }
}
function SignaturePadComponent_div_0_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵgetCurrentView"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](0, "div", 2)(1, "div", 3)(2, "header")(3, "h2");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](4, "Sign Here");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](5, SignaturePadComponent_div_0_h3_5_Template, 4, 1, "h3", 4);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](6, "div", 5)(7, "button", 6);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function SignaturePadComponent_div_0_Template_button_click_7_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.drawSignature());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](8, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](9, "Sign New Signature");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](10, "button", 7);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function SignaturePadComponent_div_0_Template_button_click_10_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.useSignature());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](11, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](12, "Use My Signature");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](13, SignaturePadComponent_div_0_div_13_Template, 6, 0, "div", 8)(14, SignaturePadComponent_div_0_div_14_Template, 3, 3, "div", 9);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](15, "div", 10)(16, "button", 11);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function SignaturePadComponent_div_0_Template_button_click_16_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.closeView());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](17, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](18, "Cancel");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](19, "button", 12);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵlistener"]("click", function SignaturePadComponent_div_0_Template_button_click_19_listener() {
      _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵrestoreView"](_r1);
      const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
      return _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵresetView"](ctx_r1.save());
    });
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementStart"](20, "label");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtext"](21, "Save Signature");
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵelementEnd"]()()()();
  }
  if (rf & 2) {
    const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵnextContext"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](5);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx_r1.name != null);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵclassProp"]("drawing", ctx_r1.drawingNew)("using", !ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](4);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("disabled", (ctx_r1.signer == null ? null : ctx_r1.signer.signature_B64) == null);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](3);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", !ctx_r1.drawingNew);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵadvance"](5);
    _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("disabled", !ctx_r1.canSaveSignature);
  }
}
let SignaturePadComponent = /*#__PURE__*/(() => {
  class SignaturePadComponent {
    constructor(apiService, uiService, documentService) {
      this.apiService = apiService;
      this.uiService = uiService;
      this.documentService = documentService;
      this.canSaveSignature = false;
      this.drawingNew = true;
      this.padWidth = 1990;
      this.padHeight = 600;
      // #endregion
      // #region Document
      this.fieldId = null;
      this.close = new rxjs__WEBPACK_IMPORTED_MODULE_6__.Subject();
      this.initialized = false;
    }
    clearSignature() {
      if (this.signaturePad != null) {
        this.signaturePad.clear();
        this.canSaveSignature = false;
      }
    }
    drawSignature() {
      this.drawingNew = true;
      this.initPad();
    }
    useSignature() {
      this.drawingNew = false;
      this.canSaveSignature = this.signer?.signature_B64 != null;
    }
    resizeSignature() {
      const signaturePadElm = this.signaturePadElm?.nativeElement;
      if (this.signaturePad != null && signaturePadElm != null) {
        const ratio = Math.max(window.devicePixelRatio || 1, 1);
        signaturePadElm.width = signaturePadElm.offsetWidth * ratio;
        signaturePadElm.height = signaturePadElm.offsetHeight * ratio;
        signaturePadElm.getContext("2d")?.scale(ratio, ratio);
        this.signaturePad.clear();
      }
    }
    initSignature() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return new Promise(/*#__PURE__*/function () {
          var _ref = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (res, rej) {
            if (_this.fieldId != null && _this.name != null) {
              _this.signature = yield _this.documentService.initSignature(_this.name, _this.fieldId);
              res();
            } else {
              rej();
            }
          });
          return function (_x, _x2) {
            return _ref.apply(this, arguments);
          };
        }());
      })();
    }
    initPad() {
      setTimeout(() => {
        const signaturePadElm = this.signaturePadElm?.nativeElement;
        if (signaturePadElm != null) {
          this.signaturePad = new signature_pad__WEBPACK_IMPORTED_MODULE_1__["default"](signaturePadElm, {
            minWidth: 1.5,
            maxWidth: 4,
            penColor: "rgb(0,0,0)"
          });
          this.signaturePad.addEventListener('endStroke', () => {
            this.timestamp = new Date();
            this.canSaveSignature = true;
          });
          this.resizeSignature();
        }
      }, 0);
    }
    exportSignature() {
      if (this.signaturePad != null) {
        return this.signaturePad.toDataURL("image/svg+xml");
      }
      return undefined;
    }
    updateDocumentSignature() {
      if (this.signature != null) {
        if (this.drawingNew) {
          const signature_B64 = this.exportSignature();
          this.signature.signature_B64 = signature_B64;
        } else if (this.signer?.signature_B64 != null) {
          this.signature.signature_B64 = this.signer.signature_B64;
        }
        this.signature = this.documentService.signSignature(this.signature);
      }
    }
    get name() {
      return this.signer?.fullName;
    }
    reset() {
      this.clearSignature();
      this.timestamp = undefined;
      this.canSaveSignature = false;
      if (this.signer?.signature_B64 != null) {
        this.drawingNew = false;
        this.canSaveSignature = true;
      }
    }
    closeView() {
      this.reset();
      this.close.next(undefined);
    }
    save() {
      if (this.drawingNew) {
        const signature_B64 = this.exportSignature();
        if (signature_B64 != null) {
          this.updateDocumentSignature();
          this.close.next(this.signature);
        } else {
          this.close.next(undefined);
        }
      } else if (this.signer?.signature_B64 != null) {
        this.updateDocumentSignature();
        this.close.next(this.signature);
      } else {
        this.close.next(undefined);
      }
    }
    init() {
      this.reset();
      this.initSignature().then(e => {
        this.initialized = true;
        this.initPad();
      });
    }
    // #endregion
    ngOnInit() {
      this.init();
    }
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function SignaturePadComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || SignaturePadComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_system_services_api_service__WEBPACK_IMPORTED_MODULE_2__.ApiService), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_3__.UiService), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdirectiveInject"](src_app_shared_documents_services_document_service__WEBPACK_IMPORTED_MODULE_4__.DocumentService));
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineComponent"]({
      type: SignaturePadComponent,
      selectors: [["signature-pad"]],
      viewQuery: function SignaturePadComponent_Query(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵviewQuery"](_c0, 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵviewQuery"](_c1, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵloadQuery"]()) && (ctx.signaturePadElm = _t.first);
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵloadQuery"]()) && (ctx.componentElm = _t.first);
        }
      },
      inputs: {
        fieldId: "fieldId",
        signer: "signer"
      },
      outputs: {
        close: "close"
      },
      standalone: false,
      decls: 1,
      vars: 1,
      consts: [["signaturePadElm", ""], ["class", "signature-pad", 4, "ngIf"], [1, "signature-pad"], [1, "pad"], [4, "ngIf"], [1, "tabs"], [1, "tab", "drawing", 3, "click"], [1, "tab", "using", 3, "click", "disabled"], ["class", "pad", 4, "ngIf"], ["class", "using", 4, "ngIf"], [1, "controls"], [1, "control", 3, "click"], [1, "control", "success", 3, "click", "disabled"], [1, "value"], ["id", "signaturePad", "width", "1990", "height", "600"], [1, "fa-solid", "fa-eraser"], [1, "using"], [3, "width", "height"], [3, "src"]],
      template: function SignaturePadComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵtemplate"](0, SignaturePadComponent_div_0_Template, 22, 9, "div", 1);
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵproperty"]("ngIf", ctx.initialized);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_7__.NgIf],
      styles: [".signature-pad[_ngcontent-%COMP%] {\n  position: relative;\n  background-color: var(--color2);\n  border-radius: 1vw;\n  padding: 1vw;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   header[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  font-size: 1.4vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   header[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n  font-size: 1vw;\n  text-transform: uppercase;\n  color: var(--color1Alt1);\n  font-weight: var(--strong);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  display: flex;\n  background-color: var(--color2Alt3);\n  border-radius: 999px;\n  padding: 0.5vw;\n  position: relative;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]:before {\n  content: \"\";\n  position: absolute;\n  top: 0.5vw;\n  left: 0.5vw;\n  right: auto;\n  bottom: 0.5vw;\n  width: calc(50% - 0.5vw);\n  background-color: var(--color2);\n  border-radius: 999px;\n  transition: transform 0.25s linear;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%] {\n  width: calc(50% - 0.5vw);\n  margin-left: 1vw;\n  cursor: pointer;\n  padding: 0.5vw;\n  text-align: center;\n  position: relative;\n  z-index: 1;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.4vw;\n  color: var(--color1Alt3);\n  font-weight: var(--strong);\n  transition: color 0.2s linear;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs[_ngcontent-%COMP%]    > .tab[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.drawing[_ngcontent-%COMP%]:before {\n  transform: translateX(0);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.drawing[_ngcontent-%COMP%]    > .drawing[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color1);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.using[_ngcontent-%COMP%]:before {\n  transform: translateX(100%);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .tabs.using[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color1);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  border: 0.1vw var(--color2Alt2) solid;\n  border-radius: 0.5vw;\n  overflow: hidden;\n  position: relative;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]   canvas[_ngcontent-%COMP%] {\n  width: 100%;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0.5vw;\n  right: 0.5vw;\n  border-radius: 100%;\n  padding: 0.25vw;\n  background-color: var(--color2Alt3);\n  display: flex;\n  align-items: center;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  height: 2vw;\n  width: 2vw;\n  border-radius: 100%;\n  position: relative;\n  background-color: var(--color2);\n  transition: background-color 0.1s linear;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > i[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  font-size: 1.2vw;\n  color: var(--color1);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active {\n  background-color: var(--color2Alt1);\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  border: 0.1vw var(--color2Alt2) solid;\n  border-radius: 0.5vw;\n  overflow: hidden;\n  position: relative;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]   canvas[_ngcontent-%COMP%] {\n  width: 100%;\n}\n.signature-pad[_ngcontent-%COMP%]    > .pad[_ngcontent-%COMP%]    > .using[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  height: 100%;\n  width: 100%;\n  -webkit-object-fit: contain;\n  -moz-object-fit: contain;\n  -o-background-size: contain;\n  object-fit: contain;\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%] {\n  margin-top: 1vw;\n  display: flex;\n  align-items: center;\n  justify-content: flex-end;\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%] {\n  margin-left: 0.5vw;\n  padding: 0.8vw 2vw;\n  border-radius: 999px;\n  cursor: pointer;\n  margin-left: 1vw;\n  display: flex;\n  align-items: center;\n  background-color: var(--color2Alt4);\n  border: 0.1vw transparent solid;\n  transition: background-color 0.1s linear;\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  font-size: 1.2vw;\n  color: var(--color1);\n  font-weight: var(--strong);\n  line-height: 1;\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.success[_ngcontent-%COMP%] {\n  background-color: var(--success);\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control.success[_ngcontent-%COMP%]    > label[_ngcontent-%COMP%] {\n  color: var(--color2);\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[disabled][_ngcontent-%COMP%] {\n  opacity: 0.6;\n  pointer-events: none;\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active {\n  background-color: var(--color2Alt4);\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:active.success {\n  background-color: var(--successAlt4);\n}\n.signature-pad[_ngcontent-%COMP%]    > .controls[_ngcontent-%COMP%]    > .control[_ngcontent-%COMP%]:first-child {\n  margin-left: 0;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return SignaturePadComponent;
})();

/***/ }),

/***/ 3749:
/*!******************************************************!*\
  !*** ./src/app/shared/documents/documents.module.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SharedDocumentsModule: () => (/* binding */ SharedDocumentsModule)
/* harmony export */ });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/forms */ 8335);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/router */ 4947);
/* harmony import */ var _components_signature_pad_signature_pad_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/signature-pad/signature-pad.component */ 4812);
/* harmony import */ var _components_initial_pad_initial_pad_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/initial-pad/initial-pad.component */ 1400);
/* harmony import */ var _components_consent_consent_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/consent/consent.component */ 3528);
/* harmony import */ var _components_appointment_document_appointment_document_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/appointment-document/appointment-document.component */ 6488);
/* harmony import */ var _ui_ui_module__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../ui/ui.module */ 663);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/core */ 4380);



/* Components */




/* Modules */


let SharedDocumentsModule = /*#__PURE__*/(() => {
  class SharedDocumentsModule {
    static #_ = (() => this.ɵfac = function SharedDocumentsModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || SharedDocumentsModule)();
    })();
    static #_2 = (() => this.ɵmod = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineNgModule"]({
      type: SharedDocumentsModule
    }))();
    static #_3 = (() => this.ɵinj = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjector"]({
      imports: [_angular_common__WEBPACK_IMPORTED_MODULE_6__.CommonModule, _angular_router__WEBPACK_IMPORTED_MODULE_7__.RouterModule, _ui_ui_module__WEBPACK_IMPORTED_MODULE_4__.UiModule, _angular_forms__WEBPACK_IMPORTED_MODULE_8__.ReactiveFormsModule, _angular_forms__WEBPACK_IMPORTED_MODULE_8__.FormsModule]
    }))();
  }
  return SharedDocumentsModule;
})();
(function () {
  (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵsetNgModuleScope"](SharedDocumentsModule, {
    declarations: [_components_signature_pad_signature_pad_component__WEBPACK_IMPORTED_MODULE_0__.SignaturePadComponent, _components_initial_pad_initial_pad_component__WEBPACK_IMPORTED_MODULE_1__.InitialPadComponent, _components_consent_consent_component__WEBPACK_IMPORTED_MODULE_2__.ConsentComponent, _components_appointment_document_appointment_document_component__WEBPACK_IMPORTED_MODULE_3__.AppointmentDocumentComponent],
    imports: [_angular_common__WEBPACK_IMPORTED_MODULE_6__.CommonModule, _angular_router__WEBPACK_IMPORTED_MODULE_7__.RouterModule, _ui_ui_module__WEBPACK_IMPORTED_MODULE_4__.UiModule, _angular_forms__WEBPACK_IMPORTED_MODULE_8__.ReactiveFormsModule, _angular_forms__WEBPACK_IMPORTED_MODULE_8__.FormsModule],
    exports: [_components_signature_pad_signature_pad_component__WEBPACK_IMPORTED_MODULE_0__.SignaturePadComponent, _components_appointment_document_appointment_document_component__WEBPACK_IMPORTED_MODULE_3__.AppointmentDocumentComponent, _components_consent_consent_component__WEBPACK_IMPORTED_MODULE_2__.ConsentComponent, _components_initial_pad_initial_pad_component__WEBPACK_IMPORTED_MODULE_1__.InitialPadComponent]
  });
})();

/***/ }),

/***/ 5477:
/*!****************************************************!*\
  !*** ./src/app/shared/documents/models/content.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DocumentResponseContent: () => (/* binding */ DocumentResponseContent)
/* harmony export */ });
class DocumentResponseContent {}

/***/ }),

/***/ 735:
/*!*****************************************************!*\
  !*** ./src/app/shared/documents/models/document.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Document: () => (/* binding */ Document),
/* harmony export */   DocumentFieldMapping: () => (/* binding */ DocumentFieldMapping),
/* harmony export */   DocumentMapping: () => (/* binding */ DocumentMapping),
/* harmony export */   DocumentPage: () => (/* binding */ DocumentPage),
/* harmony export */   DocumentRule: () => (/* binding */ DocumentRule),
/* harmony export */   DocumentRuleCriteria: () => (/* binding */ DocumentRuleCriteria),
/* harmony export */   DocumentRuleCriteriaTriggerType: () => (/* binding */ DocumentRuleCriteriaTriggerType),
/* harmony export */   DocumentRuleCriteriaType: () => (/* binding */ DocumentRuleCriteriaType),
/* harmony export */   DocumentSignature: () => (/* binding */ DocumentSignature),
/* harmony export */   DocumentSigner: () => (/* binding */ DocumentSigner),
/* harmony export */   DocumentSignerType: () => (/* binding */ DocumentSignerType),
/* harmony export */   DocumentSigningConsent: () => (/* binding */ DocumentSigningConsent),
/* harmony export */   DocumentUserContent: () => (/* binding */ DocumentUserContent)
/* harmony export */ });
/* harmony import */ var _content_models_binary__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../content/models/binary */ 4768);

class Document {
  get completed() {
    return this.executedHash != null;
  }
  constructor(id, name, customerFacing, shopFacing, standalone, dynamic, alwaysShow, mapping, displayOrder = 0, content = undefined, signers = [], rules = [], documents = [], signatures = [], userContent = [], executedDocument = undefined, executedDocument_B64 = undefined, executedHash = undefined, lastUpdated_Utc = undefined, created_Utc = undefined) {
    this.id = "";
    this.name = "";
    this.customerFacing = false;
    this.shopFacing = false;
    this.standalone = false;
    this.alwaysShow = true;
    this.dynamic = false;
    this.displayOrder = 0;
    this.rules = [];
    this.signers = [];
    this.signatures = [];
    this.userContent = [];
    /* Local */
    this.active = false;
    this.documents = [];
    this.id = id;
    this.name = name;
    this.customerFacing = customerFacing;
    this.shopFacing = shopFacing;
    this.standalone = standalone;
    this.dynamic = dynamic;
    this.alwaysShow = alwaysShow;
    this.mapping = mapping;
    this.displayOrder = displayOrder;
    this.content = content;
    this.documents = documents;
    this.signers = signers;
    this.signatures = signatures;
    this.userContent = userContent;
    this.rules = rules;
    this.executedDocument = executedDocument != null ? new _content_models_binary__WEBPACK_IMPORTED_MODULE_0__.ContentBinary(executedDocument) : undefined;
    this.executedDocument_B64 = executedDocument_B64;
    this.executedHash = executedHash, this.lastUpdated_Utc = lastUpdated_Utc, this.created_Utc = created_Utc;
  }
}
class DocumentRule {
  constructor() {
    this.id = "";
    this.criteria = [];
  }
}
class DocumentRuleCriteria {
  constructor() {
    this.id = "";
    this.trigger = "";
    this.type = DocumentRuleCriteriaType.Exact;
    this.triggerType = DocumentRuleCriteriaTriggerType.Attribute;
    this.possibleValues = [];
  }
}
var DocumentRuleCriteriaType = /*#__PURE__*/function (DocumentRuleCriteriaType) {
  DocumentRuleCriteriaType["Exact"] = "Exact";
  DocumentRuleCriteriaType["GreaterThan"] = "GreaterThan";
  DocumentRuleCriteriaType["GreaterThanOrEqual"] = "GreaterThanOrEqual";
  DocumentRuleCriteriaType["LessThan"] = "LessThan";
  DocumentRuleCriteriaType["LessThanOrEqual"] = "LessThanOrEqual";
  return DocumentRuleCriteriaType;
}(DocumentRuleCriteriaType || {});
var DocumentRuleCriteriaTriggerType = /*#__PURE__*/function (DocumentRuleCriteriaTriggerType) {
  DocumentRuleCriteriaTriggerType["Attribute"] = "Attribute";
  return DocumentRuleCriteriaTriggerType;
}(DocumentRuleCriteriaTriggerType || {});
class DocumentUserContent {
  constructor(id, hashedId, fieldId, documentId, signerName, device, ip, latlng, appVersion, timeStamp_Utc) {
    this.id = "";
    this.id = id;
    this.hashedId = hashedId;
    this.fieldId = fieldId;
    this.documentId = documentId;
    this.signerName = signerName;
    this.device = device;
    this.ip = ip;
    this.latlng = latlng;
    this.appVersion = appVersion;
    this.timeStamp_Utc = timeStamp_Utc;
  }
}
class DocumentSignature {
  constructor(id, hashedId, fieldId, documentId, signerName, device, ip, latlng, appVersion, timeStamp_Utc) {
    this.id = "";
    this.id = id;
    this.hashedId = hashedId;
    this.fieldId = fieldId;
    this.documentId = documentId;
    this.signerName = signerName;
    this.device = device;
    this.ip = ip;
    this.latlng = latlng;
    this.appVersion = appVersion;
    this.timeStamp_Utc = timeStamp_Utc;
  }
}
class DocumentSigningConsent {
  constructor(id, hashedId, device, ip, fullName, latlng, appVersion, timeStamp_Utc) {
    this.id = "";
    this.id = id;
    this.hashedId = hashedId;
    this.fullName = fullName;
    this.device = device;
    this.ip = ip;
    this.latlng = latlng;
    this.appVersion = appVersion;
    this.timeStamp_Utc = timeStamp_Utc;
  }
}
class DocumentMapping {
  constructor() {
    this.pages = [];
  }
}
class DocumentPage {
  constructor() {
    this.fields = [];
  }
}
class DocumentFieldMapping {
  get displayX() {
    return `${this.x * this.ratio}px`;
  }
  get displayY() {
    return `${this.y * this.ratio}px`;
  }
  get displayWidth() {
    return `${this.width * this.ratio}px`;
  }
  get displayHeight() {
    return `${this.height * this.ratio}px`;
  }
  constructor(field, ratio = 1) {
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
    this.pageNumber = 1;
    /* Local */
    this.ratio = 1;
    this.id = field.id;
    this.fieldId = field.fieldId;
    this.content = field.content ?? field.id ?? "";
    this.pageNumber = field.pageNumber;
    this.x = field.x;
    this.y = field.y;
    this.width = field.width;
    this.height = field.height;
    this.ratio = ratio;
  }
}
class DocumentSigner {
  constructor(fullName, phoneNumber, emailAddress, type) {
    /* Local */
    this.consented = false;
    this.fullName = fullName;
    this.phoneNumber = phoneNumber;
    this.emailAddress = emailAddress;
    this.type = type;
  }
}
var DocumentSignerType = /*#__PURE__*/function (DocumentSignerType) {
  DocumentSignerType["Customer"] = "Customer";
  DocumentSignerType["Consultant"] = "Consultant";
  return DocumentSignerType;
}(DocumentSignerType || {});

/***/ }),

/***/ 3040:
/*!***************************************************************!*\
  !*** ./src/app/shared/documents/services/document.service.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DocumentService: () => (/* binding */ DocumentService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var src_environments_environment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! src/environments/environment */ 1618);
/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! crypto-js/hmac-sha256 */ 1398);
/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _helpers_methods_methods__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../helpers/methods/methods */ 2853);
/* harmony import */ var _models_document__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../models/document */ 735);
/* harmony import */ var _contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../contact-information/models/contact-information */ 904);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _system_services_system_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../system/services/system.service */ 1901);
/* harmony import */ var _ui_services_ui_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../ui/services/ui.service */ 345);




/* Models */






let DocumentService = /*#__PURE__*/(() => {
  class DocumentService {
    constructor(http, systemService, uiService) {
      this.http = http;
      this.systemService = systemService;
      this.uiService = uiService;
      this.initialingFieldId = null;
      this.initialing = false;
      this.initials = new rxjs__WEBPACK_IMPORTED_MODULE_7__.Subject();
      this.signingFieldId = null;
      this.signing = false;
      this.signature = new rxjs__WEBPACK_IMPORTED_MODULE_7__.Subject();
    }
    ngOnDestroy() {}
    // #region Signing
    getAppointmentContent(key) {
      let url = `{{openApi}}/documents/signing/content/${key}`;
      return this.http.get(url);
    }
    // #endregion
    // #region Updating // ONLY USE IF CUSTOMER FACING, OTHERWISE STORE APPOINTMENT
    updateAppointmentDocuments(signingKey, appointmentId, documents) {
      let url = `{{openApi}}/documents/signing/update/${appointmentId}`;
      const headers = {
        "Content-Type": "application/json"
      };
      const request = {
        signingKey: signingKey,
        appointmentId: appointmentId,
        documents: documents
      };
      return this.http.post(url, JSON.stringify(request), {
        headers: headers
      });
    }
    // #endregion
    // #region Completing // ONLY USE IF CUSTOMER FACING, OTHERWISE STORE APPOINTMENT
    completeAppointmentDocuments(signingKey, appointmentId, documents) {
      let url = `{{openApi}}/documents/signing/complete/${appointmentId}`;
      const headers = {
        "Content-Type": "application/json"
      };
      const request = {
        signingKey: signingKey,
        appointmentId: appointmentId,
        documents: documents
      };
      return this.http.post(url, JSON.stringify(request), {
        headers: headers
      });
    }
    updateSigners(documents) {
      window.clearTimeout(this.signerDebounce);
      this.signerDebounce = window.setTimeout(() => {
        const signers = [];
        for (var i = 0, len = documents.length; i < len; i++) {
          const document = documents[i];
          for (var j = 0, jlen = document.signers.length; j < jlen; j++) {
            const signer = document.signers[j];
            const existingSigner = signers.find(x => x.fullName == signer.fullName);
            if (existingSigner == null) {
              signers.push(signer);
            } else {
              if (existingSigner.initials_B64 == null && signer.initials_B64 == null) {
                existingSigner.initials_B64 = signer.initials_B64;
              }
              if (existingSigner.signature_B64 == null && signer.signature_B64 == null) {
                existingSigner.signature_B64 = signer.signature_B64;
              }
            }
          }
          document.signers = signers;
        }
      }, 500);
    }
    generateSigners(document, content) {
      const signers = [];
      let customerAdded = false;
      let consultantAdded = false;
      if (document.mapping != null) {
        for (var i = 0, len = document.mapping.pages.length; i < len; i++) {
          const page = document.mapping.pages[i];
          for (var j = 0, jlen = page.fields.length; j < jlen; j++) {
            const field = page.fields[j];
            if ((field.id?.includes("initial.customer") || field.id?.includes("signature.customer")) && !customerAdded) {
              if (content?.customer != null) {
                const fullName = `${content.customer.firstName} ${content.customer.lastName}`;
                const email = content.customer.contactInformation.find(x => x.type == _contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.Email);
                const phone = content.customer.contactInformation.find(x => x.type == _contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.CellPhone);
                const signer = new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSigner(fullName, phone?.value, email?.value, _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSignerType.Customer);
                signers.push(signer);
                customerAdded = true;
              }
            }
            if ((field.id?.includes("initial.consultant") || field.id?.includes("signature.consultant")) && !consultantAdded) {
              if (content?.consultant != null) {
                const fullName = `${content.consultant.firstName} ${content.consultant.lastName}`;
                const email = content.consultant.emailAddress;
                const phone = content.consultant.phone;
                const signer = new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSigner(fullName, phone, email, _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSignerType.Consultant);
                signers.push(signer);
                consultantAdded = true;
              }
            }
          }
        }
      }
      if (document.content != null) {
        if ((document.content.includes("initial.customer") || document.content.includes("signature.customer")) && !customerAdded) {
          if (content.customer != null) {
            const fullName = `${content.customer.firstName} ${content.customer.lastName}`;
            const email = content.customer.contactInformation.find(x => x.type == _contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.Email);
            const phone = content.customer.contactInformation.find(x => x.type == _contact_information_models_contact_information__WEBPACK_IMPORTED_MODULE_4__.ContactInformationType.CellPhone);
            const signer = new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSigner(fullName, phone?.value, email?.value, _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSignerType.Customer);
            signers.push(signer);
            customerAdded = true;
          }
        }
        if ((document.content.includes("initial.consultant") || document.content.includes("signature.consultant")) && !consultantAdded) {
          if (content.consultant != null) {
            const fullName = `${content.consultant.firstName} ${content.consultant.lastName}`;
            const email = content.consultant.emailAddress;
            const phone = content.consultant.phone;
            const signer = new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSigner(fullName, phone, email, _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSignerType.Consultant);
            signers.push(signer);
            consultantAdded = true;
          }
        }
      }
      return signers;
    }
    // #endregion
    // #region Crypto
    signSignature(signature) {
      const signingKey = src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.DOCUMENT_KEY;
      if (signingKey != null) {
        const payloadString = JSON.stringify(signature);
        const hmac = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_1___default()('sha256', payloadString).toString();
        signature.hash_SHA256 = hmac;
        return signature;
      } else {
        throw "Signature could not be signed.";
      }
    }
    // #endregion
    // #region Consent
    initConsent(signerName) {
      const id = this.uiService.generateId();
      const hashedId = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_2__.hashString)(id);
      const appVersion = src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.APP_VERSION;
      const device = navigator.userAgent;
      const ip = this.systemService.ip.getValue();
      const position = this.systemService.location.getValue();
      const latlng = position != null ? `${position.coords.latitude},${position.coords.longitude}` : undefined;
      return new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSigningConsent(id, hashedId, device, ip, signerName, latlng, appVersion.toString(), new Date());
    }
    closeInitials(initials) {
      const event = {
        signature: initials,
        signer: this.initialer
      };
      this.initials.next(event);
      this.initialer = undefined;
      this.initialingFieldId = null;
      this.initialing = false;
    }
    startInitialing(initialer, fieldId) {
      this.initialer = initialer;
      this.initialingFieldId = fieldId;
      this.initialing = true;
    }
    closeSignature(signature) {
      const event = {
        signature: signature,
        signer: this.signer
      };
      this.signature.next(event);
      this.signer = undefined;
      this.signingFieldId = null;
      this.signing = false;
    }
    startSigning(signer, fieldId) {
      this.signer = signer;
      this.signingFieldId = fieldId;
      this.signing = true;
    }
    initSignature(signerName, fieldId = undefined, documentId = undefined) {
      const id = this.uiService.generateId();
      const hashedId = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_2__.hashString)(id);
      const appVersion = src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.APP_VERSION;
      const device = navigator.userAgent;
      const ip = this.systemService.ip.getValue();
      const position = this.systemService.location.getValue();
      const latlng = position != null ? `${position.coords.latitude},${position.coords.longitude}` : undefined;
      return new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentSignature(id, hashedId, fieldId, documentId, signerName, device, ip, latlng, appVersion.toString(), new Date());
    }
    // #endregion
    // #region User Content
    initUserContent(signerName, fieldId = undefined, documentId = undefined) {
      const id = this.uiService.generateId();
      const hashedId = (0,_helpers_methods_methods__WEBPACK_IMPORTED_MODULE_2__.hashString)(id);
      const appVersion = src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.APP_VERSION;
      const device = navigator.userAgent;
      const ip = this.systemService.ip.getValue();
      const position = this.systemService.location.getValue();
      const latlng = position != null ? `${position.coords.latitude},${position.coords.longitude}` : undefined;
      return new _models_document__WEBPACK_IMPORTED_MODULE_3__.DocumentUserContent(id, hashedId, fieldId, documentId, signerName, device, ip, latlng, appVersion.toString(), new Date());
    }
    static #_ = (() => this.ɵfac = function DocumentService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DocumentService)(_angular_core__WEBPACK_IMPORTED_MODULE_8__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_9__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_8__["ɵɵinject"](_system_services_system_service__WEBPACK_IMPORTED_MODULE_5__.SystemService), _angular_core__WEBPACK_IMPORTED_MODULE_8__["ɵɵinject"](_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_6__.UiService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_8__["ɵɵdefineInjectable"]({
      token: DocumentService,
      factory: DocumentService.ɵfac
    }))();
  }
  return DocumentService;
})();

/***/ }),

/***/ 7720:
/*!******************************************************!*\
  !*** ./src/app/shared/entities/models/attributes.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EntityAttribute: () => (/* binding */ EntityAttribute),
/* harmony export */   EntityAttributeMatch: () => (/* binding */ EntityAttributeMatch),
/* harmony export */   EntityAttributeRule: () => (/* binding */ EntityAttributeRule),
/* harmony export */   EntityAttributeType: () => (/* binding */ EntityAttributeType)
/* harmony export */ });
class EntityAttribute {
  /* Local */
  get valid() {
    return this.values.length > 0 || this.disabled;
  }
  get shouldHide() {
    return this.hidden || this.hiddenByRule;
  }
  constructor(id, name, customerFacing, possibleValues, type, displayOrder = 0, defaultValue = undefined, hidden = false, rules = [], values = undefined, functionName = undefined) {
    this.id = "";
    this.name = "";
    this.possibleValues = [];
    this.customerFacing = true;
    this.type = EntityAttributeType.Select;
    this.displayOrder = 0;
    this.rules = [];
    this.values = [];
    this.disabled = false;
    this.hidden = false;
    this.hiddenByRule = false;
    this.touched = false;
    this.storing = false;
    this.appliedRules = [];
    this.id = id;
    this.name = name;
    this.possibleValues = possibleValues;
    this.defaultValue = defaultValue;
    this.hidden = hidden;
    this.type = type;
    this.displayOrder = displayOrder;
    this.rules = rules;
    this.customerFacing = customerFacing;
    this.functionName = functionName;
    if (values != null && values.length > 0) {
      this.values = values;
    } else if (defaultValue != null) {
      if (defaultValue.toLocaleLowerCase() == 'yes') {
        this.values[0] = 'true';
      } else if (defaultValue.toLocaleLowerCase() == 'no') {
        this.values[0] = 'false';
      } else if (this.defaultValue != null) {
        this.values[0] = this.defaultValue;
      }
    }
  }
  toJSON() {
    var values = [];
    this.values.forEach(value => {
      if (value != null) {
        const strValue = value.toString();
        values.push(strValue);
      }
    });
    return {
      id: this.id,
      name: this.name,
      customerFacing: this.customerFacing,
      possibleValues: this.possibleValues,
      defaultValue: this.defaultValue,
      functionName: this.functionName,
      type: this.type,
      displayOrder: this.displayOrder,
      lastUpdated_Utc: this.lastUpdated_Utc,
      rules: this.rules,
      values: values,
      disabled: this.disabled,
      hidden: this.hidden
    };
  }
}
var EntityAttributeType = /*#__PURE__*/function (EntityAttributeType) {
  EntityAttributeType["Boolean"] = "Boolean";
  EntityAttributeType["Select"] = "Select";
  EntityAttributeType["MultiSelect"] = "MultiSelect";
  EntityAttributeType["Number"] = "Number";
  EntityAttributeType["Input"] = "Input";
  return EntityAttributeType;
}(EntityAttributeType || {});
class EntityAttributeRule {
  constructor() {
    this.id = "";
    this.triggerValue = "";
    this.targetAttributeId = "";
    this.shouldDisable = false;
    this.shouldHide = false;
    this.shouldMakeReadonly = false;
  }
}
class EntityAttributeMatch {
  constructor() {
    this.name = "";
    this.value = "";
  }
}

/***/ }),

/***/ 822:
/*!*************************************************!*\
  !*** ./src/app/shared/entities/models/rules.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EntityCriteriaTriggerType: () => (/* binding */ EntityCriteriaTriggerType),
/* harmony export */   EntityRule: () => (/* binding */ EntityRule),
/* harmony export */   EntityRuleCriteria: () => (/* binding */ EntityRuleCriteria),
/* harmony export */   EntityRuleCriteriaType: () => (/* binding */ EntityRuleCriteriaType),
/* harmony export */   EntityRuleResultType: () => (/* binding */ EntityRuleResultType)
/* harmony export */ });
class EntityRule {
  constructor() {
    this.id = "";
    this.trigger = "";
    this.skuId = "";
    this.result = "";
    this.resultType = EntityRuleResultType.Quantity;
    this.criteria = [];
  }
}
var EntityRuleResultType = /*#__PURE__*/function (EntityRuleResultType) {
  EntityRuleResultType["Quantity"] = "Quantity";
  EntityRuleResultType["ReferenceQuantity"] = "ReferenceQuantity";
  return EntityRuleResultType;
}(EntityRuleResultType || {});
class EntityRuleCriteria {
  constructor() {
    this.id = "";
    this.trigger = "";
    this.triggerType = EntityCriteriaTriggerType.Attribute;
    this.possibleValues = [];
    this.type = EntityRuleCriteriaType.Exact;
  }
}
var EntityCriteriaTriggerType = /*#__PURE__*/function (EntityCriteriaTriggerType) {
  EntityCriteriaTriggerType["Attribute"] = "Attribute";
  EntityCriteriaTriggerType["ParentRestriction"] = "ParentRestriction";
  return EntityCriteriaTriggerType;
}(EntityCriteriaTriggerType || {});
var EntityRuleCriteriaType = /*#__PURE__*/function (EntityRuleCriteriaType) {
  EntityRuleCriteriaType["Exact"] = "Exact";
  EntityRuleCriteriaType["GreaterThan"] = "GreaterThan";
  EntityRuleCriteriaType["GreaterThanOrEqual"] = "GreaterThanOrEqual";
  EntityRuleCriteriaType["LessThan"] = "LessThan";
  EntityRuleCriteriaType["LessThanOrEqual"] = "LessThanOrEqual";
  return EntityRuleCriteriaType;
}(EntityRuleCriteriaType || {});

/***/ }),

/***/ 1735:
/*!***************************************************!*\
  !*** ./src/app/shared/fixtures/models/fixture.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Fixture: () => (/* binding */ Fixture),
/* harmony export */   FixtureCategory: () => (/* binding */ FixtureCategory)
/* harmony export */ });
class Fixture {
  constructor(id, entityId, name, imageSrc_Base64, attributes = []) {
    this.id = "";
    this.entityId = "";
    this.name = "";
    this.imageSrc_Base64 = "";
    this.attributes = [];
    this.rules = [];
    /* Local */
    this.active = false;
    this.shouldRender = true;
    this.storing = false;
    this.id = id;
    this.entityId = entityId;
    this.name = name;
    this.imageSrc_Base64 = imageSrc_Base64;
    this.attributes = attributes;
  }
}
class FixtureCategory {
  constructor() {
    this.id = "";
    this.name = "";
    this.fixtures = [];
    /* Local */
    this.active = false;
  }
}

/***/ }),

/***/ 2853:
/*!***************************************************!*\
  !*** ./src/app/shared/helpers/methods/methods.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   generateId: () => (/* binding */ generateId),
/* harmony export */   hashString: () => (/* binding */ hashString)
/* harmony export */ });
/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! crypto-js/hmac-sha256 */ 1398);
/* harmony import */ var crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_0__);

function generateId() {
  const guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : r & 0x3 | 0x8;
    return v.toString(16);
  });
  return guid;
}
function hashString(str) {
  const payloadString = JSON.stringify(str);
  const hmac = crypto_js_hmac_sha256__WEBPACK_IMPORTED_MODULE_0___default()('sha256', payloadString).toString();
  return hmac;
}

/***/ }),

/***/ 5561:
/*!****************************************************!*\
  !*** ./src/app/shared/helpers/models/responses.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   GeneralResponse: () => (/* binding */ GeneralResponse),
/* harmony export */   GeneralResponseState: () => (/* binding */ GeneralResponseState),
/* harmony export */   GeneralResponseWithData: () => (/* binding */ GeneralResponseWithData),
/* harmony export */   HandleValidationResponse: () => (/* binding */ HandleValidationResponse),
/* harmony export */   ValidationResponse: () => (/* binding */ ValidationResponse),
/* harmony export */   ValidationResponseWithData: () => (/* binding */ ValidationResponseWithData)
/* harmony export */ });
class GeneralResponse {}
class GeneralResponseWithData extends GeneralResponse {}
var GeneralResponseState = /*#__PURE__*/function (GeneralResponseState) {
  GeneralResponseState["Successful"] = "Successful";
  GeneralResponseState["GeneralFailure"] = "GeneralFailure";
  GeneralResponseState["StorageFailure"] = "StorageFailure";
  GeneralResponseState["DataConflict"] = "DataConflict";
  GeneralResponseState["IncorrectInput"] = "IncorrectInput";
  GeneralResponseState["MissingData"] = "MissingData";
  return GeneralResponseState;
}(GeneralResponseState || {});
class HandleValidationResponse {
  constructor() {
    this.available = true;
    this.suggestedAlternatives = [];
  }
}
class ValidationResponse {
  constructor() {
    this.valid = false;
  }
}
class ValidationResponseWithData extends ValidationResponse {}

/***/ }),

/***/ 1083:
/*!***************************************************!*\
  !*** ./src/app/shared/payments/models/payment.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Payment: () => (/* binding */ Payment),
/* harmony export */   PaymentDetail: () => (/* binding */ PaymentDetail),
/* harmony export */   PaymentMethod: () => (/* binding */ PaymentMethod),
/* harmony export */   PaymentMethodType: () => (/* binding */ PaymentMethodType),
/* harmony export */   PaymentSetting: () => (/* binding */ PaymentSetting),
/* harmony export */   PaymentStatus: () => (/* binding */ PaymentStatus)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ 2714);

class PaymentSetting {
  constructor() {
    this.id = "";
    this.defaultNumberOfPayments = 1;
    this.minimumPayments = 1;
    this.details = [];
    this.methods = [];
  }
}
class PaymentDetail {
  constructor(detail, amount = 0) {
    this.id = "";
    this.name = "";
    this.priority = 0;
    this.minimumAmount = 0;
    this.lenderAmounts = [];
    this.defaultPercent = 0;
    this.amount = 0;
    /* Local */
    this.hasMinimumAmount = false;
    this.hasMaximumAmount = false;
    this.canEditAmount = false;
    this.originalAmount = 0;
    this.originalAmount$ = new rxjs__WEBPACK_IMPORTED_MODULE_0__.Subject();
    this.id = detail.id;
    this.name = detail.name;
    this.priority = detail.priority;
    this.minimumAmount = detail.minimumAmount;
    this.maximumAmount = detail.maximumAmount;
    this.defaultPercent = detail.defaultPercent;
    this.amount = amount;
  }
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      priority: this.priority,
      minimumAmount: this.minimumAmount,
      maximumAmount: this.maximumAmount,
      defaultPercent: this.defaultPercent,
      amount: this.amount
    };
  }
}
class PaymentMethod {
  constructor() {
    this.id = "";
    this.name = "";
    this.type = PaymentMethodType.None;
    /* Local */
    this.added = false;
  }
}
var PaymentMethodType = /*#__PURE__*/function (PaymentMethodType) {
  PaymentMethodType["None"] = "None";
  PaymentMethodType["Cash"] = "Cash";
  PaymentMethodType["Debit"] = "Debit";
  PaymentMethodType["Credit"] = "Credit";
  PaymentMethodType["EPayment"] = "EPayment";
  PaymentMethodType["ACH"] = "ACH";
  PaymentMethodType["EFT"] = "EFT";
  PaymentMethodType["Check"] = "Check";
  PaymentMethodType["Financing"] = "Financing";
  return PaymentMethodType;
}(PaymentMethodType || {});
class Payment {
  constructor(id, method, status = PaymentStatus.Initiated, amount = 0, iso4217 = "USD", appliedManually = false) {
    this.id = "";
    this.appliedManually = false;
    this.iso4217 = "USD";
    this.status = PaymentStatus.Initiated;
    this.id = id;
    this.paymentMethodId = method.id;
    this.status = status;
    this.amount = amount;
    this.iso4217 = iso4217;
    this.appliedManually = appliedManually;
    this.timeStamp_Utc = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate(), new Date().getUTCHours(), new Date().getUTCMinutes(), new Date().getUTCSeconds()));
  }
}
var PaymentStatus = /*#__PURE__*/function (PaymentStatus) {
  PaymentStatus["Initiated"] = "Initiated";
  PaymentStatus["Completed"] = "Completed";
  return PaymentStatus;
}(PaymentStatus || {});

/***/ }),

/***/ 8083:
/*!*******************************************************!*\
  !*** ./src/app/shared/promotions/models/promotion.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Promotion: () => (/* binding */ Promotion),
/* harmony export */   PromotionType: () => (/* binding */ PromotionType)
/* harmony export */ });
class Promotion {
  constructor() {
    this.id = "";
    this.name = "";
    this.type = PromotionType.Percent;
    this.autoApply = false;
    this.manual = false;
    this.stackable = false;
    this.priority = 0;
    /* Local */
    this.active = false;
  }
}
var PromotionType = /*#__PURE__*/function (PromotionType) {
  PromotionType["Percent"] = "Percent";
  PromotionType["Amount"] = "Amount";
  return PromotionType;
}(PromotionType || {});

/***/ }),

/***/ 1750:
/*!******************************************************!*\
  !*** ./src/app/shared/properties/models/property.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   MeasurementUnitType: () => (/* binding */ MeasurementUnitType),
/* harmony export */   Property: () => (/* binding */ Property),
/* harmony export */   PropertyEntity: () => (/* binding */ PropertyEntity),
/* harmony export */   PropertyEntityCategory: () => (/* binding */ PropertyEntityCategory),
/* harmony export */   PropertyEntityType: () => (/* binding */ PropertyEntityType),
/* harmony export */   PropertyPhoto: () => (/* binding */ PropertyPhoto),
/* harmony export */   WallType: () => (/* binding */ WallType)
/* harmony export */ });
/* harmony import */ var _entities_models_attributes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../entities/models/attributes */ 7720);

class Property {
  constructor() {
    this.id = "";
    this.yearBuilt = 1900;
    this.existingPipeTypes = [];
    this.foundationTypes = [];
    this.listedBathrooms = 0;
    this.listedStories = 0;
    this.listedSquareDimensions = 0;
    this.dimensionsMeasurementType = MeasurementUnitType.Feet;
    this.created_Utc = new Date();
    this.lastUpdated_Utc = new Date();
  }
}
var MeasurementUnitType = /*#__PURE__*/function (MeasurementUnitType) {
  MeasurementUnitType["Feet"] = "Feet";
  MeasurementUnitType["Meters"] = "Meters";
  return MeasurementUnitType;
}(MeasurementUnitType || {});
class PropertyPhoto {
  constructor(id, x = 0, y = 0) {
    this.name = "Photo";
    this.mimeType = "";
    this.width = 1280;
    this.height = 960;
    this.x = 0;
    this.y = 0;
    this.notes = "";
    this.id = id;
    this.x = x;
    this.y = y;
  }
}
class PropertyEntity {
  constructor(id, entityId, type, name, attributes = [], fixtures = []) {
    this.id = "";
    this.entityId = "";
    this.type = PropertyEntityType.Property;
    this.attributes = [];
    this.entities = [];
    this.fixtures = [];
    this.rules = [];
    this.id = id;
    this.entityId = entityId;
    this.type = type;
    this.name = name;
    const newAttributes = [];
    attributes.forEach(attribute => {
      const newAttribute = new _entities_models_attributes__WEBPACK_IMPORTED_MODULE_0__.EntityAttribute(attribute.id, attribute.name, attribute.customerFacing, attribute.possibleValues, attribute.type, attribute.displayOrder, attribute.defaultValue, attribute.hidden, attribute.rules, attribute.values, attribute.functionName);
      newAttributes.push(newAttribute);
    });
    this.attributes = newAttributes;
    this.fixtures = fixtures;
  }
}
var WallType = /*#__PURE__*/function (WallType) {
  WallType["Interior"] = "Interior";
  WallType["Exterior"] = "Exterior";
  WallType["Absent"] = "Absent";
  WallType["Missing"] = "Missing";
  return WallType;
}(WallType || {});
var PropertyEntityType = /*#__PURE__*/function (PropertyEntityType) {
  PropertyEntityType["Property"] = "Property";
  PropertyEntityType["Unit"] = "Unit";
  PropertyEntityType["Structure"] = "Structure";
  PropertyEntityType["Floor"] = "Floor";
  PropertyEntityType["Room"] = "Room";
  PropertyEntityType["Job"] = "Job";
  return PropertyEntityType;
}(PropertyEntityType || {});
class PropertyEntityCategory {
  constructor() {
    this.id = "";
    this.name = "";
    this.entities = [];
  }
}

/***/ }),

/***/ 1160:
/*!*******************************************************!*\
  !*** ./src/app/shared/system/services/api.service.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ApiService: () => (/* binding */ ApiService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var src_environments_environment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! src/environments/environment */ 1618);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../authentication/services/auth-ref.service */ 4387);





let ApiService = /*#__PURE__*/(() => {
  class ApiService {
    constructor(http, authRefService) {
      this.http = http;
      this.authRefService = authRefService;
      // #endregion
      // #region Online Status
      this.onlineCheckInitialized = false;
      this.checkingOnlineStatus = false;
      this.online = new rxjs__WEBPACK_IMPORTED_MODULE_2__.BehaviorSubject(true);
      this.watchAuth();
    }
    watchAuth() {
      this.authSubscription = this.authRefService.authenticated.subscribe({
        next: authenticated => {
          if (authenticated) {
            this.initOnlineCheck();
          } else {
            this.stopOnlineCheck();
          }
        }
      });
    }
    setOnlineStatus(status) {
      this.online.next(status);
    }
    scheduleNextOnlineCheck() {
      this.onlineTimer = window.setTimeout(() => {
        this.checkOnlineStatus();
      }, 2500);
    }
    checkOnlineStatus() {
      if (!this.checkingOnlineStatus) {
        window.clearTimeout(this.onlineTimer);
        this.checkingOnlineStatus = true;
        const url = `{{openApi}}/helpers/talk-to-me-goose`;
        this.http.get(url).subscribe({
          next: () => {
            this.setOnlineStatus(true);
            this.checkingOnlineStatus = false;
            this.scheduleNextOnlineCheck();
          },
          error: e => {
            if (!e.message.includes("NG0200")) {
              this.setOnlineStatus(false);
            }
            this.checkingOnlineStatus = false;
            this.scheduleNextOnlineCheck();
          }
        });
      }
    }
    stopOnlineCheck() {
      window.clearTimeout(this.onlineTimer);
      this.onlineCheckInitialized = false;
    }
    initOnlineCheck() {
      if (!this.onlineCheckInitialized) {
        this.checkOnlineStatus();
        this.onlineCheckInitialized = true;
      }
    }
    // #endregion
    // #region API
    get apiUrl() {
      return src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.API_URL;
    }
    getContentUrl(fileName) {
      const b64 = btoa(fileName).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
      return `${src_environments_environment__WEBPACK_IMPORTED_MODULE_0__.environment.CONTENT_URL}/${b64}`;
    }
    // #endregion
    ngOnDestroy() {
      this.authSubscription?.unsubscribe();
      window.clearTimeout(this.onlineTimer);
    }
    static #_ = (() => this.ɵfac = function ApiService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ApiService)(_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_4__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_authentication_services_auth_ref_service__WEBPACK_IMPORTED_MODULE_1__.AuthRefService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdefineInjectable"]({
      token: ApiService,
      factory: ApiService.ɵfac
    }))();
  }
  return ApiService;
})();

/***/ }),

/***/ 6763:
/*!*******************************************************!*\
  !*** ./src/app/shared/system/services/app.service.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppService: () => (/* binding */ AppService)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _capacitor_preferences__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @capacitor/preferences */ 2522);
/* harmony import */ var _capacitor_network__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @capacitor/network */ 926);
/* harmony import */ var _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @capacitor/filesystem */ 2565);
/* harmony import */ var fflate__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! fflate */ 6845);
/* harmony import */ var crypto_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! crypto-js */ 6723);
/* harmony import */ var crypto_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(crypto_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var capacitor_plugin_app_tracking_transparency__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! capacitor-plugin-app-tracking-transparency */ 6556);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _api_service__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./api.service */ 1160);










/* Pipes */
let AppService = /*#__PURE__*/(() => {
  class AppService {
    constructor(apiService) {
      this.apiService = apiService;
      // #region App Tracking
      this.appTrackingPermitted = false;
      // #endregion   
      // #region Version
      this.currentVersion = null;
      this.initLocalVersion();
      this.requestTrackingInformation().then();
    }
    setAppTrackingPermitted(permitted) {
      this.appTrackingPermitted = permitted;
    }
    requestTrackingInformation() {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const statusResponse = yield capacitor_plugin_app_tracking_transparency__WEBPACK_IMPORTED_MODULE_6__.AppTrackingTransparency.getStatus();
        if (statusResponse.status === 'notDetermined') {
          const requestResponse = yield capacitor_plugin_app_tracking_transparency__WEBPACK_IMPORTED_MODULE_6__.AppTrackingTransparency.requestPermission();
          if (requestResponse.status === 'authorized') {
            _this.setAppTrackingPermitted(true);
          } else {
            _this.setAppTrackingPermitted(false);
          }
        } else if (statusResponse.status === 'authorized') {
          _this.setAppTrackingPermitted(true);
        } else {
          _this.setAppTrackingPermitted(false);
        }
      })();
    }
    getLocalVersion() {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const {
          value
        } = yield _capacitor_preferences__WEBPACK_IMPORTED_MODULE_2__.Preferences.get({
          key: 'appVersion'
        });
        return value;
      })();
    }
    setLocalVersion(version) {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        sessionStorage.setItem("tav", version);
        yield _capacitor_preferences__WEBPACK_IMPORTED_MODULE_2__.Preferences.set({
          key: 'appVersion',
          value: "0"
        });
        // await Preferences.set({ key: 'appVersion', value: version });
      })();
    }
    isNewerVersion(version) {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const tav = sessionStorage.getItem("tav");
        const latestVersion = yield _this2.getLocalVersion();
        if (latestVersion == null) {
          return true;
        }
        return tav == null && version > latestVersion;
      })();
    }
    initLocalVersion() {
      this.getLocalVersion().then(version => {
        this.currentVersion = version;
      });
    }
    // #endregion
    // #region Update
    fileExists(path, directory) {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.stat({
            path,
            directory
          });
          return true;
        } catch (error) {
          return false;
        }
      })();
    }
    directoryExists(path, directory) {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.stat({
            path,
            directory
          });
          return true;
        } catch (error) {
          return false;
        }
      })();
    }
    setWebViewBasePath() {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          // Step 1: Get the filesystem path for Directory.Data/dist
          const distPath = 'dist';
          const dataDir = yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.getUri({
            path: distPath,
            directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data
          });
          // Step 2: Verify that index.html exists in the dist directory
          const indexFile = 'index.html';
          try {
            yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.stat({
              path: `${distPath}/${indexFile}`,
              directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data
            });
          } catch (error) {
            console.error(`Error: ${indexFile} not found in ${distPath}`, error);
            throw new Error(`Failed to find ${indexFile} in ${distPath}`);
          }
          // Step 3: Convert the URI to a filesystem path (remove file:// scheme if present)
          let serverPath = dataDir.uri;
          if (serverPath.startsWith('file://')) {
            serverPath = serverPath.replace('file://', '');
          }
          // Step 4: Set the new server base path
          yield _capacitor_core__WEBPACK_IMPORTED_MODULE_1__.WebView.setServerBasePath({
            path: serverPath
          });
          yield _capacitor_core__WEBPACK_IMPORTED_MODULE_1__.WebView.persistServerBasePath();
          yield _capacitor_preferences__WEBPACK_IMPORTED_MODULE_2__.Preferences.remove({
            key: 'serverBasePath'
          });
          window.location.reload(); // Reloads the WebView with the new base path
        } catch (error) {
          console.error('Failed to set WebView base path:', error);
          throw error;
        }
      })();
    }
    checkForUpdate() {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          const url = `${_this3.apiService.apiUrl}/systems/app/version/ios`;
          const status = yield _capacitor_network__WEBPACK_IMPORTED_MODULE_3__.Network.getStatus();
          if (!status.connected) return null;
          const response = yield fetch(url, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json'
            }
          });
          if (!response.ok) throw new Error('Failed to fetch version');
          const data = yield response.json();
          const isNewerVersion = yield _this3.isNewerVersion(data.version);
          if (isNewerVersion) {
            return data;
          }
          return null;
        } catch (error) {
          return null;
        }
      })();
    }
    downloadAndApplyUpdate(update) {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        try {
          console.log("Beginning to download app update.");
          if (yield _this4.directoryExists('dist', _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data)) {
            yield _this4.backupCurrentApp();
          } else {
            console.log('No dist directory found in Directory.Data, skipping backup');
          }
          // Download the zip file
          const response = yield fetch(update.url);
          if (!response.ok) throw new Error(`Failed to download zip: ${response.statusText}`);
          const arrayBuffer = yield response.arrayBuffer();
          // Validate checksum (SHA-256)
          const binaryString = new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '');
          const wordArray = crypto_js__WEBPACK_IMPORTED_MODULE_5___default().enc.Latin1.parse(binaryString);
          const hash = crypto_js__WEBPACK_IMPORTED_MODULE_5___default().SHA256(wordArray).toString((crypto_js__WEBPACK_IMPORTED_MODULE_5___default().enc).Hex);
          if (hash !== update.checksum) {
            throw new Error(`Checksum mismatch: expected ${update.checksum}, got ${hash}`);
          }
          // Extract zip in memory using fflate
          const files = yield new Promise((resolve, reject) => {
            (0,fflate__WEBPACK_IMPORTED_MODULE_8__.unzip)(new Uint8Array(arrayBuffer), (err, files) => {
              if (err) {
                reject(new Error(`Failed to unzip: ${err.message}`));
              } else {
                resolve(files);
              }
            });
          });
          // Clear dist directory if it exists, or create it
          if (yield _this4.directoryExists('dist', _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data)) {
            console.log('Clearing dist directory');
            yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.rmdir({
              path: 'dist',
              directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
              recursive: true
            });
          }
          yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.mkdir({
            path: 'dist',
            directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
            recursive: true
          });
          // Ensure directory creation is complete
          yield new Promise(resolve => setTimeout(resolve, 500));
          // Verify dist directory exists
          if (!(yield _this4.directoryExists('dist', _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data))) {
            throw new Error('Failed to create dist directory');
          }
          // Write extracted files
          let fileCount = 0;
          for (const [relativePath, content] of Object.entries(files)) {
            if (!relativePath.endsWith('/')) {
              // Skip directories
              const binaryStringContent = new Uint8Array(content).reduce((data, byte) => data + String.fromCharCode(byte), '');
              const base64Content = btoa(binaryStringContent); // Convert to base64 for Filesystem
              const pathParts = relativePath.split('/');
              let currentPath = 'dist';
              for (let i = 0; i < pathParts.length - 1; i++) {
                currentPath += `/${pathParts[i]}`;
                try {
                  yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.mkdir({
                    path: currentPath,
                    directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
                    recursive: true
                  });
                } catch (error) {
                  throw new Error(`Directory creation failed for ${currentPath}: ${error.message}`);
                }
              }
              yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.writeFile({
                path: `dist/${relativePath}`,
                data: base64Content,
                directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data
              });
              fileCount++;
            }
          }
          // Update local version
          yield _this4.setLocalVersion(update.version);
          // Force WebView to load from Directory.Data/dist
          yield _this4.setWebViewBasePath();
          console.log("Finished applying app update. Reloading.");
          return true;
        } catch (error) {
          console.error('Update failed:', error);
          // Attempt to restore backup only if it exists
          try {
            yield _this4.restoreBackup();
          } catch (restoreError) {
            console.error('Restore failed:', restoreError);
          }
          return false;
        }
      })();
    }
    backupCurrentApp() {
      var _this5 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const backupPath = `dist-backup-${Date.now()}`; // Unique backup path with timestamp
        // Remove existing backup directory if it exists
        if (yield _this5.directoryExists(backupPath, _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data)) {
          yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.rmdir({
            path: backupPath,
            directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
            recursive: true
          });
        }
        // Copy dist to backup
        try {
          console.log('Copying dist to backup');
          yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.copy({
            from: 'dist',
            to: backupPath,
            directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
            toDirectory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data
          });
          console.log('Backup completed successfully');
        } catch (error) {
          console.error(`Backup failed: ${error.message}`);
          throw new Error(`Failed to back up dist directory: ${error.message}`);
        }
      })();
    }
    restoreBackup() {
      var _this6 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const backupPath = `dist-backup-${Date.now()}`; // Adjust to match backup path or use a stored path
        if (yield _this6.directoryExists(backupPath, _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data)) {
          console.log('Restoring dist from backup');
          try {
            // Remove current dist directory if it exists
            if (yield _this6.directoryExists('dist', _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data)) {
              yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.rmdir({
                path: 'dist',
                directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
                recursive: true
              });
            }
            // Restore from backup
            yield _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Filesystem.copy({
              from: backupPath,
              to: 'dist',
              directory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data,
              toDirectory: _capacitor_filesystem__WEBPACK_IMPORTED_MODULE_4__.Directory.Data
            });
            console.log('Restore completed successfully');
          } catch (error) {
            console.error(`Restore failed: ${error.message}`);
            throw new Error(`Failed to restore dist directory: ${error.message}`);
          }
        } else {
          console.log('No backup found, skipping restore');
        }
      })();
    }
    // #endregion
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function AppService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AppService)(_angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵinject"](_api_service__WEBPACK_IMPORTED_MODULE_7__.ApiService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_9__["ɵɵdefineInjectable"]({
      token: AppService,
      factory: AppService.ɵfac
    }))();
  }
  return AppService;
})();

/***/ }),

/***/ 1901:
/*!**********************************************************!*\
  !*** ./src/app/shared/system/services/system.service.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SystemService: () => (/* binding */ SystemService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var _system_services_api_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../system/services/api.service */ 1160);
/* harmony import */ var _ui_services_ui_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../ui/services/ui.service */ 345);





let SystemService = /*#__PURE__*/(() => {
  class SystemService {
    constructor(http, apiService, uiService) {
      this.http = http;
      this.apiService = apiService;
      this.uiService = uiService;
      // #region Device
      this.ip = new rxjs__WEBPACK_IMPORTED_MODULE_2__.BehaviorSubject(undefined);
      this.deviceInfo = new rxjs__WEBPACK_IMPORTED_MODULE_2__.BehaviorSubject(undefined);
      // #endregion
      // #region Location
      this.location = new rxjs__WEBPACK_IMPORTED_MODULE_2__.BehaviorSubject(undefined);
      this.init();
    }
    init() {
      this.getDeviceInfo();
      this.getLocation();
    }
    getDeviceInfo() {
      const url = `{{openApi}}/system/device-info`;
      this.http.get(url).subscribe({
        next: info => {
          this.deviceInfo.next(info);
        }
      });
    }
    watchDeviceInfo() {}
    getLocation() {
      const location = this.location.getValue();
      if (navigator.geolocation != null && location != null) {
        navigator.geolocation.getCurrentPosition(pos => {
          this.location.next(pos);
        }, err => {}, {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0
        });
      }
    }
    // #endregion
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function SystemService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || SystemService)(_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_4__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_system_services_api_service__WEBPACK_IMPORTED_MODULE_0__.ApiService), _angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵinject"](_ui_services_ui_service__WEBPACK_IMPORTED_MODULE_1__.UiService));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_3__["ɵɵdefineInjectable"]({
      token: SystemService,
      factory: SystemService.ɵfac
    }))();
  }
  return SystemService;
})();

/***/ }),

/***/ 9000:
/*!*********************************************************************************!*\
  !*** ./src/app/shared/ui/components/currency-input/currency-input.component.ts ***!
  \*********************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CurrencyInputComponent: () => (/* binding */ CurrencyInputComponent)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/forms */ 8335);



const _c0 = ["currencyInput"];
/* Models */
let CurrencyInputComponent = /*#__PURE__*/(() => {
  class CurrencyInputComponent {
    constructor() {
      this.enabled = true;
      this.placeholder = "";
      this.selectedLocale = "en-US";
      this.iso4217 = "USD";
      this.minAmount = 0;
      this.update = new rxjs__WEBPACK_IMPORTED_MODULE_0__.Subject();
      this.currencyOutput = new rxjs__WEBPACK_IMPORTED_MODULE_0__.Subject();
      this.amount = 0;
      this.value = "";
    }
    preventBadKeys(e) {
      const key = e.key; // 'key' gives you the character
      if (key >= '0' && key <= '9' || key === "-" || key === '.' || key === 'Backspace' || key === 'Delete') {
        // Allowed
      } else {
        e.preventDefault();
        e.stopPropagation();
      }
    }
    preventBadPaste(e) {
      this.value = e.clipboardData?.getData('text/plain') ?? this.value;
      setTimeout(() => {
        this.formatCurrency();
      }, 0);
    }
    updateResult() {
      if (this.value.length > 0) {
        const cleaned = this.value.replace(/[^0-9.-]/g, '');
        this.amount = parseFloat(cleaned) || 0;
        const result = {
          amount: this.amount,
          value: this.value
        };
        this.currencyOutput.next(result);
      } else {
        const result = {
          amount: undefined,
          value: ""
        };
        this.currencyOutput.next(result);
      }
    }
    watchUpdate() {
      this.updateSubscription = this.update.subscribe({
        next: currencyInput => {
          this.currencyInput = currencyInput;
          this.init();
        }
      });
    }
    formatCurrency() {
      if (this.value.length > 0) {
        const cleaned = this.value.replace(/[^0-9.-]/g, '');
        const validNumber = /^-?\d*\.?\d*$/.test(cleaned);
        if (validNumber) {
          this.amount = parseFloat(cleaned) || 0;
          const formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          });
          this.value = formatter.format(this.amount);
        }
      }
    }
    // #region Bootstrapping
    init() {
      if (this.currencyInput != null) {
        this.value = this.currencyInput.toString();
        this.formatCurrency();
      }
    }
    // #endregion
    ngOnInit() {
      this.watchUpdate();
      this.init();
    }
    ngOnDestroy() {
      this.updateSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function CurrencyInputComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || CurrencyInputComponent)();
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineComponent"]({
      type: CurrencyInputComponent,
      selectors: [["currency-input"]],
      viewQuery: function CurrencyInputComponent_Query(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵviewQuery"](_c0, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵloadQuery"]()) && (ctx.currencyInputElm = _t.first);
        }
      },
      inputs: {
        enabled: "enabled",
        placeholder: "placeholder",
        currencyInput: "currencyInput",
        selectedLocale: "selectedLocale",
        iso4217: "iso4217",
        maxAmount: "maxAmount",
        minAmount: "minAmount",
        update: "update"
      },
      outputs: {
        currencyOutput: "currencyOutput"
      },
      standalone: false,
      decls: 2,
      vars: 5,
      consts: [["currentInput", ""], ["inputmode", "decimal", 3, "ngModelChange", "input", "blur", "keydown", "paste", "disabled", "max", "min", "ngModel"]],
      template: function CurrencyInputComponent_Template(rf, ctx) {
        if (rf & 1) {
          const _r1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetCurrentView"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](0, "input", 1, 0);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayListener"]("ngModelChange", function CurrencyInputComponent_Template_input_ngModelChange_0_listener($event) {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayBindingSet"](ctx.value, $event) || (ctx.value = $event);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"]($event);
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("input", function CurrencyInputComponent_Template_input_input_0_listener() {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.updateResult());
          })("blur", function CurrencyInputComponent_Template_input_blur_0_listener() {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.formatCurrency());
          })("keydown", function CurrencyInputComponent_Template_input_keydown_0_listener($event) {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.preventBadKeys($event));
          })("paste", function CurrencyInputComponent_Template_input_paste_0_listener($event) {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.preventBadPaste($event));
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵproperty"]("disabled", !ctx.enabled)("max", ctx.maxAmount)("min", ctx.minAmount);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayProperty"]("ngModel", ctx.value);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵattribute"]("placeholder", ctx.placeholder);
        }
      },
      dependencies: [_angular_forms__WEBPACK_IMPORTED_MODULE_2__.DefaultValueAccessor, _angular_forms__WEBPACK_IMPORTED_MODULE_2__.NgControlStatus, _angular_forms__WEBPACK_IMPORTED_MODULE_2__.NgModel],
      styles: ["/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsInNvdXJjZVJvb3QiOiIifQ== */"]
    }))();
  }
  return CurrencyInputComponent;
})();

/***/ }),

/***/ 5086:
/*!*****************************************************************!*\
  !*** ./src/app/shared/ui/components/loader/loader.component.ts ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   LoaderComponent: () => (/* binding */ LoaderComponent)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);

/* Models */
/* Models */
let LoaderComponent = /*#__PURE__*/(() => {
  class LoaderComponent {
    constructor() {
      // #region Bootstrapping
      this.fill = false;
    }
    // #endregion
    ngOnInit() {}
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function LoaderComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || LoaderComponent)();
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({
      type: LoaderComponent,
      selectors: [["loader"]],
      inputs: {
        fill: "fill"
      },
      standalone: false,
      decls: 3,
      vars: 2,
      consts: [[1, "loader"], [1, "bounds"], [1, "wave"]],
      template: function LoaderComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 0)(1, "div", 1);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](2, "div", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵclassProp"]("fill", ctx.fill);
        }
      },
      styles: ["@keyframes _ngcontent-%COMP%_waveLoader {\n  0% {\n    transform: translate(-50%, -65%) rotate(0deg);\n  }\n  100% {\n    transform: translate(-50%, -65%) rotate(360deg);\n  }\n}\n@keyframes _ngcontent-%COMP%_waveFill {\n  0% {\n    transform: translateY(50%);\n  }\n  100% {\n    transform: translateY(0);\n  }\n}\n.loader[_ngcontent-%COMP%] {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n.loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%] {\n  position: relative;\n  width: 100%;\n  height: 100%;\n  background: var(--color2);\n  border: 0.2vw var(--color2) solid;\n  border-radius: 50%;\n  overflow: hidden;\n}\n.loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%] {\n  position: relative;\n  width: 100%;\n  height: 100%;\n  background: var(--color3);\n  border-radius: 50%;\n  transform-origin: bottom center;\n}\n.loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%]:before, .loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%]:after {\n  content: \"\";\n  position: absolute;\n  top: -15%;\n  left: 50%;\n  width: 200%;\n  height: 200%;\n  transform: translate(-50%, -65%);\n  background: var(--color1);\n}\n.loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%]:before {\n  border-radius: 45%;\n  background: rgba(var(--color2-raw), 1);\n  animation-name: _ngcontent-%COMP%_waveLoader;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n  animation-duration: 5s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n.loader[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%]:after {\n  border-radius: 40%;\n  background: rgba(var(--color2-raw), 0.5);\n  animation-name: _ngcontent-%COMP%_waveLoader;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n  animation-duration: 5s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n.loader.fill[_ngcontent-%COMP%]   .bounds[_ngcontent-%COMP%]   .wave[_ngcontent-%COMP%] {\n  animation-name: _ngcontent-%COMP%_waveFill;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: var(--fillSpeed);\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n.loader[_ngcontent-%COMP%]:not(.fill) {\n  --fillY: 1;\n  --fillX: 1;\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return LoaderComponent;
})();

/***/ }),

/***/ 8318:
/*!***************************************************************************!*\
  !*** ./src/app/shared/ui/components/phone-input/phone-input.component.ts ***!
  \***************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   PhoneInputComponent: () => (/* binding */ PhoneInputComponent)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var awesome_phonenumber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! awesome-phonenumber */ 4968);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/forms */ 8335);





const _c0 = ["phoneInput"];
function PhoneInputComponent_option_1_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](0, "option", 4);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtext"](1);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
  }
  if (rf & 2) {
    const country_r2 = ctx.$implicit;
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵproperty"]("value", country_r2);
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"]();
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtextInterpolate"](country_r2.label);
  }
}
/* Models */
let PhoneInputComponent = /*#__PURE__*/(() => {
  class PhoneInputComponent {
    constructor() {
      this.reset = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
      this.enabled = true;
      this.numberOutput = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
      this.number = "";
      this.availableCountries = [{
        iso3166: "US",
        label: "US +1"
      }];
      this.selectedCountry = this.availableCountries[0];
    }
    watchReset() {
      this.resetSubscription = this.reset.subscribe({
        next: () => {
          this.number = "";
        }
      });
    }
    focusInput() {
      this.phoneInput?.nativeElement.focus();
    }
    updatePhone(number) {
      setTimeout(() => {
        if (this.selectedCountry != null) {
          const validation = (0,awesome_phonenumber__WEBPACK_IMPORTED_MODULE_0__.parsePhoneNumber)(number, {
            regionCode: this.selectedCountry.iso3166
          });
          this.number = validation.number?.national ?? number;
          this.numberOutput.next({
            number: validation.number?.e164 ?? this.number,
            sanitizedNumber: this.sanitizePhone(validation.countryCode, this.number),
            valid: validation.valid
          });
        }
      }, 0);
    }
    formatPhone(number) {
      if (number != null && number.length > 0) {
        setTimeout(() => {
          this.updatePhone(number);
        }, 0);
      } else {
        const newValue = "";
        this.updatePhone(newValue);
      }
    }
    sanitizePhone(countryCode = 1, phoneNumber) {
      return `${countryCode}${phoneNumber.replace(/[^0-9]/g, '')}`;
    }
    init() {
      this.watchReset();
      if (this.numberInput != null) {
        this.updatePhone(this.numberInput);
      }
    }
    ngOnInit() {
      this.init();
    }
    ngOnDestroy() {
      this.resetSubscription?.unsubscribe();
    }
    static #_ = (() => this.ɵfac = function PhoneInputComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PhoneInputComponent)();
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineComponent"]({
      type: PhoneInputComponent,
      selectors: [["phone-input"]],
      viewQuery: function PhoneInputComponent_Query(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵviewQuery"](_c0, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵloadQuery"]()) && (ctx.phoneInput = _t.first);
        }
      },
      inputs: {
        reset: "reset",
        enabled: "enabled",
        placeholder: "placeholder",
        numberInput: "numberInput"
      },
      outputs: {
        numberOutput: "numberOutput"
      },
      standalone: false,
      decls: 4,
      vars: 4,
      consts: [["phoneInput", ""], ["name", "countryCode", 3, "ngModelChange", "ngModel"], [3, "value", 4, "ngFor", "ngForOf"], ["type", "tel", "name", "number", 3, "ngModelChange", "input", "ngModel"], [3, "value"]],
      template: function PhoneInputComponent_Template(rf, ctx) {
        if (rf & 1) {
          const _r1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetCurrentView"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](0, "select", 1);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayListener"]("ngModelChange", function PhoneInputComponent_Template_select_ngModelChange_0_listener($event) {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayBindingSet"](ctx.selectedCountry, $event) || (ctx.selectedCountry = $event);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"]($event);
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtemplate"](1, PhoneInputComponent_option_1_Template, 2, 2, "option", 2);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementStart"](2, "input", 3, 0);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayListener"]("ngModelChange", function PhoneInputComponent_Template_input_ngModelChange_2_listener($event) {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayBindingSet"](ctx.number, $event) || (ctx.number = $event);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"]($event);
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("input", function PhoneInputComponent_Template_input_input_2_listener() {
            _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵrestoreView"](_r1);
            return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵresetView"](ctx.formatPhone(ctx.number));
          });
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelementEnd"]();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayProperty"]("ngModel", ctx.selectedCountry);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵproperty"]("ngForOf", ctx.availableCountries);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵadvance"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵtwoWayProperty"]("ngModel", ctx.number);
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵattribute"]("placeholder", ctx.placeholder);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_3__.NgForOf, _angular_forms__WEBPACK_IMPORTED_MODULE_4__.NgSelectOption, _angular_forms__WEBPACK_IMPORTED_MODULE_4__["ɵNgSelectMultipleOption"], _angular_forms__WEBPACK_IMPORTED_MODULE_4__.DefaultValueAccessor, _angular_forms__WEBPACK_IMPORTED_MODULE_4__.SelectControlValueAccessor, _angular_forms__WEBPACK_IMPORTED_MODULE_4__.NgControlStatus, _angular_forms__WEBPACK_IMPORTED_MODULE_4__.NgModel],
      styles: ["/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsInNvdXJjZVJvb3QiOiIifQ== */"]
    }))();
  }
  return PhoneInputComponent;
})();
class PhoneCountry {
  constructor() {
    this.iso3166 = "US";
    this.label = "United States";
  }
}

/***/ }),

/***/ 5854:
/*!***************************************************************!*\
  !*** ./src/app/shared/ui/components/pipes/pipes.component.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   PipesComponent: () => (/* binding */ PipesComponent)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/common */ 6216);


function PipesComponent_div_63_Template(rf, ctx) {
  if (rf & 1) {
    _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 36);
    _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](1, "img", 37);
    _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
  }
}
/* Models */
/* Models */
let PipesComponent = /*#__PURE__*/(() => {
  class PipesComponent {
    constructor() {
      // #region Bootstrapping
      this.textured = true;
      this.showLogo = false;
    }
    // #endregion
    ngOnInit() {}
    ngOnDestroy() {}
    static #_ = (() => this.ɵfac = function PipesComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PipesComponent)();
    })();
    static #_2 = (() => this.ɵcmp = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({
      type: PipesComponent,
      selectors: [["pipes"]],
      inputs: {
        textured: "textured",
        showLogo: "showLogo"
      },
      standalone: false,
      decls: 93,
      vars: 3,
      consts: [["id", "pipes"], [1, "animation"], [1, "pipes", "main"], [1, "pipe", "left-pipe"], [1, "tube"], [1, "joints"], [1, "joint"], [1, "curved-joint"], [1, "pipe", "left-connecting-pipe"], [1, "valves"], [1, "wheel-valve"], [1, "block"], [1, "base"], [1, "wheel"], [1, "mask"], [1, "pipe", "main-pipe"], [1, "front-wheel-valve"], [1, "cross"], [1, "pressure-valve"], [1, "meter"], [1, "line-1"], [1, "line-2"], [1, "needle"], [1, "ball"], [1, "stick"], [1, "pipe", "accent-pipe"], ["class", "image", 4, "ngIf"], [1, "pipe", "right-pipe"], [1, "ball-valve"], [1, "wrap"], [1, "handle-base"], [1, "handle"], [1, "a"], [1, "b"], [1, "c"], [1, "pipe", "right-connecting-pipe"], [1, "image"], ["src", "/assets/images/uponor_logo.svg"]],
      template: function PipesComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 0)(1, "div", 1)(2, "div", 2)(3, "div", 3);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](4, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](5, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](6, "div", 6)(7, "div", 6)(8, "div", 6)(9, "div", 7);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](10, "div", 8);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](11, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](12, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](13, "div", 6);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](14, "div", 9)(15, "div", 10);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](16, "div", 11)(17, "div", 12);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](18, "div", 13);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](19, "div", 14);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](20, "div", 15);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](21, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](22, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](23, "div", 6)(24, "div", 6)(25, "div", 6);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](26, "div", 9)(27, "div", 16);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](28, "div", 11);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](29, "div", 13);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](30, "div", 17)(31, "div", 17);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](32, "div", 18);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](33, "div", 11)(34, "div", 12);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](35, "div", 19)(36, "div", 20)(37, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](38, "10");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](39, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](40, "20");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](41, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](42, "30");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](43, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](44, "40");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](45, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](46, "50");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](47, "div", 21)(48, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](49, "0");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](50, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](51, "1");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](52, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](53, "2");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](54, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](55, "3");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](56, "span");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](57, "4");
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](58, "div", 22);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](59, "div", 23)(60, "div", 24);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()()()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](61, "div", 25)(62, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](63, PipesComponent_div_63_Template, 2, 0, "div", 26);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](64, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](65, "div", 6)(66, "div", 6);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](67, "div", 27);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](68, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](69, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](70, "div", 6)(71, "div", 6)(72, "div", 6)(73, "div", 7);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](74, "div", 9)(75, "div", 28)(76, "div", 29);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](77, "div", 12)(78, "div", 30);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](79, "div", 31);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](80, "div", 32)(81, "div", 33)(82, "div", 34);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()()()()();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](83, "div", 35);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](84, "div", 4);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](85, "div", 5);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](86, "div", 6);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]();
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](87, "div", 9)(88, "div", 10);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](89, "div", 11)(90, "div", 12);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](91, "div", 13);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](92, "div", 14);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"]()()()()()()();
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵclassProp"]("textured", ctx.textured);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](63);
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngIf", ctx.showLogo);
        }
      },
      dependencies: [_angular_common__WEBPACK_IMPORTED_MODULE_1__.NgIf],
      styles: ["@keyframes _ngcontent-%COMP%_vertPipe {\n  0% {\n    transform: scaleY(0);\n  }\n  100% {\n    transform: scaleY(100%);\n  }\n}\n@keyframes _ngcontent-%COMP%_horzPipe {\n  0% {\n    transform: scaleX(0);\n  }\n  100% {\n    transform: scaleX(100%);\n  }\n}\n@keyframes _ngcontent-%COMP%_jointH {\n  0% {\n    transform: scaleX(0);\n  }\n  100% {\n    transform: scaleX(100%);\n  }\n}\n@keyframes _ngcontent-%COMP%_jointV {\n  0% {\n    transform: scaleY(0);\n  }\n  100% {\n    transform: scaleY(100%);\n  }\n}\n@keyframes _ngcontent-%COMP%_curvedJointH {\n  0% {\n    transform: scaleX(0);\n  }\n  100% {\n    transform: scaleX(100%);\n  }\n}\n@keyframes _ngcontent-%COMP%_wheel {\n  0% {\n    transform: translateX(-50%);\n  }\n  100% {\n    transform: translateX(0%);\n  }\n}\n@keyframes _ngcontent-%COMP%_valveLoadIn {\n  0% {\n    transform: scale(0);\n  }\n  100% {\n    transform: scale(1);\n  }\n}\n@keyframes _ngcontent-%COMP%_frontWheel {\n  0% {\n    transform: rotateZ(0);\n  }\n  100% {\n    transform: rotateZ(360deg);\n  }\n}\n@keyframes _ngcontent-%COMP%_meter {\n  0% {\n    transform: rotateZ(-45deg);\n  }\n  15% {\n    transform: rotateZ(75deg);\n  }\n  35% {\n    transform: rotateZ(-20deg);\n  }\n  58% {\n    transform: rotateZ(120deg);\n  }\n  76% {\n    transform: rotateZ(-90deg);\n  }\n  100% {\n    transform: rotateZ(-45deg);\n  }\n}\n@keyframes _ngcontent-%COMP%_ballValve {\n  0% {\n    transform: rotateZ(-90deg);\n  }\n  30% {\n    transform: rotateZ(0deg);\n  }\n  60% {\n    transform: rotateZ(0deg);\n  }\n  80% {\n    transform: rotateZ(-90deg);\n  }\n  100% {\n    transform: rotateZ(-90deg);\n  }\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 0;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 1;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  position: absolute;\n  background-color: var(--color2Alt4);\n  box-sizing: content-box;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  z-index: 2;\n  height: 2vw;\n  width: 10%;\n  left: 0;\n  bottom: calc(35% + 0.4vw);\n  border-top: 0.3vw var(--color2Alt3) solid;\n  border-bottom: 0.3vw var(--color2Alt3) solid;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_horzPipe;\n  animation-iteration-count: 1;\n  animation-timing-function: linear;\n  animation-duration: 0.25s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  z-index: 2;\n  border-left: 0.2vw var(--color2Alt3) solid;\n  border-right: 0.2vw var(--color2Alt3) solid;\n  height: 3vw;\n  width: 1.1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  left: 7%;\n  bottom: calc(35% + 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.2s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: calc(35% + 3vw);\n  left: 3%;\n  width: 2vw;\n  transform: scale(0);\n  transform-origin: bottom center;\n  animation-name: _ngcontent-%COMP%_valveLoadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.1666666667s;\n  animation-direction: normal;\n  animation-delay: 0.1666666667s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  width: 2vw;\n  height: 2vw;\n  background-color: var(--color2Alt4);\n  border: 0.3vw var(--color2Alt3) solid;\n  border-bottom: none;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 2vw;\n  left: 0.5vw;\n  width: 1vw;\n  height: 0.5vw;\n  background-color: var(--color2Alt4);\n  border: 0.1vw var(--color2Alt3) solid;\n  border-bottom: none;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%] {\n  position: absolute;\n  left: -1.5vw;\n  bottom: 2.5vw;\n  width: 5vw;\n  height: 1vw;\n  border-radius: 0.5vw;\n  overflow: hidden;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .mask[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: auto;\n  bottom: 0;\n  width: 200%;\n  transform: translateX(-50%);\n  background-color: var(--happyred);\n  background-color: var(--happy) 0%;\n  background-image: linear-gradient(to right, var(--happy) 0%, var(--happyred) 50%, var(--happy) 50%, var(--happyred) 100%);\n  animation-name: _ngcontent-%COMP%_wheel;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n  animation-duration: 2s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  width: 2vw;\n  height: 35%;\n  z-index: 0;\n  bottom: 0;\n  left: 10%;\n  background-color: var(--color2Alt4);\n  border-left: 0.3vw var(--color2Alt3) solid;\n  border-right: 0.3vw var(--color2Alt3) solid;\n  transform: scaleY(0);\n  transform-origin: top center;\n  animation-name: _ngcontent-%COMP%_vertPipe;\n  animation-iteration-count: 1;\n  animation-timing-function: linear;\n  animation-duration: 0.5s;\n  animation-direction: normal;\n  animation-delay: 0.3s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  border-top: 0.2vw var(--color2Alt3) solid;\n  border-bottom: 0.2vw var(--color2Alt3) solid;\n  height: 1.1vw;\n  width: 3vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  bottom: 3%;\n  left: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.75s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(2) {\n  bottom: 15%;\n  left: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.6s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(3) {\n  bottom: 32%;\n  left: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.315s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .curved-joint[_ngcontent-%COMP%] {\n  position: absolute;\n  width: 2vw;\n  height: 3vw;\n  bottom: 35%;\n  left: 10%;\n  box-sizing: content-box;\n  background-color: var(--color2Alt4);\n  border-left: 0.3vw var(--color2Alt3) solid;\n  border-right: 0.3vw var(--color2Alt3) solid;\n  border-top-right-radius: 2vw;\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_curvedJointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.05s;\n  animation-direction: normal;\n  animation-delay: 0.25s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  z-index: 1;\n  height: 2vw;\n  width: calc(80% - 3vw);\n  left: calc(10% + 1.5vw);\n  bottom: 22.5%;\n  border-top: 0.3vw var(--color2Alt3) solid;\n  border-bottom: 0.3vw var(--color2Alt3) solid;\n  border-radius: 1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 2s;\n  animation-direction: normal;\n  animation-delay: 0.42s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%]    > .image[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  left: 6.2vw;\n  height: 1.6vw;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%]    > .image[_ngcontent-%COMP%]   img[_ngcontent-%COMP%] {\n  height: 100%;\n  -moz-filter: brightness(0) invert(100%);\n  -o-filter: brightness(0) invert(100%);\n  -ms-filter: brightness(0) invert(100%);\n  filter: brightness(0) invert(100%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  z-index: 2;\n  border-left: 0.2vw var(--color2Alt3) solid;\n  border-right: 0.2vw var(--color2Alt3) solid;\n  height: 3vw;\n  width: 1.1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  left: 14%;\n  bottom: calc(22.5% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.675s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(2) {\n  left: 85%;\n  bottom: calc(22.5% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 2.175s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  z-index: 1;\n  height: 2vw;\n  width: calc(80% - 3vw);\n  left: calc(10% + 1.5vw);\n  bottom: 8%;\n  border-top: 0.3vw var(--color2Alt3) solid;\n  border-bottom: 0.3vw var(--color2Alt3) solid;\n  border-radius: 1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 1.5s;\n  animation-direction: normal;\n  animation-delay: 0.675s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  z-index: 2;\n  border-left: 0.2vw var(--color2Alt3) solid;\n  border-right: 0.2vw var(--color2Alt3) solid;\n  height: 3vw;\n  width: 1.1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleY(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  left: 14%;\n  bottom: calc(8% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 0.9s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(2) {\n  left: 50%;\n  bottom: calc(8% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 1.5s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(3) {\n  left: 85%;\n  bottom: calc(8% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 1.98s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%] {\n  position: absolute;\n  left: 25%;\n  width: 3vw;\n  bottom: 8%;\n  z-index: 1;\n  transform: scale(0);\n  transform-origin: center center;\n  animation-name: _ngcontent-%COMP%_valveLoadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.1666666667s;\n  animation-direction: normal;\n  animation-delay: 1.2s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  width: 3vw;\n  height: 2.4vw;\n  border-left: 0.2vw var(--color2Alt3) solid;\n  border-right: 0.2vw var(--color2Alt3) solid;\n  background-color: var(--color2Alt4);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: -1.75vw;\n  left: -1.5vw;\n  -moz-filter: drop-shadow(0 0 0.3vw rgba(var(--color1-raw), 0.5));\n  -o-filter: drop-shadow(0 0 0.3vw rgba(var(--color1-raw), 0.5));\n  -ms-filter: drop-shadow(0 0 0.3vw rgba(var(--color1-raw), 0.5));\n  filter: drop-shadow(0 0 0.3vw rgba(var(--color1-raw), 0.5));\n  border-radius: 100%;\n  height: 6vw;\n  width: 6vw;\n  animation-name: _ngcontent-%COMP%_frontWheel;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n  animation-duration: 8s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .cross[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  height: 80%;\n  width: 0.5vw;\n  background-color: var(--happyred);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .cross[_ngcontent-%COMP%]:first-child {\n  transform: translate(-50%, -50%) rotateZ(90deg);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%] {\n  position: absolute;\n  right: 25%;\n  width: 2vw;\n  bottom: calc(8% + 2.4vw);\n  z-index: 1;\n  transform: scale(0);\n  transform-origin: bottom center;\n  animation-name: _ngcontent-%COMP%_valveLoadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.1666666667s;\n  animation-direction: normal;\n  animation-delay: 1.68s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  width: 2vw;\n  height: 1.5vw;\n  border: 0.2vw var(--color2Alt3) solid;\n  border-bottom: none;\n  background-color: var(--color2Alt4);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 1.5vw;\n  left: 0.5vw;\n  width: 1vw;\n  height: 0.5vw;\n  border: 0.1vw var(--color2Alt3) solid;\n  border-bottom: none;\n  background-color: var(--color2Alt4);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 2vw;\n  left: -1vw;\n  height: 4vw;\n  width: 4vw;\n  border-radius: 100%;\n  border: 0.2vw var(--color2Alt4) solid;\n  background-color: var(--color2);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  border: 0.06vw var(--color1Alt3) solid;\n  height: 75%;\n  width: 75%;\n  border-radius: 100%;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%] {\n  position: absolute;\n  font-size: 0.3vw;\n  color: var(--color1);\n  font-weight: var(--stdweight);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(1) {\n  left: -17.5%;\n  top: 50%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(2) {\n  left: 0;\n  top: 5%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(3) {\n  left: 50%;\n  top: -20%;\n  transform: translateX(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(4) {\n  right: 0;\n  top: 5%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-1[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(5) {\n  right: -17.5%;\n  top: 50%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  border: 0.06vw var(--red) solid;\n  height: 62%;\n  width: 62%;\n  border-radius: 100%;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%] {\n  position: absolute;\n  font-size: 0.3vw;\n  color: var(--red);\n  font-weight: var(--stdweight);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(1) {\n  left: 5%;\n  top: 50%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(2) {\n  left: 20%;\n  top: 25%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(3) {\n  left: 50%;\n  top: 5%;\n  transform: translateX(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(4) {\n  right: 20%;\n  top: 25%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .line-2[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%]:nth-child(5) {\n  right: 5%;\n  top: 50%;\n  transform: translateY(-50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .needle[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .needle[_ngcontent-%COMP%]    > .ball[_ngcontent-%COMP%] {\n  height: 0.3vw;\n  width: 0.3vw;\n  border-radius: 100%;\n  background-color: var(--color1);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .meter[_ngcontent-%COMP%]    > .needle[_ngcontent-%COMP%]    > .stick[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0.1vw;\n  transform-origin: bottom center;\n  height: 1.6vw;\n  width: 0.2vw;\n  border-bottom: solid 1.6vw var(--color1);\n  border-left: solid 0.2vw transparent;\n  border-right: solid 0.2vw transparent;\n  animation-name: _ngcontent-%COMP%_meter;\n  animation-iteration-count: infinite;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 10s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: both;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  width: 2vw;\n  height: 35%;\n  z-index: 0;\n  bottom: 0;\n  right: 10%;\n  background-color: var(--color2Alt4);\n  border-left: 0.3vw var(--color2Alt3) solid;\n  border-right: 0.3vw var(--color2Alt3) solid;\n  transform: scaleY(0);\n  transform-origin: bottom center;\n  animation-name: _ngcontent-%COMP%_vertPipe;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 1s;\n  animation-direction: normal;\n  animation-delay: 1.2375s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  border-top: 0.2vw var(--color2Alt3) solid;\n  border-bottom: 0.2vw var(--color2Alt3) solid;\n  height: 1.1vw;\n  width: 3vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  bottom: 3%;\n  right: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 1.43s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(2) {\n  bottom: 15%;\n  right: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 1.76s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(3) {\n  bottom: 32%;\n  right: calc(10% - 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 2.09s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .curved-joint[_ngcontent-%COMP%] {\n  position: absolute;\n  width: 2vw;\n  height: 3vw;\n  bottom: 35%;\n  right: 10%;\n  box-sizing: content-box;\n  background-color: var(--color2Alt4);\n  border-left: 0.3vw var(--color2Alt3) solid;\n  border-right: 0.3vw var(--color2Alt3) solid;\n  border-top-left-radius: 2vw;\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_curvedJointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 2.205s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 28%;\n  right: calc(10% + 0.5vw);\n  height: 1.8vw;\n  width: 1.8vw;\n  z-index: 1;\n  transform: scale(0);\n  transform-origin: bottom center;\n  animation-name: _ngcontent-%COMP%_valveLoadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.1666666667s;\n  animation-direction: normal;\n  animation-delay: 1.98s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  transform-origin: center center;\n  animation-name: _ngcontent-%COMP%_ballValve;\n  animation-iteration-count: infinite;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 12s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  position: absolute;\n  z-index: 1;\n  right: 0;\n  bottom: 0;\n  height: 1.8vw;\n  width: 1.8vw;\n  border-radius: 100%;\n  background-color: var(--happyAlt3);\n  border: 0.1vw var(--happyAlt4) solid;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%]:after {\n  content: \"\";\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  background-color: rgba(var(--color2-raw), 0.5);\n  height: 0.6vw;\n  width: 0.6vw;\n  border-radius: 100%;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  z-index: 2;\n  right: -0.9vw;\n  perspective: 2vw;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .a[_ngcontent-%COMP%], \n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .b[_ngcontent-%COMP%], \n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .c[_ngcontent-%COMP%] {\n  border-top: 0.1vw var(--happyAlt4) solid;\n  border-bottom: 0.1vw var(--happyAlt4) solid;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .a[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  right: 0.4vw;\n  height: 0.75vw;\n  width: 0.6vw;\n  background-color: var(--happyAlt3);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .b[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  right: -0.1vw;\n  height: 0.75vw;\n  width: 0.55vw;\n  background-color: var(--happyAlt4);\n  transform-origin: left center;\n  transform: translateY(-50%) rotateY(-45deg);\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .handle[_ngcontent-%COMP%]    > .c[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  right: -1.3vw;\n  height: 1vw;\n  width: 1.5vw;\n  background-color: var(--happyAlt3);\n  border-right: 0.1vw var(--happyAlt4) solid;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  z-index: 2;\n  height: 2vw;\n  width: 10%;\n  right: 0;\n  bottom: calc(35% + 0.4vw);\n  background-color: var(--color2Alt4);\n  border-top: 0.3vw var(--color2Alt3) solid;\n  border-bottom: 0.3vw var(--color2Alt3) solid;\n  transform: scaleX(0);\n  transform-origin: left center;\n  animation-name: _ngcontent-%COMP%_curvedJointH;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.5s;\n  animation-direction: normal;\n  animation-delay: 2.205s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  z-index: 2;\n  border-left: 0.2vw var(--color2Alt3) solid;\n  border-right: 0.2vw var(--color2Alt3) solid;\n  height: 3vw;\n  width: 1.1vw;\n  background-color: var(--color2Alt4);\n  transform: scaleX(0);\n  transform-origin: left center;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%]:nth-child(1) {\n  right: 7%;\n  bottom: calc(35% + 0.2vw);\n  animation-name: _ngcontent-%COMP%_jointV;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.0833333333s;\n  animation-direction: normal;\n  animation-delay: 2.415s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: calc(35% + 3vw);\n  right: 5%;\n  width: 2vw;\n  transform: scale(0);\n  transform-origin: bottom center;\n  animation-name: _ngcontent-%COMP%_valveLoadIn;\n  animation-iteration-count: 1;\n  animation-timing-function: var(--easeInOutQuad);\n  animation-duration: 0.1666666667s;\n  animation-direction: normal;\n  animation-delay: 2.415s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  width: 2vw;\n  height: 2vw;\n  background-color: var(--color2Alt4);\n  border: 0.3vw var(--color2Alt3) solid;\n  border-bottom: none;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  position: absolute;\n  bottom: 2vw;\n  left: 0.5vw;\n  width: 1vw;\n  height: 0.5vw;\n  background-color: var(--color2Alt4);\n  border: 0.1vw var(--color2Alt3) solid;\n  border-bottom: none;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%] {\n  position: absolute;\n  left: -1.5vw;\n  bottom: 2.5vw;\n  width: 5vw;\n  height: 1vw;\n  border-radius: 0.5vw;\n  overflow: hidden;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .mask[_ngcontent-%COMP%] {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: auto;\n  bottom: 0;\n  width: 200%;\n  transform: translateX(-50%);\n  background-color: var(--happyred);\n  background-color: var(--happy) 0%;\n  background-image: linear-gradient(to right, var(--happy) 0%, var(--happyred) 50%, var(--happy) 50%, var(--happyred) 100%);\n  animation-name: _ngcontent-%COMP%_wheel;\n  animation-iteration-count: infinite;\n  animation-timing-function: linear;\n  animation-duration: 2s;\n  animation-direction: normal;\n  animation-delay: 0s;\n  animation-fill-mode: forwards;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  position: absolute;\n  box-sizing: content-box;\n  background-color: var(--color1Alt4);\n  z-index: 1;\n}\n#pipes[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes.main[_ngcontent-%COMP%] {\n  z-index: 2;\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to top, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to top, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 58%, var(--color2Alt3) 85%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .mask[_ngcontent-%COMP%] {\n  background-color: var(--happy) 0%;\n  background-image: linear-gradient(to right, var(--happy) 0%, var(--happyAlt4) 12.5%, var(--happyAlt3) 25%, var(--happyAlt4) 37.5%, var(--happyred) 50%, var(--happyred) 50%, var(--happyAlt4) 62.5%, var(--happyAlt3) 75%, var(--happyAlt4) 87.5%, var(--happyred) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.left-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .curved-joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: radial-gradient(ellipse farthest-corner at 0 90%, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 25%, var(--color1Alt1) 42%, var(--color2Alt3) 68%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to bottom, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.accent-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to bottom, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to bottom, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to bottom, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt1) 0%;\n  background-image: linear-gradient(to bottom, var(--color2Alt1) 0%, var(--color2Alt2) 15%, var(--color2Alt3) 35%, var(--color2Alt4) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%] {\n  background: radial-gradient(circle at 50% 50%, transparent 55%, var(--happyAlt3) 56%, var(--happyAlt3) 72%, var(--happyAlt4) 80%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .front-wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .cross[_ngcontent-%COMP%] {\n  background-color: var(--happyAlt4) 0%;\n  background-image: linear-gradient(to bottom, var(--happyAlt4) 0%, var(--happyAlt3) 25%, var(--happy) 50%, var(--happyAlt3) 75%, var(--happyAlt4) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt1) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt1) 0%, var(--color2Alt2) 15%, var(--color2Alt3) 35%, var(--color2Alt4) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.main-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .pressure-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt1) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt1) 0%, var(--color2Alt2) 15%, var(--color2Alt3) 35%, var(--color2Alt4) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to left, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to left, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .curved-joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: radial-gradient(ellipse farthest-corner at 90% 90%, var(--color2Alt2) 0%, var(--color2Alt3) 8%, var(--color2Alt3) 15%, var(--color1Alt1) 42%, var(--color2Alt3) 68%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .ball-valve[_ngcontent-%COMP%]    > .wrap[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  background-color: var(--happy) 0%;\n  background-image: radial-gradient(circle at 50% 50%, var(--happy) 0%, var(--happyAlt4) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .tube[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to top, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .joints[_ngcontent-%COMP%]    > .joint[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to top, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 58%, var(--color2Alt3) 85%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .block[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .base[_ngcontent-%COMP%] {\n  background-color: var(--color2Alt2) 0%;\n  background-image: linear-gradient(to right, var(--color2Alt2) 0%, var(--color2Alt3) 15%, var(--color2Alt3) 35%, var(--color1Alt1) 60%, var(--color2Alt3) 100%);\n}\n#pipes.textured[_ngcontent-%COMP%]    > .animation[_ngcontent-%COMP%]    > .pipes[_ngcontent-%COMP%]   .pipe.right-connecting-pipe[_ngcontent-%COMP%]    > .valves[_ngcontent-%COMP%]    > .wheel-valve[_ngcontent-%COMP%]    > .wheel[_ngcontent-%COMP%]    > .mask[_ngcontent-%COMP%] {\n  background-color: var(--happy) 0%;\n  background-image: linear-gradient(to right, var(--happy) 0%, var(--happyAlt4) 12.5%, var(--happyAlt3) 25%, var(--happyAlt4) 37.5%, var(--happy) 50%, var(--happy) 50%, var(--happyAlt4) 62.5%, var(--happyAlt3) 75%, var(--happyAlt4) 87.5%, var(--happy) 100%);\n}\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */"]
    }))();
  }
  return PipesComponent;
})();

/***/ }),

/***/ 2943:
/*!***************************************************!*\
  !*** ./src/app/shared/ui/pipes/filter-by.pipe.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FilterByPipe: () => (/* binding */ FilterByPipe)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);

let FilterByPipe = /*#__PURE__*/(() => {
  class FilterByPipe {
    transform(items, searchText, fieldName) {
      if (!items || !searchText) {
        return items;
      }
      searchText = searchText.toLowerCase();
      return items.filter(item => item[fieldName]?.toString().toLowerCase().includes(searchText));
    }
    static #_ = (() => this.ɵfac = function FilterByPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FilterByPipe)();
    })();
    static #_2 = (() => this.ɵpipe = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({
      name: "filterBy",
      type: FilterByPipe,
      pure: true,
      standalone: false
    }))();
  }
  return FilterByPipe;
})();

/***/ }),

/***/ 9093:
/*!**************************************************!*\
  !*** ./src/app/shared/ui/pipes/order-by.pipe.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   OrderByPipe: () => (/* binding */ OrderByPipe)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);

let OrderByPipe = /*#__PURE__*/(() => {
  class OrderByPipe {
    transform(value, keyName, desc = false) {
      let result = value.sort((a, b) => {
        if (a[keyName] == null || a[keyName] < b[keyName]) return -1;
        if (a[keyName] === b[keyName]) return 0;
        if (a[keyName] > b[keyName]) return 1;
        return 0;
      });
      if (desc) {
        return result.reverse();
      }
      return result;
    }
    static #_ = (() => this.ɵfac = function OrderByPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || OrderByPipe)();
    })();
    static #_2 = (() => this.ɵpipe = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({
      name: "orderBy",
      type: OrderByPipe,
      pure: false,
      standalone: false
    }))();
  }
  return OrderByPipe;
})();

/***/ }),

/***/ 3407:
/*!***********************************************!*\
  !*** ./src/app/shared/ui/pipes/phone.pipe.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   PhoneFormatPipe: () => (/* binding */ PhoneFormatPipe)
/* harmony export */ });
/* harmony import */ var awesome_phonenumber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! awesome-phonenumber */ 4968);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);


let PhoneFormatPipe = /*#__PURE__*/(() => {
  class PhoneFormatPipe {
    transform(value) {
      if (value != null) {
        const phone = (0,awesome_phonenumber__WEBPACK_IMPORTED_MODULE_0__.parsePhoneNumber)(value);
        const result = phone.number?.national ?? value;
        return result;
      }
      return "";
    }
    static #_ = (() => this.ɵfac = function PhoneFormatPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PhoneFormatPipe)();
    })();
    static #_2 = (() => this.ɵpipe = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "phone",
      type: PhoneFormatPipe,
      pure: true,
      standalone: false
    }))();
  }
  return PhoneFormatPipe;
})();

/***/ }),

/***/ 345:
/*!**************************************************!*\
  !*** ./src/app/shared/ui/services/ui.service.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   UiService: () => (/* binding */ UiService)
/* harmony export */ });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 1969);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/common */ 6216);



let UiService = /*#__PURE__*/(() => {
  class UiService {
    constructor(datePipe) {
      this.datePipe = datePipe;
      // #endregion
      // #region Prompts
      this.showPrompt = false;
      this.promptHandled = new rxjs__WEBPACK_IMPORTED_MODULE_0__.Subject();
      // #endregion
      // #region Device Support
      this.isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      this.isLegacySafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) && parseInt((navigator.userAgent.match(/version\/(\d+)/i) || [])[1]) <= 17;
      this.isPWA = window.matchMedia('(display-mode: standalone)').matches;
    }
    // #region IDs
    generateId() {
      const guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : r & 0x3 | 0x8;
        return v.toString(16);
      });
      return guid;
    }
    // #endregion
    // #region Shims
    deepClone(obj, seen = new WeakMap()) {
      if (obj === null || typeof obj !== 'object') {
        return obj;
      }
      if (Array.isArray(obj) && obj.every(item => typeof item !== 'object' && typeof item !== 'function')) {
        return [...obj];
      }
      if (seen.has(obj)) {
        return seen.get(obj);
      }
      if (obj instanceof Date) {
        return new Date(obj.getTime());
      }
      if (obj instanceof Map) {
        const clone = new Map();
        seen.set(obj, clone);
        obj.forEach((value, key) => {
          if (typeof value !== 'function') {
            clone.set(this.deepClone(key, seen), this.deepClone(value, seen));
          }
        });
        return clone;
      }
      if (obj instanceof Set) {
        const clone = new Set();
        seen.set(obj, clone);
        obj.forEach(value => {
          if (typeof value !== 'function') {
            clone.add(this.deepClone(value, seen));
          }
        });
        return clone;
      }
      if (Array.isArray(obj)) {
        const clone = [];
        seen.set(obj, clone);
        for (let i = 0; i < obj.length; i++) {
          if (typeof obj[i] !== 'function') {
            clone[i] = this.deepClone(obj[i], seen);
          }
        }
        return clone;
      }
      const clone = {};
      seen.set(obj, clone);
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          const value = obj[key];
          if (typeof value !== 'function') {
            clone[key] = this.deepClone(value, seen);
          }
        }
      }
      return clone;
    }
    base64UrlEncode(input) {
      const base64 = btoa(input);
      return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    // #endregion
    // #region Dates
    transformDate(date, format) {
      return this.datePipe.transform(date, format);
    }
    getDateOnly(date, local = true) {
      if (local) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      } else {
        return date.toISOString().slice(0, 16);
      }
    }
    getDateAsString(date, local = true) {
      if (local) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      } else {
        return date.toISOString().slice(0, 16);
      }
    }
    prompt(header, description, confirmLabel, cancelLabel = undefined) {
      this.resetPrompt();
      this.promptHeader = header;
      this.promptDescription = description;
      this.promptConfirmLabel = confirmLabel;
      this.promptCancelLabel = cancelLabel;
      this.showPrompt = true;
      return this.promptHandled.pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_1__.take)(1));
    }
    resetPrompt() {
      this.promptHandled = new rxjs__WEBPACK_IMPORTED_MODULE_0__.Subject();
    }
    cancelPrompt() {
      this.promptHandled.next(false);
      this.showPrompt = false;
    }
    confirmPrompt() {
      this.promptHandled.next(true);
      this.showPrompt = false;
    }
    static #_ = (() => this.ɵfac = function UiService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UiService)(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_3__.DatePipe));
    })();
    static #_2 = (() => this.ɵprov = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({
      token: UiService,
      factory: UiService.ɵfac
    }))();
  }
  return UiService;
})();

/***/ }),

/***/ 663:
/*!****************************************!*\
  !*** ./src/app/shared/ui/ui.module.ts ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   UiModule: () => (/* binding */ UiModule)
/* harmony export */ });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @angular/forms */ 8335);
/* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @angular/router */ 4947);
/* harmony import */ var _components_phone_input_phone_input_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/phone-input/phone-input.component */ 8318);
/* harmony import */ var _components_currency_input_currency_input_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/currency-input/currency-input.component */ 9000);
/* harmony import */ var _components_loader_loader_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/loader/loader.component */ 5086);
/* harmony import */ var _components_pipes_pipes_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/pipes/pipes.component */ 5854);
/* harmony import */ var _pipes_filter_by_pipe__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pipes/filter-by.pipe */ 2943);
/* harmony import */ var _pipes_order_by_pipe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pipes/order-by.pipe */ 9093);
/* harmony import */ var _pipes_phone_pipe__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./pipes/phone.pipe */ 3407);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/core */ 4380);



/* Components */




/* Pipes */




let UiModule = /*#__PURE__*/(() => {
  class UiModule {
    static #_ = (() => this.ɵfac = function UiModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UiModule)();
    })();
    static #_2 = (() => this.ɵmod = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵdefineNgModule"]({
      type: UiModule
    }))();
    static #_3 = (() => this.ɵinj = /*@__PURE__*/_angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵdefineInjector"]({
      imports: [_angular_common__WEBPACK_IMPORTED_MODULE_8__.CommonModule, _angular_router__WEBPACK_IMPORTED_MODULE_9__.RouterModule, _angular_forms__WEBPACK_IMPORTED_MODULE_10__.ReactiveFormsModule, _angular_forms__WEBPACK_IMPORTED_MODULE_10__.FormsModule]
    }))();
  }
  return UiModule;
})();
(function () {
  (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_7__["ɵɵsetNgModuleScope"](UiModule, {
    declarations: [_pipes_order_by_pipe__WEBPACK_IMPORTED_MODULE_5__.OrderByPipe, _pipes_filter_by_pipe__WEBPACK_IMPORTED_MODULE_4__.FilterByPipe, _pipes_phone_pipe__WEBPACK_IMPORTED_MODULE_6__.PhoneFormatPipe, _components_phone_input_phone_input_component__WEBPACK_IMPORTED_MODULE_0__.PhoneInputComponent, _components_currency_input_currency_input_component__WEBPACK_IMPORTED_MODULE_1__.CurrencyInputComponent, _components_loader_loader_component__WEBPACK_IMPORTED_MODULE_2__.LoaderComponent, _components_pipes_pipes_component__WEBPACK_IMPORTED_MODULE_3__.PipesComponent],
    imports: [_angular_common__WEBPACK_IMPORTED_MODULE_8__.CommonModule, _angular_router__WEBPACK_IMPORTED_MODULE_9__.RouterModule, _angular_forms__WEBPACK_IMPORTED_MODULE_10__.ReactiveFormsModule, _angular_forms__WEBPACK_IMPORTED_MODULE_10__.FormsModule],
    exports: [_pipes_order_by_pipe__WEBPACK_IMPORTED_MODULE_5__.OrderByPipe, _pipes_filter_by_pipe__WEBPACK_IMPORTED_MODULE_4__.FilterByPipe, _pipes_phone_pipe__WEBPACK_IMPORTED_MODULE_6__.PhoneFormatPipe, _components_phone_input_phone_input_component__WEBPACK_IMPORTED_MODULE_0__.PhoneInputComponent, _components_currency_input_currency_input_component__WEBPACK_IMPORTED_MODULE_1__.CurrencyInputComponent, _components_loader_loader_component__WEBPACK_IMPORTED_MODULE_2__.LoaderComponent, _components_pipes_pipes_component__WEBPACK_IMPORTED_MODULE_3__.PipesComponent]
  });
})();

/***/ }),

/***/ 1618:
/*!*****************************************!*\
  !*** ./src/environments/environment.ts ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   environment: () => (/* binding */ environment)
/* harmony export */ });
const environment = {
  production: true,
  APP_VERSION: 1019,
  DOCUMENT_KEY: "fejta9-tehByc-fafgyd",
  API_URL: 'https://dev.api.repipe.cloud',
  CONTENT_URL: 'https://dev.api.repipe.cloud/i'
};

/***/ }),

/***/ 4675:
/*!*********************!*\
  !*** ./src/main.ts ***!
  \*********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/platform-browser */ 4604);
/* harmony import */ var _app_app_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./app/app.module */ 3009);


_angular_platform_browser__WEBPACK_IMPORTED_MODULE_1__.platformBrowser().bootstrapModule(_app_app_module__WEBPACK_IMPORTED_MODULE_0__.AppModule).catch(err => console.error(err));

/***/ }),

/***/ 8081:
/*!***************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+app@6.0.2_@capacitor+core@6.2.0/node_modules/@capacitor/app/dist/esm/definitions.js ***!
  \***************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);


/***/ }),

/***/ 6627:
/*!*********************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+app@6.0.2_@capacitor+core@6.2.0/node_modules/@capacitor/app/dist/esm/index.js ***!
  \*********************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   App: () => (/* binding */ App)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 8081);

const App = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('App', {
  web: () => __webpack_require__.e(/*! import() */ 513).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 3513)).then(m => new m.AppWeb())
});



/***/ }),

/***/ 3755:
/*!***********************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+browser@6.0.4_@capacitor+core@6.2.0/node_modules/@capacitor/browser/dist/esm/definitions.js ***!
  \***********************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);


/***/ }),

/***/ 333:
/*!*****************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+browser@6.0.4_@capacitor+core@6.2.0/node_modules/@capacitor/browser/dist/esm/index.js ***!
  \*****************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Browser: () => (/* binding */ Browser)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 3755);

const Browser = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('Browser', {
  web: () => __webpack_require__.e(/*! import() */ 151).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 4151)).then(m => new m.BrowserWeb())
});



/***/ }),

/***/ 688:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+core@6.2.0/node_modules/@capacitor/core/dist/index.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Capacitor: () => (/* binding */ Capacitor),
/* harmony export */   CapacitorCookies: () => (/* binding */ CapacitorCookies),
/* harmony export */   CapacitorException: () => (/* binding */ CapacitorException),
/* harmony export */   CapacitorHttp: () => (/* binding */ CapacitorHttp),
/* harmony export */   CapacitorPlatforms: () => (/* binding */ CapacitorPlatforms),
/* harmony export */   ExceptionCode: () => (/* binding */ ExceptionCode),
/* harmony export */   Plugins: () => (/* binding */ Plugins),
/* harmony export */   WebPlugin: () => (/* binding */ WebPlugin),
/* harmony export */   WebView: () => (/* binding */ WebView),
/* harmony export */   addPlatform: () => (/* binding */ addPlatform),
/* harmony export */   buildRequestInit: () => (/* binding */ buildRequestInit),
/* harmony export */   registerPlugin: () => (/* binding */ registerPlugin),
/* harmony export */   registerWebPlugin: () => (/* binding */ registerWebPlugin),
/* harmony export */   setPlatform: () => (/* binding */ setPlatform)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);

/*! Capacitor: https://capacitorjs.com/ - MIT License */
const createCapacitorPlatforms = win => {
  const defaultPlatformMap = new Map();
  defaultPlatformMap.set('web', {
    name: 'web'
  });
  const capPlatforms = win.CapacitorPlatforms || {
    currentPlatform: {
      name: 'web'
    },
    platforms: defaultPlatformMap
  };
  const addPlatform = (name, platform) => {
    capPlatforms.platforms.set(name, platform);
  };
  const setPlatform = name => {
    if (capPlatforms.platforms.has(name)) {
      capPlatforms.currentPlatform = capPlatforms.platforms.get(name);
    }
  };
  capPlatforms.addPlatform = addPlatform;
  capPlatforms.setPlatform = setPlatform;
  return capPlatforms;
};
const initPlatforms = win => win.CapacitorPlatforms = createCapacitorPlatforms(win);
/**
 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
 */
const CapacitorPlatforms = /*#__PURE__*/initPlatforms(typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {});
/**
 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
 */
const addPlatform = CapacitorPlatforms.addPlatform;
/**
 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
 */
const setPlatform = CapacitorPlatforms.setPlatform;
const legacyRegisterWebPlugin = (cap, webPlugin) => {
  var _a;
  const config = webPlugin.config;
  const Plugins = cap.Plugins;
  if (!(config === null || config === void 0 ? void 0 : config.name)) {
    // TODO: add link to upgrade guide
    throw new Error(`Capacitor WebPlugin is using the deprecated "registerWebPlugin()" function, but without the config. Please use "registerPlugin()" instead to register this web plugin."`);
  }
  // TODO: add link to upgrade guide
  console.warn(`Capacitor plugin "${config.name}" is using the deprecated "registerWebPlugin()" function`);
  if (!Plugins[config.name] || ((_a = config === null || config === void 0 ? void 0 : config.platforms) === null || _a === void 0 ? void 0 : _a.includes(cap.getPlatform()))) {
    // Add the web plugin into the plugins registry if there already isn't
    // an existing one. If it doesn't already exist, that means
    // there's no existing native implementation for it.
    // - OR -
    // If we already have a plugin registered (meaning it was defined in the native layer),
    // then we should only overwrite it if the corresponding web plugin activates on
    // a certain platform. For example: Geolocation uses the WebPlugin on Android but not iOS
    Plugins[config.name] = webPlugin;
  }
};
var ExceptionCode = /*#__PURE__*/function (ExceptionCode) {
  /**
   * API is not implemented.
   *
   * This usually means the API can't be used because it is not implemented for
   * the current platform.
   */
  ExceptionCode["Unimplemented"] = "UNIMPLEMENTED";
  /**
   * API is not available.
   *
   * This means the API can't be used right now because:
   *   - it is currently missing a prerequisite, such as network connectivity
   *   - it requires a particular platform or browser version
   */
  ExceptionCode["Unavailable"] = "UNAVAILABLE";
  return ExceptionCode;
}(ExceptionCode || {});
class CapacitorException extends Error {
  constructor(message, code, data) {
    super(message);
    this.message = message;
    this.code = code;
    this.data = data;
  }
}
const getPlatformId = win => {
  var _a, _b;
  if (win === null || win === void 0 ? void 0 : win.androidBridge) {
    return 'android';
  } else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
    return 'ios';
  } else {
    return 'web';
  }
};
const createCapacitor = win => {
  var _a, _b, _c, _d, _e;
  const capCustomPlatform = win.CapacitorCustomPlatform || null;
  const cap = win.Capacitor || {};
  const Plugins = cap.Plugins = cap.Plugins || {};
  /**
   * @deprecated Use `capCustomPlatform` instead, default functions like registerPlugin will function with the new object.
   */
  const capPlatforms = win.CapacitorPlatforms;
  const defaultGetPlatform = () => {
    return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);
  };
  const getPlatform = ((_a = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _a === void 0 ? void 0 : _a.getPlatform) || defaultGetPlatform;
  const defaultIsNativePlatform = () => getPlatform() !== 'web';
  const isNativePlatform = ((_b = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _b === void 0 ? void 0 : _b.isNativePlatform) || defaultIsNativePlatform;
  const defaultIsPluginAvailable = pluginName => {
    const plugin = registeredPlugins.get(pluginName);
    if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {
      // JS implementation available for the current platform.
      return true;
    }
    if (getPluginHeader(pluginName)) {
      // Native implementation available.
      return true;
    }
    return false;
  };
  const isPluginAvailable = ((_c = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _c === void 0 ? void 0 : _c.isPluginAvailable) || defaultIsPluginAvailable;
  const defaultGetPluginHeader = pluginName => {
    var _a;
    return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find(h => h.name === pluginName);
  };
  const getPluginHeader = ((_d = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _d === void 0 ? void 0 : _d.getPluginHeader) || defaultGetPluginHeader;
  const handleError = err => win.console.error(err);
  const pluginMethodNoop = (_target, prop, pluginName) => {
    return Promise.reject(`${pluginName} does not have an implementation of "${prop}".`);
  };
  const registeredPlugins = new Map();
  const defaultRegisterPlugin = (pluginName, jsImplementations = {}) => {
    const registeredPlugin = registeredPlugins.get(pluginName);
    if (registeredPlugin) {
      console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
      return registeredPlugin.proxy;
    }
    const platform = getPlatform();
    const pluginHeader = getPluginHeader(pluginName);
    let jsImplementation;
    const loadPluginImplementation = /*#__PURE__*/function () {
      var _ref = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (!jsImplementation && platform in jsImplementations) {
          jsImplementation = typeof jsImplementations[platform] === 'function' ? jsImplementation = yield jsImplementations[platform]() : jsImplementation = jsImplementations[platform];
        } else if (capCustomPlatform !== null && !jsImplementation && 'web' in jsImplementations) {
          jsImplementation = typeof jsImplementations['web'] === 'function' ? jsImplementation = yield jsImplementations['web']() : jsImplementation = jsImplementations['web'];
        }
        return jsImplementation;
      });
      return function loadPluginImplementation() {
        return _ref.apply(this, arguments);
      };
    }();
    const createPluginMethod = (impl, prop) => {
      var _a, _b;
      if (pluginHeader) {
        const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find(m => prop === m.name);
        if (methodHeader) {
          if (methodHeader.rtype === 'promise') {
            return options => cap.nativePromise(pluginName, prop.toString(), options);
          } else {
            return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
          }
        } else if (impl) {
          return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);
        }
      } else if (impl) {
        return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);
      } else {
        throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);
      }
    };
    const createPluginMethodWrapper = prop => {
      let remove;
      const wrapper = (...args) => {
        const p = loadPluginImplementation().then(impl => {
          const fn = createPluginMethod(impl, prop);
          if (fn) {
            const p = fn(...args);
            remove = p === null || p === void 0 ? void 0 : p.remove;
            return p;
          } else {
            throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented);
          }
        });
        if (prop === 'addListener') {
          p.remove = /*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
            return remove();
          });
        }
        return p;
      };
      // Some flair ✨
      wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
      Object.defineProperty(wrapper, 'name', {
        value: prop,
        writable: false,
        configurable: false
      });
      return wrapper;
    };
    const addListener = createPluginMethodWrapper('addListener');
    const removeListener = createPluginMethodWrapper('removeListener');
    const addListenerNative = (eventName, callback) => {
      const call = addListener({
        eventName
      }, callback);
      const remove = /*#__PURE__*/function () {
        var _ref3 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
          const callbackId = yield call;
          removeListener({
            eventName,
            callbackId
          }, callback);
        });
        return function remove() {
          return _ref3.apply(this, arguments);
        };
      }();
      const p = new Promise(resolve => call.then(() => resolve({
        remove
      })));
      p.remove = /*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        console.warn(`Using addListener() without 'await' is deprecated.`);
        yield remove();
      });
      return p;
    };
    const proxy = new Proxy({}, {
      get(_, prop) {
        switch (prop) {
          // https://github.com/facebook/react/issues/20030
          case '$$typeof':
            return undefined;
          case 'toJSON':
            return () => ({});
          case 'addListener':
            return pluginHeader ? addListenerNative : addListener;
          case 'removeListener':
            return removeListener;
          default:
            return createPluginMethodWrapper(prop);
        }
      }
    });
    Plugins[pluginName] = proxy;
    registeredPlugins.set(pluginName, {
      name: pluginName,
      proxy,
      platforms: new Set([...Object.keys(jsImplementations), ...(pluginHeader ? [platform] : [])])
    });
    return proxy;
  };
  const registerPlugin = ((_e = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _e === void 0 ? void 0 : _e.registerPlugin) || defaultRegisterPlugin;
  // Add in convertFileSrc for web, it will already be available in native context
  if (!cap.convertFileSrc) {
    cap.convertFileSrc = filePath => filePath;
  }
  cap.getPlatform = getPlatform;
  cap.handleError = handleError;
  cap.isNativePlatform = isNativePlatform;
  cap.isPluginAvailable = isPluginAvailable;
  cap.pluginMethodNoop = pluginMethodNoop;
  cap.registerPlugin = registerPlugin;
  cap.Exception = CapacitorException;
  cap.DEBUG = !!cap.DEBUG;
  cap.isLoggingEnabled = !!cap.isLoggingEnabled;
  // Deprecated props
  cap.platform = cap.getPlatform();
  cap.isNative = cap.isNativePlatform();
  return cap;
};
const initCapacitorGlobal = win => win.Capacitor = createCapacitor(win);
const Capacitor = /*#__PURE__*/initCapacitorGlobal(typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {});
const registerPlugin = Capacitor.registerPlugin;
/**
 * @deprecated Provided for backwards compatibility for Capacitor v2 plugins.
 * Capacitor v3 plugins should import the plugin directly. This "Plugins"
 * export is deprecated in v3, and will be removed in v4.
 */
const Plugins = Capacitor.Plugins;
/**
 * Provided for backwards compatibility. Use the registerPlugin() API
 * instead, and provide the web plugin as the "web" implmenetation.
 * For example
 *
 * export const Example = registerPlugin('Example', {
 *   web: () => import('./web').then(m => new m.Example())
 * })
 *
 * @deprecated Deprecated in v3, will be removed from v4.
 */
const registerWebPlugin = plugin => legacyRegisterWebPlugin(Capacitor, plugin);

/**
 * Base class web plugins should extend.
 */
class WebPlugin {
  constructor(config) {
    this.listeners = {};
    this.retainedEventArguments = {};
    this.windowListeners = {};
    if (config) {
      // TODO: add link to upgrade guide
      console.warn(`Capacitor WebPlugin "${config.name}" config object was deprecated in v3 and will be removed in v4.`);
      this.config = config;
    }
  }
  addListener(eventName, listenerFunc) {
    var _this = this;
    let firstListener = false;
    const listeners = this.listeners[eventName];
    if (!listeners) {
      this.listeners[eventName] = [];
      firstListener = true;
    }
    this.listeners[eventName].push(listenerFunc);
    // If we haven't added a window listener for this event and it requires one,
    // go ahead and add it
    const windowListener = this.windowListeners[eventName];
    if (windowListener && !windowListener.registered) {
      this.addWindowListener(windowListener);
    }
    if (firstListener) {
      this.sendRetainedArgumentsForEvent(eventName);
    }
    const remove = /*#__PURE__*/function () {
      var _ref5 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        return _this.removeListener(eventName, listenerFunc);
      });
      return function remove() {
        return _ref5.apply(this, arguments);
      };
    }();
    const p = Promise.resolve({
      remove
    });
    return p;
  }
  removeAllListeners() {
    var _this2 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      _this2.listeners = {};
      for (const listener in _this2.windowListeners) {
        _this2.removeWindowListener(_this2.windowListeners[listener]);
      }
      _this2.windowListeners = {};
    })();
  }
  notifyListeners(eventName, data, retainUntilConsumed) {
    const listeners = this.listeners[eventName];
    if (!listeners) {
      if (retainUntilConsumed) {
        let args = this.retainedEventArguments[eventName];
        if (!args) {
          args = [];
        }
        args.push(data);
        this.retainedEventArguments[eventName] = args;
      }
      return;
    }
    listeners.forEach(listener => listener(data));
  }
  hasListeners(eventName) {
    return !!this.listeners[eventName].length;
  }
  registerWindowListener(windowEventName, pluginEventName) {
    this.windowListeners[pluginEventName] = {
      registered: false,
      windowEventName,
      pluginEventName,
      handler: event => {
        this.notifyListeners(pluginEventName, event);
      }
    };
  }
  unimplemented(msg = 'not implemented') {
    return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);
  }
  unavailable(msg = 'not available') {
    return new Capacitor.Exception(msg, ExceptionCode.Unavailable);
  }
  removeListener(eventName, listenerFunc) {
    var _this3 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      const listeners = _this3.listeners[eventName];
      if (!listeners) {
        return;
      }
      const index = listeners.indexOf(listenerFunc);
      _this3.listeners[eventName].splice(index, 1);
      // If there are no more listeners for this type of event,
      // remove the window listener
      if (!_this3.listeners[eventName].length) {
        _this3.removeWindowListener(_this3.windowListeners[eventName]);
      }
    })();
  }
  addWindowListener(handle) {
    window.addEventListener(handle.windowEventName, handle.handler);
    handle.registered = true;
  }
  removeWindowListener(handle) {
    if (!handle) {
      return;
    }
    window.removeEventListener(handle.windowEventName, handle.handler);
    handle.registered = false;
  }
  sendRetainedArgumentsForEvent(eventName) {
    const args = this.retainedEventArguments[eventName];
    if (!args) {
      return;
    }
    delete this.retainedEventArguments[eventName];
    args.forEach(arg => {
      this.notifyListeners(eventName, arg);
    });
  }
}
const WebView = /*#__PURE__*/registerPlugin('WebView');
/******** END WEB VIEW PLUGIN ********/
/******** COOKIES PLUGIN ********/
/**
 * Safely web encode a string value (inspired by js-cookie)
 * @param str The string value to encode
 */
const encode = str => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
/**
 * Safely web decode a string value (inspired by js-cookie)
 * @param str The string value to decode
 */
const decode = str => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
class CapacitorCookiesPluginWeb extends WebPlugin {
  getCookies() {
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      const cookies = document.cookie;
      const cookieMap = {};
      cookies.split(';').forEach(cookie => {
        if (cookie.length <= 0) return;
        // Replace first "=" with CAP_COOKIE to prevent splitting on additional "="
        let [key, value] = cookie.replace(/=/, 'CAP_COOKIE').split('CAP_COOKIE');
        key = decode(key).trim();
        value = decode(value).trim();
        cookieMap[key] = value;
      });
      return cookieMap;
    })();
  }
  setCookie(options) {
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      try {
        // Safely Encoded Key/Value
        const encodedKey = encode(options.key);
        const encodedValue = encode(options.value);
        // Clean & sanitize options
        const expires = `; expires=${(options.expires || '').replace('expires=', '')}`; // Default is "; expires="
        const path = (options.path || '/').replace('path=', ''); // Default is "path=/"
        const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : '';
        document.cookie = `${encodedKey}=${encodedValue || ''}${expires}; path=${path}; ${domain};`;
      } catch (error) {
        return Promise.reject(error);
      }
    })();
  }
  deleteCookie(options) {
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      try {
        document.cookie = `${options.key}=; Max-Age=0`;
      } catch (error) {
        return Promise.reject(error);
      }
    })();
  }
  clearCookies() {
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      try {
        const cookies = document.cookie.split(';') || [];
        for (const cookie of cookies) {
          document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    })();
  }
  clearAllCookies() {
    var _this4 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      try {
        yield _this4.clearCookies();
      } catch (error) {
        return Promise.reject(error);
      }
    })();
  }
}
const CapacitorCookies = registerPlugin('CapacitorCookies', {
  web: () => new CapacitorCookiesPluginWeb()
});
// UTILITY FUNCTIONS
/**
 * Read in a Blob value and return it as a base64 string
 * @param blob The blob value to convert to a base64 string
 */
const readBlobAsBase64 = /*#__PURE__*/function () {
  var _ref6 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const base64String = reader.result;
        // remove prefix "data:application/pdf;base64,"
        resolve(base64String.indexOf(',') >= 0 ? base64String.split(',')[1] : base64String);
      };
      reader.onerror = error => reject(error);
      reader.readAsDataURL(blob);
    });
  });
  return function readBlobAsBase64(_x) {
    return _ref6.apply(this, arguments);
  };
}();
/**
 * Normalize an HttpHeaders map by lowercasing all of the values
 * @param headers The HttpHeaders object to normalize
 */
const normalizeHttpHeaders = (headers = {}) => {
  const originalKeys = Object.keys(headers);
  const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase());
  const normalized = loweredKeys.reduce((acc, key, index) => {
    acc[key] = headers[originalKeys[index]];
    return acc;
  }, {});
  return normalized;
};
/**
 * Builds a string of url parameters that
 * @param params A map of url parameters
 * @param shouldEncode true if you should encodeURIComponent() the values (true by default)
 */
const buildUrlParams = (params, shouldEncode = true) => {
  if (!params) return null;
  const output = Object.entries(params).reduce((accumulator, entry) => {
    const [key, value] = entry;
    let encodedValue;
    let item;
    if (Array.isArray(value)) {
      item = '';
      value.forEach(str => {
        encodedValue = shouldEncode ? encodeURIComponent(str) : str;
        item += `${key}=${encodedValue}&`;
      });
      // last character will always be "&" so slice it off
      item.slice(0, -1);
    } else {
      encodedValue = shouldEncode ? encodeURIComponent(value) : value;
      item = `${key}=${encodedValue}`;
    }
    return `${accumulator}&${item}`;
  }, '');
  // Remove initial "&" from the reduce
  return output.substr(1);
};
/**
 * Build the RequestInit object based on the options passed into the initial request
 * @param options The Http plugin options
 * @param extra Any extra RequestInit values
 */
const buildRequestInit = (options, extra = {}) => {
  const output = Object.assign({
    method: options.method || 'GET',
    headers: options.headers
  }, extra);
  // Get the content-type
  const headers = normalizeHttpHeaders(options.headers);
  const type = headers['content-type'] || '';
  // If body is already a string, then pass it through as-is.
  if (typeof options.data === 'string') {
    output.body = options.data;
  }
  // Build request initializers based off of content-type
  else if (type.includes('application/x-www-form-urlencoded')) {
    const params = new URLSearchParams();
    for (const [key, value] of Object.entries(options.data || {})) {
      params.set(key, value);
    }
    output.body = params.toString();
  } else if (type.includes('multipart/form-data') || options.data instanceof FormData) {
    const form = new FormData();
    if (options.data instanceof FormData) {
      options.data.forEach((value, key) => {
        form.append(key, value);
      });
    } else {
      for (const key of Object.keys(options.data)) {
        form.append(key, options.data[key]);
      }
    }
    output.body = form;
    const headers = new Headers(output.headers);
    headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary
    output.headers = headers;
  } else if (type.includes('application/json') || typeof options.data === 'object') {
    output.body = JSON.stringify(options.data);
  }
  return output;
};
// WEB IMPLEMENTATION
class CapacitorHttpPluginWeb extends WebPlugin {
  /**
   * Perform an Http request given a set of options
   * @param options Options to build the HTTP request
   */
  request(options) {
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      const requestInit = buildRequestInit(options, options.webFetchExtra);
      const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);
      const url = urlParams ? `${options.url}?${urlParams}` : options.url;
      const response = yield fetch(url, requestInit);
      const contentType = response.headers.get('content-type') || '';
      // Default to 'text' responseType so no parsing happens
      let {
        responseType = 'text'
      } = response.ok ? options : {};
      // If the response content-type is json, force the response to be json
      if (contentType.includes('application/json')) {
        responseType = 'json';
      }
      let data;
      let blob;
      switch (responseType) {
        case 'arraybuffer':
        case 'blob':
          blob = yield response.blob();
          data = yield readBlobAsBase64(blob);
          break;
        case 'json':
          data = yield response.json();
          break;
        case 'document':
        case 'text':
        default:
          data = yield response.text();
      }
      // Convert fetch headers to Capacitor HttpHeaders
      const headers = {};
      response.headers.forEach((value, key) => {
        headers[key] = value;
      });
      return {
        data,
        headers,
        status: response.status,
        url: response.url
      };
    })();
  }
  /**
   * Perform an Http GET request given a set of options
   * @param options Options to build the HTTP request
   */
  get(options) {
    var _this5 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      return _this5.request(Object.assign(Object.assign({}, options), {
        method: 'GET'
      }));
    })();
  }
  /**
   * Perform an Http POST request given a set of options
   * @param options Options to build the HTTP request
   */
  post(options) {
    var _this6 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      return _this6.request(Object.assign(Object.assign({}, options), {
        method: 'POST'
      }));
    })();
  }
  /**
   * Perform an Http PUT request given a set of options
   * @param options Options to build the HTTP request
   */
  put(options) {
    var _this7 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      return _this7.request(Object.assign(Object.assign({}, options), {
        method: 'PUT'
      }));
    })();
  }
  /**
   * Perform an Http PATCH request given a set of options
   * @param options Options to build the HTTP request
   */
  patch(options) {
    var _this8 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      return _this8.request(Object.assign(Object.assign({}, options), {
        method: 'PATCH'
      }));
    })();
  }
  /**
   * Perform an Http DELETE request given a set of options
   * @param options Options to build the HTTP request
   */
  delete(options) {
    var _this9 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      return _this9.request(Object.assign(Object.assign({}, options), {
        method: 'DELETE'
      }));
    })();
  }
}
const CapacitorHttp = registerPlugin('CapacitorHttp', {
  web: () => new CapacitorHttpPluginWeb()
});
/******** END HTTP PLUGIN ********/



/***/ }),

/***/ 1011:
/*!*****************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+filesystem@6.0.2_@capacitor+core@6.2.0/node_modules/@capacitor/filesystem/dist/esm/definitions.js ***!
  \*****************************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Directory: () => (/* binding */ Directory),
/* harmony export */   Encoding: () => (/* binding */ Encoding),
/* harmony export */   FilesystemDirectory: () => (/* binding */ FilesystemDirectory),
/* harmony export */   FilesystemEncoding: () => (/* binding */ FilesystemEncoding)
/* harmony export */ });
var Directory = /*#__PURE__*/function (Directory) {
  /**
   * The Documents directory.
   * On iOS it's the app's documents directory.
   * Use this directory to store user-generated content.
   * On Android it's the Public Documents folder, so it's accessible from other apps.
   * It's not accesible on Android 10 unless the app enables legacy External Storage
   * by adding `android:requestLegacyExternalStorage="true"` in the `application` tag
   * in the `AndroidManifest.xml`.
   * On Android 11 or newer the app can only access the files/folders the app created.
   *
   * @since 1.0.0
   */
  Directory["Documents"] = "DOCUMENTS";
  /**
   * The Data directory.
   * On iOS it will use the Documents directory.
   * On Android it's the directory holding application files.
   * Files will be deleted when the application is uninstalled.
   *
   * @since 1.0.0
   */
  Directory["Data"] = "DATA";
  /**
   * The Library directory.
   * On iOS it will use the Library directory.
   * On Android it's the directory holding application files.
   * Files will be deleted when the application is uninstalled.
   *
   * @since 1.1.0
   */
  Directory["Library"] = "LIBRARY";
  /**
   * The Cache directory.
   * Can be deleted in cases of low memory, so use this directory to write app-specific files.
   * that your app can re-create easily.
   *
   * @since 1.0.0
   */
  Directory["Cache"] = "CACHE";
  /**
   * The external directory.
   * On iOS it will use the Documents directory.
   * On Android it's the directory on the primary shared/external
   * storage device where the application can place persistent files it owns.
   * These files are internal to the applications, and not typically visible
   * to the user as media.
   * Files will be deleted when the application is uninstalled.
   *
   * @since 1.0.0
   */
  Directory["External"] = "EXTERNAL";
  /**
   * The external storage directory.
   * On iOS it will use the Documents directory.
   * On Android it's the primary shared/external storage directory.
   * It's not accesible on Android 10 unless the app enables legacy External Storage
   * by adding `android:requestLegacyExternalStorage="true"` in the `application` tag
   * in the `AndroidManifest.xml`.
   * It's not accesible on Android 11 or newer.
   *
   * @since 1.0.0
   */
  Directory["ExternalStorage"] = "EXTERNAL_STORAGE";
  return Directory;
}(Directory || {});
var Encoding = /*#__PURE__*/function (Encoding) {
  /**
   * Eight-bit UCS Transformation Format
   *
   * @since 1.0.0
   */
  Encoding["UTF8"] = "utf8";
  /**
   * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the
   * Unicode character set
   * This encoding is only supported on Android.
   *
   * @since 1.0.0
   */
  Encoding["ASCII"] = "ascii";
  /**
   * Sixteen-bit UCS Transformation Format, byte order identified by an
   * optional byte-order mark
   * This encoding is only supported on Android.
   *
   * @since 1.0.0
   */
  Encoding["UTF16"] = "utf16";
  return Encoding;
}(Encoding || {});
/**
 * @deprecated Use `Directory`.
 * @since 1.0.0
 */
const FilesystemDirectory = Directory;
/**
 * @deprecated Use `Encoding`.
 * @since 1.0.0
 */
const FilesystemEncoding = Encoding;

/***/ }),

/***/ 2565:
/*!***********************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+filesystem@6.0.2_@capacitor+core@6.2.0/node_modules/@capacitor/filesystem/dist/esm/index.js ***!
  \***********************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Directory: () => (/* reexport safe */ _definitions__WEBPACK_IMPORTED_MODULE_1__.Directory),
/* harmony export */   Encoding: () => (/* reexport safe */ _definitions__WEBPACK_IMPORTED_MODULE_1__.Encoding),
/* harmony export */   Filesystem: () => (/* binding */ Filesystem),
/* harmony export */   FilesystemDirectory: () => (/* reexport safe */ _definitions__WEBPACK_IMPORTED_MODULE_1__.FilesystemDirectory),
/* harmony export */   FilesystemEncoding: () => (/* reexport safe */ _definitions__WEBPACK_IMPORTED_MODULE_1__.FilesystemEncoding)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 1011);

const Filesystem = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('Filesystem', {
  web: () => __webpack_require__.e(/*! import() */ 367).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 8367)).then(m => new m.FilesystemWeb())
});



/***/ }),

/***/ 4208:
/*!***********************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+network@6.0.3_@capacitor+core@6.2.0/node_modules/@capacitor/network/dist/esm/definitions.js ***!
  \***********************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);


/***/ }),

/***/ 926:
/*!*****************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+network@6.0.3_@capacitor+core@6.2.0/node_modules/@capacitor/network/dist/esm/index.js ***!
  \*****************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Network: () => (/* binding */ Network)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 4208);

const Network = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('Network', {
  web: () => __webpack_require__.e(/*! import() */ 380).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 2380)).then(m => new m.NetworkWeb())
});



/***/ }),

/***/ 3836:
/*!*******************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+preferences@6.0.3_@capacitor+core@6.2.0/node_modules/@capacitor/preferences/dist/esm/definitions.js ***!
  \*******************************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);


/***/ }),

/***/ 2522:
/*!*************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@capacitor+preferences@6.0.3_@capacitor+core@6.2.0/node_modules/@capacitor/preferences/dist/esm/index.js ***!
  \*************************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Preferences: () => (/* binding */ Preferences)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 3836);

const Preferences = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('Preferences', {
  web: () => __webpack_require__.e(/*! import() */ 448).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 6448)).then(m => new m.PreferencesWeb())
});



/***/ }),

/***/ 2094:
/*!***********************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/capacitor-plugin-app-tracking-transparency@2.0.5_@capacitor+core@6.2.0/node_modules/capacitor-plugin-app-tracking-transparency/dist/esm/definitions.js ***!
  \***********************************************************************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);


/***/ }),

/***/ 6556:
/*!*****************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/capacitor-plugin-app-tracking-transparency@2.0.5_@capacitor+core@6.2.0/node_modules/capacitor-plugin-app-tracking-transparency/dist/esm/index.js ***!
  \*****************************************************************************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AppTrackingTransparency: () => (/* binding */ AppTrackingTransparency)
/* harmony export */ });
/* harmony import */ var _capacitor_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @capacitor/core */ 688);
/* harmony import */ var _definitions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./definitions */ 2094);

const AppTrackingTransparency = (0,_capacitor_core__WEBPACK_IMPORTED_MODULE_0__.registerPlugin)('AppTrackingTransparency', {
  web: () => __webpack_require__.e(/*! import() */ 182).then(__webpack_require__.bind(__webpack_require__, /*! ./web */ 2182)).then(m => new m.AppTrackingTransparencyWeb())
});



/***/ }),

/***/ 1992:
/*!**************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/aes.js ***!
  \**************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Lookup tables
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX_0 = [];
    var SUB_MIX_1 = [];
    var SUB_MIX_2 = [];
    var SUB_MIX_3 = [];
    var INV_SUB_MIX_0 = [];
    var INV_SUB_MIX_1 = [];
    var INV_SUB_MIX_2 = [];
    var INV_SUB_MIX_3 = [];

    // Compute lookup tables
    (function () {
      // Compute double table
      var d = [];
      for (var i = 0; i < 256; i++) {
        if (i < 128) {
          d[i] = i << 1;
        } else {
          d[i] = i << 1 ^ 0x11b;
        }
      }

      // Walk GF(2^8)
      var x = 0;
      var xi = 0;
      for (var i = 0; i < 256; i++) {
        // Compute sbox
        var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
        sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
        SBOX[x] = sx;
        INV_SBOX[sx] = x;

        // Compute multiplication
        var x2 = d[x];
        var x4 = d[x2];
        var x8 = d[x4];

        // Compute sub bytes, mix columns tables
        var t = d[sx] * 0x101 ^ sx * 0x1010100;
        SUB_MIX_0[x] = t << 24 | t >>> 8;
        SUB_MIX_1[x] = t << 16 | t >>> 16;
        SUB_MIX_2[x] = t << 8 | t >>> 24;
        SUB_MIX_3[x] = t;

        // Compute inv sub bytes, inv mix columns tables
        var t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
        INV_SUB_MIX_0[sx] = t << 24 | t >>> 8;
        INV_SUB_MIX_1[sx] = t << 16 | t >>> 16;
        INV_SUB_MIX_2[sx] = t << 8 | t >>> 24;
        INV_SUB_MIX_3[sx] = t;

        // Compute next counter
        if (!x) {
          x = xi = 1;
        } else {
          x = x2 ^ d[d[d[x8 ^ x2]]];
          xi ^= d[d[xi]];
        }
      }
    })();

    // Precomputed Rcon lookup
    var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];

    /**
     * AES block cipher algorithm.
     */
    var AES = C_algo.AES = BlockCipher.extend({
      _doReset: function () {
        var t;

        // Skip reset of nRounds has been set before and key did not change
        if (this._nRounds && this._keyPriorReset === this._key) {
          return;
        }

        // Shortcuts
        var key = this._keyPriorReset = this._key;
        var keyWords = key.words;
        var keySize = key.sigBytes / 4;

        // Compute number of rounds
        var nRounds = this._nRounds = keySize + 6;

        // Compute number of key schedule rows
        var ksRows = (nRounds + 1) * 4;

        // Compute key schedule
        var keySchedule = this._keySchedule = [];
        for (var ksRow = 0; ksRow < ksRows; ksRow++) {
          if (ksRow < keySize) {
            keySchedule[ksRow] = keyWords[ksRow];
          } else {
            t = keySchedule[ksRow - 1];
            if (!(ksRow % keySize)) {
              // Rot word
              t = t << 8 | t >>> 24;

              // Sub word
              t = SBOX[t >>> 24] << 24 | SBOX[t >>> 16 & 0xff] << 16 | SBOX[t >>> 8 & 0xff] << 8 | SBOX[t & 0xff];

              // Mix Rcon
              t ^= RCON[ksRow / keySize | 0] << 24;
            } else if (keySize > 6 && ksRow % keySize == 4) {
              // Sub word
              t = SBOX[t >>> 24] << 24 | SBOX[t >>> 16 & 0xff] << 16 | SBOX[t >>> 8 & 0xff] << 8 | SBOX[t & 0xff];
            }
            keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
          }
        }

        // Compute inv key schedule
        var invKeySchedule = this._invKeySchedule = [];
        for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
          var ksRow = ksRows - invKsRow;
          if (invKsRow % 4) {
            var t = keySchedule[ksRow];
          } else {
            var t = keySchedule[ksRow - 4];
          }
          if (invKsRow < 4 || ksRow <= 4) {
            invKeySchedule[invKsRow] = t;
          } else {
            invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[t >>> 16 & 0xff]] ^ INV_SUB_MIX_2[SBOX[t >>> 8 & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
          }
        }
      },
      encryptBlock: function (M, offset) {
        this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
      },
      decryptBlock: function (M, offset) {
        // Swap 2nd and 4th rows
        var t = M[offset + 1];
        M[offset + 1] = M[offset + 3];
        M[offset + 3] = t;
        this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);

        // Inv swap 2nd and 4th rows
        var t = M[offset + 1];
        M[offset + 1] = M[offset + 3];
        M[offset + 3] = t;
      },
      _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
        // Shortcut
        var nRounds = this._nRounds;

        // Get input, add round key
        var s0 = M[offset] ^ keySchedule[0];
        var s1 = M[offset + 1] ^ keySchedule[1];
        var s2 = M[offset + 2] ^ keySchedule[2];
        var s3 = M[offset + 3] ^ keySchedule[3];

        // Key schedule row counter
        var ksRow = 4;

        // Rounds
        for (var round = 1; round < nRounds; round++) {
          // Shift rows, sub bytes, mix columns, add round key
          var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[s1 >>> 16 & 0xff] ^ SUB_MIX_2[s2 >>> 8 & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
          var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[s2 >>> 16 & 0xff] ^ SUB_MIX_2[s3 >>> 8 & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
          var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[s3 >>> 16 & 0xff] ^ SUB_MIX_2[s0 >>> 8 & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
          var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[s0 >>> 16 & 0xff] ^ SUB_MIX_2[s1 >>> 8 & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];

          // Update state
          s0 = t0;
          s1 = t1;
          s2 = t2;
          s3 = t3;
        }

        // Shift rows, sub bytes, add round key
        var t0 = (SBOX[s0 >>> 24] << 24 | SBOX[s1 >>> 16 & 0xff] << 16 | SBOX[s2 >>> 8 & 0xff] << 8 | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
        var t1 = (SBOX[s1 >>> 24] << 24 | SBOX[s2 >>> 16 & 0xff] << 16 | SBOX[s3 >>> 8 & 0xff] << 8 | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
        var t2 = (SBOX[s2 >>> 24] << 24 | SBOX[s3 >>> 16 & 0xff] << 16 | SBOX[s0 >>> 8 & 0xff] << 8 | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
        var t3 = (SBOX[s3 >>> 24] << 24 | SBOX[s0 >>> 16 & 0xff] << 16 | SBOX[s1 >>> 8 & 0xff] << 8 | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];

        // Set output
        M[offset] = t0;
        M[offset + 1] = t1;
        M[offset + 2] = t2;
        M[offset + 3] = t3;
      },
      keySize: 256 / 32
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
     */
    C.AES = BlockCipher._createHelper(AES);
  })();
  return CryptoJS.AES;
});

/***/ }),

/***/ 1817:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/blowfish.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;
    const N = 16;

    //Origin pbox and sbox, derived from PI
    const ORIG_P = [0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, 0x9216D5D9, 0x8979FB1B];
    const ORIG_S = [[0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A], [0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7], [0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0], [0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6]];
    var BLOWFISH_CTX = {
      pbox: [],
      sbox: []
    };
    function F(ctx, x) {
      let a = x >> 24 & 0xFF;
      let b = x >> 16 & 0xFF;
      let c = x >> 8 & 0xFF;
      let d = x & 0xFF;
      let y = ctx.sbox[0][a] + ctx.sbox[1][b];
      y = y ^ ctx.sbox[2][c];
      y = y + ctx.sbox[3][d];
      return y;
    }
    function BlowFish_Encrypt(ctx, left, right) {
      let Xl = left;
      let Xr = right;
      let temp;
      for (let i = 0; i < N; ++i) {
        Xl = Xl ^ ctx.pbox[i];
        Xr = F(ctx, Xl) ^ Xr;
        temp = Xl;
        Xl = Xr;
        Xr = temp;
      }
      temp = Xl;
      Xl = Xr;
      Xr = temp;
      Xr = Xr ^ ctx.pbox[N];
      Xl = Xl ^ ctx.pbox[N + 1];
      return {
        left: Xl,
        right: Xr
      };
    }
    function BlowFish_Decrypt(ctx, left, right) {
      let Xl = left;
      let Xr = right;
      let temp;
      for (let i = N + 1; i > 1; --i) {
        Xl = Xl ^ ctx.pbox[i];
        Xr = F(ctx, Xl) ^ Xr;
        temp = Xl;
        Xl = Xr;
        Xr = temp;
      }
      temp = Xl;
      Xl = Xr;
      Xr = temp;
      Xr = Xr ^ ctx.pbox[1];
      Xl = Xl ^ ctx.pbox[0];
      return {
        left: Xl,
        right: Xr
      };
    }

    /**
     * Initialization ctx's pbox and sbox.
     *
     * @param {Object} ctx The object has pbox and sbox.
     * @param {Array} key An array of 32-bit words.
     * @param {int} keysize The length of the key.
     *
     * @example
     *
     *     BlowFishInit(BLOWFISH_CTX, key, 128/32);
     */
    function BlowFishInit(ctx, key, keysize) {
      for (let Row = 0; Row < 4; Row++) {
        ctx.sbox[Row] = [];
        for (let Col = 0; Col < 256; Col++) {
          ctx.sbox[Row][Col] = ORIG_S[Row][Col];
        }
      }
      let keyIndex = 0;
      for (let index = 0; index < N + 2; index++) {
        ctx.pbox[index] = ORIG_P[index] ^ key[keyIndex];
        keyIndex++;
        if (keyIndex >= keysize) {
          keyIndex = 0;
        }
      }
      let Data1 = 0;
      let Data2 = 0;
      let res = 0;
      for (let i = 0; i < N + 2; i += 2) {
        res = BlowFish_Encrypt(ctx, Data1, Data2);
        Data1 = res.left;
        Data2 = res.right;
        ctx.pbox[i] = Data1;
        ctx.pbox[i + 1] = Data2;
      }
      for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 256; j += 2) {
          res = BlowFish_Encrypt(ctx, Data1, Data2);
          Data1 = res.left;
          Data2 = res.right;
          ctx.sbox[i][j] = Data1;
          ctx.sbox[i][j + 1] = Data2;
        }
      }
      return true;
    }

    /**
     * Blowfish block cipher algorithm.
     */
    var Blowfish = C_algo.Blowfish = BlockCipher.extend({
      _doReset: function () {
        // Skip reset of nRounds has been set before and key did not change
        if (this._keyPriorReset === this._key) {
          return;
        }

        // Shortcuts
        var key = this._keyPriorReset = this._key;
        var keyWords = key.words;
        var keySize = key.sigBytes / 4;

        //Initialization pbox and sbox
        BlowFishInit(BLOWFISH_CTX, keyWords, keySize);
      },
      encryptBlock: function (M, offset) {
        var res = BlowFish_Encrypt(BLOWFISH_CTX, M[offset], M[offset + 1]);
        M[offset] = res.left;
        M[offset + 1] = res.right;
      },
      decryptBlock: function (M, offset) {
        var res = BlowFish_Decrypt(BLOWFISH_CTX, M[offset], M[offset + 1]);
        M[offset] = res.left;
        M[offset + 1] = res.right;
      },
      blockSize: 64 / 32,
      keySize: 128 / 32,
      ivSize: 64 / 32
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.Blowfish.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.Blowfish.decrypt(ciphertext, key, cfg);
     */
    C.Blowfish = BlockCipher._createHelper(Blowfish);
  })();
  return CryptoJS.Blowfish;
});

/***/ }),

/***/ 2698:
/*!**********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/cipher-core.js ***!
  \**********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./evpkdf */ 4631));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Cipher core components.
   */
  CryptoJS.lib.Cipher || function (undefined) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Base = C_lib.Base;
    var WordArray = C_lib.WordArray;
    var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
    var C_enc = C.enc;
    var Utf8 = C_enc.Utf8;
    var Base64 = C_enc.Base64;
    var C_algo = C.algo;
    var EvpKDF = C_algo.EvpKDF;

    /**
     * Abstract base cipher template.
     *
     * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
     * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
     * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
     * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
     */
    var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
      /**
       * Configuration options.
       *
       * @property {WordArray} iv The IV to use for this operation.
       */
      cfg: Base.extend(),
      /**
       * Creates this cipher in encryption mode.
       *
       * @param {WordArray} key The key.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {Cipher} A cipher instance.
       *
       * @static
       *
       * @example
       *
       *     var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
       */
      createEncryptor: function (key, cfg) {
        return this.create(this._ENC_XFORM_MODE, key, cfg);
      },
      /**
       * Creates this cipher in decryption mode.
       *
       * @param {WordArray} key The key.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {Cipher} A cipher instance.
       *
       * @static
       *
       * @example
       *
       *     var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
       */
      createDecryptor: function (key, cfg) {
        return this.create(this._DEC_XFORM_MODE, key, cfg);
      },
      /**
       * Initializes a newly created cipher.
       *
       * @param {number} xformMode Either the encryption or decryption transormation mode constant.
       * @param {WordArray} key The key.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @example
       *
       *     var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
       */
      init: function (xformMode, key, cfg) {
        // Apply config defaults
        this.cfg = this.cfg.extend(cfg);

        // Store transform mode and key
        this._xformMode = xformMode;
        this._key = key;

        // Set initial values
        this.reset();
      },
      /**
       * Resets this cipher to its initial state.
       *
       * @example
       *
       *     cipher.reset();
       */
      reset: function () {
        // Reset data buffer
        BufferedBlockAlgorithm.reset.call(this);

        // Perform concrete-cipher logic
        this._doReset();
      },
      /**
       * Adds data to be encrypted or decrypted.
       *
       * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
       *
       * @return {WordArray} The data after processing.
       *
       * @example
       *
       *     var encrypted = cipher.process('data');
       *     var encrypted = cipher.process(wordArray);
       */
      process: function (dataUpdate) {
        // Append
        this._append(dataUpdate);

        // Process available blocks
        return this._process();
      },
      /**
       * Finalizes the encryption or decryption process.
       * Note that the finalize operation is effectively a destructive, read-once operation.
       *
       * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
       *
       * @return {WordArray} The data after final processing.
       *
       * @example
       *
       *     var encrypted = cipher.finalize();
       *     var encrypted = cipher.finalize('data');
       *     var encrypted = cipher.finalize(wordArray);
       */
      finalize: function (dataUpdate) {
        // Final data update
        if (dataUpdate) {
          this._append(dataUpdate);
        }

        // Perform concrete-cipher logic
        var finalProcessedData = this._doFinalize();
        return finalProcessedData;
      },
      keySize: 128 / 32,
      ivSize: 128 / 32,
      _ENC_XFORM_MODE: 1,
      _DEC_XFORM_MODE: 2,
      /**
       * Creates shortcut functions to a cipher's object interface.
       *
       * @param {Cipher} cipher The cipher to create a helper for.
       *
       * @return {Object} An object with encrypt and decrypt shortcut functions.
       *
       * @static
       *
       * @example
       *
       *     var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
       */
      _createHelper: function () {
        function selectCipherStrategy(key) {
          if (typeof key == 'string') {
            return PasswordBasedCipher;
          } else {
            return SerializableCipher;
          }
        }
        return function (cipher) {
          return {
            encrypt: function (message, key, cfg) {
              return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
            },
            decrypt: function (ciphertext, key, cfg) {
              return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
            }
          };
        };
      }()
    });

    /**
     * Abstract base stream cipher template.
     *
     * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
     */
    var StreamCipher = C_lib.StreamCipher = Cipher.extend({
      _doFinalize: function () {
        // Process partial blocks
        var finalProcessedBlocks = this._process(!!'flush');
        return finalProcessedBlocks;
      },
      blockSize: 1
    });

    /**
     * Mode namespace.
     */
    var C_mode = C.mode = {};

    /**
     * Abstract base block cipher mode template.
     */
    var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
      /**
       * Creates this mode for encryption.
       *
       * @param {Cipher} cipher A block cipher instance.
       * @param {Array} iv The IV words.
       *
       * @static
       *
       * @example
       *
       *     var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
       */
      createEncryptor: function (cipher, iv) {
        return this.Encryptor.create(cipher, iv);
      },
      /**
       * Creates this mode for decryption.
       *
       * @param {Cipher} cipher A block cipher instance.
       * @param {Array} iv The IV words.
       *
       * @static
       *
       * @example
       *
       *     var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
       */
      createDecryptor: function (cipher, iv) {
        return this.Decryptor.create(cipher, iv);
      },
      /**
       * Initializes a newly created mode.
       *
       * @param {Cipher} cipher A block cipher instance.
       * @param {Array} iv The IV words.
       *
       * @example
       *
       *     var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
       */
      init: function (cipher, iv) {
        this._cipher = cipher;
        this._iv = iv;
      }
    });

    /**
     * Cipher Block Chaining mode.
     */
    var CBC = C_mode.CBC = function () {
      /**
       * Abstract base CBC mode.
       */
      var CBC = BlockCipherMode.extend();

      /**
       * CBC encryptor.
       */
      CBC.Encryptor = CBC.extend({
        /**
         * Processes the data block at offset.
         *
         * @param {Array} words The data words to operate on.
         * @param {number} offset The offset where the block starts.
         *
         * @example
         *
         *     mode.processBlock(data.words, offset);
         */
        processBlock: function (words, offset) {
          // Shortcuts
          var cipher = this._cipher;
          var blockSize = cipher.blockSize;

          // XOR and encrypt
          xorBlock.call(this, words, offset, blockSize);
          cipher.encryptBlock(words, offset);

          // Remember this block to use with next block
          this._prevBlock = words.slice(offset, offset + blockSize);
        }
      });

      /**
       * CBC decryptor.
       */
      CBC.Decryptor = CBC.extend({
        /**
         * Processes the data block at offset.
         *
         * @param {Array} words The data words to operate on.
         * @param {number} offset The offset where the block starts.
         *
         * @example
         *
         *     mode.processBlock(data.words, offset);
         */
        processBlock: function (words, offset) {
          // Shortcuts
          var cipher = this._cipher;
          var blockSize = cipher.blockSize;

          // Remember this block to use with next block
          var thisBlock = words.slice(offset, offset + blockSize);

          // Decrypt and XOR
          cipher.decryptBlock(words, offset);
          xorBlock.call(this, words, offset, blockSize);

          // This block becomes the previous block
          this._prevBlock = thisBlock;
        }
      });
      function xorBlock(words, offset, blockSize) {
        var block;

        // Shortcut
        var iv = this._iv;

        // Choose mixing block
        if (iv) {
          block = iv;

          // Remove IV for subsequent blocks
          this._iv = undefined;
        } else {
          block = this._prevBlock;
        }

        // XOR blocks
        for (var i = 0; i < blockSize; i++) {
          words[offset + i] ^= block[i];
        }
      }
      return CBC;
    }();

    /**
     * Padding namespace.
     */
    var C_pad = C.pad = {};

    /**
     * PKCS #5/7 padding strategy.
     */
    var Pkcs7 = C_pad.Pkcs7 = {
      /**
       * Pads data using the algorithm defined in PKCS #5/7.
       *
       * @param {WordArray} data The data to pad.
       * @param {number} blockSize The multiple that the data should be padded to.
       *
       * @static
       *
       * @example
       *
       *     CryptoJS.pad.Pkcs7.pad(wordArray, 4);
       */
      pad: function (data, blockSize) {
        // Shortcut
        var blockSizeBytes = blockSize * 4;

        // Count padding bytes
        var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;

        // Create padding word
        var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes;

        // Create padding
        var paddingWords = [];
        for (var i = 0; i < nPaddingBytes; i += 4) {
          paddingWords.push(paddingWord);
        }
        var padding = WordArray.create(paddingWords, nPaddingBytes);

        // Add padding
        data.concat(padding);
      },
      /**
       * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
       *
       * @param {WordArray} data The data to unpad.
       *
       * @static
       *
       * @example
       *
       *     CryptoJS.pad.Pkcs7.unpad(wordArray);
       */
      unpad: function (data) {
        // Get number of padding bytes from last byte
        var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 0xff;

        // Remove padding
        data.sigBytes -= nPaddingBytes;
      }
    };

    /**
     * Abstract base block cipher template.
     *
     * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
     */
    var BlockCipher = C_lib.BlockCipher = Cipher.extend({
      /**
       * Configuration options.
       *
       * @property {Mode} mode The block mode to use. Default: CBC
       * @property {Padding} padding The padding strategy to use. Default: Pkcs7
       */
      cfg: Cipher.cfg.extend({
        mode: CBC,
        padding: Pkcs7
      }),
      reset: function () {
        var modeCreator;

        // Reset cipher
        Cipher.reset.call(this);

        // Shortcuts
        var cfg = this.cfg;
        var iv = cfg.iv;
        var mode = cfg.mode;

        // Reset block mode
        if (this._xformMode == this._ENC_XFORM_MODE) {
          modeCreator = mode.createEncryptor;
        } else /* if (this._xformMode == this._DEC_XFORM_MODE) */{
            modeCreator = mode.createDecryptor;
            // Keep at least one block in the buffer for unpadding
            this._minBufferSize = 1;
          }
        if (this._mode && this._mode.__creator == modeCreator) {
          this._mode.init(this, iv && iv.words);
        } else {
          this._mode = modeCreator.call(mode, this, iv && iv.words);
          this._mode.__creator = modeCreator;
        }
      },
      _doProcessBlock: function (words, offset) {
        this._mode.processBlock(words, offset);
      },
      _doFinalize: function () {
        var finalProcessedBlocks;

        // Shortcut
        var padding = this.cfg.padding;

        // Finalize
        if (this._xformMode == this._ENC_XFORM_MODE) {
          // Pad data
          padding.pad(this._data, this.blockSize);

          // Process final blocks
          finalProcessedBlocks = this._process(!!'flush');
        } else /* if (this._xformMode == this._DEC_XFORM_MODE) */{
            // Process final blocks
            finalProcessedBlocks = this._process(!!'flush');

            // Unpad data
            padding.unpad(finalProcessedBlocks);
          }
        return finalProcessedBlocks;
      },
      blockSize: 128 / 32
    });

    /**
     * A collection of cipher parameters.
     *
     * @property {WordArray} ciphertext The raw ciphertext.
     * @property {WordArray} key The key to this ciphertext.
     * @property {WordArray} iv The IV used in the ciphering operation.
     * @property {WordArray} salt The salt used with a key derivation function.
     * @property {Cipher} algorithm The cipher algorithm.
     * @property {Mode} mode The block mode used in the ciphering operation.
     * @property {Padding} padding The padding scheme used in the ciphering operation.
     * @property {number} blockSize The block size of the cipher.
     * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
     */
    var CipherParams = C_lib.CipherParams = Base.extend({
      /**
       * Initializes a newly created cipher params object.
       *
       * @param {Object} cipherParams An object with any of the possible cipher parameters.
       *
       * @example
       *
       *     var cipherParams = CryptoJS.lib.CipherParams.create({
       *         ciphertext: ciphertextWordArray,
       *         key: keyWordArray,
       *         iv: ivWordArray,
       *         salt: saltWordArray,
       *         algorithm: CryptoJS.algo.AES,
       *         mode: CryptoJS.mode.CBC,
       *         padding: CryptoJS.pad.PKCS7,
       *         blockSize: 4,
       *         formatter: CryptoJS.format.OpenSSL
       *     });
       */
      init: function (cipherParams) {
        this.mixIn(cipherParams);
      },
      /**
       * Converts this cipher params object to a string.
       *
       * @param {Format} formatter (Optional) The formatting strategy to use.
       *
       * @return {string} The stringified cipher params.
       *
       * @throws Error If neither the formatter nor the default formatter is set.
       *
       * @example
       *
       *     var string = cipherParams + '';
       *     var string = cipherParams.toString();
       *     var string = cipherParams.toString(CryptoJS.format.OpenSSL);
       */
      toString: function (formatter) {
        return (formatter || this.formatter).stringify(this);
      }
    });

    /**
     * Format namespace.
     */
    var C_format = C.format = {};

    /**
     * OpenSSL formatting strategy.
     */
    var OpenSSLFormatter = C_format.OpenSSL = {
      /**
       * Converts a cipher params object to an OpenSSL-compatible string.
       *
       * @param {CipherParams} cipherParams The cipher params object.
       *
       * @return {string} The OpenSSL-compatible string.
       *
       * @static
       *
       * @example
       *
       *     var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
       */
      stringify: function (cipherParams) {
        var wordArray;

        // Shortcuts
        var ciphertext = cipherParams.ciphertext;
        var salt = cipherParams.salt;

        // Format
        if (salt) {
          wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
        } else {
          wordArray = ciphertext;
        }
        return wordArray.toString(Base64);
      },
      /**
       * Converts an OpenSSL-compatible string to a cipher params object.
       *
       * @param {string} openSSLStr The OpenSSL-compatible string.
       *
       * @return {CipherParams} The cipher params object.
       *
       * @static
       *
       * @example
       *
       *     var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
       */
      parse: function (openSSLStr) {
        var salt;

        // Parse base64
        var ciphertext = Base64.parse(openSSLStr);

        // Shortcut
        var ciphertextWords = ciphertext.words;

        // Test for salt
        if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
          // Extract salt
          salt = WordArray.create(ciphertextWords.slice(2, 4));

          // Remove salt from ciphertext
          ciphertextWords.splice(0, 4);
          ciphertext.sigBytes -= 16;
        }
        return CipherParams.create({
          ciphertext: ciphertext,
          salt: salt
        });
      }
    };

    /**
     * A cipher wrapper that returns ciphertext as a serializable cipher params object.
     */
    var SerializableCipher = C_lib.SerializableCipher = Base.extend({
      /**
       * Configuration options.
       *
       * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
       */
      cfg: Base.extend({
        format: OpenSSLFormatter
      }),
      /**
       * Encrypts a message.
       *
       * @param {Cipher} cipher The cipher algorithm to use.
       * @param {WordArray|string} message The message to encrypt.
       * @param {WordArray} key The key.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {CipherParams} A cipher params object.
       *
       * @static
       *
       * @example
       *
       *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
       *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
       *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
       */
      encrypt: function (cipher, message, key, cfg) {
        // Apply config defaults
        cfg = this.cfg.extend(cfg);

        // Encrypt
        var encryptor = cipher.createEncryptor(key, cfg);
        var ciphertext = encryptor.finalize(message);

        // Shortcut
        var cipherCfg = encryptor.cfg;

        // Create and return serializable cipher params
        return CipherParams.create({
          ciphertext: ciphertext,
          key: key,
          iv: cipherCfg.iv,
          algorithm: cipher,
          mode: cipherCfg.mode,
          padding: cipherCfg.padding,
          blockSize: cipher.blockSize,
          formatter: cfg.format
        });
      },
      /**
       * Decrypts serialized ciphertext.
       *
       * @param {Cipher} cipher The cipher algorithm to use.
       * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
       * @param {WordArray} key The key.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {WordArray} The plaintext.
       *
       * @static
       *
       * @example
       *
       *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
       *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
       */
      decrypt: function (cipher, ciphertext, key, cfg) {
        // Apply config defaults
        cfg = this.cfg.extend(cfg);

        // Convert string to CipherParams
        ciphertext = this._parse(ciphertext, cfg.format);

        // Decrypt
        var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
        return plaintext;
      },
      /**
       * Converts serialized ciphertext to CipherParams,
       * else assumed CipherParams already and returns ciphertext unchanged.
       *
       * @param {CipherParams|string} ciphertext The ciphertext.
       * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
       *
       * @return {CipherParams} The unserialized ciphertext.
       *
       * @static
       *
       * @example
       *
       *     var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
       */
      _parse: function (ciphertext, format) {
        if (typeof ciphertext == 'string') {
          return format.parse(ciphertext, this);
        } else {
          return ciphertext;
        }
      }
    });

    /**
     * Key derivation function namespace.
     */
    var C_kdf = C.kdf = {};

    /**
     * OpenSSL key derivation function.
     */
    var OpenSSLKdf = C_kdf.OpenSSL = {
      /**
       * Derives a key and IV from a password.
       *
       * @param {string} password The password to derive from.
       * @param {number} keySize The size in words of the key to generate.
       * @param {number} ivSize The size in words of the IV to generate.
       * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
       *
       * @return {CipherParams} A cipher params object with the key, IV, and salt.
       *
       * @static
       *
       * @example
       *
       *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
       *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
       */
      execute: function (password, keySize, ivSize, salt, hasher) {
        // Generate random salt
        if (!salt) {
          salt = WordArray.random(64 / 8);
        }

        // Derive key and IV
        if (!hasher) {
          var key = EvpKDF.create({
            keySize: keySize + ivSize
          }).compute(password, salt);
        } else {
          var key = EvpKDF.create({
            keySize: keySize + ivSize,
            hasher: hasher
          }).compute(password, salt);
        }

        // Separate key and IV
        var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
        key.sigBytes = keySize * 4;

        // Return params
        return CipherParams.create({
          key: key,
          iv: iv,
          salt: salt
        });
      }
    };

    /**
     * A serializable cipher wrapper that derives the key from a password,
     * and returns ciphertext as a serializable cipher params object.
     */
    var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
      /**
       * Configuration options.
       *
       * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
       */
      cfg: SerializableCipher.cfg.extend({
        kdf: OpenSSLKdf
      }),
      /**
       * Encrypts a message using a password.
       *
       * @param {Cipher} cipher The cipher algorithm to use.
       * @param {WordArray|string} message The message to encrypt.
       * @param {string} password The password.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {CipherParams} A cipher params object.
       *
       * @static
       *
       * @example
       *
       *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
       *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
       */
      encrypt: function (cipher, message, password, cfg) {
        // Apply config defaults
        cfg = this.cfg.extend(cfg);

        // Derive key and other params
        var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher);

        // Add IV to config
        cfg.iv = derivedParams.iv;

        // Encrypt
        var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);

        // Mix in derived params
        ciphertext.mixIn(derivedParams);
        return ciphertext;
      },
      /**
       * Decrypts serialized ciphertext using a password.
       *
       * @param {Cipher} cipher The cipher algorithm to use.
       * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
       * @param {string} password The password.
       * @param {Object} cfg (Optional) The configuration options to use for this operation.
       *
       * @return {WordArray} The plaintext.
       *
       * @static
       *
       * @example
       *
       *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
       *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
       */
      decrypt: function (cipher, ciphertext, password, cfg) {
        // Apply config defaults
        cfg = this.cfg.extend(cfg);

        // Convert string to CipherParams
        ciphertext = this._parse(ciphertext, cfg.format);

        // Derive key and other params
        var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher);

        // Add IV to config
        cfg.iv = derivedParams.iv;

        // Decrypt
        var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
        return plaintext;
      }
    });
  }();
});

/***/ }),

/***/ 7868:
/*!***************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/core.js ***!
  \***************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory();
  } else {}
})(this, function () {
  /*globals window, global, require*/

  /**
   * CryptoJS core components.
   */
  var CryptoJS = CryptoJS || function (Math, undefined) {
    var crypto;

    // Native crypto from window (Browser)
    if (typeof window !== 'undefined' && window.crypto) {
      crypto = window.crypto;
    }

    // Native crypto in web worker (Browser)
    if (typeof self !== 'undefined' && self.crypto) {
      crypto = self.crypto;
    }

    // Native crypto from worker
    if (typeof globalThis !== 'undefined' && globalThis.crypto) {
      crypto = globalThis.crypto;
    }

    // Native (experimental IE 11) crypto from window (Browser)
    if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
      crypto = window.msCrypto;
    }

    // Native crypto from global (NodeJS)
    if (!crypto && typeof global !== 'undefined' && global.crypto) {
      crypto = global.crypto;
    }

    // Native crypto import via require (NodeJS)
    if (!crypto && "function" === 'function') {
      try {
        crypto = __webpack_require__(/*! crypto */ 3936);
      } catch (err) {}
    }

    /*
     * Cryptographically secure pseudorandom number generator
     *
     * As Math.random() is cryptographically not safe to use
     */
    var cryptoSecureRandomInt = function () {
      if (crypto) {
        // Use getRandomValues method (Browser)
        if (typeof crypto.getRandomValues === 'function') {
          try {
            return crypto.getRandomValues(new Uint32Array(1))[0];
          } catch (err) {}
        }

        // Use randomBytes method (NodeJS)
        if (typeof crypto.randomBytes === 'function') {
          try {
            return crypto.randomBytes(4).readInt32LE();
          } catch (err) {}
        }
      }
      throw new Error('Native crypto module could not be used to get secure random number.');
    };

    /*
     * Local polyfill of Object.create
      */
    var create = Object.create || function () {
      function F() {}
      return function (obj) {
        var subtype;
        F.prototype = obj;
        subtype = new F();
        F.prototype = null;
        return subtype;
      };
    }();

    /**
     * CryptoJS namespace.
     */
    var C = {};

    /**
     * Library namespace.
     */
    var C_lib = C.lib = {};

    /**
     * Base object for prototypal inheritance.
     */
    var Base = C_lib.Base = function () {
      return {
        /**
         * Creates a new object that inherits from this object.
         *
         * @param {Object} overrides Properties to copy into the new object.
         *
         * @return {Object} The new object.
         *
         * @static
         *
         * @example
         *
         *     var MyType = CryptoJS.lib.Base.extend({
         *         field: 'value',
         *
         *         method: function () {
         *         }
         *     });
         */
        extend: function (overrides) {
          // Spawn
          var subtype = create(this);

          // Augment
          if (overrides) {
            subtype.mixIn(overrides);
          }

          // Create default initializer
          if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
            subtype.init = function () {
              subtype.$super.init.apply(this, arguments);
            };
          }

          // Initializer's prototype is the subtype object
          subtype.init.prototype = subtype;

          // Reference supertype
          subtype.$super = this;
          return subtype;
        },
        /**
         * Extends this object and runs the init method.
         * Arguments to create() will be passed to init().
         *
         * @return {Object} The new object.
         *
         * @static
         *
         * @example
         *
         *     var instance = MyType.create();
         */
        create: function () {
          var instance = this.extend();
          instance.init.apply(instance, arguments);
          return instance;
        },
        /**
         * Initializes a newly created object.
         * Override this method to add some logic when your objects are created.
         *
         * @example
         *
         *     var MyType = CryptoJS.lib.Base.extend({
         *         init: function () {
         *             // ...
         *         }
         *     });
         */
        init: function () {},
        /**
         * Copies properties into this object.
         *
         * @param {Object} properties The properties to mix in.
         *
         * @example
         *
         *     MyType.mixIn({
         *         field: 'value'
         *     });
         */
        mixIn: function (properties) {
          for (var propertyName in properties) {
            if (properties.hasOwnProperty(propertyName)) {
              this[propertyName] = properties[propertyName];
            }
          }

          // IE won't copy toString using the loop above
          if (properties.hasOwnProperty('toString')) {
            this.toString = properties.toString;
          }
        },
        /**
         * Creates a copy of this object.
         *
         * @return {Object} The clone.
         *
         * @example
         *
         *     var clone = instance.clone();
         */
        clone: function () {
          return this.init.prototype.extend(this);
        }
      };
    }();

    /**
     * An array of 32-bit words.
     *
     * @property {Array} words The array of 32-bit words.
     * @property {number} sigBytes The number of significant bytes in this word array.
     */
    var WordArray = C_lib.WordArray = Base.extend({
      /**
       * Initializes a newly created word array.
       *
       * @param {Array} words (Optional) An array of 32-bit words.
       * @param {number} sigBytes (Optional) The number of significant bytes in the words.
       *
       * @example
       *
       *     var wordArray = CryptoJS.lib.WordArray.create();
       *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
       *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
       */
      init: function (words, sigBytes) {
        words = this.words = words || [];
        if (sigBytes != undefined) {
          this.sigBytes = sigBytes;
        } else {
          this.sigBytes = words.length * 4;
        }
      },
      /**
       * Converts this word array to a string.
       *
       * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
       *
       * @return {string} The stringified word array.
       *
       * @example
       *
       *     var string = wordArray + '';
       *     var string = wordArray.toString();
       *     var string = wordArray.toString(CryptoJS.enc.Utf8);
       */
      toString: function (encoder) {
        return (encoder || Hex).stringify(this);
      },
      /**
       * Concatenates a word array to this word array.
       *
       * @param {WordArray} wordArray The word array to append.
       *
       * @return {WordArray} This word array.
       *
       * @example
       *
       *     wordArray1.concat(wordArray2);
       */
      concat: function (wordArray) {
        // Shortcuts
        var thisWords = this.words;
        var thatWords = wordArray.words;
        var thisSigBytes = this.sigBytes;
        var thatSigBytes = wordArray.sigBytes;

        // Clamp excess bits
        this.clamp();

        // Concat
        if (thisSigBytes % 4) {
          // Copy one byte at a time
          for (var i = 0; i < thatSigBytes; i++) {
            var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
            thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
          }
        } else {
          // Copy one word at a time
          for (var j = 0; j < thatSigBytes; j += 4) {
            thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
          }
        }
        this.sigBytes += thatSigBytes;

        // Chainable
        return this;
      },
      /**
       * Removes insignificant bits.
       *
       * @example
       *
       *     wordArray.clamp();
       */
      clamp: function () {
        // Shortcuts
        var words = this.words;
        var sigBytes = this.sigBytes;

        // Clamp
        words[sigBytes >>> 2] &= 0xffffffff << 32 - sigBytes % 4 * 8;
        words.length = Math.ceil(sigBytes / 4);
      },
      /**
       * Creates a copy of this word array.
       *
       * @return {WordArray} The clone.
       *
       * @example
       *
       *     var clone = wordArray.clone();
       */
      clone: function () {
        var clone = Base.clone.call(this);
        clone.words = this.words.slice(0);
        return clone;
      },
      /**
       * Creates a word array filled with random bytes.
       *
       * @param {number} nBytes The number of random bytes to generate.
       *
       * @return {WordArray} The random word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.lib.WordArray.random(16);
       */
      random: function (nBytes) {
        var words = [];
        for (var i = 0; i < nBytes; i += 4) {
          words.push(cryptoSecureRandomInt());
        }
        return new WordArray.init(words, nBytes);
      }
    });

    /**
     * Encoder namespace.
     */
    var C_enc = C.enc = {};

    /**
     * Hex encoding strategy.
     */
    var Hex = C_enc.Hex = {
      /**
       * Converts a word array to a hex string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The hex string.
       *
       * @static
       *
       * @example
       *
       *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
       */
      stringify: function (wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;

        // Convert
        var hexChars = [];
        for (var i = 0; i < sigBytes; i++) {
          var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
          hexChars.push((bite >>> 4).toString(16));
          hexChars.push((bite & 0x0f).toString(16));
        }
        return hexChars.join('');
      },
      /**
       * Converts a hex string to a word array.
       *
       * @param {string} hexStr The hex string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
       */
      parse: function (hexStr) {
        // Shortcut
        var hexStrLength = hexStr.length;

        // Convert
        var words = [];
        for (var i = 0; i < hexStrLength; i += 2) {
          words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
        }
        return new WordArray.init(words, hexStrLength / 2);
      }
    };

    /**
     * Latin1 encoding strategy.
     */
    var Latin1 = C_enc.Latin1 = {
      /**
       * Converts a word array to a Latin1 string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The Latin1 string.
       *
       * @static
       *
       * @example
       *
       *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
       */
      stringify: function (wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;

        // Convert
        var latin1Chars = [];
        for (var i = 0; i < sigBytes; i++) {
          var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
          latin1Chars.push(String.fromCharCode(bite));
        }
        return latin1Chars.join('');
      },
      /**
       * Converts a Latin1 string to a word array.
       *
       * @param {string} latin1Str The Latin1 string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
       */
      parse: function (latin1Str) {
        // Shortcut
        var latin1StrLength = latin1Str.length;

        // Convert
        var words = [];
        for (var i = 0; i < latin1StrLength; i++) {
          words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << 24 - i % 4 * 8;
        }
        return new WordArray.init(words, latin1StrLength);
      }
    };

    /**
     * UTF-8 encoding strategy.
     */
    var Utf8 = C_enc.Utf8 = {
      /**
       * Converts a word array to a UTF-8 string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The UTF-8 string.
       *
       * @static
       *
       * @example
       *
       *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
       */
      stringify: function (wordArray) {
        try {
          return decodeURIComponent(escape(Latin1.stringify(wordArray)));
        } catch (e) {
          throw new Error('Malformed UTF-8 data');
        }
      },
      /**
       * Converts a UTF-8 string to a word array.
       *
       * @param {string} utf8Str The UTF-8 string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
       */
      parse: function (utf8Str) {
        return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
      }
    };

    /**
     * Abstract buffered block algorithm template.
     *
     * The property blockSize must be implemented in a concrete subtype.
     *
     * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
     */
    var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
      /**
       * Resets this block algorithm's data buffer to its initial state.
       *
       * @example
       *
       *     bufferedBlockAlgorithm.reset();
       */
      reset: function () {
        // Initial values
        this._data = new WordArray.init();
        this._nDataBytes = 0;
      },
      /**
       * Adds new data to this block algorithm's buffer.
       *
       * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
       *
       * @example
       *
       *     bufferedBlockAlgorithm._append('data');
       *     bufferedBlockAlgorithm._append(wordArray);
       */
      _append: function (data) {
        // Convert string to WordArray, else assume WordArray already
        if (typeof data == 'string') {
          data = Utf8.parse(data);
        }

        // Append
        this._data.concat(data);
        this._nDataBytes += data.sigBytes;
      },
      /**
       * Processes available data blocks.
       *
       * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
       *
       * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
       *
       * @return {WordArray} The processed data.
       *
       * @example
       *
       *     var processedData = bufferedBlockAlgorithm._process();
       *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
       */
      _process: function (doFlush) {
        var processedWords;

        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var dataSigBytes = data.sigBytes;
        var blockSize = this.blockSize;
        var blockSizeBytes = blockSize * 4;

        // Count blocks ready
        var nBlocksReady = dataSigBytes / blockSizeBytes;
        if (doFlush) {
          // Round up to include partial blocks
          nBlocksReady = Math.ceil(nBlocksReady);
        } else {
          // Round down to include only full blocks,
          // less the number of blocks that must remain in the buffer
          nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
        }

        // Count words ready
        var nWordsReady = nBlocksReady * blockSize;

        // Count bytes ready
        var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);

        // Process blocks
        if (nWordsReady) {
          for (var offset = 0; offset < nWordsReady; offset += blockSize) {
            // Perform concrete-algorithm logic
            this._doProcessBlock(dataWords, offset);
          }

          // Remove processed words
          processedWords = dataWords.splice(0, nWordsReady);
          data.sigBytes -= nBytesReady;
        }

        // Return processed words
        return new WordArray.init(processedWords, nBytesReady);
      },
      /**
       * Creates a copy of this object.
       *
       * @return {Object} The clone.
       *
       * @example
       *
       *     var clone = bufferedBlockAlgorithm.clone();
       */
      clone: function () {
        var clone = Base.clone.call(this);
        clone._data = this._data.clone();
        return clone;
      },
      _minBufferSize: 0
    });

    /**
     * Abstract hasher template.
     *
     * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
     */
    var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
      /**
       * Configuration options.
       */
      cfg: Base.extend(),
      /**
       * Initializes a newly created hasher.
       *
       * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
       *
       * @example
       *
       *     var hasher = CryptoJS.algo.SHA256.create();
       */
      init: function (cfg) {
        // Apply config defaults
        this.cfg = this.cfg.extend(cfg);

        // Set initial values
        this.reset();
      },
      /**
       * Resets this hasher to its initial state.
       *
       * @example
       *
       *     hasher.reset();
       */
      reset: function () {
        // Reset data buffer
        BufferedBlockAlgorithm.reset.call(this);

        // Perform concrete-hasher logic
        this._doReset();
      },
      /**
       * Updates this hasher with a message.
       *
       * @param {WordArray|string} messageUpdate The message to append.
       *
       * @return {Hasher} This hasher.
       *
       * @example
       *
       *     hasher.update('message');
       *     hasher.update(wordArray);
       */
      update: function (messageUpdate) {
        // Append
        this._append(messageUpdate);

        // Update the hash
        this._process();

        // Chainable
        return this;
      },
      /**
       * Finalizes the hash computation.
       * Note that the finalize operation is effectively a destructive, read-once operation.
       *
       * @param {WordArray|string} messageUpdate (Optional) A final message update.
       *
       * @return {WordArray} The hash.
       *
       * @example
       *
       *     var hash = hasher.finalize();
       *     var hash = hasher.finalize('message');
       *     var hash = hasher.finalize(wordArray);
       */
      finalize: function (messageUpdate) {
        // Final message update
        if (messageUpdate) {
          this._append(messageUpdate);
        }

        // Perform concrete-hasher logic
        var hash = this._doFinalize();
        return hash;
      },
      blockSize: 512 / 32,
      /**
       * Creates a shortcut function to a hasher's object interface.
       *
       * @param {Hasher} hasher The hasher to create a helper for.
       *
       * @return {Function} The shortcut function.
       *
       * @static
       *
       * @example
       *
       *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
       */
      _createHelper: function (hasher) {
        return function (message, cfg) {
          return new hasher.init(cfg).finalize(message);
        };
      },
      /**
       * Creates a shortcut function to the HMAC's object interface.
       *
       * @param {Hasher} hasher The hasher to use in this HMAC helper.
       *
       * @return {Function} The shortcut function.
       *
       * @static
       *
       * @example
       *
       *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
       */
      _createHmacHelper: function (hasher) {
        return function (message, key) {
          return new C_algo.HMAC.init(hasher, key).finalize(message);
        };
      }
    });

    /**
     * Algorithm namespace.
     */
    var C_algo = C.algo = {};
    return C;
  }(Math);
  return CryptoJS;
});

/***/ }),

/***/ 9039:
/*!*********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/enc-base64.js ***!
  \*********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var C_enc = C.enc;

    /**
     * Base64 encoding strategy.
     */
    var Base64 = C_enc.Base64 = {
      /**
       * Converts a word array to a Base64 string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The Base64 string.
       *
       * @static
       *
       * @example
       *
       *     var base64String = CryptoJS.enc.Base64.stringify(wordArray);
       */
      stringify: function (wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;
        var map = this._map;

        // Clamp excess bits
        wordArray.clamp();

        // Convert
        var base64Chars = [];
        for (var i = 0; i < sigBytes; i += 3) {
          var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
          var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
          var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
          var triplet = byte1 << 16 | byte2 << 8 | byte3;
          for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
            base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
          }
        }

        // Add padding
        var paddingChar = map.charAt(64);
        if (paddingChar) {
          while (base64Chars.length % 4) {
            base64Chars.push(paddingChar);
          }
        }
        return base64Chars.join('');
      },
      /**
       * Converts a Base64 string to a word array.
       *
       * @param {string} base64Str The Base64 string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Base64.parse(base64String);
       */
      parse: function (base64Str) {
        // Shortcuts
        var base64StrLength = base64Str.length;
        var map = this._map;
        var reverseMap = this._reverseMap;
        if (!reverseMap) {
          reverseMap = this._reverseMap = [];
          for (var j = 0; j < map.length; j++) {
            reverseMap[map.charCodeAt(j)] = j;
          }
        }

        // Ignore padding
        var paddingChar = map.charAt(64);
        if (paddingChar) {
          var paddingIndex = base64Str.indexOf(paddingChar);
          if (paddingIndex !== -1) {
            base64StrLength = paddingIndex;
          }
        }

        // Convert
        return parseLoop(base64Str, base64StrLength, reverseMap);
      },
      _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
    };
    function parseLoop(base64Str, base64StrLength, reverseMap) {
      var words = [];
      var nBytes = 0;
      for (var i = 0; i < base64StrLength; i++) {
        if (i % 4) {
          var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << i % 4 * 2;
          var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> 6 - i % 4 * 2;
          var bitsCombined = bits1 | bits2;
          words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
          nBytes++;
        }
      }
      return WordArray.create(words, nBytes);
    }
  })();
  return CryptoJS.enc.Base64;
});

/***/ }),

/***/ 8370:
/*!************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/enc-base64url.js ***!
  \************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var C_enc = C.enc;

    /**
     * Base64url encoding strategy.
     */
    var Base64url = C_enc.Base64url = {
      /**
       * Converts a word array to a Base64url string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @param {boolean} urlSafe Whether to use url safe
       *
       * @return {string} The Base64url string.
       *
       * @static
       *
       * @example
       *
       *     var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
       */
      stringify: function (wordArray, urlSafe) {
        if (urlSafe === undefined) {
          urlSafe = true;
        }
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;
        var map = urlSafe ? this._safe_map : this._map;

        // Clamp excess bits
        wordArray.clamp();

        // Convert
        var base64Chars = [];
        for (var i = 0; i < sigBytes; i += 3) {
          var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
          var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
          var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
          var triplet = byte1 << 16 | byte2 << 8 | byte3;
          for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
            base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
          }
        }

        // Add padding
        var paddingChar = map.charAt(64);
        if (paddingChar) {
          while (base64Chars.length % 4) {
            base64Chars.push(paddingChar);
          }
        }
        return base64Chars.join('');
      },
      /**
       * Converts a Base64url string to a word array.
       *
       * @param {string} base64Str The Base64url string.
       *
       * @param {boolean} urlSafe Whether to use url safe
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Base64url.parse(base64String);
       */
      parse: function (base64Str, urlSafe) {
        if (urlSafe === undefined) {
          urlSafe = true;
        }

        // Shortcuts
        var base64StrLength = base64Str.length;
        var map = urlSafe ? this._safe_map : this._map;
        var reverseMap = this._reverseMap;
        if (!reverseMap) {
          reverseMap = this._reverseMap = [];
          for (var j = 0; j < map.length; j++) {
            reverseMap[map.charCodeAt(j)] = j;
          }
        }

        // Ignore padding
        var paddingChar = map.charAt(64);
        if (paddingChar) {
          var paddingIndex = base64Str.indexOf(paddingChar);
          if (paddingIndex !== -1) {
            base64StrLength = paddingIndex;
          }
        }

        // Convert
        return parseLoop(base64Str, base64StrLength, reverseMap);
      },
      _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
      _safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    };
    function parseLoop(base64Str, base64StrLength, reverseMap) {
      var words = [];
      var nBytes = 0;
      for (var i = 0; i < base64StrLength; i++) {
        if (i % 4) {
          var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << i % 4 * 2;
          var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> 6 - i % 4 * 2;
          var bitsCombined = bits1 | bits2;
          words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
          nBytes++;
        }
      }
      return WordArray.create(words, nBytes);
    }
  })();
  return CryptoJS.enc.Base64url;
});

/***/ }),

/***/ 732:
/*!********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/enc-utf16.js ***!
  \********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var C_enc = C.enc;

    /**
     * UTF-16 BE encoding strategy.
     */
    var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
      /**
       * Converts a word array to a UTF-16 BE string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The UTF-16 BE string.
       *
       * @static
       *
       * @example
       *
       *     var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
       */
      stringify: function (wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;

        // Convert
        var utf16Chars = [];
        for (var i = 0; i < sigBytes; i += 2) {
          var codePoint = words[i >>> 2] >>> 16 - i % 4 * 8 & 0xffff;
          utf16Chars.push(String.fromCharCode(codePoint));
        }
        return utf16Chars.join('');
      },
      /**
       * Converts a UTF-16 BE string to a word array.
       *
       * @param {string} utf16Str The UTF-16 BE string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
       */
      parse: function (utf16Str) {
        // Shortcut
        var utf16StrLength = utf16Str.length;

        // Convert
        var words = [];
        for (var i = 0; i < utf16StrLength; i++) {
          words[i >>> 1] |= utf16Str.charCodeAt(i) << 16 - i % 2 * 16;
        }
        return WordArray.create(words, utf16StrLength * 2);
      }
    };

    /**
     * UTF-16 LE encoding strategy.
     */
    C_enc.Utf16LE = {
      /**
       * Converts a word array to a UTF-16 LE string.
       *
       * @param {WordArray} wordArray The word array.
       *
       * @return {string} The UTF-16 LE string.
       *
       * @static
       *
       * @example
       *
       *     var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
       */
      stringify: function (wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;

        // Convert
        var utf16Chars = [];
        for (var i = 0; i < sigBytes; i += 2) {
          var codePoint = swapEndian(words[i >>> 2] >>> 16 - i % 4 * 8 & 0xffff);
          utf16Chars.push(String.fromCharCode(codePoint));
        }
        return utf16Chars.join('');
      },
      /**
       * Converts a UTF-16 LE string to a word array.
       *
       * @param {string} utf16Str The UTF-16 LE string.
       *
       * @return {WordArray} The word array.
       *
       * @static
       *
       * @example
       *
       *     var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
       */
      parse: function (utf16Str) {
        // Shortcut
        var utf16StrLength = utf16Str.length;

        // Convert
        var words = [];
        for (var i = 0; i < utf16StrLength; i++) {
          words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << 16 - i % 2 * 16);
        }
        return WordArray.create(words, utf16StrLength * 2);
      }
    };
    function swapEndian(word) {
      return word << 8 & 0xff00ff00 | word >>> 8 & 0x00ff00ff;
    }
  })();
  return CryptoJS.enc.Utf16;
});

/***/ }),

/***/ 4631:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/evpkdf.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./sha1 */ 438), __webpack_require__(/*! ./hmac */ 376));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Base = C_lib.Base;
    var WordArray = C_lib.WordArray;
    var C_algo = C.algo;
    var MD5 = C_algo.MD5;

    /**
     * This key derivation function is meant to conform with EVP_BytesToKey.
     * www.openssl.org/docs/crypto/EVP_BytesToKey.html
     */
    var EvpKDF = C_algo.EvpKDF = Base.extend({
      /**
       * Configuration options.
       *
       * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
       * @property {Hasher} hasher The hash algorithm to use. Default: MD5
       * @property {number} iterations The number of iterations to perform. Default: 1
       */
      cfg: Base.extend({
        keySize: 128 / 32,
        hasher: MD5,
        iterations: 1
      }),
      /**
       * Initializes a newly created key derivation function.
       *
       * @param {Object} cfg (Optional) The configuration options to use for the derivation.
       *
       * @example
       *
       *     var kdf = CryptoJS.algo.EvpKDF.create();
       *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
       *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
       */
      init: function (cfg) {
        this.cfg = this.cfg.extend(cfg);
      },
      /**
       * Derives a key from a password.
       *
       * @param {WordArray|string} password The password.
       * @param {WordArray|string} salt A salt.
       *
       * @return {WordArray} The derived key.
       *
       * @example
       *
       *     var key = kdf.compute(password, salt);
       */
      compute: function (password, salt) {
        var block;

        // Shortcut
        var cfg = this.cfg;

        // Init hasher
        var hasher = cfg.hasher.create();

        // Initial values
        var derivedKey = WordArray.create();

        // Shortcuts
        var derivedKeyWords = derivedKey.words;
        var keySize = cfg.keySize;
        var iterations = cfg.iterations;

        // Generate key
        while (derivedKeyWords.length < keySize) {
          if (block) {
            hasher.update(block);
          }
          block = hasher.update(password).finalize(salt);
          hasher.reset();

          // Iterations
          for (var i = 1; i < iterations; i++) {
            block = hasher.finalize(block);
            hasher.reset();
          }
          derivedKey.concat(block);
        }
        derivedKey.sigBytes = keySize * 4;
        return derivedKey;
      }
    });

    /**
     * Derives a key from a password.
     *
     * @param {WordArray|string} password The password.
     * @param {WordArray|string} salt A salt.
     * @param {Object} cfg (Optional) The configuration options to use for this computation.
     *
     * @return {WordArray} The derived key.
     *
     * @static
     *
     * @example
     *
     *     var key = CryptoJS.EvpKDF(password, salt);
     *     var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
     *     var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
     */
    C.EvpKDF = function (password, salt, cfg) {
      return EvpKDF.create(cfg).compute(password, salt);
    };
  })();
  return CryptoJS.EvpKDF;
});

/***/ }),

/***/ 9464:
/*!*********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/format-hex.js ***!
  \*********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function (undefined) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var CipherParams = C_lib.CipherParams;
    var C_enc = C.enc;
    var Hex = C_enc.Hex;
    var C_format = C.format;
    var HexFormatter = C_format.Hex = {
      /**
       * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
       *
       * @param {CipherParams} cipherParams The cipher params object.
       *
       * @return {string} The hexadecimally encoded string.
       *
       * @static
       *
       * @example
       *
       *     var hexString = CryptoJS.format.Hex.stringify(cipherParams);
       */
      stringify: function (cipherParams) {
        return cipherParams.ciphertext.toString(Hex);
      },
      /**
       * Converts a hexadecimally encoded ciphertext string to a cipher params object.
       *
       * @param {string} input The hexadecimally encoded string.
       *
       * @return {CipherParams} The cipher params object.
       *
       * @static
       *
       * @example
       *
       *     var cipherParams = CryptoJS.format.Hex.parse(hexString);
       */
      parse: function (input) {
        var ciphertext = Hex.parse(input);
        return CipherParams.create({
          ciphertext: ciphertext
        });
      }
    };
  })();
  return CryptoJS.format.Hex;
});

/***/ }),

/***/ 1398:
/*!**********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/hmac-sha256.js ***!
  \**********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./sha256 */ 4004), __webpack_require__(/*! ./hmac */ 376));
  } else {}
})(this, function (CryptoJS) {
  return CryptoJS.HmacSHA256;
});

/***/ }),

/***/ 376:
/*!***************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/hmac.js ***!
  \***************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Base = C_lib.Base;
    var C_enc = C.enc;
    var Utf8 = C_enc.Utf8;
    var C_algo = C.algo;

    /**
     * HMAC algorithm.
     */
    var HMAC = C_algo.HMAC = Base.extend({
      /**
       * Initializes a newly created HMAC.
       *
       * @param {Hasher} hasher The hash algorithm to use.
       * @param {WordArray|string} key The secret key.
       *
       * @example
       *
       *     var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
       */
      init: function (hasher, key) {
        // Init hasher
        hasher = this._hasher = new hasher.init();

        // Convert string to WordArray, else assume WordArray already
        if (typeof key == 'string') {
          key = Utf8.parse(key);
        }

        // Shortcuts
        var hasherBlockSize = hasher.blockSize;
        var hasherBlockSizeBytes = hasherBlockSize * 4;

        // Allow arbitrary length keys
        if (key.sigBytes > hasherBlockSizeBytes) {
          key = hasher.finalize(key);
        }

        // Clamp excess bits
        key.clamp();

        // Clone key for inner and outer pads
        var oKey = this._oKey = key.clone();
        var iKey = this._iKey = key.clone();

        // Shortcuts
        var oKeyWords = oKey.words;
        var iKeyWords = iKey.words;

        // XOR keys with pad constants
        for (var i = 0; i < hasherBlockSize; i++) {
          oKeyWords[i] ^= 0x5c5c5c5c;
          iKeyWords[i] ^= 0x36363636;
        }
        oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;

        // Set initial values
        this.reset();
      },
      /**
       * Resets this HMAC to its initial state.
       *
       * @example
       *
       *     hmacHasher.reset();
       */
      reset: function () {
        // Shortcut
        var hasher = this._hasher;

        // Reset
        hasher.reset();
        hasher.update(this._iKey);
      },
      /**
       * Updates this HMAC with a message.
       *
       * @param {WordArray|string} messageUpdate The message to append.
       *
       * @return {HMAC} This HMAC instance.
       *
       * @example
       *
       *     hmacHasher.update('message');
       *     hmacHasher.update(wordArray);
       */
      update: function (messageUpdate) {
        this._hasher.update(messageUpdate);

        // Chainable
        return this;
      },
      /**
       * Finalizes the HMAC computation.
       * Note that the finalize operation is effectively a destructive, read-once operation.
       *
       * @param {WordArray|string} messageUpdate (Optional) A final message update.
       *
       * @return {WordArray} The HMAC.
       *
       * @example
       *
       *     var hmac = hmacHasher.finalize();
       *     var hmac = hmacHasher.finalize('message');
       *     var hmac = hmacHasher.finalize(wordArray);
       */
      finalize: function (messageUpdate) {
        // Shortcut
        var hasher = this._hasher;

        // Compute HMAC
        var innerHash = hasher.finalize(messageUpdate);
        hasher.reset();
        var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
        return hmac;
      }
    });
  })();
});

/***/ }),

/***/ 6723:
/*!****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/index.js ***!
  \****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./x64-core */ 1569), __webpack_require__(/*! ./lib-typedarrays */ 7243), __webpack_require__(/*! ./enc-utf16 */ 732), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./enc-base64url */ 8370), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./sha1 */ 438), __webpack_require__(/*! ./sha256 */ 4004), __webpack_require__(/*! ./sha224 */ 9109), __webpack_require__(/*! ./sha512 */ 2817), __webpack_require__(/*! ./sha384 */ 8736), __webpack_require__(/*! ./sha3 */ 8684), __webpack_require__(/*! ./ripemd160 */ 6859), __webpack_require__(/*! ./hmac */ 376), __webpack_require__(/*! ./pbkdf2 */ 1358), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698), __webpack_require__(/*! ./mode-cfb */ 8828), __webpack_require__(/*! ./mode-ctr */ 4814), __webpack_require__(/*! ./mode-ctr-gladman */ 2101), __webpack_require__(/*! ./mode-ofb */ 8968), __webpack_require__(/*! ./mode-ecb */ 887), __webpack_require__(/*! ./pad-ansix923 */ 2312), __webpack_require__(/*! ./pad-iso10126 */ 6528), __webpack_require__(/*! ./pad-iso97971 */ 4083), __webpack_require__(/*! ./pad-zeropadding */ 3744), __webpack_require__(/*! ./pad-nopadding */ 915), __webpack_require__(/*! ./format-hex */ 9464), __webpack_require__(/*! ./aes */ 1992), __webpack_require__(/*! ./tripledes */ 4103), __webpack_require__(/*! ./rc4 */ 6266), __webpack_require__(/*! ./rabbit */ 9559), __webpack_require__(/*! ./rabbit-legacy */ 6591), __webpack_require__(/*! ./blowfish */ 1817));
  } else {}
})(this, function (CryptoJS) {
  return CryptoJS;
});

/***/ }),

/***/ 7243:
/*!**************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/lib-typedarrays.js ***!
  \**************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Check if typed arrays are supported
    if (typeof ArrayBuffer != 'function') {
      return;
    }

    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;

    // Reference original init
    var superInit = WordArray.init;

    // Augment WordArray.init to handle typed arrays
    var subInit = WordArray.init = function (typedArray) {
      // Convert buffers to uint8
      if (typedArray instanceof ArrayBuffer) {
        typedArray = new Uint8Array(typedArray);
      }

      // Convert other array views to uint8
      if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
        typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
      }

      // Handle Uint8Array
      if (typedArray instanceof Uint8Array) {
        // Shortcut
        var typedArrayByteLength = typedArray.byteLength;

        // Extract bytes
        var words = [];
        for (var i = 0; i < typedArrayByteLength; i++) {
          words[i >>> 2] |= typedArray[i] << 24 - i % 4 * 8;
        }

        // Initialize this word array
        superInit.call(this, words, typedArrayByteLength);
      } else {
        // Else call normal init
        superInit.apply(this, arguments);
      }
    };
    subInit.prototype = WordArray;
  })();
  return CryptoJS.lib.WordArray;
});

/***/ }),

/***/ 1483:
/*!**************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/md5.js ***!
  \**************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function (Math) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var Hasher = C_lib.Hasher;
    var C_algo = C.algo;

    // Constants table
    var T = [];

    // Compute constants
    (function () {
      for (var i = 0; i < 64; i++) {
        T[i] = Math.abs(Math.sin(i + 1)) * 0x100000000 | 0;
      }
    })();

    /**
     * MD5 hash algorithm.
     */
    var MD5 = C_algo.MD5 = Hasher.extend({
      _doReset: function () {
        this._hash = new WordArray.init([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
      },
      _doProcessBlock: function (M, offset) {
        // Swap endian
        for (var i = 0; i < 16; i++) {
          // Shortcuts
          var offset_i = offset + i;
          var M_offset_i = M[offset_i];
          M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 0x00ff00ff | (M_offset_i << 24 | M_offset_i >>> 8) & 0xff00ff00;
        }

        // Shortcuts
        var H = this._hash.words;
        var M_offset_0 = M[offset + 0];
        var M_offset_1 = M[offset + 1];
        var M_offset_2 = M[offset + 2];
        var M_offset_3 = M[offset + 3];
        var M_offset_4 = M[offset + 4];
        var M_offset_5 = M[offset + 5];
        var M_offset_6 = M[offset + 6];
        var M_offset_7 = M[offset + 7];
        var M_offset_8 = M[offset + 8];
        var M_offset_9 = M[offset + 9];
        var M_offset_10 = M[offset + 10];
        var M_offset_11 = M[offset + 11];
        var M_offset_12 = M[offset + 12];
        var M_offset_13 = M[offset + 13];
        var M_offset_14 = M[offset + 14];
        var M_offset_15 = M[offset + 15];

        // Working variables
        var a = H[0];
        var b = H[1];
        var c = H[2];
        var d = H[3];

        // Computation
        a = FF(a, b, c, d, M_offset_0, 7, T[0]);
        d = FF(d, a, b, c, M_offset_1, 12, T[1]);
        c = FF(c, d, a, b, M_offset_2, 17, T[2]);
        b = FF(b, c, d, a, M_offset_3, 22, T[3]);
        a = FF(a, b, c, d, M_offset_4, 7, T[4]);
        d = FF(d, a, b, c, M_offset_5, 12, T[5]);
        c = FF(c, d, a, b, M_offset_6, 17, T[6]);
        b = FF(b, c, d, a, M_offset_7, 22, T[7]);
        a = FF(a, b, c, d, M_offset_8, 7, T[8]);
        d = FF(d, a, b, c, M_offset_9, 12, T[9]);
        c = FF(c, d, a, b, M_offset_10, 17, T[10]);
        b = FF(b, c, d, a, M_offset_11, 22, T[11]);
        a = FF(a, b, c, d, M_offset_12, 7, T[12]);
        d = FF(d, a, b, c, M_offset_13, 12, T[13]);
        c = FF(c, d, a, b, M_offset_14, 17, T[14]);
        b = FF(b, c, d, a, M_offset_15, 22, T[15]);
        a = GG(a, b, c, d, M_offset_1, 5, T[16]);
        d = GG(d, a, b, c, M_offset_6, 9, T[17]);
        c = GG(c, d, a, b, M_offset_11, 14, T[18]);
        b = GG(b, c, d, a, M_offset_0, 20, T[19]);
        a = GG(a, b, c, d, M_offset_5, 5, T[20]);
        d = GG(d, a, b, c, M_offset_10, 9, T[21]);
        c = GG(c, d, a, b, M_offset_15, 14, T[22]);
        b = GG(b, c, d, a, M_offset_4, 20, T[23]);
        a = GG(a, b, c, d, M_offset_9, 5, T[24]);
        d = GG(d, a, b, c, M_offset_14, 9, T[25]);
        c = GG(c, d, a, b, M_offset_3, 14, T[26]);
        b = GG(b, c, d, a, M_offset_8, 20, T[27]);
        a = GG(a, b, c, d, M_offset_13, 5, T[28]);
        d = GG(d, a, b, c, M_offset_2, 9, T[29]);
        c = GG(c, d, a, b, M_offset_7, 14, T[30]);
        b = GG(b, c, d, a, M_offset_12, 20, T[31]);
        a = HH(a, b, c, d, M_offset_5, 4, T[32]);
        d = HH(d, a, b, c, M_offset_8, 11, T[33]);
        c = HH(c, d, a, b, M_offset_11, 16, T[34]);
        b = HH(b, c, d, a, M_offset_14, 23, T[35]);
        a = HH(a, b, c, d, M_offset_1, 4, T[36]);
        d = HH(d, a, b, c, M_offset_4, 11, T[37]);
        c = HH(c, d, a, b, M_offset_7, 16, T[38]);
        b = HH(b, c, d, a, M_offset_10, 23, T[39]);
        a = HH(a, b, c, d, M_offset_13, 4, T[40]);
        d = HH(d, a, b, c, M_offset_0, 11, T[41]);
        c = HH(c, d, a, b, M_offset_3, 16, T[42]);
        b = HH(b, c, d, a, M_offset_6, 23, T[43]);
        a = HH(a, b, c, d, M_offset_9, 4, T[44]);
        d = HH(d, a, b, c, M_offset_12, 11, T[45]);
        c = HH(c, d, a, b, M_offset_15, 16, T[46]);
        b = HH(b, c, d, a, M_offset_2, 23, T[47]);
        a = II(a, b, c, d, M_offset_0, 6, T[48]);
        d = II(d, a, b, c, M_offset_7, 10, T[49]);
        c = II(c, d, a, b, M_offset_14, 15, T[50]);
        b = II(b, c, d, a, M_offset_5, 21, T[51]);
        a = II(a, b, c, d, M_offset_12, 6, T[52]);
        d = II(d, a, b, c, M_offset_3, 10, T[53]);
        c = II(c, d, a, b, M_offset_10, 15, T[54]);
        b = II(b, c, d, a, M_offset_1, 21, T[55]);
        a = II(a, b, c, d, M_offset_8, 6, T[56]);
        d = II(d, a, b, c, M_offset_15, 10, T[57]);
        c = II(c, d, a, b, M_offset_6, 15, T[58]);
        b = II(b, c, d, a, M_offset_13, 21, T[59]);
        a = II(a, b, c, d, M_offset_4, 6, T[60]);
        d = II(d, a, b, c, M_offset_11, 10, T[61]);
        c = II(c, d, a, b, M_offset_2, 15, T[62]);
        b = II(b, c, d, a, M_offset_9, 21, T[63]);

        // Intermediate hash value
        H[0] = H[0] + a | 0;
        H[1] = H[1] + b | 0;
        H[2] = H[2] + c | 0;
        H[3] = H[3] + d | 0;
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x80 << 24 - nBitsLeft % 32;
        var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
        var nBitsTotalL = nBitsTotal;
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 0x00ff00ff | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 0xff00ff00;
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 0x00ff00ff | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 0xff00ff00;
        data.sigBytes = (dataWords.length + 1) * 4;

        // Hash final blocks
        this._process();

        // Shortcuts
        var hash = this._hash;
        var H = hash.words;

        // Swap endian
        for (var i = 0; i < 4; i++) {
          // Shortcut
          var H_i = H[i];
          H[i] = (H_i << 8 | H_i >>> 24) & 0x00ff00ff | (H_i << 24 | H_i >>> 8) & 0xff00ff00;
        }

        // Return final computed hash
        return hash;
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        clone._hash = this._hash.clone();
        return clone;
      }
    });
    function FF(a, b, c, d, x, s, t) {
      var n = a + (b & c | ~b & d) + x + t;
      return (n << s | n >>> 32 - s) + b;
    }
    function GG(a, b, c, d, x, s, t) {
      var n = a + (b & d | c & ~d) + x + t;
      return (n << s | n >>> 32 - s) + b;
    }
    function HH(a, b, c, d, x, s, t) {
      var n = a + (b ^ c ^ d) + x + t;
      return (n << s | n >>> 32 - s) + b;
    }
    function II(a, b, c, d, x, s, t) {
      var n = a + (c ^ (b | ~d)) + x + t;
      return (n << s | n >>> 32 - s) + b;
    }

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.MD5('message');
     *     var hash = CryptoJS.MD5(wordArray);
     */
    C.MD5 = Hasher._createHelper(MD5);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacMD5(message, key);
     */
    C.HmacMD5 = Hasher._createHmacHelper(MD5);
  })(Math);
  return CryptoJS.MD5;
});

/***/ }),

/***/ 8828:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/mode-cfb.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Cipher Feedback block mode.
   */
  CryptoJS.mode.CFB = function () {
    var CFB = CryptoJS.lib.BlockCipherMode.extend();
    CFB.Encryptor = CFB.extend({
      processBlock: function (words, offset) {
        // Shortcuts
        var cipher = this._cipher;
        var blockSize = cipher.blockSize;
        generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);

        // Remember this block to use with next block
        this._prevBlock = words.slice(offset, offset + blockSize);
      }
    });
    CFB.Decryptor = CFB.extend({
      processBlock: function (words, offset) {
        // Shortcuts
        var cipher = this._cipher;
        var blockSize = cipher.blockSize;

        // Remember this block to use with next block
        var thisBlock = words.slice(offset, offset + blockSize);
        generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);

        // This block becomes the previous block
        this._prevBlock = thisBlock;
      }
    });
    function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
      var keystream;

      // Shortcut
      var iv = this._iv;

      // Generate keystream
      if (iv) {
        keystream = iv.slice(0);

        // Remove IV for subsequent blocks
        this._iv = undefined;
      } else {
        keystream = this._prevBlock;
      }
      cipher.encryptBlock(keystream, 0);

      // Encrypt
      for (var i = 0; i < blockSize; i++) {
        words[offset + i] ^= keystream[i];
      }
    }
    return CFB;
  }();
  return CryptoJS.mode.CFB;
});

/***/ }),

/***/ 2101:
/*!***************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/mode-ctr-gladman.js ***!
  \***************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /** @preserve
   * Counter block mode compatible with  Dr Brian Gladman fileenc.c
   * derived from CryptoJS.mode.CTR
   * Jan Hruby jhruby.web@gmail.com
   */
  CryptoJS.mode.CTRGladman = function () {
    var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
    function incWord(word) {
      if ((word >> 24 & 0xff) === 0xff) {
        //overflow
        var b1 = word >> 16 & 0xff;
        var b2 = word >> 8 & 0xff;
        var b3 = word & 0xff;
        if (b1 === 0xff)
          // overflow b1
          {
            b1 = 0;
            if (b2 === 0xff) {
              b2 = 0;
              if (b3 === 0xff) {
                b3 = 0;
              } else {
                ++b3;
              }
            } else {
              ++b2;
            }
          } else {
          ++b1;
        }
        word = 0;
        word += b1 << 16;
        word += b2 << 8;
        word += b3;
      } else {
        word += 0x01 << 24;
      }
      return word;
    }
    function incCounter(counter) {
      if ((counter[0] = incWord(counter[0])) === 0) {
        // encr_data in fileenc.c from  Dr Brian Gladman's counts only with DWORD j < 8
        counter[1] = incWord(counter[1]);
      }
      return counter;
    }
    var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
      processBlock: function (words, offset) {
        // Shortcuts
        var cipher = this._cipher;
        var blockSize = cipher.blockSize;
        var iv = this._iv;
        var counter = this._counter;

        // Generate keystream
        if (iv) {
          counter = this._counter = iv.slice(0);

          // Remove IV for subsequent blocks
          this._iv = undefined;
        }
        incCounter(counter);
        var keystream = counter.slice(0);
        cipher.encryptBlock(keystream, 0);

        // Encrypt
        for (var i = 0; i < blockSize; i++) {
          words[offset + i] ^= keystream[i];
        }
      }
    });
    CTRGladman.Decryptor = Encryptor;
    return CTRGladman;
  }();
  return CryptoJS.mode.CTRGladman;
});

/***/ }),

/***/ 4814:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/mode-ctr.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Counter block mode.
   */
  CryptoJS.mode.CTR = function () {
    var CTR = CryptoJS.lib.BlockCipherMode.extend();
    var Encryptor = CTR.Encryptor = CTR.extend({
      processBlock: function (words, offset) {
        // Shortcuts
        var cipher = this._cipher;
        var blockSize = cipher.blockSize;
        var iv = this._iv;
        var counter = this._counter;

        // Generate keystream
        if (iv) {
          counter = this._counter = iv.slice(0);

          // Remove IV for subsequent blocks
          this._iv = undefined;
        }
        var keystream = counter.slice(0);
        cipher.encryptBlock(keystream, 0);

        // Increment counter
        counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0;

        // Encrypt
        for (var i = 0; i < blockSize; i++) {
          words[offset + i] ^= keystream[i];
        }
      }
    });
    CTR.Decryptor = Encryptor;
    return CTR;
  }();
  return CryptoJS.mode.CTR;
});

/***/ }),

/***/ 887:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/mode-ecb.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Electronic Codebook block mode.
   */
  CryptoJS.mode.ECB = function () {
    var ECB = CryptoJS.lib.BlockCipherMode.extend();
    ECB.Encryptor = ECB.extend({
      processBlock: function (words, offset) {
        this._cipher.encryptBlock(words, offset);
      }
    });
    ECB.Decryptor = ECB.extend({
      processBlock: function (words, offset) {
        this._cipher.decryptBlock(words, offset);
      }
    });
    return ECB;
  }();
  return CryptoJS.mode.ECB;
});

/***/ }),

/***/ 8968:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/mode-ofb.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Output Feedback block mode.
   */
  CryptoJS.mode.OFB = function () {
    var OFB = CryptoJS.lib.BlockCipherMode.extend();
    var Encryptor = OFB.Encryptor = OFB.extend({
      processBlock: function (words, offset) {
        // Shortcuts
        var cipher = this._cipher;
        var blockSize = cipher.blockSize;
        var iv = this._iv;
        var keystream = this._keystream;

        // Generate keystream
        if (iv) {
          keystream = this._keystream = iv.slice(0);

          // Remove IV for subsequent blocks
          this._iv = undefined;
        }
        cipher.encryptBlock(keystream, 0);

        // Encrypt
        for (var i = 0; i < blockSize; i++) {
          words[offset + i] ^= keystream[i];
        }
      }
    });
    OFB.Decryptor = Encryptor;
    return OFB;
  }();
  return CryptoJS.mode.OFB;
});

/***/ }),

/***/ 2312:
/*!***********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pad-ansix923.js ***!
  \***********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * ANSI X.923 padding strategy.
   */
  CryptoJS.pad.AnsiX923 = {
    pad: function (data, blockSize) {
      // Shortcuts
      var dataSigBytes = data.sigBytes;
      var blockSizeBytes = blockSize * 4;

      // Count padding bytes
      var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;

      // Compute last byte position
      var lastBytePos = dataSigBytes + nPaddingBytes - 1;

      // Pad
      data.clamp();
      data.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8;
      data.sigBytes += nPaddingBytes;
    },
    unpad: function (data) {
      // Get number of padding bytes from last byte
      var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 0xff;

      // Remove padding
      data.sigBytes -= nPaddingBytes;
    }
  };
  return CryptoJS.pad.Ansix923;
});

/***/ }),

/***/ 6528:
/*!***********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pad-iso10126.js ***!
  \***********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * ISO 10126 padding strategy.
   */
  CryptoJS.pad.Iso10126 = {
    pad: function (data, blockSize) {
      // Shortcut
      var blockSizeBytes = blockSize * 4;

      // Count padding bytes
      var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;

      // Pad
      data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
    },
    unpad: function (data) {
      // Get number of padding bytes from last byte
      var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 0xff;

      // Remove padding
      data.sigBytes -= nPaddingBytes;
    }
  };
  return CryptoJS.pad.Iso10126;
});

/***/ }),

/***/ 4083:
/*!***********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pad-iso97971.js ***!
  \***********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * ISO/IEC 9797-1 Padding Method 2.
   */
  CryptoJS.pad.Iso97971 = {
    pad: function (data, blockSize) {
      // Add 0x80 byte
      data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));

      // Zero pad the rest
      CryptoJS.pad.ZeroPadding.pad(data, blockSize);
    },
    unpad: function (data) {
      // Remove zero padding
      CryptoJS.pad.ZeroPadding.unpad(data);

      // Remove one more byte -- the 0x80 byte
      data.sigBytes--;
    }
  };
  return CryptoJS.pad.Iso97971;
});

/***/ }),

/***/ 915:
/*!************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pad-nopadding.js ***!
  \************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * A noop padding strategy.
   */
  CryptoJS.pad.NoPadding = {
    pad: function () {},
    unpad: function () {}
  };
  return CryptoJS.pad.NoPadding;
});

/***/ }),

/***/ 3744:
/*!**************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pad-zeropadding.js ***!
  \**************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  /**
   * Zero padding strategy.
   */
  CryptoJS.pad.ZeroPadding = {
    pad: function (data, blockSize) {
      // Shortcut
      var blockSizeBytes = blockSize * 4;

      // Pad
      data.clamp();
      data.sigBytes += blockSizeBytes - (data.sigBytes % blockSizeBytes || blockSizeBytes);
    },
    unpad: function (data) {
      // Shortcut
      var dataWords = data.words;

      // Unpad
      var i = data.sigBytes - 1;
      for (var i = data.sigBytes - 1; i >= 0; i--) {
        if (dataWords[i >>> 2] >>> 24 - i % 4 * 8 & 0xff) {
          data.sigBytes = i + 1;
          break;
        }
      }
    }
  };
  return CryptoJS.pad.ZeroPadding;
});

/***/ }),

/***/ 1358:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/pbkdf2.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./sha256 */ 4004), __webpack_require__(/*! ./hmac */ 376));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Base = C_lib.Base;
    var WordArray = C_lib.WordArray;
    var C_algo = C.algo;
    var SHA256 = C_algo.SHA256;
    var HMAC = C_algo.HMAC;

    /**
     * Password-Based Key Derivation Function 2 algorithm.
     */
    var PBKDF2 = C_algo.PBKDF2 = Base.extend({
      /**
       * Configuration options.
       *
       * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
       * @property {Hasher} hasher The hasher to use. Default: SHA256
       * @property {number} iterations The number of iterations to perform. Default: 250000
       */
      cfg: Base.extend({
        keySize: 128 / 32,
        hasher: SHA256,
        iterations: 250000
      }),
      /**
       * Initializes a newly created key derivation function.
       *
       * @param {Object} cfg (Optional) The configuration options to use for the derivation.
       *
       * @example
       *
       *     var kdf = CryptoJS.algo.PBKDF2.create();
       *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
       *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
       */
      init: function (cfg) {
        this.cfg = this.cfg.extend(cfg);
      },
      /**
       * Computes the Password-Based Key Derivation Function 2.
       *
       * @param {WordArray|string} password The password.
       * @param {WordArray|string} salt A salt.
       *
       * @return {WordArray} The derived key.
       *
       * @example
       *
       *     var key = kdf.compute(password, salt);
       */
      compute: function (password, salt) {
        // Shortcut
        var cfg = this.cfg;

        // Init HMAC
        var hmac = HMAC.create(cfg.hasher, password);

        // Initial values
        var derivedKey = WordArray.create();
        var blockIndex = WordArray.create([0x00000001]);

        // Shortcuts
        var derivedKeyWords = derivedKey.words;
        var blockIndexWords = blockIndex.words;
        var keySize = cfg.keySize;
        var iterations = cfg.iterations;

        // Generate key
        while (derivedKeyWords.length < keySize) {
          var block = hmac.update(salt).finalize(blockIndex);
          hmac.reset();

          // Shortcuts
          var blockWords = block.words;
          var blockWordsLength = blockWords.length;

          // Iterations
          var intermediate = block;
          for (var i = 1; i < iterations; i++) {
            intermediate = hmac.finalize(intermediate);
            hmac.reset();

            // Shortcut
            var intermediateWords = intermediate.words;

            // XOR intermediate with block
            for (var j = 0; j < blockWordsLength; j++) {
              blockWords[j] ^= intermediateWords[j];
            }
          }
          derivedKey.concat(block);
          blockIndexWords[0]++;
        }
        derivedKey.sigBytes = keySize * 4;
        return derivedKey;
      }
    });

    /**
     * Computes the Password-Based Key Derivation Function 2.
     *
     * @param {WordArray|string} password The password.
     * @param {WordArray|string} salt A salt.
     * @param {Object} cfg (Optional) The configuration options to use for this computation.
     *
     * @return {WordArray} The derived key.
     *
     * @static
     *
     * @example
     *
     *     var key = CryptoJS.PBKDF2(password, salt);
     *     var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
     *     var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
     */
    C.PBKDF2 = function (password, salt, cfg) {
      return PBKDF2.create(cfg).compute(password, salt);
    };
  })();
  return CryptoJS.PBKDF2;
});

/***/ }),

/***/ 6591:
/*!************************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/rabbit-legacy.js ***!
  \************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var StreamCipher = C_lib.StreamCipher;
    var C_algo = C.algo;

    // Reusable objects
    var S = [];
    var C_ = [];
    var G = [];

    /**
     * Rabbit stream cipher algorithm.
     *
     * This is a legacy version that neglected to convert the key to little-endian.
     * This error doesn't affect the cipher's security,
     * but it does affect its compatibility with other implementations.
     */
    var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
      _doReset: function () {
        // Shortcuts
        var K = this._key.words;
        var iv = this.cfg.iv;

        // Generate initial state values
        var X = this._X = [K[0], K[3] << 16 | K[2] >>> 16, K[1], K[0] << 16 | K[3] >>> 16, K[2], K[1] << 16 | K[0] >>> 16, K[3], K[2] << 16 | K[1] >>> 16];

        // Generate initial counter values
        var C = this._C = [K[2] << 16 | K[2] >>> 16, K[0] & 0xffff0000 | K[1] & 0x0000ffff, K[3] << 16 | K[3] >>> 16, K[1] & 0xffff0000 | K[2] & 0x0000ffff, K[0] << 16 | K[0] >>> 16, K[2] & 0xffff0000 | K[3] & 0x0000ffff, K[1] << 16 | K[1] >>> 16, K[3] & 0xffff0000 | K[0] & 0x0000ffff];

        // Carry bit
        this._b = 0;

        // Iterate the system four times
        for (var i = 0; i < 4; i++) {
          nextState.call(this);
        }

        // Modify the counters
        for (var i = 0; i < 8; i++) {
          C[i] ^= X[i + 4 & 7];
        }

        // IV setup
        if (iv) {
          // Shortcuts
          var IV = iv.words;
          var IV_0 = IV[0];
          var IV_1 = IV[1];

          // Generate four subvectors
          var i0 = (IV_0 << 8 | IV_0 >>> 24) & 0x00ff00ff | (IV_0 << 24 | IV_0 >>> 8) & 0xff00ff00;
          var i2 = (IV_1 << 8 | IV_1 >>> 24) & 0x00ff00ff | (IV_1 << 24 | IV_1 >>> 8) & 0xff00ff00;
          var i1 = i0 >>> 16 | i2 & 0xffff0000;
          var i3 = i2 << 16 | i0 & 0x0000ffff;

          // Modify counter values
          C[0] ^= i0;
          C[1] ^= i1;
          C[2] ^= i2;
          C[3] ^= i3;
          C[4] ^= i0;
          C[5] ^= i1;
          C[6] ^= i2;
          C[7] ^= i3;

          // Iterate the system four times
          for (var i = 0; i < 4; i++) {
            nextState.call(this);
          }
        }
      },
      _doProcessBlock: function (M, offset) {
        // Shortcut
        var X = this._X;

        // Iterate the system
        nextState.call(this);

        // Generate four keystream words
        S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
        S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
        S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
        S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
        for (var i = 0; i < 4; i++) {
          // Swap endian
          S[i] = (S[i] << 8 | S[i] >>> 24) & 0x00ff00ff | (S[i] << 24 | S[i] >>> 8) & 0xff00ff00;

          // Encrypt
          M[offset + i] ^= S[i];
        }
      },
      blockSize: 128 / 32,
      ivSize: 64 / 32
    });
    function nextState() {
      // Shortcuts
      var X = this._X;
      var C = this._C;

      // Save old counter values
      for (var i = 0; i < 8; i++) {
        C_[i] = C[i];
      }

      // Calculate new counter values
      C[0] = C[0] + 0x4d34d34d + this._b | 0;
      C[1] = C[1] + 0xd34d34d3 + (C[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
      C[2] = C[2] + 0x34d34d34 + (C[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
      C[3] = C[3] + 0x4d34d34d + (C[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
      C[4] = C[4] + 0xd34d34d3 + (C[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
      C[5] = C[5] + 0x34d34d34 + (C[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
      C[6] = C[6] + 0x4d34d34d + (C[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
      C[7] = C[7] + 0xd34d34d3 + (C[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
      this._b = C[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;

      // Calculate the g-values
      for (var i = 0; i < 8; i++) {
        var gx = X[i] + C[i];

        // Construct high and low argument for squaring
        var ga = gx & 0xffff;
        var gb = gx >>> 16;

        // Calculate high and low result of squaring
        var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
        var gl = ((gx & 0xffff0000) * gx | 0) + ((gx & 0x0000ffff) * gx | 0);

        // High XOR low
        G[i] = gh ^ gl;
      }

      // Calculate new state values
      X[0] = G[0] + (G[7] << 16 | G[7] >>> 16) + (G[6] << 16 | G[6] >>> 16) | 0;
      X[1] = G[1] + (G[0] << 8 | G[0] >>> 24) + G[7] | 0;
      X[2] = G[2] + (G[1] << 16 | G[1] >>> 16) + (G[0] << 16 | G[0] >>> 16) | 0;
      X[3] = G[3] + (G[2] << 8 | G[2] >>> 24) + G[1] | 0;
      X[4] = G[4] + (G[3] << 16 | G[3] >>> 16) + (G[2] << 16 | G[2] >>> 16) | 0;
      X[5] = G[5] + (G[4] << 8 | G[4] >>> 24) + G[3] | 0;
      X[6] = G[6] + (G[5] << 16 | G[5] >>> 16) + (G[4] << 16 | G[4] >>> 16) | 0;
      X[7] = G[7] + (G[6] << 8 | G[6] >>> 24) + G[5] | 0;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
     */
    C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
  })();
  return CryptoJS.RabbitLegacy;
});

/***/ }),

/***/ 9559:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/rabbit.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var StreamCipher = C_lib.StreamCipher;
    var C_algo = C.algo;

    // Reusable objects
    var S = [];
    var C_ = [];
    var G = [];

    /**
     * Rabbit stream cipher algorithm
     */
    var Rabbit = C_algo.Rabbit = StreamCipher.extend({
      _doReset: function () {
        // Shortcuts
        var K = this._key.words;
        var iv = this.cfg.iv;

        // Swap endian
        for (var i = 0; i < 4; i++) {
          K[i] = (K[i] << 8 | K[i] >>> 24) & 0x00ff00ff | (K[i] << 24 | K[i] >>> 8) & 0xff00ff00;
        }

        // Generate initial state values
        var X = this._X = [K[0], K[3] << 16 | K[2] >>> 16, K[1], K[0] << 16 | K[3] >>> 16, K[2], K[1] << 16 | K[0] >>> 16, K[3], K[2] << 16 | K[1] >>> 16];

        // Generate initial counter values
        var C = this._C = [K[2] << 16 | K[2] >>> 16, K[0] & 0xffff0000 | K[1] & 0x0000ffff, K[3] << 16 | K[3] >>> 16, K[1] & 0xffff0000 | K[2] & 0x0000ffff, K[0] << 16 | K[0] >>> 16, K[2] & 0xffff0000 | K[3] & 0x0000ffff, K[1] << 16 | K[1] >>> 16, K[3] & 0xffff0000 | K[0] & 0x0000ffff];

        // Carry bit
        this._b = 0;

        // Iterate the system four times
        for (var i = 0; i < 4; i++) {
          nextState.call(this);
        }

        // Modify the counters
        for (var i = 0; i < 8; i++) {
          C[i] ^= X[i + 4 & 7];
        }

        // IV setup
        if (iv) {
          // Shortcuts
          var IV = iv.words;
          var IV_0 = IV[0];
          var IV_1 = IV[1];

          // Generate four subvectors
          var i0 = (IV_0 << 8 | IV_0 >>> 24) & 0x00ff00ff | (IV_0 << 24 | IV_0 >>> 8) & 0xff00ff00;
          var i2 = (IV_1 << 8 | IV_1 >>> 24) & 0x00ff00ff | (IV_1 << 24 | IV_1 >>> 8) & 0xff00ff00;
          var i1 = i0 >>> 16 | i2 & 0xffff0000;
          var i3 = i2 << 16 | i0 & 0x0000ffff;

          // Modify counter values
          C[0] ^= i0;
          C[1] ^= i1;
          C[2] ^= i2;
          C[3] ^= i3;
          C[4] ^= i0;
          C[5] ^= i1;
          C[6] ^= i2;
          C[7] ^= i3;

          // Iterate the system four times
          for (var i = 0; i < 4; i++) {
            nextState.call(this);
          }
        }
      },
      _doProcessBlock: function (M, offset) {
        // Shortcut
        var X = this._X;

        // Iterate the system
        nextState.call(this);

        // Generate four keystream words
        S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
        S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
        S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
        S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
        for (var i = 0; i < 4; i++) {
          // Swap endian
          S[i] = (S[i] << 8 | S[i] >>> 24) & 0x00ff00ff | (S[i] << 24 | S[i] >>> 8) & 0xff00ff00;

          // Encrypt
          M[offset + i] ^= S[i];
        }
      },
      blockSize: 128 / 32,
      ivSize: 64 / 32
    });
    function nextState() {
      // Shortcuts
      var X = this._X;
      var C = this._C;

      // Save old counter values
      for (var i = 0; i < 8; i++) {
        C_[i] = C[i];
      }

      // Calculate new counter values
      C[0] = C[0] + 0x4d34d34d + this._b | 0;
      C[1] = C[1] + 0xd34d34d3 + (C[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
      C[2] = C[2] + 0x34d34d34 + (C[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
      C[3] = C[3] + 0x4d34d34d + (C[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
      C[4] = C[4] + 0xd34d34d3 + (C[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
      C[5] = C[5] + 0x34d34d34 + (C[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
      C[6] = C[6] + 0x4d34d34d + (C[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
      C[7] = C[7] + 0xd34d34d3 + (C[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
      this._b = C[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;

      // Calculate the g-values
      for (var i = 0; i < 8; i++) {
        var gx = X[i] + C[i];

        // Construct high and low argument for squaring
        var ga = gx & 0xffff;
        var gb = gx >>> 16;

        // Calculate high and low result of squaring
        var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
        var gl = ((gx & 0xffff0000) * gx | 0) + ((gx & 0x0000ffff) * gx | 0);

        // High XOR low
        G[i] = gh ^ gl;
      }

      // Calculate new state values
      X[0] = G[0] + (G[7] << 16 | G[7] >>> 16) + (G[6] << 16 | G[6] >>> 16) | 0;
      X[1] = G[1] + (G[0] << 8 | G[0] >>> 24) + G[7] | 0;
      X[2] = G[2] + (G[1] << 16 | G[1] >>> 16) + (G[0] << 16 | G[0] >>> 16) | 0;
      X[3] = G[3] + (G[2] << 8 | G[2] >>> 24) + G[1] | 0;
      X[4] = G[4] + (G[3] << 16 | G[3] >>> 16) + (G[2] << 16 | G[2] >>> 16) | 0;
      X[5] = G[5] + (G[4] << 8 | G[4] >>> 24) + G[3] | 0;
      X[6] = G[6] + (G[5] << 16 | G[5] >>> 16) + (G[4] << 16 | G[4] >>> 16) | 0;
      X[7] = G[7] + (G[6] << 8 | G[6] >>> 24) + G[5] | 0;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
     */
    C.Rabbit = StreamCipher._createHelper(Rabbit);
  })();
  return CryptoJS.Rabbit;
});

/***/ }),

/***/ 6266:
/*!**************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/rc4.js ***!
  \**************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var StreamCipher = C_lib.StreamCipher;
    var C_algo = C.algo;

    /**
     * RC4 stream cipher algorithm.
     */
    var RC4 = C_algo.RC4 = StreamCipher.extend({
      _doReset: function () {
        // Shortcuts
        var key = this._key;
        var keyWords = key.words;
        var keySigBytes = key.sigBytes;

        // Init sbox
        var S = this._S = [];
        for (var i = 0; i < 256; i++) {
          S[i] = i;
        }

        // Key setup
        for (var i = 0, j = 0; i < 256; i++) {
          var keyByteIndex = i % keySigBytes;
          var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 0xff;
          j = (j + S[i] + keyByte) % 256;

          // Swap
          var t = S[i];
          S[i] = S[j];
          S[j] = t;
        }

        // Counters
        this._i = this._j = 0;
      },
      _doProcessBlock: function (M, offset) {
        M[offset] ^= generateKeystreamWord.call(this);
      },
      keySize: 256 / 32,
      ivSize: 0
    });
    function generateKeystreamWord() {
      // Shortcuts
      var S = this._S;
      var i = this._i;
      var j = this._j;

      // Generate keystream word
      var keystreamWord = 0;
      for (var n = 0; n < 4; n++) {
        i = (i + 1) % 256;
        j = (j + S[i]) % 256;

        // Swap
        var t = S[i];
        S[i] = S[j];
        S[j] = t;
        keystreamWord |= S[(S[i] + S[j]) % 256] << 24 - n * 8;
      }

      // Update counters
      this._i = i;
      this._j = j;
      return keystreamWord;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
     */
    C.RC4 = StreamCipher._createHelper(RC4);

    /**
     * Modified RC4 stream cipher algorithm.
     */
    var RC4Drop = C_algo.RC4Drop = RC4.extend({
      /**
       * Configuration options.
       *
       * @property {number} drop The number of keystream words to drop. Default 192
       */
      cfg: RC4.cfg.extend({
        drop: 192
      }),
      _doReset: function () {
        RC4._doReset.call(this);

        // Drop
        for (var i = this.cfg.drop; i > 0; i--) {
          generateKeystreamWord.call(this);
        }
      }
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
     */
    C.RC4Drop = StreamCipher._createHelper(RC4Drop);
  })();
  return CryptoJS.RC4;
});

/***/ }),

/***/ 6859:
/*!********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/ripemd160.js ***!
  \********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  /** @preserve
  (c) 2012 by Cédric Mesnil. All rights reserved.
  	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  	    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */

  (function (Math) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var Hasher = C_lib.Hasher;
    var C_algo = C.algo;

    // Constants table
    var _zl = WordArray.create([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
    var _zr = WordArray.create([5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
    var _sl = WordArray.create([11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]);
    var _sr = WordArray.create([8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]);
    var _hl = WordArray.create([0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
    var _hr = WordArray.create([0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);

    /**
     * RIPEMD160 hash algorithm.
     */
    var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
      _doReset: function () {
        this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
      },
      _doProcessBlock: function (M, offset) {
        // Swap endian
        for (var i = 0; i < 16; i++) {
          // Shortcuts
          var offset_i = offset + i;
          var M_offset_i = M[offset_i];

          // Swap
          M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 0x00ff00ff | (M_offset_i << 24 | M_offset_i >>> 8) & 0xff00ff00;
        }
        // Shortcut
        var H = this._hash.words;
        var hl = _hl.words;
        var hr = _hr.words;
        var zl = _zl.words;
        var zr = _zr.words;
        var sl = _sl.words;
        var sr = _sr.words;

        // Working variables
        var al, bl, cl, dl, el;
        var ar, br, cr, dr, er;
        ar = al = H[0];
        br = bl = H[1];
        cr = cl = H[2];
        dr = dl = H[3];
        er = el = H[4];
        // Computation
        var t;
        for (var i = 0; i < 80; i += 1) {
          t = al + M[offset + zl[i]] | 0;
          if (i < 16) {
            t += f1(bl, cl, dl) + hl[0];
          } else if (i < 32) {
            t += f2(bl, cl, dl) + hl[1];
          } else if (i < 48) {
            t += f3(bl, cl, dl) + hl[2];
          } else if (i < 64) {
            t += f4(bl, cl, dl) + hl[3];
          } else {
            // if (i<80) {
            t += f5(bl, cl, dl) + hl[4];
          }
          t = t | 0;
          t = rotl(t, sl[i]);
          t = t + el | 0;
          al = el;
          el = dl;
          dl = rotl(cl, 10);
          cl = bl;
          bl = t;
          t = ar + M[offset + zr[i]] | 0;
          if (i < 16) {
            t += f5(br, cr, dr) + hr[0];
          } else if (i < 32) {
            t += f4(br, cr, dr) + hr[1];
          } else if (i < 48) {
            t += f3(br, cr, dr) + hr[2];
          } else if (i < 64) {
            t += f2(br, cr, dr) + hr[3];
          } else {
            // if (i<80) {
            t += f1(br, cr, dr) + hr[4];
          }
          t = t | 0;
          t = rotl(t, sr[i]);
          t = t + er | 0;
          ar = er;
          er = dr;
          dr = rotl(cr, 10);
          cr = br;
          br = t;
        }
        // Intermediate hash value
        t = H[1] + cl + dr | 0;
        H[1] = H[2] + dl + er | 0;
        H[2] = H[3] + el + ar | 0;
        H[3] = H[4] + al + br | 0;
        H[4] = H[0] + bl + cr | 0;
        H[0] = t;
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x80 << 24 - nBitsLeft % 32;
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 0x00ff00ff | (nBitsTotal << 24 | nBitsTotal >>> 8) & 0xff00ff00;
        data.sigBytes = (dataWords.length + 1) * 4;

        // Hash final blocks
        this._process();

        // Shortcuts
        var hash = this._hash;
        var H = hash.words;

        // Swap endian
        for (var i = 0; i < 5; i++) {
          // Shortcut
          var H_i = H[i];

          // Swap
          H[i] = (H_i << 8 | H_i >>> 24) & 0x00ff00ff | (H_i << 24 | H_i >>> 8) & 0xff00ff00;
        }

        // Return final computed hash
        return hash;
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        clone._hash = this._hash.clone();
        return clone;
      }
    });
    function f1(x, y, z) {
      return x ^ y ^ z;
    }
    function f2(x, y, z) {
      return x & y | ~x & z;
    }
    function f3(x, y, z) {
      return (x | ~y) ^ z;
    }
    function f4(x, y, z) {
      return x & z | y & ~z;
    }
    function f5(x, y, z) {
      return x ^ (y | ~z);
    }
    function rotl(x, n) {
      return x << n | x >>> 32 - n;
    }

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.RIPEMD160('message');
     *     var hash = CryptoJS.RIPEMD160(wordArray);
     */
    C.RIPEMD160 = Hasher._createHelper(RIPEMD160);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacRIPEMD160(message, key);
     */
    C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
  })(Math);
  return CryptoJS.RIPEMD160;
});

/***/ }),

/***/ 438:
/*!***************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha1.js ***!
  \***************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var Hasher = C_lib.Hasher;
    var C_algo = C.algo;

    // Reusable object
    var W = [];

    /**
     * SHA-1 hash algorithm.
     */
    var SHA1 = C_algo.SHA1 = Hasher.extend({
      _doReset: function () {
        this._hash = new WordArray.init([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]);
      },
      _doProcessBlock: function (M, offset) {
        // Shortcut
        var H = this._hash.words;

        // Working variables
        var a = H[0];
        var b = H[1];
        var c = H[2];
        var d = H[3];
        var e = H[4];

        // Computation
        for (var i = 0; i < 80; i++) {
          if (i < 16) {
            W[i] = M[offset + i] | 0;
          } else {
            var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
            W[i] = n << 1 | n >>> 31;
          }
          var t = (a << 5 | a >>> 27) + e + W[i];
          if (i < 20) {
            t += (b & c | ~b & d) + 0x5a827999;
          } else if (i < 40) {
            t += (b ^ c ^ d) + 0x6ed9eba1;
          } else if (i < 60) {
            t += (b & c | b & d | c & d) - 0x70e44324;
          } else /* if (i < 80) */{
              t += (b ^ c ^ d) - 0x359d3e2a;
            }
          e = d;
          d = c;
          c = b << 30 | b >>> 2;
          b = a;
          a = t;
        }

        // Intermediate hash value
        H[0] = H[0] + a | 0;
        H[1] = H[1] + b | 0;
        H[2] = H[2] + c | 0;
        H[3] = H[3] + d | 0;
        H[4] = H[4] + e | 0;
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x80 << 24 - nBitsLeft % 32;
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
        data.sigBytes = dataWords.length * 4;

        // Hash final blocks
        this._process();

        // Return final computed hash
        return this._hash;
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        clone._hash = this._hash.clone();
        return clone;
      }
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA1('message');
     *     var hash = CryptoJS.SHA1(wordArray);
     */
    C.SHA1 = Hasher._createHelper(SHA1);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA1(message, key);
     */
    C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
  })();
  return CryptoJS.SHA1;
});

/***/ }),

/***/ 9109:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha224.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./sha256 */ 4004));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var C_algo = C.algo;
    var SHA256 = C_algo.SHA256;

    /**
     * SHA-224 hash algorithm.
     */
    var SHA224 = C_algo.SHA224 = SHA256.extend({
      _doReset: function () {
        this._hash = new WordArray.init([0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]);
      },
      _doFinalize: function () {
        var hash = SHA256._doFinalize.call(this);
        hash.sigBytes -= 4;
        return hash;
      }
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA224('message');
     *     var hash = CryptoJS.SHA224(wordArray);
     */
    C.SHA224 = SHA256._createHelper(SHA224);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA224(message, key);
     */
    C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
  })();
  return CryptoJS.SHA224;
});

/***/ }),

/***/ 4004:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha256.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function (Math) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var Hasher = C_lib.Hasher;
    var C_algo = C.algo;

    // Initialization and round constants tables
    var H = [];
    var K = [];

    // Compute constants
    (function () {
      function isPrime(n) {
        var sqrtN = Math.sqrt(n);
        for (var factor = 2; factor <= sqrtN; factor++) {
          if (!(n % factor)) {
            return false;
          }
        }
        return true;
      }
      function getFractionalBits(n) {
        return (n - (n | 0)) * 0x100000000 | 0;
      }
      var n = 2;
      var nPrime = 0;
      while (nPrime < 64) {
        if (isPrime(n)) {
          if (nPrime < 8) {
            H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
          }
          K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
          nPrime++;
        }
        n++;
      }
    })();

    // Reusable object
    var W = [];

    /**
     * SHA-256 hash algorithm.
     */
    var SHA256 = C_algo.SHA256 = Hasher.extend({
      _doReset: function () {
        this._hash = new WordArray.init(H.slice(0));
      },
      _doProcessBlock: function (M, offset) {
        // Shortcut
        var H = this._hash.words;

        // Working variables
        var a = H[0];
        var b = H[1];
        var c = H[2];
        var d = H[3];
        var e = H[4];
        var f = H[5];
        var g = H[6];
        var h = H[7];

        // Computation
        for (var i = 0; i < 64; i++) {
          if (i < 16) {
            W[i] = M[offset + i] | 0;
          } else {
            var gamma0x = W[i - 15];
            var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
            var gamma1x = W[i - 2];
            var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
            W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
          }
          var ch = e & f ^ ~e & g;
          var maj = a & b ^ a & c ^ b & c;
          var sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
          var sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
          var t1 = h + sigma1 + ch + K[i] + W[i];
          var t2 = sigma0 + maj;
          h = g;
          g = f;
          f = e;
          e = d + t1 | 0;
          d = c;
          c = b;
          b = a;
          a = t1 + t2 | 0;
        }

        // Intermediate hash value
        H[0] = H[0] + a | 0;
        H[1] = H[1] + b | 0;
        H[2] = H[2] + c | 0;
        H[3] = H[3] + d | 0;
        H[4] = H[4] + e | 0;
        H[5] = H[5] + f | 0;
        H[6] = H[6] + g | 0;
        H[7] = H[7] + h | 0;
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x80 << 24 - nBitsLeft % 32;
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
        dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
        data.sigBytes = dataWords.length * 4;

        // Hash final blocks
        this._process();

        // Return final computed hash
        return this._hash;
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        clone._hash = this._hash.clone();
        return clone;
      }
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA256('message');
     *     var hash = CryptoJS.SHA256(wordArray);
     */
    C.SHA256 = Hasher._createHelper(SHA256);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA256(message, key);
     */
    C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
  })(Math);
  return CryptoJS.SHA256;
});

/***/ }),

/***/ 8684:
/*!***************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha3.js ***!
  \***************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./x64-core */ 1569));
  } else {}
})(this, function (CryptoJS) {
  (function (Math) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var Hasher = C_lib.Hasher;
    var C_x64 = C.x64;
    var X64Word = C_x64.Word;
    var C_algo = C.algo;

    // Constants tables
    var RHO_OFFSETS = [];
    var PI_INDEXES = [];
    var ROUND_CONSTANTS = [];

    // Compute Constants
    (function () {
      // Compute rho offset constants
      var x = 1,
        y = 0;
      for (var t = 0; t < 24; t++) {
        RHO_OFFSETS[x + 5 * y] = (t + 1) * (t + 2) / 2 % 64;
        var newX = y % 5;
        var newY = (2 * x + 3 * y) % 5;
        x = newX;
        y = newY;
      }

      // Compute pi index constants
      for (var x = 0; x < 5; x++) {
        for (var y = 0; y < 5; y++) {
          PI_INDEXES[x + 5 * y] = y + (2 * x + 3 * y) % 5 * 5;
        }
      }

      // Compute round constants
      var LFSR = 0x01;
      for (var i = 0; i < 24; i++) {
        var roundConstantMsw = 0;
        var roundConstantLsw = 0;
        for (var j = 0; j < 7; j++) {
          if (LFSR & 0x01) {
            var bitPosition = (1 << j) - 1;
            if (bitPosition < 32) {
              roundConstantLsw ^= 1 << bitPosition;
            } else /* if (bitPosition >= 32) */{
                roundConstantMsw ^= 1 << bitPosition - 32;
              }
          }

          // Compute next LFSR
          if (LFSR & 0x80) {
            // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
            LFSR = LFSR << 1 ^ 0x71;
          } else {
            LFSR <<= 1;
          }
        }
        ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
      }
    })();

    // Reusable objects for temporary values
    var T = [];
    (function () {
      for (var i = 0; i < 25; i++) {
        T[i] = X64Word.create();
      }
    })();

    /**
     * SHA-3 hash algorithm.
     */
    var SHA3 = C_algo.SHA3 = Hasher.extend({
      /**
       * Configuration options.
       *
       * @property {number} outputLength
       *   The desired number of bits in the output hash.
       *   Only values permitted are: 224, 256, 384, 512.
       *   Default: 512
       */
      cfg: Hasher.cfg.extend({
        outputLength: 512
      }),
      _doReset: function () {
        var state = this._state = [];
        for (var i = 0; i < 25; i++) {
          state[i] = new X64Word.init();
        }
        this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
      },
      _doProcessBlock: function (M, offset) {
        // Shortcuts
        var state = this._state;
        var nBlockSizeLanes = this.blockSize / 2;

        // Absorb
        for (var i = 0; i < nBlockSizeLanes; i++) {
          // Shortcuts
          var M2i = M[offset + 2 * i];
          var M2i1 = M[offset + 2 * i + 1];

          // Swap endian
          M2i = (M2i << 8 | M2i >>> 24) & 0x00ff00ff | (M2i << 24 | M2i >>> 8) & 0xff00ff00;
          M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 0x00ff00ff | (M2i1 << 24 | M2i1 >>> 8) & 0xff00ff00;

          // Absorb message into state
          var lane = state[i];
          lane.high ^= M2i1;
          lane.low ^= M2i;
        }

        // Rounds
        for (var round = 0; round < 24; round++) {
          // Theta
          for (var x = 0; x < 5; x++) {
            // Mix column lanes
            var tMsw = 0,
              tLsw = 0;
            for (var y = 0; y < 5; y++) {
              var lane = state[x + 5 * y];
              tMsw ^= lane.high;
              tLsw ^= lane.low;
            }

            // Temporary values
            var Tx = T[x];
            Tx.high = tMsw;
            Tx.low = tLsw;
          }
          for (var x = 0; x < 5; x++) {
            // Shortcuts
            var Tx4 = T[(x + 4) % 5];
            var Tx1 = T[(x + 1) % 5];
            var Tx1Msw = Tx1.high;
            var Tx1Lsw = Tx1.low;

            // Mix surrounding columns
            var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31);
            var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31);
            for (var y = 0; y < 5; y++) {
              var lane = state[x + 5 * y];
              lane.high ^= tMsw;
              lane.low ^= tLsw;
            }
          }

          // Rho Pi
          for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
            var tMsw;
            var tLsw;

            // Shortcuts
            var lane = state[laneIndex];
            var laneMsw = lane.high;
            var laneLsw = lane.low;
            var rhoOffset = RHO_OFFSETS[laneIndex];

            // Rotate lanes
            if (rhoOffset < 32) {
              tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset;
              tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset;
            } else /* if (rhoOffset >= 32) */{
                tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset;
                tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset;
              }

            // Transpose lanes
            var TPiLane = T[PI_INDEXES[laneIndex]];
            TPiLane.high = tMsw;
            TPiLane.low = tLsw;
          }

          // Rho pi at x = y = 0
          var T0 = T[0];
          var state0 = state[0];
          T0.high = state0.high;
          T0.low = state0.low;

          // Chi
          for (var x = 0; x < 5; x++) {
            for (var y = 0; y < 5; y++) {
              // Shortcuts
              var laneIndex = x + 5 * y;
              var lane = state[laneIndex];
              var TLane = T[laneIndex];
              var Tx1Lane = T[(x + 1) % 5 + 5 * y];
              var Tx2Lane = T[(x + 2) % 5 + 5 * y];

              // Mix rows
              lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
              lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
            }
          }

          // Iota
          var lane = state[0];
          var roundConstant = ROUND_CONSTANTS[round];
          lane.high ^= roundConstant.high;
          lane.low ^= roundConstant.low;
        }
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;
        var blockSizeBits = this.blockSize * 32;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x1 << 24 - nBitsLeft % 32;
        dataWords[(Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 0x80;
        data.sigBytes = dataWords.length * 4;

        // Hash final blocks
        this._process();

        // Shortcuts
        var state = this._state;
        var outputLengthBytes = this.cfg.outputLength / 8;
        var outputLengthLanes = outputLengthBytes / 8;

        // Squeeze
        var hashWords = [];
        for (var i = 0; i < outputLengthLanes; i++) {
          // Shortcuts
          var lane = state[i];
          var laneMsw = lane.high;
          var laneLsw = lane.low;

          // Swap endian
          laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 0x00ff00ff | (laneMsw << 24 | laneMsw >>> 8) & 0xff00ff00;
          laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 0x00ff00ff | (laneLsw << 24 | laneLsw >>> 8) & 0xff00ff00;

          // Squeeze state to retrieve hash
          hashWords.push(laneLsw);
          hashWords.push(laneMsw);
        }

        // Return final computed hash
        return new WordArray.init(hashWords, outputLengthBytes);
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        var state = clone._state = this._state.slice(0);
        for (var i = 0; i < 25; i++) {
          state[i] = state[i].clone();
        }
        return clone;
      }
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA3('message');
     *     var hash = CryptoJS.SHA3(wordArray);
     */
    C.SHA3 = Hasher._createHelper(SHA3);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA3(message, key);
     */
    C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
  })(Math);
  return CryptoJS.SHA3;
});

/***/ }),

/***/ 8736:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha384.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./x64-core */ 1569), __webpack_require__(/*! ./sha512 */ 2817));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_x64 = C.x64;
    var X64Word = C_x64.Word;
    var X64WordArray = C_x64.WordArray;
    var C_algo = C.algo;
    var SHA512 = C_algo.SHA512;

    /**
     * SHA-384 hash algorithm.
     */
    var SHA384 = C_algo.SHA384 = SHA512.extend({
      _doReset: function () {
        this._hash = new X64WordArray.init([new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)]);
      },
      _doFinalize: function () {
        var hash = SHA512._doFinalize.call(this);
        hash.sigBytes -= 16;
        return hash;
      }
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA384('message');
     *     var hash = CryptoJS.SHA384(wordArray);
     */
    C.SHA384 = SHA512._createHelper(SHA384);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA384(message, key);
     */
    C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
  })();
  return CryptoJS.SHA384;
});

/***/ }),

/***/ 2817:
/*!*****************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/sha512.js ***!
  \*****************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./x64-core */ 1569));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Hasher = C_lib.Hasher;
    var C_x64 = C.x64;
    var X64Word = C_x64.Word;
    var X64WordArray = C_x64.WordArray;
    var C_algo = C.algo;
    function X64Word_create() {
      return X64Word.create.apply(X64Word, arguments);
    }

    // Constants
    var K = [X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)];

    // Reusable objects
    var W = [];
    (function () {
      for (var i = 0; i < 80; i++) {
        W[i] = X64Word_create();
      }
    })();

    /**
     * SHA-512 hash algorithm.
     */
    var SHA512 = C_algo.SHA512 = Hasher.extend({
      _doReset: function () {
        this._hash = new X64WordArray.init([new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)]);
      },
      _doProcessBlock: function (M, offset) {
        // Shortcuts
        var H = this._hash.words;
        var H0 = H[0];
        var H1 = H[1];
        var H2 = H[2];
        var H3 = H[3];
        var H4 = H[4];
        var H5 = H[5];
        var H6 = H[6];
        var H7 = H[7];
        var H0h = H0.high;
        var H0l = H0.low;
        var H1h = H1.high;
        var H1l = H1.low;
        var H2h = H2.high;
        var H2l = H2.low;
        var H3h = H3.high;
        var H3l = H3.low;
        var H4h = H4.high;
        var H4l = H4.low;
        var H5h = H5.high;
        var H5l = H5.low;
        var H6h = H6.high;
        var H6l = H6.low;
        var H7h = H7.high;
        var H7l = H7.low;

        // Working variables
        var ah = H0h;
        var al = H0l;
        var bh = H1h;
        var bl = H1l;
        var ch = H2h;
        var cl = H2l;
        var dh = H3h;
        var dl = H3l;
        var eh = H4h;
        var el = H4l;
        var fh = H5h;
        var fl = H5l;
        var gh = H6h;
        var gl = H6l;
        var hh = H7h;
        var hl = H7l;

        // Rounds
        for (var i = 0; i < 80; i++) {
          var Wil;
          var Wih;

          // Shortcut
          var Wi = W[i];

          // Extend message
          if (i < 16) {
            Wih = Wi.high = M[offset + i * 2] | 0;
            Wil = Wi.low = M[offset + i * 2 + 1] | 0;
          } else {
            // Gamma0
            var gamma0x = W[i - 15];
            var gamma0xh = gamma0x.high;
            var gamma0xl = gamma0x.low;
            var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7;
            var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25);

            // Gamma1
            var gamma1x = W[i - 2];
            var gamma1xh = gamma1x.high;
            var gamma1xl = gamma1x.low;
            var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6;
            var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26);

            // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
            var Wi7 = W[i - 7];
            var Wi7h = Wi7.high;
            var Wi7l = Wi7.low;
            var Wi16 = W[i - 16];
            var Wi16h = Wi16.high;
            var Wi16l = Wi16.low;
            Wil = gamma0l + Wi7l;
            Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0);
            Wil = Wil + gamma1l;
            Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0);
            Wil = Wil + Wi16l;
            Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0);
            Wi.high = Wih;
            Wi.low = Wil;
          }
          var chh = eh & fh ^ ~eh & gh;
          var chl = el & fl ^ ~el & gl;
          var majh = ah & bh ^ ah & ch ^ bh & ch;
          var majl = al & bl ^ al & cl ^ bl & cl;
          var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7);
          var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7);
          var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9);
          var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9);

          // t1 = h + sigma1 + ch + K[i] + W[i]
          var Ki = K[i];
          var Kih = Ki.high;
          var Kil = Ki.low;
          var t1l = hl + sigma1l;
          var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0);
          var t1l = t1l + chl;
          var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0);
          var t1l = t1l + Kil;
          var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0);
          var t1l = t1l + Wil;
          var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0);

          // t2 = sigma0 + maj
          var t2l = sigma0l + majl;
          var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0);

          // Update working variables
          hh = gh;
          hl = gl;
          gh = fh;
          gl = fl;
          fh = eh;
          fl = el;
          el = dl + t1l | 0;
          eh = dh + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0;
          dh = ch;
          dl = cl;
          ch = bh;
          cl = bl;
          bh = ah;
          bl = al;
          al = t1l + t2l | 0;
          ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0;
        }

        // Intermediate hash value
        H0l = H0.low = H0l + al;
        H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0);
        H1l = H1.low = H1l + bl;
        H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0);
        H2l = H2.low = H2l + cl;
        H2.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0);
        H3l = H3.low = H3l + dl;
        H3.high = H3h + dh + (H3l >>> 0 < dl >>> 0 ? 1 : 0);
        H4l = H4.low = H4l + el;
        H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0);
        H5l = H5.low = H5l + fl;
        H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0);
        H6l = H6.low = H6l + gl;
        H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0);
        H7l = H7.low = H7l + hl;
        H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0);
      },
      _doFinalize: function () {
        // Shortcuts
        var data = this._data;
        var dataWords = data.words;
        var nBitsTotal = this._nDataBytes * 8;
        var nBitsLeft = data.sigBytes * 8;

        // Add padding
        dataWords[nBitsLeft >>> 5] |= 0x80 << 24 - nBitsLeft % 32;
        dataWords[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
        dataWords[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal;
        data.sigBytes = dataWords.length * 4;

        // Hash final blocks
        this._process();

        // Convert hash to 32-bit word array before returning
        var hash = this._hash.toX32();

        // Return final computed hash
        return hash;
      },
      clone: function () {
        var clone = Hasher.clone.call(this);
        clone._hash = this._hash.clone();
        return clone;
      },
      blockSize: 1024 / 32
    });

    /**
     * Shortcut function to the hasher's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     *
     * @return {WordArray} The hash.
     *
     * @static
     *
     * @example
     *
     *     var hash = CryptoJS.SHA512('message');
     *     var hash = CryptoJS.SHA512(wordArray);
     */
    C.SHA512 = Hasher._createHelper(SHA512);

    /**
     * Shortcut function to the HMAC's object interface.
     *
     * @param {WordArray|string} message The message to hash.
     * @param {WordArray|string} key The secret key.
     *
     * @return {WordArray} The HMAC.
     *
     * @static
     *
     * @example
     *
     *     var hmac = CryptoJS.HmacSHA512(message, key);
     */
    C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
  })();
  return CryptoJS.SHA512;
});

/***/ }),

/***/ 4103:
/*!********************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/tripledes.js ***!
  \********************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory, undef) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868), __webpack_require__(/*! ./enc-base64 */ 9039), __webpack_require__(/*! ./md5 */ 1483), __webpack_require__(/*! ./evpkdf */ 4631), __webpack_require__(/*! ./cipher-core */ 2698));
  } else {}
})(this, function (CryptoJS) {
  (function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var WordArray = C_lib.WordArray;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Permuted Choice 1 constants
    var PC1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4];

    // Permuted Choice 2 constants
    var PC2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32];

    // Cumulative bit shift constants
    var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];

    // SBOXes and round permutation constants
    var SBOX_P = [{
      0x0: 0x808200,
      0x10000000: 0x8000,
      0x20000000: 0x808002,
      0x30000000: 0x2,
      0x40000000: 0x200,
      0x50000000: 0x808202,
      0x60000000: 0x800202,
      0x70000000: 0x800000,
      0x80000000: 0x202,
      0x90000000: 0x800200,
      0xa0000000: 0x8200,
      0xb0000000: 0x808000,
      0xc0000000: 0x8002,
      0xd0000000: 0x800002,
      0xe0000000: 0x0,
      0xf0000000: 0x8202,
      0x8000000: 0x0,
      0x18000000: 0x808202,
      0x28000000: 0x8202,
      0x38000000: 0x8000,
      0x48000000: 0x808200,
      0x58000000: 0x200,
      0x68000000: 0x808002,
      0x78000000: 0x2,
      0x88000000: 0x800200,
      0x98000000: 0x8200,
      0xa8000000: 0x808000,
      0xb8000000: 0x800202,
      0xc8000000: 0x800002,
      0xd8000000: 0x8002,
      0xe8000000: 0x202,
      0xf8000000: 0x800000,
      0x1: 0x8000,
      0x10000001: 0x2,
      0x20000001: 0x808200,
      0x30000001: 0x800000,
      0x40000001: 0x808002,
      0x50000001: 0x8200,
      0x60000001: 0x200,
      0x70000001: 0x800202,
      0x80000001: 0x808202,
      0x90000001: 0x808000,
      0xa0000001: 0x800002,
      0xb0000001: 0x8202,
      0xc0000001: 0x202,
      0xd0000001: 0x800200,
      0xe0000001: 0x8002,
      0xf0000001: 0x0,
      0x8000001: 0x808202,
      0x18000001: 0x808000,
      0x28000001: 0x800000,
      0x38000001: 0x200,
      0x48000001: 0x8000,
      0x58000001: 0x800002,
      0x68000001: 0x2,
      0x78000001: 0x8202,
      0x88000001: 0x8002,
      0x98000001: 0x800202,
      0xa8000001: 0x202,
      0xb8000001: 0x808200,
      0xc8000001: 0x800200,
      0xd8000001: 0x0,
      0xe8000001: 0x8200,
      0xf8000001: 0x808002
    }, {
      0x0: 0x40084010,
      0x1000000: 0x4000,
      0x2000000: 0x80000,
      0x3000000: 0x40080010,
      0x4000000: 0x40000010,
      0x5000000: 0x40084000,
      0x6000000: 0x40004000,
      0x7000000: 0x10,
      0x8000000: 0x84000,
      0x9000000: 0x40004010,
      0xa000000: 0x40000000,
      0xb000000: 0x84010,
      0xc000000: 0x80010,
      0xd000000: 0x0,
      0xe000000: 0x4010,
      0xf000000: 0x40080000,
      0x800000: 0x40004000,
      0x1800000: 0x84010,
      0x2800000: 0x10,
      0x3800000: 0x40004010,
      0x4800000: 0x40084010,
      0x5800000: 0x40000000,
      0x6800000: 0x80000,
      0x7800000: 0x40080010,
      0x8800000: 0x80010,
      0x9800000: 0x0,
      0xa800000: 0x4000,
      0xb800000: 0x40080000,
      0xc800000: 0x40000010,
      0xd800000: 0x84000,
      0xe800000: 0x40084000,
      0xf800000: 0x4010,
      0x10000000: 0x0,
      0x11000000: 0x40080010,
      0x12000000: 0x40004010,
      0x13000000: 0x40084000,
      0x14000000: 0x40080000,
      0x15000000: 0x10,
      0x16000000: 0x84010,
      0x17000000: 0x4000,
      0x18000000: 0x4010,
      0x19000000: 0x80000,
      0x1a000000: 0x80010,
      0x1b000000: 0x40000010,
      0x1c000000: 0x84000,
      0x1d000000: 0x40004000,
      0x1e000000: 0x40000000,
      0x1f000000: 0x40084010,
      0x10800000: 0x84010,
      0x11800000: 0x80000,
      0x12800000: 0x40080000,
      0x13800000: 0x4000,
      0x14800000: 0x40004000,
      0x15800000: 0x40084010,
      0x16800000: 0x10,
      0x17800000: 0x40000000,
      0x18800000: 0x40084000,
      0x19800000: 0x40000010,
      0x1a800000: 0x40004010,
      0x1b800000: 0x80010,
      0x1c800000: 0x0,
      0x1d800000: 0x4010,
      0x1e800000: 0x40080010,
      0x1f800000: 0x84000
    }, {
      0x0: 0x104,
      0x100000: 0x0,
      0x200000: 0x4000100,
      0x300000: 0x10104,
      0x400000: 0x10004,
      0x500000: 0x4000004,
      0x600000: 0x4010104,
      0x700000: 0x4010000,
      0x800000: 0x4000000,
      0x900000: 0x4010100,
      0xa00000: 0x10100,
      0xb00000: 0x4010004,
      0xc00000: 0x4000104,
      0xd00000: 0x10000,
      0xe00000: 0x4,
      0xf00000: 0x100,
      0x80000: 0x4010100,
      0x180000: 0x4010004,
      0x280000: 0x0,
      0x380000: 0x4000100,
      0x480000: 0x4000004,
      0x580000: 0x10000,
      0x680000: 0x10004,
      0x780000: 0x104,
      0x880000: 0x4,
      0x980000: 0x100,
      0xa80000: 0x4010000,
      0xb80000: 0x10104,
      0xc80000: 0x10100,
      0xd80000: 0x4000104,
      0xe80000: 0x4010104,
      0xf80000: 0x4000000,
      0x1000000: 0x4010100,
      0x1100000: 0x10004,
      0x1200000: 0x10000,
      0x1300000: 0x4000100,
      0x1400000: 0x100,
      0x1500000: 0x4010104,
      0x1600000: 0x4000004,
      0x1700000: 0x0,
      0x1800000: 0x4000104,
      0x1900000: 0x4000000,
      0x1a00000: 0x4,
      0x1b00000: 0x10100,
      0x1c00000: 0x4010000,
      0x1d00000: 0x104,
      0x1e00000: 0x10104,
      0x1f00000: 0x4010004,
      0x1080000: 0x4000000,
      0x1180000: 0x104,
      0x1280000: 0x4010100,
      0x1380000: 0x0,
      0x1480000: 0x10004,
      0x1580000: 0x4000100,
      0x1680000: 0x100,
      0x1780000: 0x4010004,
      0x1880000: 0x10000,
      0x1980000: 0x4010104,
      0x1a80000: 0x10104,
      0x1b80000: 0x4000004,
      0x1c80000: 0x4000104,
      0x1d80000: 0x4010000,
      0x1e80000: 0x4,
      0x1f80000: 0x10100
    }, {
      0x0: 0x80401000,
      0x10000: 0x80001040,
      0x20000: 0x401040,
      0x30000: 0x80400000,
      0x40000: 0x0,
      0x50000: 0x401000,
      0x60000: 0x80000040,
      0x70000: 0x400040,
      0x80000: 0x80000000,
      0x90000: 0x400000,
      0xa0000: 0x40,
      0xb0000: 0x80001000,
      0xc0000: 0x80400040,
      0xd0000: 0x1040,
      0xe0000: 0x1000,
      0xf0000: 0x80401040,
      0x8000: 0x80001040,
      0x18000: 0x40,
      0x28000: 0x80400040,
      0x38000: 0x80001000,
      0x48000: 0x401000,
      0x58000: 0x80401040,
      0x68000: 0x0,
      0x78000: 0x80400000,
      0x88000: 0x1000,
      0x98000: 0x80401000,
      0xa8000: 0x400000,
      0xb8000: 0x1040,
      0xc8000: 0x80000000,
      0xd8000: 0x400040,
      0xe8000: 0x401040,
      0xf8000: 0x80000040,
      0x100000: 0x400040,
      0x110000: 0x401000,
      0x120000: 0x80000040,
      0x130000: 0x0,
      0x140000: 0x1040,
      0x150000: 0x80400040,
      0x160000: 0x80401000,
      0x170000: 0x80001040,
      0x180000: 0x80401040,
      0x190000: 0x80000000,
      0x1a0000: 0x80400000,
      0x1b0000: 0x401040,
      0x1c0000: 0x80001000,
      0x1d0000: 0x400000,
      0x1e0000: 0x40,
      0x1f0000: 0x1000,
      0x108000: 0x80400000,
      0x118000: 0x80401040,
      0x128000: 0x0,
      0x138000: 0x401000,
      0x148000: 0x400040,
      0x158000: 0x80000000,
      0x168000: 0x80001040,
      0x178000: 0x40,
      0x188000: 0x80000040,
      0x198000: 0x1000,
      0x1a8000: 0x80001000,
      0x1b8000: 0x80400040,
      0x1c8000: 0x1040,
      0x1d8000: 0x80401000,
      0x1e8000: 0x400000,
      0x1f8000: 0x401040
    }, {
      0x0: 0x80,
      0x1000: 0x1040000,
      0x2000: 0x40000,
      0x3000: 0x20000000,
      0x4000: 0x20040080,
      0x5000: 0x1000080,
      0x6000: 0x21000080,
      0x7000: 0x40080,
      0x8000: 0x1000000,
      0x9000: 0x20040000,
      0xa000: 0x20000080,
      0xb000: 0x21040080,
      0xc000: 0x21040000,
      0xd000: 0x0,
      0xe000: 0x1040080,
      0xf000: 0x21000000,
      0x800: 0x1040080,
      0x1800: 0x21000080,
      0x2800: 0x80,
      0x3800: 0x1040000,
      0x4800: 0x40000,
      0x5800: 0x20040080,
      0x6800: 0x21040000,
      0x7800: 0x20000000,
      0x8800: 0x20040000,
      0x9800: 0x0,
      0xa800: 0x21040080,
      0xb800: 0x1000080,
      0xc800: 0x20000080,
      0xd800: 0x21000000,
      0xe800: 0x1000000,
      0xf800: 0x40080,
      0x10000: 0x40000,
      0x11000: 0x80,
      0x12000: 0x20000000,
      0x13000: 0x21000080,
      0x14000: 0x1000080,
      0x15000: 0x21040000,
      0x16000: 0x20040080,
      0x17000: 0x1000000,
      0x18000: 0x21040080,
      0x19000: 0x21000000,
      0x1a000: 0x1040000,
      0x1b000: 0x20040000,
      0x1c000: 0x40080,
      0x1d000: 0x20000080,
      0x1e000: 0x0,
      0x1f000: 0x1040080,
      0x10800: 0x21000080,
      0x11800: 0x1000000,
      0x12800: 0x1040000,
      0x13800: 0x20040080,
      0x14800: 0x20000000,
      0x15800: 0x1040080,
      0x16800: 0x80,
      0x17800: 0x21040000,
      0x18800: 0x40080,
      0x19800: 0x21040080,
      0x1a800: 0x0,
      0x1b800: 0x21000000,
      0x1c800: 0x1000080,
      0x1d800: 0x40000,
      0x1e800: 0x20040000,
      0x1f800: 0x20000080
    }, {
      0x0: 0x10000008,
      0x100: 0x2000,
      0x200: 0x10200000,
      0x300: 0x10202008,
      0x400: 0x10002000,
      0x500: 0x200000,
      0x600: 0x200008,
      0x700: 0x10000000,
      0x800: 0x0,
      0x900: 0x10002008,
      0xa00: 0x202000,
      0xb00: 0x8,
      0xc00: 0x10200008,
      0xd00: 0x202008,
      0xe00: 0x2008,
      0xf00: 0x10202000,
      0x80: 0x10200000,
      0x180: 0x10202008,
      0x280: 0x8,
      0x380: 0x200000,
      0x480: 0x202008,
      0x580: 0x10000008,
      0x680: 0x10002000,
      0x780: 0x2008,
      0x880: 0x200008,
      0x980: 0x2000,
      0xa80: 0x10002008,
      0xb80: 0x10200008,
      0xc80: 0x0,
      0xd80: 0x10202000,
      0xe80: 0x202000,
      0xf80: 0x10000000,
      0x1000: 0x10002000,
      0x1100: 0x10200008,
      0x1200: 0x10202008,
      0x1300: 0x2008,
      0x1400: 0x200000,
      0x1500: 0x10000000,
      0x1600: 0x10000008,
      0x1700: 0x202000,
      0x1800: 0x202008,
      0x1900: 0x0,
      0x1a00: 0x8,
      0x1b00: 0x10200000,
      0x1c00: 0x2000,
      0x1d00: 0x10002008,
      0x1e00: 0x10202000,
      0x1f00: 0x200008,
      0x1080: 0x8,
      0x1180: 0x202000,
      0x1280: 0x200000,
      0x1380: 0x10000008,
      0x1480: 0x10002000,
      0x1580: 0x2008,
      0x1680: 0x10202008,
      0x1780: 0x10200000,
      0x1880: 0x10202000,
      0x1980: 0x10200008,
      0x1a80: 0x2000,
      0x1b80: 0x202008,
      0x1c80: 0x200008,
      0x1d80: 0x0,
      0x1e80: 0x10000000,
      0x1f80: 0x10002008
    }, {
      0x0: 0x100000,
      0x10: 0x2000401,
      0x20: 0x400,
      0x30: 0x100401,
      0x40: 0x2100401,
      0x50: 0x0,
      0x60: 0x1,
      0x70: 0x2100001,
      0x80: 0x2000400,
      0x90: 0x100001,
      0xa0: 0x2000001,
      0xb0: 0x2100400,
      0xc0: 0x2100000,
      0xd0: 0x401,
      0xe0: 0x100400,
      0xf0: 0x2000000,
      0x8: 0x2100001,
      0x18: 0x0,
      0x28: 0x2000401,
      0x38: 0x2100400,
      0x48: 0x100000,
      0x58: 0x2000001,
      0x68: 0x2000000,
      0x78: 0x401,
      0x88: 0x100401,
      0x98: 0x2000400,
      0xa8: 0x2100000,
      0xb8: 0x100001,
      0xc8: 0x400,
      0xd8: 0x2100401,
      0xe8: 0x1,
      0xf8: 0x100400,
      0x100: 0x2000000,
      0x110: 0x100000,
      0x120: 0x2000401,
      0x130: 0x2100001,
      0x140: 0x100001,
      0x150: 0x2000400,
      0x160: 0x2100400,
      0x170: 0x100401,
      0x180: 0x401,
      0x190: 0x2100401,
      0x1a0: 0x100400,
      0x1b0: 0x1,
      0x1c0: 0x0,
      0x1d0: 0x2100000,
      0x1e0: 0x2000001,
      0x1f0: 0x400,
      0x108: 0x100400,
      0x118: 0x2000401,
      0x128: 0x2100001,
      0x138: 0x1,
      0x148: 0x2000000,
      0x158: 0x100000,
      0x168: 0x401,
      0x178: 0x2100400,
      0x188: 0x2000001,
      0x198: 0x2100000,
      0x1a8: 0x0,
      0x1b8: 0x2100401,
      0x1c8: 0x100401,
      0x1d8: 0x400,
      0x1e8: 0x2000400,
      0x1f8: 0x100001
    }, {
      0x0: 0x8000820,
      0x1: 0x20000,
      0x2: 0x8000000,
      0x3: 0x20,
      0x4: 0x20020,
      0x5: 0x8020820,
      0x6: 0x8020800,
      0x7: 0x800,
      0x8: 0x8020000,
      0x9: 0x8000800,
      0xa: 0x20800,
      0xb: 0x8020020,
      0xc: 0x820,
      0xd: 0x0,
      0xe: 0x8000020,
      0xf: 0x20820,
      0x80000000: 0x800,
      0x80000001: 0x8020820,
      0x80000002: 0x8000820,
      0x80000003: 0x8000000,
      0x80000004: 0x8020000,
      0x80000005: 0x20800,
      0x80000006: 0x20820,
      0x80000007: 0x20,
      0x80000008: 0x8000020,
      0x80000009: 0x820,
      0x8000000a: 0x20020,
      0x8000000b: 0x8020800,
      0x8000000c: 0x0,
      0x8000000d: 0x8020020,
      0x8000000e: 0x8000800,
      0x8000000f: 0x20000,
      0x10: 0x20820,
      0x11: 0x8020800,
      0x12: 0x20,
      0x13: 0x800,
      0x14: 0x8000800,
      0x15: 0x8000020,
      0x16: 0x8020020,
      0x17: 0x20000,
      0x18: 0x0,
      0x19: 0x20020,
      0x1a: 0x8020000,
      0x1b: 0x8000820,
      0x1c: 0x8020820,
      0x1d: 0x20800,
      0x1e: 0x820,
      0x1f: 0x8000000,
      0x80000010: 0x20000,
      0x80000011: 0x800,
      0x80000012: 0x8020020,
      0x80000013: 0x20820,
      0x80000014: 0x20,
      0x80000015: 0x8020000,
      0x80000016: 0x8000000,
      0x80000017: 0x8000820,
      0x80000018: 0x8020820,
      0x80000019: 0x8000020,
      0x8000001a: 0x8000800,
      0x8000001b: 0x0,
      0x8000001c: 0x20800,
      0x8000001d: 0x820,
      0x8000001e: 0x20020,
      0x8000001f: 0x8020800
    }];

    // Masks that select the SBOX input
    var SBOX_MASK = [0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f];

    /**
     * DES block cipher algorithm.
     */
    var DES = C_algo.DES = BlockCipher.extend({
      _doReset: function () {
        // Shortcuts
        var key = this._key;
        var keyWords = key.words;

        // Select 56 bits according to PC1
        var keyBits = [];
        for (var i = 0; i < 56; i++) {
          var keyBitPos = PC1[i] - 1;
          keyBits[i] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1;
        }

        // Assemble 16 subkeys
        var subKeys = this._subKeys = [];
        for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
          // Create subkey
          var subKey = subKeys[nSubKey] = [];

          // Shortcut
          var bitShift = BIT_SHIFTS[nSubKey];

          // Select 48 bits according to PC2
          for (var i = 0; i < 24; i++) {
            // Select from the left 28 key bits
            subKey[i / 6 | 0] |= keyBits[(PC2[i] - 1 + bitShift) % 28] << 31 - i % 6;

            // Select from the right 28 key bits
            subKey[4 + (i / 6 | 0)] |= keyBits[28 + (PC2[i + 24] - 1 + bitShift) % 28] << 31 - i % 6;
          }

          // Since each subkey is applied to an expanded 32-bit input,
          // the subkey can be broken into 8 values scaled to 32-bits,
          // which allows the key to be used without expansion
          subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
          for (var i = 1; i < 7; i++) {
            subKey[i] = subKey[i] >>> (i - 1) * 4 + 3;
          }
          subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
        }

        // Compute inverse subkeys
        var invSubKeys = this._invSubKeys = [];
        for (var i = 0; i < 16; i++) {
          invSubKeys[i] = subKeys[15 - i];
        }
      },
      encryptBlock: function (M, offset) {
        this._doCryptBlock(M, offset, this._subKeys);
      },
      decryptBlock: function (M, offset) {
        this._doCryptBlock(M, offset, this._invSubKeys);
      },
      _doCryptBlock: function (M, offset, subKeys) {
        // Get input
        this._lBlock = M[offset];
        this._rBlock = M[offset + 1];

        // Initial permutation
        exchangeLR.call(this, 4, 0x0f0f0f0f);
        exchangeLR.call(this, 16, 0x0000ffff);
        exchangeRL.call(this, 2, 0x33333333);
        exchangeRL.call(this, 8, 0x00ff00ff);
        exchangeLR.call(this, 1, 0x55555555);

        // Rounds
        for (var round = 0; round < 16; round++) {
          // Shortcuts
          var subKey = subKeys[round];
          var lBlock = this._lBlock;
          var rBlock = this._rBlock;

          // Feistel function
          var f = 0;
          for (var i = 0; i < 8; i++) {
            f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
          }
          this._lBlock = rBlock;
          this._rBlock = lBlock ^ f;
        }

        // Undo swap from last round
        var t = this._lBlock;
        this._lBlock = this._rBlock;
        this._rBlock = t;

        // Final permutation
        exchangeLR.call(this, 1, 0x55555555);
        exchangeRL.call(this, 8, 0x00ff00ff);
        exchangeRL.call(this, 2, 0x33333333);
        exchangeLR.call(this, 16, 0x0000ffff);
        exchangeLR.call(this, 4, 0x0f0f0f0f);

        // Set output
        M[offset] = this._lBlock;
        M[offset + 1] = this._rBlock;
      },
      keySize: 64 / 32,
      ivSize: 64 / 32,
      blockSize: 64 / 32
    });

    // Swap bits across the left and right words
    function exchangeLR(offset, mask) {
      var t = (this._lBlock >>> offset ^ this._rBlock) & mask;
      this._rBlock ^= t;
      this._lBlock ^= t << offset;
    }
    function exchangeRL(offset, mask) {
      var t = (this._rBlock >>> offset ^ this._lBlock) & mask;
      this._lBlock ^= t;
      this._rBlock ^= t << offset;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.DES.decrypt(ciphertext, key, cfg);
     */
    C.DES = BlockCipher._createHelper(DES);

    /**
     * Triple-DES block cipher algorithm.
     */
    var TripleDES = C_algo.TripleDES = BlockCipher.extend({
      _doReset: function () {
        // Shortcuts
        var key = this._key;
        var keyWords = key.words;
        // Make sure the key length is valid (64, 128 or >= 192 bit)
        if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
          throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.');
        }

        // Extend the key according to the keying options defined in 3DES standard
        var key1 = keyWords.slice(0, 2);
        var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
        var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);

        // Create DES instances
        this._des1 = DES.createEncryptor(WordArray.create(key1));
        this._des2 = DES.createEncryptor(WordArray.create(key2));
        this._des3 = DES.createEncryptor(WordArray.create(key3));
      },
      encryptBlock: function (M, offset) {
        this._des1.encryptBlock(M, offset);
        this._des2.decryptBlock(M, offset);
        this._des3.encryptBlock(M, offset);
      },
      decryptBlock: function (M, offset) {
        this._des3.decryptBlock(M, offset);
        this._des2.encryptBlock(M, offset);
        this._des1.decryptBlock(M, offset);
      },
      keySize: 192 / 32,
      ivSize: 64 / 32,
      blockSize: 64 / 32
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
     */
    C.TripleDES = BlockCipher._createHelper(TripleDES);
  })();
  return CryptoJS.TripleDES;
});

/***/ }),

/***/ 1569:
/*!*******************************************************************************!*\
  !*** ./node_modules/.pnpm/crypto-js@4.2.0/node_modules/crypto-js/x64-core.js ***!
  \*******************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

;
(function (root, factory) {
  if (true) {
    // CommonJS
    module.exports = exports = factory(__webpack_require__(/*! ./core */ 7868));
  } else {}
})(this, function (CryptoJS) {
  (function (undefined) {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var Base = C_lib.Base;
    var X32WordArray = C_lib.WordArray;

    /**
     * x64 namespace.
     */
    var C_x64 = C.x64 = {};

    /**
     * A 64-bit word.
     */
    var X64Word = C_x64.Word = Base.extend({
      /**
       * Initializes a newly created 64-bit word.
       *
       * @param {number} high The high 32 bits.
       * @param {number} low The low 32 bits.
       *
       * @example
       *
       *     var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
       */
      init: function (high, low) {
        this.high = high;
        this.low = low;
      }

      /**
       * Bitwise NOTs this word.
       *
       * @return {X64Word} A new x64-Word object after negating.
       *
       * @example
       *
       *     var negated = x64Word.not();
       */
      // not: function () {
      // var high = ~this.high;
      // var low = ~this.low;

      // return X64Word.create(high, low);
      // },

      /**
       * Bitwise ANDs this word with the passed word.
       *
       * @param {X64Word} word The x64-Word to AND with this word.
       *
       * @return {X64Word} A new x64-Word object after ANDing.
       *
       * @example
       *
       *     var anded = x64Word.and(anotherX64Word);
       */
      // and: function (word) {
      // var high = this.high & word.high;
      // var low = this.low & word.low;

      // return X64Word.create(high, low);
      // },

      /**
       * Bitwise ORs this word with the passed word.
       *
       * @param {X64Word} word The x64-Word to OR with this word.
       *
       * @return {X64Word} A new x64-Word object after ORing.
       *
       * @example
       *
       *     var ored = x64Word.or(anotherX64Word);
       */
      // or: function (word) {
      // var high = this.high | word.high;
      // var low = this.low | word.low;

      // return X64Word.create(high, low);
      // },

      /**
       * Bitwise XORs this word with the passed word.
       *
       * @param {X64Word} word The x64-Word to XOR with this word.
       *
       * @return {X64Word} A new x64-Word object after XORing.
       *
       * @example
       *
       *     var xored = x64Word.xor(anotherX64Word);
       */
      // xor: function (word) {
      // var high = this.high ^ word.high;
      // var low = this.low ^ word.low;

      // return X64Word.create(high, low);
      // },

      /**
       * Shifts this word n bits to the left.
       *
       * @param {number} n The number of bits to shift.
       *
       * @return {X64Word} A new x64-Word object after shifting.
       *
       * @example
       *
       *     var shifted = x64Word.shiftL(25);
       */
      // shiftL: function (n) {
      // if (n < 32) {
      // var high = (this.high << n) | (this.low >>> (32 - n));
      // var low = this.low << n;
      // } else {
      // var high = this.low << (n - 32);
      // var low = 0;
      // }

      // return X64Word.create(high, low);
      // },

      /**
       * Shifts this word n bits to the right.
       *
       * @param {number} n The number of bits to shift.
       *
       * @return {X64Word} A new x64-Word object after shifting.
       *
       * @example
       *
       *     var shifted = x64Word.shiftR(7);
       */
      // shiftR: function (n) {
      // if (n < 32) {
      // var low = (this.low >>> n) | (this.high << (32 - n));
      // var high = this.high >>> n;
      // } else {
      // var low = this.high >>> (n - 32);
      // var high = 0;
      // }

      // return X64Word.create(high, low);
      // },

      /**
       * Rotates this word n bits to the left.
       *
       * @param {number} n The number of bits to rotate.
       *
       * @return {X64Word} A new x64-Word object after rotating.
       *
       * @example
       *
       *     var rotated = x64Word.rotL(25);
       */
      // rotL: function (n) {
      // return this.shiftL(n).or(this.shiftR(64 - n));
      // },

      /**
       * Rotates this word n bits to the right.
       *
       * @param {number} n The number of bits to rotate.
       *
       * @return {X64Word} A new x64-Word object after rotating.
       *
       * @example
       *
       *     var rotated = x64Word.rotR(7);
       */
      // rotR: function (n) {
      // return this.shiftR(n).or(this.shiftL(64 - n));
      // },

      /**
       * Adds this word with the passed word.
       *
       * @param {X64Word} word The x64-Word to add with this word.
       *
       * @return {X64Word} A new x64-Word object after adding.
       *
       * @example
       *
       *     var added = x64Word.add(anotherX64Word);
       */
      // add: function (word) {
      // var low = (this.low + word.low) | 0;
      // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
      // var high = (this.high + word.high + carry) | 0;

      // return X64Word.create(high, low);
      // }
    });

    /**
     * An array of 64-bit words.
     *
     * @property {Array} words The array of CryptoJS.x64.Word objects.
     * @property {number} sigBytes The number of significant bytes in this word array.
     */
    var X64WordArray = C_x64.WordArray = Base.extend({
      /**
       * Initializes a newly created word array.
       *
       * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
       * @param {number} sigBytes (Optional) The number of significant bytes in the words.
       *
       * @example
       *
       *     var wordArray = CryptoJS.x64.WordArray.create();
       *
       *     var wordArray = CryptoJS.x64.WordArray.create([
       *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
       *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
       *     ]);
       *
       *     var wordArray = CryptoJS.x64.WordArray.create([
       *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
       *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
       *     ], 10);
       */
      init: function (words, sigBytes) {
        words = this.words = words || [];
        if (sigBytes != undefined) {
          this.sigBytes = sigBytes;
        } else {
          this.sigBytes = words.length * 8;
        }
      },
      /**
       * Converts this 64-bit word array to a 32-bit word array.
       *
       * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
       *
       * @example
       *
       *     var x32WordArray = x64WordArray.toX32();
       */
      toX32: function () {
        // Shortcuts
        var x64Words = this.words;
        var x64WordsLength = x64Words.length;

        // Convert
        var x32Words = [];
        for (var i = 0; i < x64WordsLength; i++) {
          var x64Word = x64Words[i];
          x32Words.push(x64Word.high);
          x32Words.push(x64Word.low);
        }
        return X32WordArray.create(x32Words, this.sigBytes);
      },
      /**
       * Creates a copy of this word array.
       *
       * @return {X64WordArray} The clone.
       *
       * @example
       *
       *     var clone = x64WordArray.clone();
       */
      clone: function () {
        var clone = Base.clone.call(this);

        // Clone "words" array
        var words = clone.words = this.words.slice(0);

        // Clone each X64Word object
        var wordsLength = words.length;
        for (var i = 0; i < wordsLength; i++) {
          words[i] = words[i].clone();
        }
        return clone;
      }
    });
  })();
  return CryptoJS;
});

/***/ }),

/***/ 6845:
/*!****************************************************************************!*\
  !*** ./node_modules/.pnpm/fflate@0.8.2/node_modules/fflate/esm/browser.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AsyncCompress: () => (/* binding */ AsyncGzip),
/* harmony export */   AsyncDecompress: () => (/* binding */ AsyncDecompress),
/* harmony export */   AsyncDeflate: () => (/* binding */ AsyncDeflate),
/* harmony export */   AsyncGunzip: () => (/* binding */ AsyncGunzip),
/* harmony export */   AsyncGzip: () => (/* binding */ AsyncGzip),
/* harmony export */   AsyncInflate: () => (/* binding */ AsyncInflate),
/* harmony export */   AsyncUnzipInflate: () => (/* binding */ AsyncUnzipInflate),
/* harmony export */   AsyncUnzlib: () => (/* binding */ AsyncUnzlib),
/* harmony export */   AsyncZipDeflate: () => (/* binding */ AsyncZipDeflate),
/* harmony export */   AsyncZlib: () => (/* binding */ AsyncZlib),
/* harmony export */   Compress: () => (/* binding */ Gzip),
/* harmony export */   DecodeUTF8: () => (/* binding */ DecodeUTF8),
/* harmony export */   Decompress: () => (/* binding */ Decompress),
/* harmony export */   Deflate: () => (/* binding */ Deflate),
/* harmony export */   EncodeUTF8: () => (/* binding */ EncodeUTF8),
/* harmony export */   FlateErrorCode: () => (/* binding */ FlateErrorCode),
/* harmony export */   Gunzip: () => (/* binding */ Gunzip),
/* harmony export */   Gzip: () => (/* binding */ Gzip),
/* harmony export */   Inflate: () => (/* binding */ Inflate),
/* harmony export */   Unzip: () => (/* binding */ Unzip),
/* harmony export */   UnzipInflate: () => (/* binding */ UnzipInflate),
/* harmony export */   UnzipPassThrough: () => (/* binding */ UnzipPassThrough),
/* harmony export */   Unzlib: () => (/* binding */ Unzlib),
/* harmony export */   Zip: () => (/* binding */ Zip),
/* harmony export */   ZipDeflate: () => (/* binding */ ZipDeflate),
/* harmony export */   ZipPassThrough: () => (/* binding */ ZipPassThrough),
/* harmony export */   Zlib: () => (/* binding */ Zlib),
/* harmony export */   compress: () => (/* binding */ gzip),
/* harmony export */   compressSync: () => (/* binding */ gzipSync),
/* harmony export */   decompress: () => (/* binding */ decompress),
/* harmony export */   decompressSync: () => (/* binding */ decompressSync),
/* harmony export */   deflate: () => (/* binding */ deflate),
/* harmony export */   deflateSync: () => (/* binding */ deflateSync),
/* harmony export */   gunzip: () => (/* binding */ gunzip),
/* harmony export */   gunzipSync: () => (/* binding */ gunzipSync),
/* harmony export */   gzip: () => (/* binding */ gzip),
/* harmony export */   gzipSync: () => (/* binding */ gzipSync),
/* harmony export */   inflate: () => (/* binding */ inflate),
/* harmony export */   inflateSync: () => (/* binding */ inflateSync),
/* harmony export */   strFromU8: () => (/* binding */ strFromU8),
/* harmony export */   strToU8: () => (/* binding */ strToU8),
/* harmony export */   unzip: () => (/* binding */ unzip),
/* harmony export */   unzipSync: () => (/* binding */ unzipSync),
/* harmony export */   unzlib: () => (/* binding */ unzlib),
/* harmony export */   unzlibSync: () => (/* binding */ unzlibSync),
/* harmony export */   zip: () => (/* binding */ zip),
/* harmony export */   zipSync: () => (/* binding */ zipSync),
/* harmony export */   zlib: () => (/* binding */ zlib),
/* harmony export */   zlibSync: () => (/* binding */ zlibSync)
/* harmony export */ });
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).
var ch2 = {};
var wk = function (c, id, msg, transfer, cb) {
  var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'], {
    type: 'text/javascript'
  }))));
  w.onmessage = function (e) {
    var d = e.data,
      ed = d.$e$;
    if (ed) {
      var err = new Error(ed[0]);
      err['code'] = ed[1];
      err.stack = ed[2];
      cb(err, null);
    } else cb(null, d);
  };
  w.postMessage(msg, transfer);
  return w;
};

// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array,
  u16 = Uint16Array,
  i32 = Int32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */0, 0, /* impossible */0]);
// fixed distance extra bits
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
  var b = new u16(31);
  for (var i = 0; i < 31; ++i) {
    b[i] = start += 1 << eb[i - 1];
  }
  // numbers here are at max 18 bits
  var r = new i32(b[30]);
  for (var i = 1; i < 30; ++i) {
    for (var j = b[i]; j < b[i + 1]; ++j) {
      r[j] = j - b[i] << 5 | i;
    }
  }
  return {
    b: b,
    r: r
  };
};
var _a = freb(fleb, 2),
  fl = _a.b,
  revfl = _a.r;
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0),
  fd = _b.b,
  revfd = _b.r;
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
  // reverse table algorithm from SO
  var x = (i & 0xAAAA) >> 1 | (i & 0x5555) << 1;
  x = (x & 0xCCCC) >> 2 | (x & 0x3333) << 2;
  x = (x & 0xF0F0) >> 4 | (x & 0x0F0F) << 4;
  rev[i] = ((x & 0xFF00) >> 8 | (x & 0x00FF) << 8) >> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = function (cd, mb, r) {
  var s = cd.length;
  // index
  var i = 0;
  // u16 "map": index -> # of codes with bit length = index
  var l = new u16(mb);
  // length of cd must be 288 (total # of codes)
  for (; i < s; ++i) {
    if (cd[i]) ++l[cd[i] - 1];
  }
  // u16 "map": index -> minimum code for bit length = index
  var le = new u16(mb);
  for (i = 1; i < mb; ++i) {
    le[i] = le[i - 1] + l[i - 1] << 1;
  }
  var co;
  if (r) {
    // u16 "map": index -> number of actual bits, symbol for code
    co = new u16(1 << mb);
    // bits to remove for reverser
    var rvb = 15 - mb;
    for (i = 0; i < s; ++i) {
      // ignore 0 lengths
      if (cd[i]) {
        // num encoding both symbol and bits read
        var sv = i << 4 | cd[i];
        // free bits
        var r_1 = mb - cd[i];
        // start value
        var v = le[cd[i] - 1]++ << r_1;
        // m is end value
        for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
          // every 16 bit value starting with the code yields the same result
          co[rev[v] >> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s);
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
      }
    }
  }
  return co;
};
// fixed length tree
var flt = new u8(288);
for (var i = 0; i < 144; ++i) flt[i] = 8;
for (var i = 144; i < 256; ++i) flt[i] = 9;
for (var i = 256; i < 280; ++i) flt[i] = 7;
for (var i = 280; i < 288; ++i) flt[i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var i = 0; i < 32; ++i) fdt[i] = 5;
// fixed length map
var flm = /*#__PURE__*/hMap(flt, 9, 0),
  flrm = /*#__PURE__*/hMap(flt, 9, 1);
// fixed distance map
var fdm = /*#__PURE__*/hMap(fdt, 5, 0),
  fdrm = /*#__PURE__*/hMap(fdt, 5, 1);
// find max of array
var max = function (a) {
  var m = a[0];
  for (var i = 1; i < a.length; ++i) {
    if (a[i] > m) m = a[i];
  }
  return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
// get end of byte
var shft = function (p) {
  return (p + 7) / 8 | 0;
};
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
  if (s == null || s < 0) s = 0;
  if (e == null || e > v.length) e = v.length;
  // can't use .constructor in case user-supplied
  return new u8(v.subarray(s, e));
};
/**
 * Codes for errors generated within this library
 */
var FlateErrorCode = {
  UnexpectedEOF: 0,
  InvalidBlockType: 1,
  InvalidLengthLiteral: 2,
  InvalidDistance: 3,
  StreamFinished: 4,
  NoStreamHandler: 5,
  InvalidHeader: 6,
  NoCallback: 7,
  InvalidUTF8: 8,
  ExtraFieldTooLong: 9,
  InvalidDate: 10,
  FilenameTooLong: 11,
  StreamFinishing: 12,
  InvalidZipData: 13,
  UnknownCompressionMethod: 14
};
// error codes
var ec = ['unexpected EOF', 'invalid block type', 'invalid length/literal', 'invalid distance', 'stream finished', 'no stream handler',, 'no callback', 'invalid UTF-8 data', 'extra field too long', 'date not in range 1980-2099', 'filename too long', 'stream finishing', 'invalid zip data'
// determined by unknown compression method
];
;
var err = function (ind, msg, nt) {
  var e = new Error(msg || ec[ind]);
  e.code = ind;
  if (Error.captureStackTrace) Error.captureStackTrace(e, err);
  if (!nt) throw e;
  return e;
};
// expands raw DEFLATE data
var inflt = function (dat, st, buf, dict) {
  // source length       dict length
  var sl = dat.length,
    dl = dict ? dict.length : 0;
  if (!sl || st.f && !st.l) return buf || new u8(0);
  var noBuf = !buf;
  // have to estimate size
  var resize = noBuf || st.i != 2;
  // no state
  var noSt = st.i;
  // Assumes roughly 33% compression ratio average
  if (noBuf) buf = new u8(sl * 3);
  // ensure buffer can fit at least l elements
  var cbuf = function (l) {
    var bl = buf.length;
    // need to increase size to fit
    if (l > bl) {
      // Double or set to necessary, whichever is greater
      var nbuf = new u8(Math.max(bl * 2, l));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  //  last chunk         bitpos           bytes
  var final = st.f || 0,
    pos = st.p || 0,
    bt = st.b || 0,
    lm = st.l,
    dm = st.d,
    lbt = st.m,
    dbt = st.n;
  // total bits
  var tbts = sl * 8;
  do {
    if (!lm) {
      // BFINAL - this is only 1 when last chunk is next
      final = bits(dat, pos, 1);
      // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        // go to end of byte boundary
        var s = shft(pos) + 4,
          l = dat[s - 4] | dat[s - 3] << 8,
          t = s + l;
        if (t > sl) {
          if (noSt) err(0);
          break;
        }
        // ensure size
        if (resize) cbuf(bt + l);
        // Copy over uncompressed data
        buf.set(dat.subarray(s, t), bt);
        // Get new bitpos, update byte count
        st.b = bt += l, st.p = pos = t * 8, st.f = final;
        continue;
      } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5;else if (type == 2) {
        //  literal                            lengths
        var hLit = bits(dat, pos, 31) + 257,
          hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        // length+distance tree
        var ldt = new u8(tl);
        // code length tree
        var clt = new u8(19);
        for (var i = 0; i < hcLen; ++i) {
          // use index map to get real code
          clt[clim[i]] = bits(dat, pos + i * 3, 7);
        }
        pos += hcLen * 3;
        // code lengths bits
        var clb = max(clt),
          clbmsk = (1 << clb) - 1;
        // code lengths map
        var clm = hMap(clt, clb, 1);
        for (var i = 0; i < tl;) {
          var r = clm[bits(dat, pos, clbmsk)];
          // bits read
          pos += r & 15;
          // symbol
          var s = r >> 4;
          // code length to copy
          if (s < 16) {
            ldt[i++] = s;
          } else {
            //  copy   count
            var c = 0,
              n = 0;
            if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3;else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7;
            while (n--) ldt[i++] = c;
          }
        }
        //    length tree                 distance tree
        var lt = ldt.subarray(0, hLit),
          dt = ldt.subarray(hLit);
        // max length bits
        lbt = max(lt);
        // max dist bits
        dbt = max(dt);
        lm = hMap(lt, lbt, 1);
        dm = hMap(dt, dbt, 1);
      } else err(1);
      if (pos > tbts) {
        if (noSt) err(0);
        break;
      }
    }
    // Make sure the buffer can hold this + the largest possible addition
    // Maximum chunk size (practically, theoretically infinite) is 2^17
    if (resize) cbuf(bt + 131072);
    var lms = (1 << lbt) - 1,
      dms = (1 << dbt) - 1;
    var lpos = pos;
    for (;; lpos = pos) {
      // bits read, code
      var c = lm[bits16(dat, pos) & lms],
        sym = c >> 4;
      pos += c & 15;
      if (pos > tbts) {
        if (noSt) err(0);
        break;
      }
      if (!c) err(2);
      if (sym < 256) buf[bt++] = sym;else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add = sym - 254;
        // no extra bits needed if less
        if (sym > 264) {
          // index
          var i = sym - 257,
            b = fleb[i];
          add = bits(dat, pos, (1 << b) - 1) + fl[i];
          pos += b;
        }
        // dist
        var d = dm[bits16(dat, pos) & dms],
          dsym = d >> 4;
        if (!d) err(3);
        pos += d & 15;
        var dt = fd[dsym];
        if (dsym > 3) {
          var b = fdeb[dsym];
          dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
        }
        if (pos > tbts) {
          if (noSt) err(0);
          break;
        }
        if (resize) cbuf(bt + 131072);
        var end = bt + add;
        if (bt < dt) {
          var shift = dl - dt,
            dend = Math.min(dt, end);
          if (shift + bt < 0) err(3);
          for (; bt < dend; ++bt) buf[bt] = dict[shift + bt];
        }
        for (; bt < end; ++bt) buf[bt] = buf[bt - dt];
      }
    }
    st.l = lm, st.p = lpos, st.b = bt, st.f = final;
    if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  // don't reallocate for streams or user buffers
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
// starting at p, write the minimum number of bits that can hold v to d
var wbits = function (d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
};
// starting at p, write the minimum number of bits (>8) that can hold v to d
var wbits16 = function (d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
  d[o + 2] |= v >> 16;
};
// creates code lengths from a frequency table
var hTree = function (d, mb) {
  // Need extra info to make a tree
  var t = [];
  for (var i = 0; i < d.length; ++i) {
    if (d[i]) t.push({
      s: i,
      f: d[i]
    });
  }
  var s = t.length;
  var t2 = t.slice();
  if (!s) return {
    t: et,
    l: 0
  };
  if (s == 1) {
    var v = new u8(t[0].s + 1);
    v[t[0].s] = 1;
    return {
      t: v,
      l: 1
    };
  }
  t.sort(function (a, b) {
    return a.f - b.f;
  });
  // after i2 reaches last ind, will be stopped
  // freq must be greater than largest possible number of symbols
  t.push({
    s: -1,
    f: 25001
  });
  var l = t[0],
    r = t[1],
    i0 = 0,
    i1 = 1,
    i2 = 2;
  t[0] = {
    s: -1,
    f: l.f + r.f,
    l: l,
    r: r
  };
  // efficient algorithm from UZIP.js
  // i0 is lookbehind, i2 is lookahead - after processing two low-freq
  // symbols that combined have high freq, will start processing i2 (high-freq,
  // non-composite) symbols instead
  // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
  while (i1 != s - 1) {
    l = t[t[i0].f < t[i2].f ? i0++ : i2++];
    r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
    t[i1++] = {
      s: -1,
      f: l.f + r.f,
      l: l,
      r: r
    };
  }
  var maxSym = t2[0].s;
  for (var i = 1; i < s; ++i) {
    if (t2[i].s > maxSym) maxSym = t2[i].s;
  }
  // code lengths
  var tr = new u16(maxSym + 1);
  // max bits in tree
  var mbt = ln(t[i1 - 1], tr, 0);
  if (mbt > mb) {
    // more algorithms from UZIP.js
    // TODO: find out how this code works (debt)
    //  ind    debt
    var i = 0,
      dt = 0;
    //    left            cost
    var lft = mbt - mb,
      cst = 1 << lft;
    t2.sort(function (a, b) {
      return tr[b.s] - tr[a.s] || a.f - b.f;
    });
    for (; i < s; ++i) {
      var i2_1 = t2[i].s;
      if (tr[i2_1] > mb) {
        dt += cst - (1 << mbt - tr[i2_1]);
        tr[i2_1] = mb;
      } else break;
    }
    dt >>= lft;
    while (dt > 0) {
      var i2_2 = t2[i].s;
      if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1;else ++i;
    }
    for (; i >= 0 && dt; --i) {
      var i2_3 = t2[i].s;
      if (tr[i2_3] == mb) {
        --tr[i2_3];
        ++dt;
      }
    }
    mbt = mb;
  }
  return {
    t: new u8(tr),
    l: mbt
  };
};
// get the max length and assign length codes
var ln = function (n, l, d) {
  return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
};
// length codes generation
var lc = function (c) {
  var s = c.length;
  // Note that the semicolon was intentional
  while (s && !c[--s]);
  var cl = new u16(++s);
  //  ind      num         streak
  var cli = 0,
    cln = c[0],
    cls = 1;
  var w = function (v) {
    cl[cli++] = v;
  };
  for (var i = 1; i <= s; ++i) {
    if (c[i] == cln && i != s) ++cls;else {
      if (!cln && cls > 2) {
        for (; cls > 138; cls -= 138) w(32754);
        if (cls > 2) {
          w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
          cls = 0;
        }
      } else if (cls > 3) {
        w(cln), --cls;
        for (; cls > 6; cls -= 6) w(8304);
        if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0;
      }
      while (cls--) w(cln);
      cls = 1;
      cln = c[i];
    }
  }
  return {
    c: cl.subarray(0, cli),
    n: s
  };
};
// calculate the length of output from tree, code lengths
var clen = function (cf, cl) {
  var l = 0;
  for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i];
  return l;
};
// writes a fixed block
// returns the new bit pos
var wfblk = function (out, pos, dat) {
  // no need to write 00 as type: TypedArray defaults to 0
  var s = dat.length;
  var o = shft(pos + 2);
  out[o] = s & 255;
  out[o + 1] = s >> 8;
  out[o + 2] = out[o] ^ 255;
  out[o + 3] = out[o + 1] ^ 255;
  for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i];
  return (o + 4 + s) * 8;
};
// writes a block
var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
  wbits(out, p++, final);
  ++lf[256];
  var _a = hTree(lf, 15),
    dlt = _a.t,
    mlb = _a.l;
  var _b = hTree(df, 15),
    ddt = _b.t,
    mdb = _b.l;
  var _c = lc(dlt),
    lclt = _c.c,
    nlc = _c.n;
  var _d = lc(ddt),
    lcdt = _d.c,
    ndc = _d.n;
  var lcfreq = new u16(19);
  for (var i = 0; i < lclt.length; ++i) ++lcfreq[lclt[i] & 31];
  for (var i = 0; i < lcdt.length; ++i) ++lcfreq[lcdt[i] & 31];
  var _e = hTree(lcfreq, 7),
    lct = _e.t,
    mlcb = _e.l;
  var nlcc = 19;
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc);
  var flen = bl + 5 << 3;
  var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
  var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
  if (bs >= 0 && flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl));
  var lm, ll, dm, dl;
  wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
  if (dtlen < ftlen) {
    lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
    var llm = hMap(lct, mlcb, 0);
    wbits(out, p, nlc - 257);
    wbits(out, p + 5, ndc - 1);
    wbits(out, p + 10, nlcc - 4);
    p += 14;
    for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]);
    p += 3 * nlcc;
    var lcts = [lclt, lcdt];
    for (var it = 0; it < 2; ++it) {
      var clct = lcts[it];
      for (var i = 0; i < clct.length; ++i) {
        var len = clct[i] & 31;
        wbits(out, p, llm[len]), p += lct[len];
        if (len > 15) wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
      }
    }
  } else {
    lm = flm, ll = flt, dm = fdm, dl = fdt;
  }
  for (var i = 0; i < li; ++i) {
    var sym = syms[i];
    if (sym > 255) {
      var len = sym >> 18 & 31;
      wbits16(out, p, lm[len + 257]), p += ll[len + 257];
      if (len > 7) wbits(out, p, sym >> 23 & 31), p += fleb[len];
      var dst = sym & 31;
      wbits16(out, p, dm[dst]), p += dl[dst];
      if (dst > 3) wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
    } else {
      wbits16(out, p, lm[sym]), p += ll[sym];
    }
  }
  wbits16(out, p, lm[256]);
  return p + ll[256];
};
// deflate options (nice << 13) | chain
var deo = /*#__PURE__*/new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
// empty
var et = /*#__PURE__*/new u8(0);
// compresses data into a raw DEFLATE buffer
var dflt = function (dat, lvl, plvl, pre, post, st) {
  var s = st.z || dat.length;
  var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
  // writing to this writes to the output buffer
  var w = o.subarray(pre, o.length - post);
  var lst = st.l;
  var pos = (st.r || 0) & 7;
  if (lvl) {
    if (pos) w[0] = st.r >> 3;
    var opt = deo[lvl - 1];
    var n = opt >> 13,
      c = opt & 8191;
    var msk_1 = (1 << plvl) - 1;
    //    prev 2-byte val map    curr 2-byte val map
    var prev = st.p || new u16(32768),
      head = st.h || new u16(msk_1 + 1);
    var bs1_1 = Math.ceil(plvl / 3),
      bs2_1 = 2 * bs1_1;
    var hsh = function (i) {
      return (dat[i] ^ dat[i + 1] << bs1_1 ^ dat[i + 2] << bs2_1) & msk_1;
    };
    // 24576 is an arbitrary number of maximum symbols per block
    // 424 buffer for last block
    var syms = new i32(25000);
    // length/literal freq   distance freq
    var lf = new u16(288),
      df = new u16(32);
    //  l/lcnt  exbits  index          l/lind  waitdx          blkpos
    var lc_1 = 0,
      eb = 0,
      i = st.i || 0,
      li = 0,
      wi = st.w || 0,
      bs = 0;
    for (; i + 2 < s; ++i) {
      // hash value
      var hv = hsh(i);
      // index mod 32768    previous index mod
      var imod = i & 32767,
        pimod = head[hv];
      prev[imod] = pimod;
      head[hv] = imod;
      // We always should modify head and prev, but only add symbols if
      // this data is not yet processed ("wait" for wait index)
      if (wi <= i) {
        // bytes remaining
        var rem = s - i;
        if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
          pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
          li = lc_1 = eb = 0, bs = i;
          for (var j = 0; j < 286; ++j) lf[j] = 0;
          for (var j = 0; j < 30; ++j) df[j] = 0;
        }
        //  len    dist   chain
        var l = 2,
          d = 0,
          ch_1 = c,
          dif = imod - pimod & 32767;
        if (rem > 2 && hv == hsh(i - dif)) {
          var maxn = Math.min(n, rem) - 1;
          var maxd = Math.min(32767, i);
          // max possible length
          // not capped at dif because decompressors implement "rolling" index population
          var ml = Math.min(258, rem);
          while (dif <= maxd && --ch_1 && imod != pimod) {
            if (dat[i + l] == dat[i + l - dif]) {
              var nl = 0;
              for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl);
              if (nl > l) {
                l = nl, d = dif;
                // break out early when we reach "nice" (we are satisfied enough)
                if (nl > maxn) break;
                // now, find the rarest 2-byte sequence within this
                // length of literals and search for that instead.
                // Much faster than just using the start
                var mmd = Math.min(dif, nl - 2);
                var md = 0;
                for (var j = 0; j < mmd; ++j) {
                  var ti = i - dif + j & 32767;
                  var pti = prev[ti];
                  var cd = ti - pti & 32767;
                  if (cd > md) md = cd, pimod = ti;
                }
              }
            }
            // check the previous match
            imod = pimod, pimod = prev[imod];
            dif += imod - pimod & 32767;
          }
        }
        // d will be nonzero only when a match was found
        if (d) {
          // store both dist and len data in one int32
          // Make sure this is recognized as a len/dist with 28th bit (2^28)
          syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
          var lin = revfl[l] & 31,
            din = revfd[d] & 31;
          eb += fleb[lin] + fdeb[din];
          ++lf[257 + lin];
          ++df[din];
          wi = i + l;
          ++lc_1;
        } else {
          syms[li++] = dat[i];
          ++lf[dat[i]];
        }
      }
    }
    for (i = Math.max(i, wi); i < s; ++i) {
      syms[li++] = dat[i];
      ++lf[dat[i]];
    }
    pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
    if (!lst) {
      st.r = pos & 7 | w[pos / 8 | 0] << 3;
      // shft(pos) now 1 less if pos & 7 != 0
      pos -= 7;
      st.h = head, st.p = prev, st.i = i, st.w = wi;
    }
  } else {
    for (var i = st.w || 0; i < s + lst; i += 65535) {
      // end
      var e = i + 65535;
      if (e >= s) {
        // write final block
        w[pos / 8 | 0] = lst;
        e = s;
      }
      pos = wfblk(w, pos + 1, dat.subarray(i, e));
    }
    st.i = s;
  }
  return slc(o, 0, pre + shft(pos) + post);
};
// CRC32 table
var crct = /*#__PURE__*/function () {
  var t = new Int32Array(256);
  for (var i = 0; i < 256; ++i) {
    var c = i,
      k = 9;
    while (--k) c = (c & 1 && -306674912) ^ c >>> 1;
    t[i] = c;
  }
  return t;
}();
// CRC32
var crc = function () {
  var c = -1;
  return {
    p: function (d) {
      // closures have awful performance
      var cr = c;
      for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
      c = cr;
    },
    d: function () {
      return ~c;
    }
  };
};
// Adler32
var adler = function () {
  var a = 1,
    b = 0;
  return {
    p: function (d) {
      // closures have awful performance
      var n = a,
        m = b;
      var l = d.length | 0;
      for (var i = 0; i != l;) {
        var e = Math.min(i + 2655, l);
        for (; i < e; ++i) m += n += d[i];
        n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
      }
      a = n, b = m;
    },
    d: function () {
      a %= 65521, b %= 65521;
      return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | b >> 8;
    }
  };
};
;
// deflate with opts
var dopt = function (dat, opt, pre, post, st) {
  if (!st) {
    st = {
      l: 1
    };
    if (opt.dictionary) {
      var dict = opt.dictionary.subarray(-32768);
      var newDat = new u8(dict.length + dat.length);
      newDat.set(dict);
      newDat.set(dat, dict.length);
      dat = newDat;
      st.w = dict.length;
    }
  }
  return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
};
// Walmart object spread
var mrg = function (a, b) {
  var o = {};
  for (var k in a) o[k] = a[k];
  for (var k in b) o[k] = b[k];
  return o;
};
// worker clone
// This is possibly the craziest part of the entire codebase, despite how simple it may seem.
// The only parameter to this function is a closure that returns an array of variables outside of the function scope.
// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
// This took me three weeks to figure out how to do.
var wcln = function (fn, fnStr, td) {
  var dt = fn();
  var st = fn.toString();
  var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
  for (var i = 0; i < dt.length; ++i) {
    var v = dt[i],
      k = ks[i];
    if (typeof v == 'function') {
      fnStr += ';' + k + '=';
      var st_1 = v.toString();
      if (v.prototype) {
        // for global objects
        if (st_1.indexOf('[native code]') != -1) {
          var spInd = st_1.indexOf(' ', 8) + 1;
          fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
        } else {
          fnStr += st_1;
          for (var t in v.prototype) fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
        }
      } else fnStr += st_1;
    } else td[k] = v;
  }
  return fnStr;
};
var ch = [];
// clone bufs
var cbfs = function (v) {
  var tl = [];
  for (var k in v) {
    if (v[k].buffer) {
      tl.push((v[k] = new v[k].constructor(v[k])).buffer);
    }
  }
  return tl;
};
// use a worker to execute code
var wrkr = function (fns, init, id, cb) {
  if (!ch[id]) {
    var fnStr = '',
      td_1 = {},
      m = fns.length - 1;
    for (var i = 0; i < m; ++i) fnStr = wcln(fns[i], fnStr, td_1);
    ch[id] = {
      c: wcln(fns[m], fnStr, td_1),
      e: td_1
    };
  }
  var td = mrg({}, ch[id].e);
  return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
};
// base async inflate fn
var bInflt = function () {
  return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt];
};
var bDflt = function () {
  return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf];
};
// gzip extra
var gze = function () {
  return [gzh, gzhl, wbytes, crc, crct];
};
// gunzip extra
var guze = function () {
  return [gzs, gzl];
};
// zlib extra
var zle = function () {
  return [zlh, wbytes, adler];
};
// unzlib extra
var zule = function () {
  return [zls];
};
// post buf
var pbf = function (msg) {
  return postMessage(msg, [msg.buffer]);
};
// get opts
var gopt = function (o) {
  return o && {
    out: o.size && new u8(o.size),
    dictionary: o.dictionary
  };
};
// async helper
var cbify = function (dat, opts, fns, init, id, cb) {
  var w = wrkr(fns, init, id, function (err, dat) {
    w.terminate();
    cb(err, dat);
  });
  w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
  return function () {
    w.terminate();
  };
};
// auto stream
var astrm = function (strm) {
  strm.ondata = function (dat, final) {
    return postMessage([dat, final], [dat.buffer]);
  };
  return function (ev) {
    if (ev.data.length) {
      strm.push(ev.data[0], ev.data[1]);
      postMessage([ev.data[0].length]);
    } else strm.flush();
  };
};
// async stream attach
var astrmify = function (fns, strm, opts, init, id, flush, ext) {
  var t;
  var w = wrkr(fns, init, id, function (err, dat) {
    if (err) w.terminate(), strm.ondata.call(strm, err);else if (!Array.isArray(dat)) ext(dat);else if (dat.length == 1) {
      strm.queuedSize -= dat[0];
      if (strm.ondrain) strm.ondrain(dat[0]);
    } else {
      if (dat[1]) w.terminate();
      strm.ondata.call(strm, err, dat[0], dat[1]);
    }
  });
  w.postMessage(opts);
  strm.queuedSize = 0;
  strm.push = function (d, f) {
    if (!strm.ondata) err(5);
    if (t) strm.ondata(err(4, 0, 1), null, !!f);
    strm.queuedSize += d.length;
    w.postMessage([d, t = f], [d.buffer]);
  };
  strm.terminate = function () {
    w.terminate();
  };
  if (flush) {
    strm.flush = function () {
      w.postMessage([]);
    };
  }
};
// read 2 bytes
var b2 = function (d, b) {
  return d[b] | d[b + 1] << 8;
};
// read 4 bytes
var b4 = function (d, b) {
  return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
};
var b8 = function (d, b) {
  return b4(d, b) + b4(d, b + 4) * 4294967296;
};
// write bytes
var wbytes = function (d, b, v) {
  for (; v; ++b) d[b] = v, v >>>= 8;
};
// gzip header
var gzh = function (c, o) {
  var fn = o.filename;
  c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
  if (o.mtime != 0) wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
  if (fn) {
    c[3] = 8;
    for (var i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i);
  }
};
// gzip footer: -8 to -4 = CRC, -4 to -0 is length
// gzip start
var gzs = function (d) {
  if (d[0] != 31 || d[1] != 139 || d[2] != 8) err(6, 'invalid gzip data');
  var flg = d[3];
  var st = 10;
  if (flg & 4) st += (d[10] | d[11] << 8) + 2;
  for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]);
  return st + (flg & 2);
};
// gzip length
var gzl = function (d) {
  var l = d.length;
  return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
// gzip header length
var gzhl = function (o) {
  return 10 + (o.filename ? o.filename.length + 1 : 0);
};
// zlib header
var zlh = function (c, o) {
  var lv = o.level,
    fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
  c[0] = 120, c[1] = fl << 6 | (o.dictionary && 32);
  c[1] |= 31 - (c[0] << 8 | c[1]) % 31;
  if (o.dictionary) {
    var h = adler();
    h.p(o.dictionary);
    wbytes(c, 2, h.d());
  }
};
// zlib start
var zls = function (d, dict) {
  if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31) err(6, 'invalid zlib data');
  if ((d[1] >> 5 & 1) == +!dict) err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
  return (d[1] >> 3 & 4) + 2;
};
function StrmOpt(opts, cb) {
  if (typeof opts == 'function') cb = opts, opts = {};
  this.ondata = cb;
  return opts;
}
/**
 * Streaming DEFLATE compression
 */
var Deflate = /*#__PURE__*/function () {
  function Deflate(opts, cb) {
    if (typeof opts == 'function') cb = opts, opts = {};
    this.ondata = cb;
    this.o = opts || {};
    this.s = {
      l: 0,
      i: 32768,
      w: 32768,
      z: 32768
    };
    // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev
    // 98304 = 32768 (lookback) + 65536 (common chunk size)
    this.b = new u8(98304);
    if (this.o.dictionary) {
      var dict = this.o.dictionary.subarray(-32768);
      this.b.set(dict, 32768 - dict.length);
      this.s.i = 32768 - dict.length;
    }
  }
  Deflate.prototype.p = function (c, f) {
    this.ondata(dopt(c, this.o, 0, 0, this.s), f);
  };
  /**
   * Pushes a chunk to be deflated
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Deflate.prototype.push = function (chunk, final) {
    if (!this.ondata) err(5);
    if (this.s.l) err(4);
    var endLen = chunk.length + this.s.z;
    if (endLen > this.b.length) {
      if (endLen > 2 * this.b.length - 32768) {
        var newBuf = new u8(endLen & -32768);
        newBuf.set(this.b.subarray(0, this.s.z));
        this.b = newBuf;
      }
      var split = this.b.length - this.s.z;
      this.b.set(chunk.subarray(0, split), this.s.z);
      this.s.z = this.b.length;
      this.p(this.b, false);
      this.b.set(this.b.subarray(-32768));
      this.b.set(chunk.subarray(split), 32768);
      this.s.z = chunk.length - split + 32768;
      this.s.i = 32766, this.s.w = 32768;
    } else {
      this.b.set(chunk, this.s.z);
      this.s.z += chunk.length;
    }
    this.s.l = final & 1;
    if (this.s.z > this.s.w + 8191 || final) {
      this.p(this.b, final || false);
      this.s.w = this.s.i, this.s.i -= 2;
    }
  };
  /**
   * Flushes buffered uncompressed data. Useful to immediately retrieve the
   * deflated output for small inputs.
   */
  Deflate.prototype.flush = function () {
    if (!this.ondata) err(5);
    if (this.s.l) err(4);
    this.p(this.b, false);
    this.s.w = this.s.i, this.s.i -= 2;
  };
  return Deflate;
}();

/**
 * Asynchronous streaming DEFLATE compression
 */
var AsyncDeflate = /*#__PURE__*/function () {
  function AsyncDeflate(opts, cb) {
    astrmify([bDflt, function () {
      return [astrm, Deflate];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Deflate(ev.data);
      onmessage = astrm(strm);
    }, 6, 1);
  }
  return AsyncDeflate;
}();

function deflate(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bDflt], function (ev) {
    return pbf(deflateSync(ev.data[0], ev.data[1]));
  }, 0, cb);
}
/**
 * Compresses data with DEFLATE without any wrapper
 * @param data The data to compress
 * @param opts The compression options
 * @returns The deflated version of the data
 */
function deflateSync(data, opts) {
  return dopt(data, opts || {}, 0, 0);
}
/**
 * Streaming DEFLATE decompression
 */
var Inflate = /*#__PURE__*/function () {
  function Inflate(opts, cb) {
    // no StrmOpt here to avoid adding to workerizer
    if (typeof opts == 'function') cb = opts, opts = {};
    this.ondata = cb;
    var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
    this.s = {
      i: 0,
      b: dict ? dict.length : 0
    };
    this.o = new u8(32768);
    this.p = new u8(0);
    if (dict) this.o.set(dict);
  }
  Inflate.prototype.e = function (c) {
    if (!this.ondata) err(5);
    if (this.d) err(4);
    if (!this.p.length) this.p = c;else if (c.length) {
      var n = new u8(this.p.length + c.length);
      n.set(this.p), n.set(c, this.p.length), this.p = n;
    }
  };
  Inflate.prototype.c = function (final) {
    this.s.i = +(this.d = final || false);
    var bts = this.s.b;
    var dt = inflt(this.p, this.s, this.o);
    this.ondata(slc(dt, bts, this.s.b), this.d);
    this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
    this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
  };
  /**
   * Pushes a chunk to be inflated
   * @param chunk The chunk to push
   * @param final Whether this is the final chunk
   */
  Inflate.prototype.push = function (chunk, final) {
    this.e(chunk), this.c(final);
  };
  return Inflate;
}();

/**
 * Asynchronous streaming DEFLATE decompression
 */
var AsyncInflate = /*#__PURE__*/function () {
  function AsyncInflate(opts, cb) {
    astrmify([bInflt, function () {
      return [astrm, Inflate];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Inflate(ev.data);
      onmessage = astrm(strm);
    }, 7, 0);
  }
  return AsyncInflate;
}();

function inflate(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bInflt], function (ev) {
    return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
  }, 1, cb);
}
/**
 * Expands DEFLATE data with no wrapper
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function inflateSync(data, opts) {
  return inflt(data, {
    i: 2
  }, opts && opts.out, opts && opts.dictionary);
}
// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
/**
 * Streaming GZIP compression
 */
var Gzip = /*#__PURE__*/function () {
  function Gzip(opts, cb) {
    this.c = crc();
    this.l = 0;
    this.v = 1;
    Deflate.call(this, opts, cb);
  }
  /**
   * Pushes a chunk to be GZIPped
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Gzip.prototype.push = function (chunk, final) {
    this.c.p(chunk);
    this.l += chunk.length;
    Deflate.prototype.push.call(this, chunk, final);
  };
  Gzip.prototype.p = function (c, f) {
    var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);
    if (this.v) gzh(raw, this.o), this.v = 0;
    if (f) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
    this.ondata(raw, f);
  };
  /**
   * Flushes buffered uncompressed data. Useful to immediately retrieve the
   * GZIPped output for small inputs.
   */
  Gzip.prototype.flush = function () {
    Deflate.prototype.flush.call(this);
  };
  return Gzip;
}();

/**
 * Asynchronous streaming GZIP compression
 */
var AsyncGzip = /*#__PURE__*/function () {
  function AsyncGzip(opts, cb) {
    astrmify([bDflt, gze, function () {
      return [astrm, Deflate, Gzip];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Gzip(ev.data);
      onmessage = astrm(strm);
    }, 8, 1);
  }
  return AsyncGzip;
}();

function gzip(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bDflt, gze, function () {
    return [gzipSync];
  }], function (ev) {
    return pbf(gzipSync(ev.data[0], ev.data[1]));
  }, 2, cb);
}
/**
 * Compresses data with GZIP
 * @param data The data to compress
 * @param opts The compression options
 * @returns The gzipped version of the data
 */
function gzipSync(data, opts) {
  if (!opts) opts = {};
  var c = crc(),
    l = data.length;
  c.p(data);
  var d = dopt(data, opts, gzhl(opts), 8),
    s = d.length;
  return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
}
/**
 * Streaming single or multi-member GZIP decompression
 */
var Gunzip = /*#__PURE__*/function () {
  function Gunzip(opts, cb) {
    this.v = 1;
    this.r = 0;
    Inflate.call(this, opts, cb);
  }
  /**
   * Pushes a chunk to be GUNZIPped
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Gunzip.prototype.push = function (chunk, final) {
    Inflate.prototype.e.call(this, chunk);
    this.r += chunk.length;
    if (this.v) {
      var p = this.p.subarray(this.v - 1);
      var s = p.length > 3 ? gzs(p) : 4;
      if (s > p.length) {
        if (!final) return;
      } else if (this.v > 1 && this.onmember) {
        this.onmember(this.r - p.length);
      }
      this.p = p.subarray(s), this.v = 0;
    }
    // necessary to prevent TS from using the closure value
    // This allows for workerization to function correctly
    Inflate.prototype.c.call(this, final);
    // process concatenated GZIP
    if (this.s.f && !this.s.l && !final) {
      this.v = shft(this.s.p) + 9;
      this.s = {
        i: 0
      };
      this.o = new u8(0);
      this.push(new u8(0), final);
    }
  };
  return Gunzip;
}();

/**
 * Asynchronous streaming single or multi-member GZIP decompression
 */
var AsyncGunzip = /*#__PURE__*/function () {
  function AsyncGunzip(opts, cb) {
    var _this = this;
    astrmify([bInflt, guze, function () {
      return [astrm, Inflate, Gunzip];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Gunzip(ev.data);
      strm.onmember = function (offset) {
        return postMessage(offset);
      };
      onmessage = astrm(strm);
    }, 9, 0, function (offset) {
      return _this.onmember && _this.onmember(offset);
    });
  }
  return AsyncGunzip;
}();

function gunzip(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bInflt, guze, function () {
    return [gunzipSync];
  }], function (ev) {
    return pbf(gunzipSync(ev.data[0], ev.data[1]));
  }, 3, cb);
}
/**
 * Expands GZIP data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function gunzipSync(data, opts) {
  var st = gzs(data);
  if (st + 8 > data.length) err(6, 'invalid gzip data');
  return inflt(data.subarray(st, -8), {
    i: 2
  }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
}
/**
 * Streaming Zlib compression
 */
var Zlib = /*#__PURE__*/function () {
  function Zlib(opts, cb) {
    this.c = adler();
    this.v = 1;
    Deflate.call(this, opts, cb);
  }
  /**
   * Pushes a chunk to be zlibbed
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Zlib.prototype.push = function (chunk, final) {
    this.c.p(chunk);
    Deflate.prototype.push.call(this, chunk, final);
  };
  Zlib.prototype.p = function (c, f) {
    var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
    if (this.v) zlh(raw, this.o), this.v = 0;
    if (f) wbytes(raw, raw.length - 4, this.c.d());
    this.ondata(raw, f);
  };
  /**
   * Flushes buffered uncompressed data. Useful to immediately retrieve the
   * zlibbed output for small inputs.
   */
  Zlib.prototype.flush = function () {
    Deflate.prototype.flush.call(this);
  };
  return Zlib;
}();

/**
 * Asynchronous streaming Zlib compression
 */
var AsyncZlib = /*#__PURE__*/function () {
  function AsyncZlib(opts, cb) {
    astrmify([bDflt, zle, function () {
      return [astrm, Deflate, Zlib];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Zlib(ev.data);
      onmessage = astrm(strm);
    }, 10, 1);
  }
  return AsyncZlib;
}();

function zlib(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bDflt, zle, function () {
    return [zlibSync];
  }], function (ev) {
    return pbf(zlibSync(ev.data[0], ev.data[1]));
  }, 4, cb);
}
/**
 * Compress data with Zlib
 * @param data The data to compress
 * @param opts The compression options
 * @returns The zlib-compressed version of the data
 */
function zlibSync(data, opts) {
  if (!opts) opts = {};
  var a = adler();
  a.p(data);
  var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
  return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
}
/**
 * Streaming Zlib decompression
 */
var Unzlib = /*#__PURE__*/function () {
  function Unzlib(opts, cb) {
    Inflate.call(this, opts, cb);
    this.v = opts && opts.dictionary ? 2 : 1;
  }
  /**
   * Pushes a chunk to be unzlibbed
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Unzlib.prototype.push = function (chunk, final) {
    Inflate.prototype.e.call(this, chunk);
    if (this.v) {
      if (this.p.length < 6 && !final) return;
      this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
    }
    if (final) {
      if (this.p.length < 4) err(6, 'invalid zlib data');
      this.p = this.p.subarray(0, -4);
    }
    // necessary to prevent TS from using the closure value
    // This allows for workerization to function correctly
    Inflate.prototype.c.call(this, final);
  };
  return Unzlib;
}();

/**
 * Asynchronous streaming Zlib decompression
 */
var AsyncUnzlib = /*#__PURE__*/function () {
  function AsyncUnzlib(opts, cb) {
    astrmify([bInflt, zule, function () {
      return [astrm, Inflate, Unzlib];
    }], this, StrmOpt.call(this, opts, cb), function (ev) {
      var strm = new Unzlib(ev.data);
      onmessage = astrm(strm);
    }, 11, 0);
  }
  return AsyncUnzlib;
}();

function unzlib(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return cbify(data, opts, [bInflt, zule, function () {
    return [unzlibSync];
  }], function (ev) {
    return pbf(unzlibSync(ev.data[0], gopt(ev.data[1])));
  }, 5, cb);
}
/**
 * Expands Zlib data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function unzlibSync(data, opts) {
  return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), {
    i: 2
  }, opts && opts.out, opts && opts.dictionary);
}
// Default algorithm for compression (used because having a known output size allows faster decompression)


/**
 * Streaming GZIP, Zlib, or raw DEFLATE decompression
 */
var Decompress = /*#__PURE__*/function () {
  function Decompress(opts, cb) {
    this.o = StrmOpt.call(this, opts, cb) || {};
    this.G = Gunzip;
    this.I = Inflate;
    this.Z = Unzlib;
  }
  // init substream
  // overriden by AsyncDecompress
  Decompress.prototype.i = function () {
    var _this = this;
    this.s.ondata = function (dat, final) {
      _this.ondata(dat, final);
    };
  };
  /**
   * Pushes a chunk to be decompressed
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Decompress.prototype.push = function (chunk, final) {
    if (!this.ondata) err(5);
    if (!this.s) {
      if (this.p && this.p.length) {
        var n = new u8(this.p.length + chunk.length);
        n.set(this.p), n.set(chunk, this.p.length);
      } else this.p = chunk;
      if (this.p.length > 2) {
        this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(this.o) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(this.o) : new this.Z(this.o);
        this.i();
        this.s.push(this.p, final);
        this.p = null;
      }
    } else this.s.push(chunk, final);
  };
  return Decompress;
}();

/**
 * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
 */
var AsyncDecompress = /*#__PURE__*/function () {
  function AsyncDecompress(opts, cb) {
    Decompress.call(this, opts, cb);
    this.queuedSize = 0;
    this.G = AsyncGunzip;
    this.I = AsyncInflate;
    this.Z = AsyncUnzlib;
  }
  AsyncDecompress.prototype.i = function () {
    var _this = this;
    this.s.ondata = function (err, dat, final) {
      _this.ondata(err, dat, final);
    };
    this.s.ondrain = function (size) {
      _this.queuedSize -= size;
      if (_this.ondrain) _this.ondrain(size);
    };
  };
  /**
   * Pushes a chunk to be decompressed
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  AsyncDecompress.prototype.push = function (chunk, final) {
    this.queuedSize += chunk.length;
    Decompress.prototype.push.call(this, chunk, final);
  };
  return AsyncDecompress;
}();

function decompress(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzip(data, opts, cb) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflate(data, opts, cb) : unzlib(data, opts, cb);
}
/**
 * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function decompressSync(data, opts) {
  return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
}
// flatten a directory structure
var fltn = function (d, p, t, o) {
  for (var k in d) {
    var val = d[k],
      n = p + k,
      op = o;
    if (Array.isArray(val)) op = mrg(o, val[1]), val = val[0];
    if (val instanceof u8) t[n] = [val, op];else {
      t[n += '/'] = [new u8(0), op];
      fltn(val, n, t, o);
    }
  }
};
// text encoder
var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/new TextEncoder();
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/new TextDecoder();
// text decoder stream
var tds = 0;
try {
  td.decode(et, {
    stream: true
  });
  tds = 1;
} catch (e) {}
// decode UTF8
var dutf8 = function (d) {
  for (var r = '', i = 0;;) {
    var c = d[i++];
    var eb = (c > 127) + (c > 223) + (c > 239);
    if (i + eb > d.length) return {
      s: r,
      r: slc(d, i - 1)
    };
    if (!eb) r += String.fromCharCode(c);else if (eb == 3) {
      c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
    } else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | d[i++] & 63);else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63);
  }
};
/**
 * Streaming UTF-8 decoding
 */
var DecodeUTF8 = /*#__PURE__*/function () {
  /**
   * Creates a UTF-8 decoding stream
   * @param cb The callback to call whenever data is decoded
   */
  function DecodeUTF8(cb) {
    this.ondata = cb;
    if (tds) this.t = new TextDecoder();else this.p = et;
  }
  /**
   * Pushes a chunk to be decoded from UTF-8 binary
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  DecodeUTF8.prototype.push = function (chunk, final) {
    if (!this.ondata) err(5);
    final = !!final;
    if (this.t) {
      this.ondata(this.t.decode(chunk, {
        stream: true
      }), final);
      if (final) {
        if (this.t.decode().length) err(8);
        this.t = null;
      }
      return;
    }
    if (!this.p) err(4);
    var dat = new u8(this.p.length + chunk.length);
    dat.set(this.p);
    dat.set(chunk, this.p.length);
    var _a = dutf8(dat),
      s = _a.s,
      r = _a.r;
    if (final) {
      if (r.length) err(8);
      this.p = null;
    } else this.p = r;
    this.ondata(s, final);
  };
  return DecodeUTF8;
}();

/**
 * Streaming UTF-8 encoding
 */
var EncodeUTF8 = /*#__PURE__*/function () {
  /**
   * Creates a UTF-8 decoding stream
   * @param cb The callback to call whenever data is encoded
   */
  function EncodeUTF8(cb) {
    this.ondata = cb;
  }
  /**
   * Pushes a chunk to be encoded to UTF-8
   * @param chunk The string data to push
   * @param final Whether this is the last chunk
   */
  EncodeUTF8.prototype.push = function (chunk, final) {
    if (!this.ondata) err(5);
    if (this.d) err(4);
    this.ondata(strToU8(chunk), this.d = final || false);
  };
  return EncodeUTF8;
}();

/**
 * Converts a string into a Uint8Array for use with compression/decompression methods
 * @param str The string to encode
 * @param latin1 Whether or not to interpret the data as Latin-1. This should
 *               not need to be true unless decoding a binary string.
 * @returns The string encoded in UTF-8/Latin-1 binary
 */
function strToU8(str, latin1) {
  if (latin1) {
    var ar_1 = new u8(str.length);
    for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i);
    return ar_1;
  }
  if (te) return te.encode(str);
  var l = str.length;
  var ar = new u8(str.length + (str.length >> 1));
  var ai = 0;
  var w = function (v) {
    ar[ai++] = v;
  };
  for (var i = 0; i < l; ++i) {
    if (ai + 5 > ar.length) {
      var n = new u8(ai + 8 + (l - i << 1));
      n.set(ar);
      ar = n;
    }
    var c = str.charCodeAt(i);
    if (c < 128 || latin1) w(c);else if (c < 2048) w(192 | c >> 6), w(128 | c & 63);else if (c > 55295 && c < 57344) c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
  }
  return slc(ar, 0, ai);
}
/**
 * Converts a Uint8Array to a string
 * @param dat The data to decode to string
 * @param latin1 Whether or not to interpret the data as Latin-1. This should
 *               not need to be true unless encoding to binary string.
 * @returns The original UTF-8/Latin-1 string
 */
function strFromU8(dat, latin1) {
  if (latin1) {
    var r = '';
    for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
    return r;
  } else if (td) {
    return td.decode(dat);
  } else {
    var _a = dutf8(dat),
      s = _a.s,
      r = _a.r;
    if (r.length) err(8);
    return s;
  }
}
;
// deflate bit flag
var dbf = function (l) {
  return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0;
};
// skip local zip header
var slzh = function (d, b) {
  return b + 30 + b2(d, b + 26) + b2(d, b + 28);
};
// read zip header
var zh = function (d, b, z) {
  var fnl = b2(d, b + 28),
    fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)),
    es = b + 46 + fnl,
    bs = b4(d, b + 20);
  var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)],
    sc = _a[0],
    su = _a[1],
    off = _a[2];
  return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
};
// read zip64 extra field
var z64e = function (d, b) {
  for (; b2(d, b) != 1; b += 4 + b2(d, b + 2));
  return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
};
// extra field length
var exfl = function (ex) {
  var le = 0;
  if (ex) {
    for (var k in ex) {
      var l = ex[k].length;
      if (l > 65535) err(9);
      le += l + 4;
    }
  }
  return le;
};
// write zip header
var wzh = function (d, b, f, fn, u, c, ce, co) {
  var fl = fn.length,
    ex = f.extra,
    col = co && co.length;
  var exl = exfl(ex);
  wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
  if (ce != null) d[b++] = 20, d[b++] = f.os;
  d[b] = 20, b += 2; // spec compliance? what's that?
  d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
  d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
  var dt = new Date(f.mtime == null ? Date.now() : f.mtime),
    y = dt.getFullYear() - 1980;
  if (y < 0 || y > 119) err(10);
  wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
  if (c != -1) {
    wbytes(d, b, f.crc);
    wbytes(d, b + 4, c < 0 ? -c - 2 : c);
    wbytes(d, b + 8, f.size);
  }
  wbytes(d, b + 12, fl);
  wbytes(d, b + 14, exl), b += 16;
  if (ce != null) {
    wbytes(d, b, col);
    wbytes(d, b + 6, f.attrs);
    wbytes(d, b + 10, ce), b += 14;
  }
  d.set(fn, b);
  b += fl;
  if (exl) {
    for (var k in ex) {
      var exf = ex[k],
        l = exf.length;
      wbytes(d, b, +k);
      wbytes(d, b + 2, l);
      d.set(exf, b + 4), b += 4 + l;
    }
  }
  if (col) d.set(co, b), b += col;
  return b;
};
// write zip footer (end of central directory)
var wzf = function (o, b, c, d, e) {
  wbytes(o, b, 0x6054B50); // skip disk
  wbytes(o, b + 8, c);
  wbytes(o, b + 10, c);
  wbytes(o, b + 12, d);
  wbytes(o, b + 16, e);
};
/**
 * A pass-through stream to keep data uncompressed in a ZIP archive.
 */
var ZipPassThrough = /*#__PURE__*/function () {
  /**
   * Creates a pass-through stream that can be added to ZIP archives
   * @param filename The filename to associate with this data stream
   */
  function ZipPassThrough(filename) {
    this.filename = filename;
    this.c = crc();
    this.size = 0;
    this.compression = 0;
  }
  /**
   * Processes a chunk and pushes to the output stream. You can override this
   * method in a subclass for custom behavior, but by default this passes
   * the data through. You must call this.ondata(err, chunk, final) at some
   * point in this method.
   * @param chunk The chunk to process
   * @param final Whether this is the last chunk
   */
  ZipPassThrough.prototype.process = function (chunk, final) {
    this.ondata(null, chunk, final);
  };
  /**
   * Pushes a chunk to be added. If you are subclassing this with a custom
   * compression algorithm, note that you must push data from the source
   * file only, pre-compression.
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  ZipPassThrough.prototype.push = function (chunk, final) {
    if (!this.ondata) err(5);
    this.c.p(chunk);
    this.size += chunk.length;
    if (final) this.crc = this.c.d();
    this.process(chunk, final || false);
  };
  return ZipPassThrough;
}();

// I don't extend because TypeScript extension adds 1kB of runtime bloat
/**
 * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
 * for better performance
 */
var ZipDeflate = /*#__PURE__*/function () {
  /**
   * Creates a DEFLATE stream that can be added to ZIP archives
   * @param filename The filename to associate with this data stream
   * @param opts The compression options
   */
  function ZipDeflate(filename, opts) {
    var _this = this;
    if (!opts) opts = {};
    ZipPassThrough.call(this, filename);
    this.d = new Deflate(opts, function (dat, final) {
      _this.ondata(null, dat, final);
    });
    this.compression = 8;
    this.flag = dbf(opts.level);
  }
  ZipDeflate.prototype.process = function (chunk, final) {
    try {
      this.d.push(chunk, final);
    } catch (e) {
      this.ondata(e, null, final);
    }
  };
  /**
   * Pushes a chunk to be deflated
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  ZipDeflate.prototype.push = function (chunk, final) {
    ZipPassThrough.prototype.push.call(this, chunk, final);
  };
  return ZipDeflate;
}();

/**
 * Asynchronous streaming DEFLATE compression for ZIP archives
 */
var AsyncZipDeflate = /*#__PURE__*/function () {
  /**
   * Creates an asynchronous DEFLATE stream that can be added to ZIP archives
   * @param filename The filename to associate with this data stream
   * @param opts The compression options
   */
  function AsyncZipDeflate(filename, opts) {
    var _this = this;
    if (!opts) opts = {};
    ZipPassThrough.call(this, filename);
    this.d = new AsyncDeflate(opts, function (err, dat, final) {
      _this.ondata(err, dat, final);
    });
    this.compression = 8;
    this.flag = dbf(opts.level);
    this.terminate = this.d.terminate;
  }
  AsyncZipDeflate.prototype.process = function (chunk, final) {
    this.d.push(chunk, final);
  };
  /**
   * Pushes a chunk to be deflated
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  AsyncZipDeflate.prototype.push = function (chunk, final) {
    ZipPassThrough.prototype.push.call(this, chunk, final);
  };
  return AsyncZipDeflate;
}();

// TODO: Better tree shaking
/**
 * A zippable archive to which files can incrementally be added
 */
var Zip = /*#__PURE__*/function () {
  /**
   * Creates an empty ZIP archive to which files can be added
   * @param cb The callback to call whenever data for the generated ZIP archive
   *           is available
   */
  function Zip(cb) {
    this.ondata = cb;
    this.u = [];
    this.d = 1;
  }
  /**
   * Adds a file to the ZIP archive
   * @param file The file stream to add
   */
  Zip.prototype.add = function (file) {
    var _this = this;
    if (!this.ondata) err(5);
    // finishing or finished
    if (this.d & 2) this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);else {
      var f = strToU8(file.filename),
        fl_1 = f.length;
      var com = file.comment,
        o = com && strToU8(com);
      var u = fl_1 != file.filename.length || o && com.length != o.length;
      var hl_1 = fl_1 + exfl(file.extra) + 30;
      if (fl_1 > 65535) this.ondata(err(11, 0, 1), null, false);
      var header = new u8(hl_1);
      wzh(header, 0, file, f, u, -1);
      var chks_1 = [header];
      var pAll_1 = function () {
        for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
          var chk = chks_2[_i];
          _this.ondata(null, chk, false);
        }
        chks_1 = [];
      };
      var tr_1 = this.d;
      this.d = 0;
      var ind_1 = this.u.length;
      var uf_1 = mrg(file, {
        f: f,
        u: u,
        o: o,
        t: function () {
          if (file.terminate) file.terminate();
        },
        r: function () {
          pAll_1();
          if (tr_1) {
            var nxt = _this.u[ind_1 + 1];
            if (nxt) nxt.r();else _this.d = 1;
          }
          tr_1 = 1;
        }
      });
      var cl_1 = 0;
      file.ondata = function (err, dat, final) {
        if (err) {
          _this.ondata(err, dat, final);
          _this.terminate();
        } else {
          cl_1 += dat.length;
          chks_1.push(dat);
          if (final) {
            var dd = new u8(16);
            wbytes(dd, 0, 0x8074B50);
            wbytes(dd, 4, file.crc);
            wbytes(dd, 8, cl_1);
            wbytes(dd, 12, file.size);
            chks_1.push(dd);
            uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
            if (tr_1) uf_1.r();
            tr_1 = 1;
          } else if (tr_1) pAll_1();
        }
      };
      this.u.push(uf_1);
    }
  };
  /**
   * Ends the process of adding files and prepares to emit the final chunks.
   * This *must* be called after adding all desired files for the resulting
   * ZIP file to work properly.
   */
  Zip.prototype.end = function () {
    var _this = this;
    if (this.d & 2) {
      this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
      return;
    }
    if (this.d) this.e();else this.u.push({
      r: function () {
        if (!(_this.d & 1)) return;
        _this.u.splice(-1, 1);
        _this.e();
      },
      t: function () {}
    });
    this.d = 3;
  };
  Zip.prototype.e = function () {
    var bt = 0,
      l = 0,
      tl = 0;
    for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
      var f = _a[_i];
      tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
    }
    var out = new u8(tl + 22);
    for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
      var f = _c[_b];
      wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
      bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
    }
    wzf(out, bt, this.u.length, tl, l);
    this.ondata(null, out, true);
    this.d = 2;
  };
  /**
   * A method to terminate any internal workers used by the stream. Subsequent
   * calls to add() will fail.
   */
  Zip.prototype.terminate = function () {
    for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
      var f = _a[_i];
      f.t();
    }
    this.d = 2;
  };
  return Zip;
}();

function zip(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  var r = {};
  fltn(data, '', r, opts);
  var k = Object.keys(r);
  var lft = k.length,
    o = 0,
    tot = 0;
  var slft = lft,
    files = new Array(lft);
  var term = [];
  var tAll = function () {
    for (var i = 0; i < term.length; ++i) term[i]();
  };
  var cbd = function (a, b) {
    mt(function () {
      cb(a, b);
    });
  };
  mt(function () {
    cbd = cb;
  });
  var cbf = function () {
    var out = new u8(tot + 22),
      oe = o,
      cdl = tot - o;
    tot = 0;
    for (var i = 0; i < slft; ++i) {
      var f = files[i];
      try {
        var l = f.c.length;
        wzh(out, tot, f, f.f, f.u, l);
        var badd = 30 + f.f.length + exfl(f.extra);
        var loc = tot + badd;
        out.set(f.c, loc);
        wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
      } catch (e) {
        return cbd(e, null);
      }
    }
    wzf(out, o, files.length, cdl, oe);
    cbd(null, out);
  };
  if (!lft) cbf();
  var _loop_1 = function (i) {
    var fn = k[i];
    var _a = r[fn],
      file = _a[0],
      p = _a[1];
    var c = crc(),
      size = file.length;
    c.p(file);
    var f = strToU8(fn),
      s = f.length;
    var com = p.comment,
      m = com && strToU8(com),
      ms = m && m.length;
    var exl = exfl(p.extra);
    var compression = p.level == 0 ? 0 : 8;
    var cbl = function (e, d) {
      if (e) {
        tAll();
        cbd(e, null);
      } else {
        var l = d.length;
        files[i] = mrg(p, {
          size: size,
          crc: c.d(),
          c: d,
          f: f,
          m: m,
          u: s != fn.length || m && com.length != ms,
          compression: compression
        });
        o += 30 + s + exl + l;
        tot += 76 + 2 * (s + exl) + (ms || 0) + l;
        if (! --lft) cbf();
      }
    };
    if (s > 65535) cbl(err(11, 0, 1), null);
    if (!compression) cbl(null, file);else if (size < 160000) {
      try {
        cbl(null, deflateSync(file, p));
      } catch (e) {
        cbl(e, null);
      }
    } else term.push(deflate(file, p, cbl));
  };
  // Cannot use lft because it can decrease
  for (var i = 0; i < slft; ++i) {
    _loop_1(i);
  }
  return tAll;
}
/**
 * Synchronously creates a ZIP file. Prefer using `zip` for better performance
 * with more than one file.
 * @param data The directory structure for the ZIP archive
 * @param opts The main options, merged with per-file options
 * @returns The generated ZIP archive
 */
function zipSync(data, opts) {
  if (!opts) opts = {};
  var r = {};
  var files = [];
  fltn(data, '', r, opts);
  var o = 0;
  var tot = 0;
  for (var fn in r) {
    var _a = r[fn],
      file = _a[0],
      p = _a[1];
    var compression = p.level == 0 ? 0 : 8;
    var f = strToU8(fn),
      s = f.length;
    var com = p.comment,
      m = com && strToU8(com),
      ms = m && m.length;
    var exl = exfl(p.extra);
    if (s > 65535) err(11);
    var d = compression ? deflateSync(file, p) : file,
      l = d.length;
    var c = crc();
    c.p(file);
    files.push(mrg(p, {
      size: file.length,
      crc: c.d(),
      c: d,
      f: f,
      m: m,
      u: s != fn.length || m && com.length != ms,
      o: o,
      compression: compression
    }));
    o += 30 + s + exl + l;
    tot += 76 + 2 * (s + exl) + (ms || 0) + l;
  }
  var out = new u8(tot + 22),
    oe = o,
    cdl = tot - o;
  for (var i = 0; i < files.length; ++i) {
    var f = files[i];
    wzh(out, f.o, f, f.f, f.u, f.c.length);
    var badd = 30 + f.f.length + exfl(f.extra);
    out.set(f.c, f.o + badd);
    wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
  }
  wzf(out, o, files.length, cdl, oe);
  return out;
}
/**
 * Streaming pass-through decompression for ZIP archives
 */
var UnzipPassThrough = /*#__PURE__*/function () {
  function UnzipPassThrough() {}
  UnzipPassThrough.prototype.push = function (data, final) {
    this.ondata(null, data, final);
  };
  UnzipPassThrough.compression = 0;
  return UnzipPassThrough;
}();

/**
 * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
 * better performance.
 */
var UnzipInflate = /*#__PURE__*/function () {
  /**
   * Creates a DEFLATE decompression that can be used in ZIP archives
   */
  function UnzipInflate() {
    var _this = this;
    this.i = new Inflate(function (dat, final) {
      _this.ondata(null, dat, final);
    });
  }
  UnzipInflate.prototype.push = function (data, final) {
    try {
      this.i.push(data, final);
    } catch (e) {
      this.ondata(e, null, final);
    }
  };
  UnzipInflate.compression = 8;
  return UnzipInflate;
}();

/**
 * Asynchronous streaming DEFLATE decompression for ZIP archives
 */
var AsyncUnzipInflate = /*#__PURE__*/function () {
  /**
   * Creates a DEFLATE decompression that can be used in ZIP archives
   */
  function AsyncUnzipInflate(_, sz) {
    var _this = this;
    if (sz < 320000) {
      this.i = new Inflate(function (dat, final) {
        _this.ondata(null, dat, final);
      });
    } else {
      this.i = new AsyncInflate(function (err, dat, final) {
        _this.ondata(err, dat, final);
      });
      this.terminate = this.i.terminate;
    }
  }
  AsyncUnzipInflate.prototype.push = function (data, final) {
    if (this.i.terminate) data = slc(data, 0);
    this.i.push(data, final);
  };
  AsyncUnzipInflate.compression = 8;
  return AsyncUnzipInflate;
}();

/**
 * A ZIP archive decompression stream that emits files as they are discovered
 */
var Unzip = /*#__PURE__*/function () {
  /**
   * Creates a ZIP decompression stream
   * @param cb The callback to call whenever a file in the ZIP archive is found
   */
  function Unzip(cb) {
    this.onfile = cb;
    this.k = [];
    this.o = {
      0: UnzipPassThrough
    };
    this.p = et;
  }
  /**
   * Pushes a chunk to be unzipped
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Unzip.prototype.push = function (chunk, final) {
    var _this = this;
    if (!this.onfile) err(5);
    if (!this.p) err(4);
    if (this.c > 0) {
      var len = Math.min(this.c, chunk.length);
      var toAdd = chunk.subarray(0, len);
      this.c -= len;
      if (this.d) this.d.push(toAdd, !this.c);else this.k[0].push(toAdd);
      chunk = chunk.subarray(len);
      if (chunk.length) return this.push(chunk, final);
    } else {
      var f = 0,
        i = 0,
        is = void 0,
        buf = void 0;
      if (!this.p.length) buf = chunk;else if (!chunk.length) buf = this.p;else {
        buf = new u8(this.p.length + chunk.length);
        buf.set(this.p), buf.set(chunk, this.p.length);
      }
      var l = buf.length,
        oc = this.c,
        add = oc && this.d;
      var _loop_2 = function () {
        var _a;
        var sig = b4(buf, i);
        if (sig == 0x4034B50) {
          f = 1, is = i;
          this_1.d = null;
          this_1.c = 0;
          var bf = b2(buf, i + 6),
            cmp_1 = b2(buf, i + 8),
            u = bf & 2048,
            dd = bf & 8,
            fnl = b2(buf, i + 26),
            es = b2(buf, i + 28);
          if (l > i + 30 + fnl + es) {
            var chks_3 = [];
            this_1.k.unshift(chks_3);
            f = 2;
            var sc_1 = b4(buf, i + 18),
              su_1 = b4(buf, i + 22);
            var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
            if (sc_1 == 4294967295) {
              _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
            } else if (dd) sc_1 = -1;
            i += es;
            this_1.c = sc_1;
            var d_1;
            var file_1 = {
              name: fn_1,
              compression: cmp_1,
              start: function () {
                if (!file_1.ondata) err(5);
                if (!sc_1) file_1.ondata(null, et, true);else {
                  var ctr = _this.o[cmp_1];
                  if (!ctr) file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);
                  d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
                  d_1.ondata = function (err, dat, final) {
                    file_1.ondata(err, dat, final);
                  };
                  for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
                    var dat = chks_4[_i];
                    d_1.push(dat, false);
                  }
                  if (_this.k[0] == chks_3 && _this.c) _this.d = d_1;else d_1.push(et, true);
                }
              },
              terminate: function () {
                if (d_1 && d_1.terminate) d_1.terminate();
              }
            };
            if (sc_1 >= 0) file_1.size = sc_1, file_1.originalSize = su_1;
            this_1.onfile(file_1);
          }
          return "break";
        } else if (oc) {
          if (sig == 0x8074B50) {
            is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
            return "break";
          } else if (sig == 0x2014B50) {
            is = i -= 4, f = 3, this_1.c = 0;
            return "break";
          }
        }
      };
      var this_1 = this;
      for (; i < l - 4; ++i) {
        var state_1 = _loop_2();
        if (state_1 === "break") break;
      }
      this.p = et;
      if (oc < 0) {
        var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
        if (add) add.push(dat, !!f);else this.k[+(f == 2)].push(dat);
      }
      if (f & 2) return this.push(buf.subarray(i), final);
      this.p = buf.subarray(i);
    }
    if (final) {
      if (this.c) err(13);
      this.p = null;
    }
  };
  /**
   * Registers a decoder with the stream, allowing for files compressed with
   * the compression type provided to be expanded correctly
   * @param decoder The decoder constructor
   */
  Unzip.prototype.register = function (decoder) {
    this.o[decoder.compression] = decoder;
  };
  return Unzip;
}();

var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) {
  fn();
};
function unzip(data, opts, cb) {
  if (!cb) cb = opts, opts = {};
  if (typeof cb != 'function') err(7);
  var term = [];
  var tAll = function () {
    for (var i = 0; i < term.length; ++i) term[i]();
  };
  var files = {};
  var cbd = function (a, b) {
    mt(function () {
      cb(a, b);
    });
  };
  mt(function () {
    cbd = cb;
  });
  var e = data.length - 22;
  for (; b4(data, e) != 0x6054B50; --e) {
    if (!e || data.length - e > 65558) {
      cbd(err(13, 0, 1), null);
      return tAll;
    }
  }
  ;
  var lft = b2(data, e + 8);
  if (lft) {
    var c = lft;
    var o = b4(data, e + 16);
    var z = o == 4294967295 || c == 65535;
    if (z) {
      var ze = b4(data, e - 12);
      z = b4(data, ze) == 0x6064B50;
      if (z) {
        c = lft = b4(data, ze + 32);
        o = b4(data, ze + 48);
      }
    }
    var fltr = opts && opts.filter;
    var _loop_3 = function (i) {
      var _a = zh(data, o, z),
        c_1 = _a[0],
        sc = _a[1],
        su = _a[2],
        fn = _a[3],
        no = _a[4],
        off = _a[5],
        b = slzh(data, off);
      o = no;
      var cbl = function (e, d) {
        if (e) {
          tAll();
          cbd(e, null);
        } else {
          if (d) files[fn] = d;
          if (! --lft) cbd(null, files);
        }
      };
      if (!fltr || fltr({
        name: fn,
        size: sc,
        originalSize: su,
        compression: c_1
      })) {
        if (!c_1) cbl(null, slc(data, b, b + sc));else if (c_1 == 8) {
          var infl = data.subarray(b, b + sc);
          // Synchronously decompress under 512KB, or barely-compressed data
          if (su < 524288 || sc > 0.8 * su) {
            try {
              cbl(null, inflateSync(infl, {
                out: new u8(su)
              }));
            } catch (e) {
              cbl(e, null);
            }
          } else term.push(inflate(infl, {
            size: su
          }, cbl));
        } else cbl(err(14, 'unknown compression type ' + c_1, 1), null);
      } else cbl(null, null);
    };
    for (var i = 0; i < c; ++i) {
      _loop_3(i);
    }
  } else cbd(null, {});
  return tAll;
}
/**
 * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
 * performance with more than one file.
 * @param data The raw compressed ZIP file
 * @param opts The ZIP extraction options
 * @returns The decompressed files
 */
function unzipSync(data, opts) {
  var files = {};
  var e = data.length - 22;
  for (; b4(data, e) != 0x6054B50; --e) {
    if (!e || data.length - e > 65558) err(13);
  }
  ;
  var c = b2(data, e + 8);
  if (!c) return {};
  var o = b4(data, e + 16);
  var z = o == 4294967295 || c == 65535;
  if (z) {
    var ze = b4(data, e - 12);
    z = b4(data, ze) == 0x6064B50;
    if (z) {
      c = b4(data, ze + 32);
      o = b4(data, ze + 48);
    }
  }
  var fltr = opts && opts.filter;
  for (var i = 0; i < c; ++i) {
    var _a = zh(data, o, z),
      c_2 = _a[0],
      sc = _a[1],
      su = _a[2],
      fn = _a[3],
      no = _a[4],
      off = _a[5],
      b = slzh(data, off);
    o = no;
    if (!fltr || fltr({
      name: fn,
      size: sc,
      originalSize: su,
      compression: c_2
    })) {
      if (!c_2) files[fn] = slc(data, b, b + sc);else if (c_2 == 8) files[fn] = inflateSync(data.subarray(b, b + sc), {
        out: new u8(su)
      });else err(14, 'unknown compression type ' + c_2);
    }
  }
  return files;
}

/***/ }),

/***/ 928:
/*!*************************************************************************************!*\
  !*** ./node_modules/.pnpm/jsrsasign@11.1.0/node_modules/jsrsasign/lib/jsrsasign.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

var navigator = {};
navigator.userAgent = false;
var window = {};
/*
 * jsrsasign(all) 11.1.0 (2024-02-01) (c) 2010-2023 Kenji Urushima | kjur.github.io/jsrsasign/license
 */
var VERSION = "11.1.0";
var VERSION_FULL = "jsrsasign(all) 11.1.0 (2024-02-01) (c) 2010-2023 Kenji Urushima | kjur.github.io/jsrsasign/license";

/*! CryptoJS v3.1.2 core-fix.js
 * code.google.com/p/crypto-js
 * (c) 2009-2013 by Jeff Mott. All rights reserved.
 * code.google.com/p/crypto-js/wiki/License
 * THIS IS FIX of 'core.js' to fix Hmac issue.
 * https://code.google.com/p/crypto-js/issues/detail?id=84
 * https://crypto-js.googlecode.com/svn-history/r667/branches/3.x/src/core.js
 */
var CryptoJS = CryptoJS || function (e, g) {
  var a = {};
  var b = a.lib = {};
  var j = b.Base = function () {
    function n() {}
    return {
      extend: function (p) {
        n.prototype = this;
        var o = new n();
        if (p) {
          o.mixIn(p);
        }
        if (!o.hasOwnProperty("init")) {
          o.init = function () {
            o.$super.init.apply(this, arguments);
          };
        }
        o.init.prototype = o;
        o.$super = this;
        return o;
      },
      create: function () {
        var o = this.extend();
        o.init.apply(o, arguments);
        return o;
      },
      init: function () {},
      mixIn: function (p) {
        for (var o in p) {
          if (p.hasOwnProperty(o)) {
            this[o] = p[o];
          }
        }
        if (p.hasOwnProperty("toString")) {
          this.toString = p.toString;
        }
      },
      clone: function () {
        return this.init.prototype.extend(this);
      }
    };
  }();
  var l = b.WordArray = j.extend({
    init: function (o, n) {
      o = this.words = o || [];
      if (n != g) {
        this.sigBytes = n;
      } else {
        this.sigBytes = o.length * 4;
      }
    },
    toString: function (n) {
      return (n || h).stringify(this);
    },
    concat: function (t) {
      var q = this.words;
      var p = t.words;
      var n = this.sigBytes;
      var s = t.sigBytes;
      this.clamp();
      if (n % 4) {
        for (var r = 0; r < s; r++) {
          var o = p[r >>> 2] >>> 24 - r % 4 * 8 & 255;
          q[n + r >>> 2] |= o << 24 - (n + r) % 4 * 8;
        }
      } else {
        for (var r = 0; r < s; r += 4) {
          q[n + r >>> 2] = p[r >>> 2];
        }
      }
      this.sigBytes += s;
      return this;
    },
    clamp: function () {
      var o = this.words;
      var n = this.sigBytes;
      o[n >>> 2] &= 4294967295 << 32 - n % 4 * 8;
      o.length = e.ceil(n / 4);
    },
    clone: function () {
      var n = j.clone.call(this);
      n.words = this.words.slice(0);
      return n;
    },
    random: function (p) {
      var o = [];
      for (var n = 0; n < p; n += 4) {
        o.push(e.random() * 4294967296 | 0);
      }
      return new l.init(o, p);
    }
  });
  var m = a.enc = {};
  var h = m.Hex = {
    stringify: function (p) {
      var r = p.words;
      var o = p.sigBytes;
      var q = [];
      for (var n = 0; n < o; n++) {
        var s = r[n >>> 2] >>> 24 - n % 4 * 8 & 255;
        q.push((s >>> 4).toString(16));
        q.push((s & 15).toString(16));
      }
      return q.join("");
    },
    parse: function (p) {
      var n = p.length;
      var q = [];
      for (var o = 0; o < n; o += 2) {
        q[o >>> 3] |= parseInt(p.substr(o, 2), 16) << 24 - o % 8 * 4;
      }
      return new l.init(q, n / 2);
    }
  };
  var d = m.Latin1 = {
    stringify: function (q) {
      var r = q.words;
      var p = q.sigBytes;
      var n = [];
      for (var o = 0; o < p; o++) {
        var s = r[o >>> 2] >>> 24 - o % 4 * 8 & 255;
        n.push(String.fromCharCode(s));
      }
      return n.join("");
    },
    parse: function (p) {
      var n = p.length;
      var q = [];
      for (var o = 0; o < n; o++) {
        q[o >>> 2] |= (p.charCodeAt(o) & 255) << 24 - o % 4 * 8;
      }
      return new l.init(q, n);
    }
  };
  var c = m.Utf8 = {
    stringify: function (n) {
      try {
        return decodeURIComponent(escape(d.stringify(n)));
      } catch (o) {
        throw new Error("Malformed UTF-8 data");
      }
    },
    parse: function (n) {
      return d.parse(unescape(encodeURIComponent(n)));
    }
  };
  var i = b.BufferedBlockAlgorithm = j.extend({
    reset: function () {
      this._data = new l.init();
      this._nDataBytes = 0;
    },
    _append: function (n) {
      if (typeof n == "string") {
        n = c.parse(n);
      }
      this._data.concat(n);
      this._nDataBytes += n.sigBytes;
    },
    _process: function (w) {
      var q = this._data;
      var x = q.words;
      var n = q.sigBytes;
      var t = this.blockSize;
      var v = t * 4;
      var u = n / v;
      if (w) {
        u = e.ceil(u);
      } else {
        u = e.max((u | 0) - this._minBufferSize, 0);
      }
      var s = u * t;
      var r = e.min(s * 4, n);
      if (s) {
        for (var p = 0; p < s; p += t) {
          this._doProcessBlock(x, p);
        }
        var o = x.splice(0, s);
        q.sigBytes -= r;
      }
      return new l.init(o, r);
    },
    clone: function () {
      var n = j.clone.call(this);
      n._data = this._data.clone();
      return n;
    },
    _minBufferSize: 0
  });
  var f = b.Hasher = i.extend({
    cfg: j.extend(),
    init: function (n) {
      this.cfg = this.cfg.extend(n);
      this.reset();
    },
    reset: function () {
      i.reset.call(this);
      this._doReset();
    },
    update: function (n) {
      this._append(n);
      this._process();
      return this;
    },
    finalize: function (n) {
      if (n) {
        this._append(n);
      }
      var o = this._doFinalize();
      return o;
    },
    blockSize: 512 / 32,
    _createHelper: function (n) {
      return function (p, o) {
        return new n.init(o).finalize(p);
      };
    },
    _createHmacHelper: function (n) {
      return function (p, o) {
        return new k.HMAC.init(n, o).finalize(p);
      };
    }
  });
  var k = a.algo = {};
  return a;
}(Math);
/*
CryptoJS v3.1.2 x64-core-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function (g) {
  var a = CryptoJS,
    f = a.lib,
    e = f.Base,
    h = f.WordArray,
    a = a.x64 = {};
  a.Word = e.extend({
    init: function (b, c) {
      this.high = b;
      this.low = c;
    }
  });
  a.WordArray = e.extend({
    init: function (b, c) {
      b = this.words = b || [];
      this.sigBytes = c != g ? c : 8 * b.length;
    },
    toX32: function () {
      for (var b = this.words, c = b.length, a = [], d = 0; d < c; d++) {
        var e = b[d];
        a.push(e.high);
        a.push(e.low);
      }
      return h.create(a, this.sigBytes);
    },
    clone: function () {
      for (var b = e.clone.call(this), c = b.words = this.words.slice(0), a = c.length, d = 0; d < a; d++) c[d] = c[d].clone();
      return b;
    }
  });
})();

/*
CryptoJS v3.1.2 cipher-core.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
CryptoJS.lib.Cipher || function (u) {
  var g = CryptoJS,
    f = g.lib,
    k = f.Base,
    l = f.WordArray,
    q = f.BufferedBlockAlgorithm,
    r = g.enc.Base64,
    v = g.algo.EvpKDF,
    n = f.Cipher = q.extend({
      cfg: k.extend(),
      createEncryptor: function (a, b) {
        return this.create(this._ENC_XFORM_MODE, a, b);
      },
      createDecryptor: function (a, b) {
        return this.create(this._DEC_XFORM_MODE, a, b);
      },
      init: function (a, b, c) {
        this.cfg = this.cfg.extend(c);
        this._xformMode = a;
        this._key = b;
        this.reset();
      },
      reset: function () {
        q.reset.call(this);
        this._doReset();
      },
      process: function (a) {
        this._append(a);
        return this._process();
      },
      finalize: function (a) {
        a && this._append(a);
        return this._doFinalize();
      },
      keySize: 4,
      ivSize: 4,
      _ENC_XFORM_MODE: 1,
      _DEC_XFORM_MODE: 2,
      _createHelper: function (a) {
        return {
          encrypt: function (b, c, d) {
            return ("string" == typeof c ? s : j).encrypt(a, b, c, d);
          },
          decrypt: function (b, c, d) {
            return ("string" == typeof c ? s : j).decrypt(a, b, c, d);
          }
        };
      }
    });
  f.StreamCipher = n.extend({
    _doFinalize: function () {
      return this._process(!0);
    },
    blockSize: 1
  });
  var m = g.mode = {},
    t = function (a, b, c) {
      var d = this._iv;
      d ? this._iv = u : d = this._prevBlock;
      for (var e = 0; e < c; e++) a[b + e] ^= d[e];
    },
    h = (f.BlockCipherMode = k.extend({
      createEncryptor: function (a, b) {
        return this.Encryptor.create(a, b);
      },
      createDecryptor: function (a, b) {
        return this.Decryptor.create(a, b);
      },
      init: function (a, b) {
        this._cipher = a;
        this._iv = b;
      }
    })).extend();
  h.Encryptor = h.extend({
    processBlock: function (a, b) {
      var c = this._cipher,
        d = c.blockSize;
      t.call(this, a, b, d);
      c.encryptBlock(a, b);
      this._prevBlock = a.slice(b, b + d);
    }
  });
  h.Decryptor = h.extend({
    processBlock: function (a, b) {
      var c = this._cipher,
        d = c.blockSize,
        e = a.slice(b, b + d);
      c.decryptBlock(a, b);
      t.call(this, a, b, d);
      this._prevBlock = e;
    }
  });
  m = m.CBC = h;
  h = (g.pad = {}).Pkcs7 = {
    pad: function (a, b) {
      for (var c = 4 * b, c = c - a.sigBytes % c, d = c << 24 | c << 16 | c << 8 | c, e = [], f = 0; f < c; f += 4) e.push(d);
      c = l.create(e, c);
      a.concat(c);
    },
    unpad: function (a) {
      a.sigBytes -= a.words[a.sigBytes - 1 >>> 2] & 255;
    }
  };
  f.BlockCipher = n.extend({
    cfg: n.cfg.extend({
      mode: m,
      padding: h
    }),
    reset: function () {
      n.reset.call(this);
      var a = this.cfg,
        b = a.iv,
        a = a.mode;
      if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor;else c = a.createDecryptor, this._minBufferSize = 1;
      this._mode = c.call(a, this, b && b.words);
    },
    _doProcessBlock: function (a, b) {
      this._mode.processBlock(a, b);
    },
    _doFinalize: function () {
      var a = this.cfg.padding;
      if (this._xformMode == this._ENC_XFORM_MODE) {
        a.pad(this._data, this.blockSize);
        var b = this._process(!0);
      } else b = this._process(!0), a.unpad(b);
      return b;
    },
    blockSize: 4
  });
  var p = f.CipherParams = k.extend({
      init: function (a) {
        this.mixIn(a);
      },
      toString: function (a) {
        return (a || this.formatter).stringify(this);
      }
    }),
    m = (g.format = {}).OpenSSL = {
      stringify: function (a) {
        var b = a.ciphertext;
        a = a.salt;
        return (a ? l.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r);
      },
      parse: function (a) {
        a = r.parse(a);
        var b = a.words;
        if (1398893684 == b[0] && 1701076831 == b[1]) {
          var c = l.create(b.slice(2, 4));
          b.splice(0, 4);
          a.sigBytes -= 16;
        }
        return p.create({
          ciphertext: a,
          salt: c
        });
      }
    },
    j = f.SerializableCipher = k.extend({
      cfg: k.extend({
        format: m
      }),
      encrypt: function (a, b, c, d) {
        d = this.cfg.extend(d);
        var e = a.createEncryptor(c, d);
        b = e.finalize(b);
        e = e.cfg;
        return p.create({
          ciphertext: b,
          key: c,
          iv: e.iv,
          algorithm: a,
          mode: e.mode,
          padding: e.padding,
          blockSize: a.blockSize,
          formatter: d.format
        });
      },
      decrypt: function (a, b, c, d) {
        d = this.cfg.extend(d);
        b = this._parse(b, d.format);
        return a.createDecryptor(c, d).finalize(b.ciphertext);
      },
      _parse: function (a, b) {
        return "string" == typeof a ? b.parse(a, this) : a;
      }
    }),
    g = (g.kdf = {}).OpenSSL = {
      execute: function (a, b, c, d) {
        d || (d = l.random(8));
        a = v.create({
          keySize: b + c
        }).compute(a, d);
        c = l.create(a.words.slice(b), 4 * c);
        a.sigBytes = 4 * b;
        return p.create({
          key: a,
          iv: c,
          salt: d
        });
      }
    },
    s = f.PasswordBasedCipher = j.extend({
      cfg: j.cfg.extend({
        kdf: g
      }),
      encrypt: function (a, b, c, d) {
        d = this.cfg.extend(d);
        c = d.kdf.execute(c, a.keySize, a.ivSize);
        d.iv = c.iv;
        a = j.encrypt.call(this, a, b, c.key, d);
        a.mixIn(c);
        return a;
      },
      decrypt: function (a, b, c, d) {
        d = this.cfg.extend(d);
        b = this._parse(b, d.format);
        c = d.kdf.execute(c, a.keySize, a.ivSize, b.salt);
        d.iv = c.iv;
        return j.decrypt.call(this, a, b, c.key, d);
      }
    });
}();

/*
CryptoJS v3.1.2 aes.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  for (var q = CryptoJS, x = q.lib.BlockCipher, r = q.algo, j = [], y = [], z = [], A = [], B = [], C = [], s = [], u = [], v = [], w = [], g = [], k = 0; 256 > k; k++) g[k] = 128 > k ? k << 1 : k << 1 ^ 283;
  for (var n = 0, l = 0, k = 0; 256 > k; k++) {
    var f = l ^ l << 1 ^ l << 2 ^ l << 3 ^ l << 4,
      f = f >>> 8 ^ f & 255 ^ 99;
    j[n] = f;
    y[f] = n;
    var t = g[n],
      D = g[t],
      E = g[D],
      b = 257 * g[f] ^ 16843008 * f;
    z[n] = b << 24 | b >>> 8;
    A[n] = b << 16 | b >>> 16;
    B[n] = b << 8 | b >>> 24;
    C[n] = b;
    b = 16843009 * E ^ 65537 * D ^ 257 * t ^ 16843008 * n;
    s[f] = b << 24 | b >>> 8;
    u[f] = b << 16 | b >>> 16;
    v[f] = b << 8 | b >>> 24;
    w[f] = b;
    n ? (n = t ^ g[g[g[E ^ t]]], l ^= g[g[l]]) : n = l = 1;
  }
  var F = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54],
    r = r.AES = x.extend({
      _doReset: function () {
        for (var c = this._key, e = c.words, a = c.sigBytes / 4, c = 4 * ((this._nRounds = a + 6) + 1), b = this._keySchedule = [], h = 0; h < c; h++) if (h < a) b[h] = e[h];else {
          var d = b[h - 1];
          h % a ? 6 < a && 4 == h % a && (d = j[d >>> 24] << 24 | j[d >>> 16 & 255] << 16 | j[d >>> 8 & 255] << 8 | j[d & 255]) : (d = d << 8 | d >>> 24, d = j[d >>> 24] << 24 | j[d >>> 16 & 255] << 16 | j[d >>> 8 & 255] << 8 | j[d & 255], d ^= F[h / a | 0] << 24);
          b[h] = b[h - a] ^ d;
        }
        e = this._invKeySchedule = [];
        for (a = 0; a < c; a++) h = c - a, d = a % 4 ? b[h] : b[h - 4], e[a] = 4 > a || 4 >= h ? d : s[j[d >>> 24]] ^ u[j[d >>> 16 & 255]] ^ v[j[d >>> 8 & 255]] ^ w[j[d & 255]];
      },
      encryptBlock: function (c, e) {
        this._doCryptBlock(c, e, this._keySchedule, z, A, B, C, j);
      },
      decryptBlock: function (c, e) {
        var a = c[e + 1];
        c[e + 1] = c[e + 3];
        c[e + 3] = a;
        this._doCryptBlock(c, e, this._invKeySchedule, s, u, v, w, y);
        a = c[e + 1];
        c[e + 1] = c[e + 3];
        c[e + 3] = a;
      },
      _doCryptBlock: function (c, e, a, b, h, d, j, m) {
        for (var n = this._nRounds, f = c[e] ^ a[0], g = c[e + 1] ^ a[1], k = c[e + 2] ^ a[2], p = c[e + 3] ^ a[3], l = 4, t = 1; t < n; t++) var q = b[f >>> 24] ^ h[g >>> 16 & 255] ^ d[k >>> 8 & 255] ^ j[p & 255] ^ a[l++], r = b[g >>> 24] ^ h[k >>> 16 & 255] ^ d[p >>> 8 & 255] ^ j[f & 255] ^ a[l++], s = b[k >>> 24] ^ h[p >>> 16 & 255] ^ d[f >>> 8 & 255] ^ j[g & 255] ^ a[l++], p = b[p >>> 24] ^ h[f >>> 16 & 255] ^ d[g >>> 8 & 255] ^ j[k & 255] ^ a[l++], f = q, g = r, k = s;
        q = (m[f >>> 24] << 24 | m[g >>> 16 & 255] << 16 | m[k >>> 8 & 255] << 8 | m[p & 255]) ^ a[l++];
        r = (m[g >>> 24] << 24 | m[k >>> 16 & 255] << 16 | m[p >>> 8 & 255] << 8 | m[f & 255]) ^ a[l++];
        s = (m[k >>> 24] << 24 | m[p >>> 16 & 255] << 16 | m[f >>> 8 & 255] << 8 | m[g & 255]) ^ a[l++];
        p = (m[p >>> 24] << 24 | m[f >>> 16 & 255] << 16 | m[g >>> 8 & 255] << 8 | m[k & 255]) ^ a[l++];
        c[e] = q;
        c[e + 1] = r;
        c[e + 2] = s;
        c[e + 3] = p;
      },
      keySize: 8
    });
  q.AES = x._createHelper(r);
})();

/*
CryptoJS v3.1.2 tripledes-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  function j(b, c) {
    var a = (this._lBlock >>> b ^ this._rBlock) & c;
    this._rBlock ^= a;
    this._lBlock ^= a << b;
  }
  function l(b, c) {
    var a = (this._rBlock >>> b ^ this._lBlock) & c;
    this._lBlock ^= a;
    this._rBlock ^= a << b;
  }
  var h = CryptoJS,
    e = h.lib,
    n = e.WordArray,
    e = e.BlockCipher,
    g = h.algo,
    q = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4],
    p = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32],
    r = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28],
    s = [{
      "0": 8421888,
      268435456: 32768,
      536870912: 8421378,
      805306368: 2,
      1073741824: 512,
      1342177280: 8421890,
      1610612736: 8389122,
      1879048192: 8388608,
      2147483648: 514,
      2415919104: 8389120,
      2684354560: 33280,
      2952790016: 8421376,
      3221225472: 32770,
      3489660928: 8388610,
      3758096384: 0,
      4026531840: 33282,
      134217728: 0,
      402653184: 8421890,
      671088640: 33282,
      939524096: 32768,
      1207959552: 8421888,
      1476395008: 512,
      1744830464: 8421378,
      2013265920: 2,
      2281701376: 8389120,
      2550136832: 33280,
      2818572288: 8421376,
      3087007744: 8389122,
      3355443200: 8388610,
      3623878656: 32770,
      3892314112: 514,
      4160749568: 8388608,
      1: 32768,
      268435457: 2,
      536870913: 8421888,
      805306369: 8388608,
      1073741825: 8421378,
      1342177281: 33280,
      1610612737: 512,
      1879048193: 8389122,
      2147483649: 8421890,
      2415919105: 8421376,
      2684354561: 8388610,
      2952790017: 33282,
      3221225473: 514,
      3489660929: 8389120,
      3758096385: 32770,
      4026531841: 0,
      134217729: 8421890,
      402653185: 8421376,
      671088641: 8388608,
      939524097: 512,
      1207959553: 32768,
      1476395009: 8388610,
      1744830465: 2,
      2013265921: 33282,
      2281701377: 32770,
      2550136833: 8389122,
      2818572289: 514,
      3087007745: 8421888,
      3355443201: 8389120,
      3623878657: 0,
      3892314113: 33280,
      4160749569: 8421378
    }, {
      "0": 1074282512,
      16777216: 16384,
      33554432: 524288,
      50331648: 1074266128,
      67108864: 1073741840,
      83886080: 1074282496,
      100663296: 1073758208,
      117440512: 16,
      134217728: 540672,
      150994944: 1073758224,
      167772160: 1073741824,
      184549376: 540688,
      201326592: 524304,
      218103808: 0,
      234881024: 16400,
      251658240: 1074266112,
      8388608: 1073758208,
      25165824: 540688,
      41943040: 16,
      58720256: 1073758224,
      75497472: 1074282512,
      92274688: 1073741824,
      109051904: 524288,
      125829120: 1074266128,
      142606336: 524304,
      159383552: 0,
      176160768: 16384,
      192937984: 1074266112,
      209715200: 1073741840,
      226492416: 540672,
      243269632: 1074282496,
      260046848: 16400,
      268435456: 0,
      285212672: 1074266128,
      301989888: 1073758224,
      318767104: 1074282496,
      335544320: 1074266112,
      352321536: 16,
      369098752: 540688,
      385875968: 16384,
      402653184: 16400,
      419430400: 524288,
      436207616: 524304,
      452984832: 1073741840,
      469762048: 540672,
      486539264: 1073758208,
      503316480: 1073741824,
      520093696: 1074282512,
      276824064: 540688,
      293601280: 524288,
      310378496: 1074266112,
      327155712: 16384,
      343932928: 1073758208,
      360710144: 1074282512,
      377487360: 16,
      394264576: 1073741824,
      411041792: 1074282496,
      427819008: 1073741840,
      444596224: 1073758224,
      461373440: 524304,
      478150656: 0,
      494927872: 16400,
      511705088: 1074266128,
      528482304: 540672
    }, {
      "0": 260,
      1048576: 0,
      2097152: 67109120,
      3145728: 65796,
      4194304: 65540,
      5242880: 67108868,
      6291456: 67174660,
      7340032: 67174400,
      8388608: 67108864,
      9437184: 67174656,
      10485760: 65792,
      11534336: 67174404,
      12582912: 67109124,
      13631488: 65536,
      14680064: 4,
      15728640: 256,
      524288: 67174656,
      1572864: 67174404,
      2621440: 0,
      3670016: 67109120,
      4718592: 67108868,
      5767168: 65536,
      6815744: 65540,
      7864320: 260,
      8912896: 4,
      9961472: 256,
      11010048: 67174400,
      12058624: 65796,
      13107200: 65792,
      14155776: 67109124,
      15204352: 67174660,
      16252928: 67108864,
      16777216: 67174656,
      17825792: 65540,
      18874368: 65536,
      19922944: 67109120,
      20971520: 256,
      22020096: 67174660,
      23068672: 67108868,
      24117248: 0,
      25165824: 67109124,
      26214400: 67108864,
      27262976: 4,
      28311552: 65792,
      29360128: 67174400,
      30408704: 260,
      31457280: 65796,
      32505856: 67174404,
      17301504: 67108864,
      18350080: 260,
      19398656: 67174656,
      20447232: 0,
      21495808: 65540,
      22544384: 67109120,
      23592960: 256,
      24641536: 67174404,
      25690112: 65536,
      26738688: 67174660,
      27787264: 65796,
      28835840: 67108868,
      29884416: 67109124,
      30932992: 67174400,
      31981568: 4,
      33030144: 65792
    }, {
      "0": 2151682048,
      65536: 2147487808,
      131072: 4198464,
      196608: 2151677952,
      262144: 0,
      327680: 4198400,
      393216: 2147483712,
      458752: 4194368,
      524288: 2147483648,
      589824: 4194304,
      655360: 64,
      720896: 2147487744,
      786432: 2151678016,
      851968: 4160,
      917504: 4096,
      983040: 2151682112,
      32768: 2147487808,
      98304: 64,
      163840: 2151678016,
      229376: 2147487744,
      294912: 4198400,
      360448: 2151682112,
      425984: 0,
      491520: 2151677952,
      557056: 4096,
      622592: 2151682048,
      688128: 4194304,
      753664: 4160,
      819200: 2147483648,
      884736: 4194368,
      950272: 4198464,
      1015808: 2147483712,
      1048576: 4194368,
      1114112: 4198400,
      1179648: 2147483712,
      1245184: 0,
      1310720: 4160,
      1376256: 2151678016,
      1441792: 2151682048,
      1507328: 2147487808,
      1572864: 2151682112,
      1638400: 2147483648,
      1703936: 2151677952,
      1769472: 4198464,
      1835008: 2147487744,
      1900544: 4194304,
      1966080: 64,
      2031616: 4096,
      1081344: 2151677952,
      1146880: 2151682112,
      1212416: 0,
      1277952: 4198400,
      1343488: 4194368,
      1409024: 2147483648,
      1474560: 2147487808,
      1540096: 64,
      1605632: 2147483712,
      1671168: 4096,
      1736704: 2147487744,
      1802240: 2151678016,
      1867776: 4160,
      1933312: 2151682048,
      1998848: 4194304,
      2064384: 4198464
    }, {
      "0": 128,
      4096: 17039360,
      8192: 262144,
      12288: 536870912,
      16384: 537133184,
      20480: 16777344,
      24576: 553648256,
      28672: 262272,
      32768: 16777216,
      36864: 537133056,
      40960: 536871040,
      45056: 553910400,
      49152: 553910272,
      53248: 0,
      57344: 17039488,
      61440: 553648128,
      2048: 17039488,
      6144: 553648256,
      10240: 128,
      14336: 17039360,
      18432: 262144,
      22528: 537133184,
      26624: 553910272,
      30720: 536870912,
      34816: 537133056,
      38912: 0,
      43008: 553910400,
      47104: 16777344,
      51200: 536871040,
      55296: 553648128,
      59392: 16777216,
      63488: 262272,
      65536: 262144,
      69632: 128,
      73728: 536870912,
      77824: 553648256,
      81920: 16777344,
      86016: 553910272,
      90112: 537133184,
      94208: 16777216,
      98304: 553910400,
      102400: 553648128,
      106496: 17039360,
      110592: 537133056,
      114688: 262272,
      118784: 536871040,
      122880: 0,
      126976: 17039488,
      67584: 553648256,
      71680: 16777216,
      75776: 17039360,
      79872: 537133184,
      83968: 536870912,
      88064: 17039488,
      92160: 128,
      96256: 553910272,
      100352: 262272,
      104448: 553910400,
      108544: 0,
      112640: 553648128,
      116736: 16777344,
      120832: 262144,
      124928: 537133056,
      129024: 536871040
    }, {
      "0": 268435464,
      256: 8192,
      512: 270532608,
      768: 270540808,
      1024: 268443648,
      1280: 2097152,
      1536: 2097160,
      1792: 268435456,
      2048: 0,
      2304: 268443656,
      2560: 2105344,
      2816: 8,
      3072: 270532616,
      3328: 2105352,
      3584: 8200,
      3840: 270540800,
      128: 270532608,
      384: 270540808,
      640: 8,
      896: 2097152,
      1152: 2105352,
      1408: 268435464,
      1664: 268443648,
      1920: 8200,
      2176: 2097160,
      2432: 8192,
      2688: 268443656,
      2944: 270532616,
      3200: 0,
      3456: 270540800,
      3712: 2105344,
      3968: 268435456,
      4096: 268443648,
      4352: 270532616,
      4608: 270540808,
      4864: 8200,
      5120: 2097152,
      5376: 268435456,
      5632: 268435464,
      5888: 2105344,
      6144: 2105352,
      6400: 0,
      6656: 8,
      6912: 270532608,
      7168: 8192,
      7424: 268443656,
      7680: 270540800,
      7936: 2097160,
      4224: 8,
      4480: 2105344,
      4736: 2097152,
      4992: 268435464,
      5248: 268443648,
      5504: 8200,
      5760: 270540808,
      6016: 270532608,
      6272: 270540800,
      6528: 270532616,
      6784: 8192,
      7040: 2105352,
      7296: 2097160,
      7552: 0,
      7808: 268435456,
      8064: 268443656
    }, {
      "0": 1048576,
      16: 33555457,
      32: 1024,
      48: 1049601,
      64: 34604033,
      80: 0,
      96: 1,
      112: 34603009,
      128: 33555456,
      144: 1048577,
      160: 33554433,
      176: 34604032,
      192: 34603008,
      208: 1025,
      224: 1049600,
      240: 33554432,
      8: 34603009,
      24: 0,
      40: 33555457,
      56: 34604032,
      72: 1048576,
      88: 33554433,
      104: 33554432,
      120: 1025,
      136: 1049601,
      152: 33555456,
      168: 34603008,
      184: 1048577,
      200: 1024,
      216: 34604033,
      232: 1,
      248: 1049600,
      256: 33554432,
      272: 1048576,
      288: 33555457,
      304: 34603009,
      320: 1048577,
      336: 33555456,
      352: 34604032,
      368: 1049601,
      384: 1025,
      400: 34604033,
      416: 1049600,
      432: 1,
      448: 0,
      464: 34603008,
      480: 33554433,
      496: 1024,
      264: 1049600,
      280: 33555457,
      296: 34603009,
      312: 1,
      328: 33554432,
      344: 1048576,
      360: 1025,
      376: 34604032,
      392: 33554433,
      408: 34603008,
      424: 0,
      440: 34604033,
      456: 1049601,
      472: 1024,
      488: 33555456,
      504: 1048577
    }, {
      "0": 134219808,
      1: 131072,
      2: 134217728,
      3: 32,
      4: 131104,
      5: 134350880,
      6: 134350848,
      7: 2048,
      8: 134348800,
      9: 134219776,
      10: 133120,
      11: 134348832,
      12: 2080,
      13: 0,
      14: 134217760,
      15: 133152,
      2147483648: 2048,
      2147483649: 134350880,
      2147483650: 134219808,
      2147483651: 134217728,
      2147483652: 134348800,
      2147483653: 133120,
      2147483654: 133152,
      2147483655: 32,
      2147483656: 134217760,
      2147483657: 2080,
      2147483658: 131104,
      2147483659: 134350848,
      2147483660: 0,
      2147483661: 134348832,
      2147483662: 134219776,
      2147483663: 131072,
      16: 133152,
      17: 134350848,
      18: 32,
      19: 2048,
      20: 134219776,
      21: 134217760,
      22: 134348832,
      23: 131072,
      24: 0,
      25: 131104,
      26: 134348800,
      27: 134219808,
      28: 134350880,
      29: 133120,
      30: 2080,
      31: 134217728,
      2147483664: 131072,
      2147483665: 2048,
      2147483666: 134348832,
      2147483667: 133152,
      2147483668: 32,
      2147483669: 134348800,
      2147483670: 134217728,
      2147483671: 134219808,
      2147483672: 134350880,
      2147483673: 134217760,
      2147483674: 134219776,
      2147483675: 0,
      2147483676: 133120,
      2147483677: 2080,
      2147483678: 131104,
      2147483679: 134350848
    }],
    t = [4160749569, 528482304, 33030144, 2064384, 129024, 8064, 504, 2147483679],
    m = g.DES = e.extend({
      _doReset: function () {
        for (var b = this._key.words, c = [], a = 0; 56 > a; a++) {
          var f = q[a] - 1;
          c[a] = b[f >>> 5] >>> 31 - f % 32 & 1;
        }
        b = this._subKeys = [];
        for (f = 0; 16 > f; f++) {
          for (var d = b[f] = [], e = r[f], a = 0; 24 > a; a++) d[a / 6 | 0] |= c[(p[a] - 1 + e) % 28] << 31 - a % 6, d[4 + (a / 6 | 0)] |= c[28 + (p[a + 24] - 1 + e) % 28] << 31 - a % 6;
          d[0] = d[0] << 1 | d[0] >>> 31;
          for (a = 1; 7 > a; a++) d[a] >>>= 4 * (a - 1) + 3;
          d[7] = d[7] << 5 | d[7] >>> 27;
        }
        c = this._invSubKeys = [];
        for (a = 0; 16 > a; a++) c[a] = b[15 - a];
      },
      encryptBlock: function (b, c) {
        this._doCryptBlock(b, c, this._subKeys);
      },
      decryptBlock: function (b, c) {
        this._doCryptBlock(b, c, this._invSubKeys);
      },
      _doCryptBlock: function (b, c, a) {
        this._lBlock = b[c];
        this._rBlock = b[c + 1];
        j.call(this, 4, 252645135);
        j.call(this, 16, 65535);
        l.call(this, 2, 858993459);
        l.call(this, 8, 16711935);
        j.call(this, 1, 1431655765);
        for (var f = 0; 16 > f; f++) {
          for (var d = a[f], e = this._lBlock, h = this._rBlock, g = 0, k = 0; 8 > k; k++) g |= s[k][((h ^ d[k]) & t[k]) >>> 0];
          this._lBlock = h;
          this._rBlock = e ^ g;
        }
        a = this._lBlock;
        this._lBlock = this._rBlock;
        this._rBlock = a;
        j.call(this, 1, 1431655765);
        l.call(this, 8, 16711935);
        l.call(this, 2, 858993459);
        j.call(this, 16, 65535);
        j.call(this, 4, 252645135);
        b[c] = this._lBlock;
        b[c + 1] = this._rBlock;
      },
      keySize: 2,
      ivSize: 2,
      blockSize: 2
    });
  h.DES = e._createHelper(m);
  g = g.TripleDES = e.extend({
    _doReset: function () {
      var b = this._key.words;
      this._des1 = m.createEncryptor(n.create(b.slice(0, 2)));
      this._des2 = m.createEncryptor(n.create(b.slice(2, 4)));
      this._des3 = m.createEncryptor(n.create(b.slice(4, 6)));
    },
    encryptBlock: function (b, c) {
      this._des1.encryptBlock(b, c);
      this._des2.decryptBlock(b, c);
      this._des3.encryptBlock(b, c);
    },
    decryptBlock: function (b, c) {
      this._des3.decryptBlock(b, c);
      this._des2.encryptBlock(b, c);
      this._des1.decryptBlock(b, c);
    },
    keySize: 6,
    ivSize: 2,
    blockSize: 2
  });
  h.TripleDES = e._createHelper(g);
})();

/*
CryptoJS v3.1.2 enc-base64.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var h = CryptoJS,
    j = h.lib.WordArray;
  h.enc.Base64 = {
    stringify: function (b) {
      var e = b.words,
        f = b.sigBytes,
        c = this._map;
      b.clamp();
      b = [];
      for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63));
      if (e = c.charAt(64)) for (; b.length % 4;) b.push(e);
      return b.join("");
    },
    parse: function (b) {
      var e = b.length,
        f = this._map,
        c = f.charAt(64);
      c && (c = b.indexOf(c), -1 != c && (e = c));
      for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) {
        var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4),
          h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4);
        c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4);
        a++;
      }
      return j.create(c, a);
    },
    _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  };
})();

/*
CryptoJS v3.1.2 md5.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function (E) {
  function h(a, f, g, j, p, h, k) {
    a = a + (f & g | ~f & j) + p + k;
    return (a << h | a >>> 32 - h) + f;
  }
  function k(a, f, g, j, p, h, k) {
    a = a + (f & j | g & ~j) + p + k;
    return (a << h | a >>> 32 - h) + f;
  }
  function l(a, f, g, j, h, k, l) {
    a = a + (f ^ g ^ j) + h + l;
    return (a << k | a >>> 32 - k) + f;
  }
  function n(a, f, g, j, h, k, l) {
    a = a + (g ^ (f | ~j)) + h + l;
    return (a << k | a >>> 32 - k) + f;
  }
  for (var r = CryptoJS, q = r.lib, F = q.WordArray, s = q.Hasher, q = r.algo, a = [], t = 0; 64 > t; t++) a[t] = 4294967296 * E.abs(E.sin(t + 1)) | 0;
  q = q.MD5 = s.extend({
    _doReset: function () {
      this._hash = new F.init([1732584193, 4023233417, 2562383102, 271733878]);
    },
    _doProcessBlock: function (m, f) {
      for (var g = 0; 16 > g; g++) {
        var j = f + g,
          p = m[j];
        m[j] = (p << 8 | p >>> 24) & 16711935 | (p << 24 | p >>> 8) & 4278255360;
      }
      var g = this._hash.words,
        j = m[f + 0],
        p = m[f + 1],
        q = m[f + 2],
        r = m[f + 3],
        s = m[f + 4],
        t = m[f + 5],
        u = m[f + 6],
        v = m[f + 7],
        w = m[f + 8],
        x = m[f + 9],
        y = m[f + 10],
        z = m[f + 11],
        A = m[f + 12],
        B = m[f + 13],
        C = m[f + 14],
        D = m[f + 15],
        b = g[0],
        c = g[1],
        d = g[2],
        e = g[3],
        b = h(b, c, d, e, j, 7, a[0]),
        e = h(e, b, c, d, p, 12, a[1]),
        d = h(d, e, b, c, q, 17, a[2]),
        c = h(c, d, e, b, r, 22, a[3]),
        b = h(b, c, d, e, s, 7, a[4]),
        e = h(e, b, c, d, t, 12, a[5]),
        d = h(d, e, b, c, u, 17, a[6]),
        c = h(c, d, e, b, v, 22, a[7]),
        b = h(b, c, d, e, w, 7, a[8]),
        e = h(e, b, c, d, x, 12, a[9]),
        d = h(d, e, b, c, y, 17, a[10]),
        c = h(c, d, e, b, z, 22, a[11]),
        b = h(b, c, d, e, A, 7, a[12]),
        e = h(e, b, c, d, B, 12, a[13]),
        d = h(d, e, b, c, C, 17, a[14]),
        c = h(c, d, e, b, D, 22, a[15]),
        b = k(b, c, d, e, p, 5, a[16]),
        e = k(e, b, c, d, u, 9, a[17]),
        d = k(d, e, b, c, z, 14, a[18]),
        c = k(c, d, e, b, j, 20, a[19]),
        b = k(b, c, d, e, t, 5, a[20]),
        e = k(e, b, c, d, y, 9, a[21]),
        d = k(d, e, b, c, D, 14, a[22]),
        c = k(c, d, e, b, s, 20, a[23]),
        b = k(b, c, d, e, x, 5, a[24]),
        e = k(e, b, c, d, C, 9, a[25]),
        d = k(d, e, b, c, r, 14, a[26]),
        c = k(c, d, e, b, w, 20, a[27]),
        b = k(b, c, d, e, B, 5, a[28]),
        e = k(e, b, c, d, q, 9, a[29]),
        d = k(d, e, b, c, v, 14, a[30]),
        c = k(c, d, e, b, A, 20, a[31]),
        b = l(b, c, d, e, t, 4, a[32]),
        e = l(e, b, c, d, w, 11, a[33]),
        d = l(d, e, b, c, z, 16, a[34]),
        c = l(c, d, e, b, C, 23, a[35]),
        b = l(b, c, d, e, p, 4, a[36]),
        e = l(e, b, c, d, s, 11, a[37]),
        d = l(d, e, b, c, v, 16, a[38]),
        c = l(c, d, e, b, y, 23, a[39]),
        b = l(b, c, d, e, B, 4, a[40]),
        e = l(e, b, c, d, j, 11, a[41]),
        d = l(d, e, b, c, r, 16, a[42]),
        c = l(c, d, e, b, u, 23, a[43]),
        b = l(b, c, d, e, x, 4, a[44]),
        e = l(e, b, c, d, A, 11, a[45]),
        d = l(d, e, b, c, D, 16, a[46]),
        c = l(c, d, e, b, q, 23, a[47]),
        b = n(b, c, d, e, j, 6, a[48]),
        e = n(e, b, c, d, v, 10, a[49]),
        d = n(d, e, b, c, C, 15, a[50]),
        c = n(c, d, e, b, t, 21, a[51]),
        b = n(b, c, d, e, A, 6, a[52]),
        e = n(e, b, c, d, r, 10, a[53]),
        d = n(d, e, b, c, y, 15, a[54]),
        c = n(c, d, e, b, p, 21, a[55]),
        b = n(b, c, d, e, w, 6, a[56]),
        e = n(e, b, c, d, D, 10, a[57]),
        d = n(d, e, b, c, u, 15, a[58]),
        c = n(c, d, e, b, B, 21, a[59]),
        b = n(b, c, d, e, s, 6, a[60]),
        e = n(e, b, c, d, z, 10, a[61]),
        d = n(d, e, b, c, q, 15, a[62]),
        c = n(c, d, e, b, x, 21, a[63]);
      g[0] = g[0] + b | 0;
      g[1] = g[1] + c | 0;
      g[2] = g[2] + d | 0;
      g[3] = g[3] + e | 0;
    },
    _doFinalize: function () {
      var a = this._data,
        f = a.words,
        g = 8 * this._nDataBytes,
        j = 8 * a.sigBytes;
      f[j >>> 5] |= 128 << 24 - j % 32;
      var h = E.floor(g / 4294967296);
      f[(j + 64 >>> 9 << 4) + 15] = (h << 8 | h >>> 24) & 16711935 | (h << 24 | h >>> 8) & 4278255360;
      f[(j + 64 >>> 9 << 4) + 14] = (g << 8 | g >>> 24) & 16711935 | (g << 24 | g >>> 8) & 4278255360;
      a.sigBytes = 4 * (f.length + 1);
      this._process();
      a = this._hash;
      f = a.words;
      for (g = 0; 4 > g; g++) j = f[g], f[g] = (j << 8 | j >>> 24) & 16711935 | (j << 24 | j >>> 8) & 4278255360;
      return a;
    },
    clone: function () {
      var a = s.clone.call(this);
      a._hash = this._hash.clone();
      return a;
    }
  });
  r.MD5 = s._createHelper(q);
  r.HmacMD5 = s._createHmacHelper(q);
})(Math);

/*
CryptoJS v3.1.2 sha1-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var k = CryptoJS,
    b = k.lib,
    m = b.WordArray,
    l = b.Hasher,
    d = [],
    b = k.algo.SHA1 = l.extend({
      _doReset: function () {
        this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
      },
      _doProcessBlock: function (n, p) {
        for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) {
          if (16 > c) d[c] = n[p + c] | 0;else {
            var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16];
            d[c] = g << 1 | g >>> 31;
          }
          g = (e << 5 | e >>> 27) + b + d[c];
          g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514);
          b = j;
          j = h;
          h = f << 30 | f >>> 2;
          f = e;
          e = g;
        }
        a[0] = a[0] + e | 0;
        a[1] = a[1] + f | 0;
        a[2] = a[2] + h | 0;
        a[3] = a[3] + j | 0;
        a[4] = a[4] + b | 0;
      },
      _doFinalize: function () {
        var b = this._data,
          d = b.words,
          a = 8 * this._nDataBytes,
          e = 8 * b.sigBytes;
        d[e >>> 5] |= 128 << 24 - e % 32;
        d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296);
        d[(e + 64 >>> 9 << 4) + 15] = a;
        b.sigBytes = 4 * d.length;
        this._process();
        return this._hash;
      },
      clone: function () {
        var b = l.clone.call(this);
        b._hash = this._hash.clone();
        return b;
      }
    });
  k.SHA1 = l._createHelper(b);
  k.HmacSHA1 = l._createHmacHelper(b);
})();

/*
CryptoJS v3.1.2 sha256-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function (k) {
  for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) {
      return 4294967296 * (q - (q | 0)) | 0;
    }, l = 2, b = 0; 64 > b;) {
    var d;
    a: {
      d = l;
      for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) {
        d = !1;
        break a;
      }
      d = !0;
    }
    d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++);
    l++;
  }
  var n = [],
    h = h.SHA256 = j.extend({
      _doReset: function () {
        this._hash = new v.init(s.slice(0));
      },
      _doProcessBlock: function (q, h) {
        for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) {
          if (16 > e) n[e] = q[h + e] | 0;else {
            var m = n[e - 15],
              p = n[e - 2];
            n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16];
          }
          m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e];
          p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b);
          l = j;
          j = g;
          g = f;
          f = k + m | 0;
          k = b;
          b = d;
          d = c;
          c = m + p | 0;
        }
        a[0] = a[0] + c | 0;
        a[1] = a[1] + d | 0;
        a[2] = a[2] + b | 0;
        a[3] = a[3] + k | 0;
        a[4] = a[4] + f | 0;
        a[5] = a[5] + g | 0;
        a[6] = a[6] + j | 0;
        a[7] = a[7] + l | 0;
      },
      _doFinalize: function () {
        var d = this._data,
          b = d.words,
          a = 8 * this._nDataBytes,
          c = 8 * d.sigBytes;
        b[c >>> 5] |= 128 << 24 - c % 32;
        b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296);
        b[(c + 64 >>> 9 << 4) + 15] = a;
        d.sigBytes = 4 * b.length;
        this._process();
        return this._hash;
      },
      clone: function () {
        var b = j.clone.call(this);
        b._hash = this._hash.clone();
        return b;
      }
    });
  g.SHA256 = j._createHelper(h);
  g.HmacSHA256 = j._createHmacHelper(h);
})(Math);

/*
CryptoJS v3.1.2 sha224-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var b = CryptoJS,
    d = b.lib.WordArray,
    a = b.algo,
    c = a.SHA256,
    a = a.SHA224 = c.extend({
      _doReset: function () {
        this._hash = new d.init([3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]);
      },
      _doFinalize: function () {
        var a = c._doFinalize.call(this);
        a.sigBytes -= 4;
        return a;
      }
    });
  b.SHA224 = c._createHelper(a);
  b.HmacSHA224 = c._createHmacHelper(a);
})();

/*
CryptoJS v3.1.2 sha512-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  function a() {
    return d.create.apply(d, arguments);
  }
  for (var n = CryptoJS, r = n.lib.Hasher, e = n.x64, d = e.Word, T = e.WordArray, e = n.algo, ea = [a(1116352408, 3609767458), a(1899447441, 602891725), a(3049323471, 3964484399), a(3921009573, 2173295548), a(961987163, 4081628472), a(1508970993, 3053834265), a(2453635748, 2937671579), a(2870763221, 3664609560), a(3624381080, 2734883394), a(310598401, 1164996542), a(607225278, 1323610764), a(1426881987, 3590304994), a(1925078388, 4068182383), a(2162078206, 991336113), a(2614888103, 633803317), a(3248222580, 3479774868), a(3835390401, 2666613458), a(4022224774, 944711139), a(264347078, 2341262773), a(604807628, 2007800933), a(770255983, 1495990901), a(1249150122, 1856431235), a(1555081692, 3175218132), a(1996064986, 2198950837), a(2554220882, 3999719339), a(2821834349, 766784016), a(2952996808, 2566594879), a(3210313671, 3203337956), a(3336571891, 1034457026), a(3584528711, 2466948901), a(113926993, 3758326383), a(338241895, 168717936), a(666307205, 1188179964), a(773529912, 1546045734), a(1294757372, 1522805485), a(1396182291, 2643833823), a(1695183700, 2343527390), a(1986661051, 1014477480), a(2177026350, 1206759142), a(2456956037, 344077627), a(2730485921, 1290863460), a(2820302411, 3158454273), a(3259730800, 3505952657), a(3345764771, 106217008), a(3516065817, 3606008344), a(3600352804, 1432725776), a(4094571909, 1467031594), a(275423344, 851169720), a(430227734, 3100823752), a(506948616, 1363258195), a(659060556, 3750685593), a(883997877, 3785050280), a(958139571, 3318307427), a(1322822218, 3812723403), a(1537002063, 2003034995), a(1747873779, 3602036899), a(1955562222, 1575990012), a(2024104815, 1125592928), a(2227730452, 2716904306), a(2361852424, 442776044), a(2428436474, 593698344), a(2756734187, 3733110249), a(3204031479, 2999351573), a(3329325298, 3815920427), a(3391569614, 3928383900), a(3515267271, 566280711), a(3940187606, 3454069534), a(4118630271, 4000239992), a(116418474, 1914138554), a(174292421, 2731055270), a(289380356, 3203993006), a(460393269, 320620315), a(685471733, 587496836), a(852142971, 1086792851), a(1017036298, 365543100), a(1126000580, 2618297676), a(1288033470, 3409855158), a(1501505948, 4234509866), a(1607167915, 987167468), a(1816402316, 1246189591)], v = [], w = 0; 80 > w; w++) v[w] = a();
  e = e.SHA512 = r.extend({
    _doReset: function () {
      this._hash = new T.init([new d.init(1779033703, 4089235720), new d.init(3144134277, 2227873595), new d.init(1013904242, 4271175723), new d.init(2773480762, 1595750129), new d.init(1359893119, 2917565137), new d.init(2600822924, 725511199), new d.init(528734635, 4215389547), new d.init(1541459225, 327033209)]);
    },
    _doProcessBlock: function (a, d) {
      for (var f = this._hash.words, F = f[0], e = f[1], n = f[2], r = f[3], G = f[4], H = f[5], I = f[6], f = f[7], w = F.high, J = F.low, X = e.high, K = e.low, Y = n.high, L = n.low, Z = r.high, M = r.low, $ = G.high, N = G.low, aa = H.high, O = H.low, ba = I.high, P = I.low, ca = f.high, Q = f.low, k = w, g = J, z = X, x = K, A = Y, y = L, U = Z, B = M, l = $, h = N, R = aa, C = O, S = ba, D = P, V = ca, E = Q, m = 0; 80 > m; m++) {
        var s = v[m];
        if (16 > m) var j = s.high = a[d + 2 * m] | 0,
          b = s.low = a[d + 2 * m + 1] | 0;else {
          var j = v[m - 15],
            b = j.high,
            p = j.low,
            j = (b >>> 1 | p << 31) ^ (b >>> 8 | p << 24) ^ b >>> 7,
            p = (p >>> 1 | b << 31) ^ (p >>> 8 | b << 24) ^ (p >>> 7 | b << 25),
            u = v[m - 2],
            b = u.high,
            c = u.low,
            u = (b >>> 19 | c << 13) ^ (b << 3 | c >>> 29) ^ b >>> 6,
            c = (c >>> 19 | b << 13) ^ (c << 3 | b >>> 29) ^ (c >>> 6 | b << 26),
            b = v[m - 7],
            W = b.high,
            t = v[m - 16],
            q = t.high,
            t = t.low,
            b = p + b.low,
            j = j + W + (b >>> 0 < p >>> 0 ? 1 : 0),
            b = b + c,
            j = j + u + (b >>> 0 < c >>> 0 ? 1 : 0),
            b = b + t,
            j = j + q + (b >>> 0 < t >>> 0 ? 1 : 0);
          s.high = j;
          s.low = b;
        }
        var W = l & R ^ ~l & S,
          t = h & C ^ ~h & D,
          s = k & z ^ k & A ^ z & A,
          T = g & x ^ g & y ^ x & y,
          p = (k >>> 28 | g << 4) ^ (k << 30 | g >>> 2) ^ (k << 25 | g >>> 7),
          u = (g >>> 28 | k << 4) ^ (g << 30 | k >>> 2) ^ (g << 25 | k >>> 7),
          c = ea[m],
          fa = c.high,
          da = c.low,
          c = E + ((h >>> 14 | l << 18) ^ (h >>> 18 | l << 14) ^ (h << 23 | l >>> 9)),
          q = V + ((l >>> 14 | h << 18) ^ (l >>> 18 | h << 14) ^ (l << 23 | h >>> 9)) + (c >>> 0 < E >>> 0 ? 1 : 0),
          c = c + t,
          q = q + W + (c >>> 0 < t >>> 0 ? 1 : 0),
          c = c + da,
          q = q + fa + (c >>> 0 < da >>> 0 ? 1 : 0),
          c = c + b,
          q = q + j + (c >>> 0 < b >>> 0 ? 1 : 0),
          b = u + T,
          s = p + s + (b >>> 0 < u >>> 0 ? 1 : 0),
          V = S,
          E = D,
          S = R,
          D = C,
          R = l,
          C = h,
          h = B + c | 0,
          l = U + q + (h >>> 0 < B >>> 0 ? 1 : 0) | 0,
          U = A,
          B = y,
          A = z,
          y = x,
          z = k,
          x = g,
          g = c + b | 0,
          k = q + s + (g >>> 0 < c >>> 0 ? 1 : 0) | 0;
      }
      J = F.low = J + g;
      F.high = w + k + (J >>> 0 < g >>> 0 ? 1 : 0);
      K = e.low = K + x;
      e.high = X + z + (K >>> 0 < x >>> 0 ? 1 : 0);
      L = n.low = L + y;
      n.high = Y + A + (L >>> 0 < y >>> 0 ? 1 : 0);
      M = r.low = M + B;
      r.high = Z + U + (M >>> 0 < B >>> 0 ? 1 : 0);
      N = G.low = N + h;
      G.high = $ + l + (N >>> 0 < h >>> 0 ? 1 : 0);
      O = H.low = O + C;
      H.high = aa + R + (O >>> 0 < C >>> 0 ? 1 : 0);
      P = I.low = P + D;
      I.high = ba + S + (P >>> 0 < D >>> 0 ? 1 : 0);
      Q = f.low = Q + E;
      f.high = ca + V + (Q >>> 0 < E >>> 0 ? 1 : 0);
    },
    _doFinalize: function () {
      var a = this._data,
        d = a.words,
        f = 8 * this._nDataBytes,
        e = 8 * a.sigBytes;
      d[e >>> 5] |= 128 << 24 - e % 32;
      d[(e + 128 >>> 10 << 5) + 30] = Math.floor(f / 4294967296);
      d[(e + 128 >>> 10 << 5) + 31] = f;
      a.sigBytes = 4 * d.length;
      this._process();
      return this._hash.toX32();
    },
    clone: function () {
      var a = r.clone.call(this);
      a._hash = this._hash.clone();
      return a;
    },
    blockSize: 32
  });
  n.SHA512 = r._createHelper(e);
  n.HmacSHA512 = r._createHmacHelper(e);
})();

/*
CryptoJS v3.1.2 sha384-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var c = CryptoJS,
    a = c.x64,
    b = a.Word,
    e = a.WordArray,
    a = c.algo,
    d = a.SHA512,
    a = a.SHA384 = d.extend({
      _doReset: function () {
        this._hash = new e.init([new b.init(3418070365, 3238371032), new b.init(1654270250, 914150663), new b.init(2438529370, 812702999), new b.init(355462360, 4144912697), new b.init(1731405415, 4290775857), new b.init(2394180231, 1750603025), new b.init(3675008525, 1694076839), new b.init(1203062813, 3204075428)]);
      },
      _doFinalize: function () {
        var a = d._doFinalize.call(this);
        a.sigBytes -= 16;
        return a;
      }
    });
  c.SHA384 = d._createHelper(a);
  c.HmacSHA384 = d._createHmacHelper(a);
})();

/*
CryptoJS v3.1.2 ripemd160-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/*

(c) 2012 by Cedric Mesnil. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function () {
  var q = CryptoJS,
    d = q.lib,
    n = d.WordArray,
    p = d.Hasher,
    d = q.algo,
    x = n.create([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]),
    y = n.create([5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]),
    z = n.create([11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]),
    A = n.create([8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]),
    B = n.create([0, 1518500249, 1859775393, 2400959708, 2840853838]),
    C = n.create([1352829926, 1548603684, 1836072691, 2053994217, 0]),
    d = d.RIPEMD160 = p.extend({
      _doReset: function () {
        this._hash = n.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
      },
      _doProcessBlock: function (e, v) {
        for (var b = 0; 16 > b; b++) {
          var c = v + b,
            f = e[c];
          e[c] = (f << 8 | f >>> 24) & 16711935 | (f << 24 | f >>> 8) & 4278255360;
        }
        var c = this._hash.words,
          f = B.words,
          d = C.words,
          n = x.words,
          q = y.words,
          p = z.words,
          w = A.words,
          t,
          g,
          h,
          j,
          r,
          u,
          k,
          l,
          m,
          s;
        u = t = c[0];
        k = g = c[1];
        l = h = c[2];
        m = j = c[3];
        s = r = c[4];
        for (var a, b = 0; 80 > b; b += 1) a = t + e[v + n[b]] | 0, a = 16 > b ? a + ((g ^ h ^ j) + f[0]) : 32 > b ? a + ((g & h | ~g & j) + f[1]) : 48 > b ? a + (((g | ~h) ^ j) + f[2]) : 64 > b ? a + ((g & j | h & ~j) + f[3]) : a + ((g ^ (h | ~j)) + f[4]), a |= 0, a = a << p[b] | a >>> 32 - p[b], a = a + r | 0, t = r, r = j, j = h << 10 | h >>> 22, h = g, g = a, a = u + e[v + q[b]] | 0, a = 16 > b ? a + ((k ^ (l | ~m)) + d[0]) : 32 > b ? a + ((k & m | l & ~m) + d[1]) : 48 > b ? a + (((k | ~l) ^ m) + d[2]) : 64 > b ? a + ((k & l | ~k & m) + d[3]) : a + ((k ^ l ^ m) + d[4]), a |= 0, a = a << w[b] | a >>> 32 - w[b], a = a + s | 0, u = s, s = m, m = l << 10 | l >>> 22, l = k, k = a;
        a = c[1] + h + m | 0;
        c[1] = c[2] + j + s | 0;
        c[2] = c[3] + r + u | 0;
        c[3] = c[4] + t + k | 0;
        c[4] = c[0] + g + l | 0;
        c[0] = a;
      },
      _doFinalize: function () {
        var e = this._data,
          d = e.words,
          b = 8 * this._nDataBytes,
          c = 8 * e.sigBytes;
        d[c >>> 5] |= 128 << 24 - c % 32;
        d[(c + 64 >>> 9 << 4) + 14] = (b << 8 | b >>> 24) & 16711935 | (b << 24 | b >>> 8) & 4278255360;
        e.sigBytes = 4 * (d.length + 1);
        this._process();
        e = this._hash;
        d = e.words;
        for (b = 0; 5 > b; b++) c = d[b], d[b] = (c << 8 | c >>> 24) & 16711935 | (c << 24 | c >>> 8) & 4278255360;
        return e;
      },
      clone: function () {
        var d = p.clone.call(this);
        d._hash = this._hash.clone();
        return d;
      }
    });
  q.RIPEMD160 = p._createHelper(d);
  q.HmacRIPEMD160 = p._createHmacHelper(d);
})(Math);

/*
CryptoJS v3.1.2 hmac.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var c = CryptoJS,
    k = c.enc.Utf8;
  c.algo.HMAC = c.lib.Base.extend({
    init: function (a, b) {
      a = this._hasher = new a.init();
      "string" == typeof b && (b = k.parse(b));
      var c = a.blockSize,
        e = 4 * c;
      b.sigBytes > e && (b = a.finalize(b));
      b.clamp();
      for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486;
      f.sigBytes = g.sigBytes = e;
      this.reset();
    },
    reset: function () {
      var a = this._hasher;
      a.reset();
      a.update(this._iKey);
    },
    update: function (a) {
      this._hasher.update(a);
      return this;
    },
    finalize: function (a) {
      var b = this._hasher;
      a = b.finalize(a);
      b.reset();
      return b.finalize(this._oKey.clone().concat(a));
    }
  });
})();

/*
CryptoJS v3.1.2 pbkdf2-min.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
  var b = CryptoJS,
    a = b.lib,
    d = a.Base,
    m = a.WordArray,
    a = b.algo,
    q = a.HMAC,
    l = a.PBKDF2 = d.extend({
      cfg: d.extend({
        keySize: 4,
        hasher: a.SHA1,
        iterations: 1
      }),
      init: function (a) {
        this.cfg = this.cfg.extend(a);
      },
      compute: function (a, b) {
        for (var c = this.cfg, f = q.create(c.hasher, a), g = m.create(), d = m.create([1]), l = g.words, r = d.words, n = c.keySize, c = c.iterations; l.length < n;) {
          var h = f.update(b).finalize(d);
          f.reset();
          for (var j = h.words, s = j.length, k = h, p = 1; p < c; p++) {
            k = f.finalize(k);
            f.reset();
            for (var t = k.words, e = 0; e < s; e++) j[e] ^= t[e];
          }
          g.concat(h);
          r[0]++;
        }
        g.sigBytes = 4 * n;
        return g;
      }
    });
  b.PBKDF2 = function (a, b, c) {
    return l.create(c).compute(a, b);
  };
})();

/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad = "=";
function hex2b64(d) {
  var b;
  var e;
  var a = "";
  for (b = 0; b + 3 <= d.length; b += 3) {
    e = parseInt(d.substring(b, b + 3), 16);
    a += b64map.charAt(e >> 6) + b64map.charAt(e & 63);
  }
  if (b + 1 == d.length) {
    e = parseInt(d.substring(b, b + 1), 16);
    a += b64map.charAt(e << 2);
  } else {
    if (b + 2 == d.length) {
      e = parseInt(d.substring(b, b + 2), 16);
      a += b64map.charAt(e >> 2) + b64map.charAt((e & 3) << 4);
    }
  }
  if (b64pad) {
    while ((a.length & 3) > 0) {
      a += b64pad;
    }
  }
  return a;
}
function b64tohex(f) {
  var d = "";
  var e;
  var b = 0;
  var c;
  var a;
  for (e = 0; e < f.length; ++e) {
    if (f.charAt(e) == b64pad) {
      break;
    }
    a = b64map.indexOf(f.charAt(e));
    if (a < 0) {
      continue;
    }
    if (b == 0) {
      d += int2char(a >> 2);
      c = a & 3;
      b = 1;
    } else {
      if (b == 1) {
        d += int2char(c << 2 | a >> 4);
        c = a & 15;
        b = 2;
      } else {
        if (b == 2) {
          d += int2char(c);
          d += int2char(a >> 2);
          c = a & 3;
          b = 3;
        } else {
          d += int2char(c << 2 | a >> 4);
          d += int2char(a & 15);
          b = 0;
        }
      }
    }
  }
  if (b == 1) {
    d += int2char(c << 2);
  }
  return d;
}
function b64toBA(e) {
  var d = b64tohex(e);
  var c;
  var b = new Array();
  for (c = 0; 2 * c < d.length; ++c) {
    b[c] = parseInt(d.substring(2 * c, 2 * c + 2), 16);
  }
  return b;
}
;
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
var dbits;
var canary = 244837814094590;
var j_lm = (canary & 16777215) == 15715070;
function BigInteger(e, d, f) {
  if (e != null) {
    if ("number" == typeof e) {
      this.fromNumber(e, d, f);
    } else {
      if (d == null && "string" != typeof e) {
        this.fromString(e, 256);
      } else {
        this.fromString(e, d);
      }
    }
  }
}
function nbi() {
  return new BigInteger(null);
}
function am1(f, a, b, e, h, g) {
  while (--g >= 0) {
    var d = a * this[f++] + b[e] + h;
    h = Math.floor(d / 67108864);
    b[e++] = d & 67108863;
  }
  return h;
}
function am2(f, q, r, e, o, a) {
  var k = q & 32767,
    p = q >> 15;
  while (--a >= 0) {
    var d = this[f] & 32767;
    var g = this[f++] >> 15;
    var b = p * d + g * k;
    d = k * d + ((b & 32767) << 15) + r[e] + (o & 1073741823);
    o = (d >>> 30) + (b >>> 15) + p * g + (o >>> 30);
    r[e++] = d & 1073741823;
  }
  return o;
}
function am3(f, q, r, e, o, a) {
  var k = q & 16383,
    p = q >> 14;
  while (--a >= 0) {
    var d = this[f] & 16383;
    var g = this[f++] >> 14;
    var b = p * d + g * k;
    d = k * d + ((b & 16383) << 14) + r[e] + o;
    o = (d >> 28) + (b >> 14) + p * g;
    r[e++] = d & 268435455;
  }
  return o;
}
if (j_lm && navigator.appName == "Microsoft Internet Explorer") {
  BigInteger.prototype.am = am2;
  dbits = 30;
} else {
  if (j_lm && navigator.appName != "Netscape") {
    BigInteger.prototype.am = am1;
    dbits = 26;
  } else {
    BigInteger.prototype.am = am3;
    dbits = 28;
  }
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = (1 << dbits) - 1;
BigInteger.prototype.DV = 1 << dbits;
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2, BI_FP);
BigInteger.prototype.F1 = BI_FP - dbits;
BigInteger.prototype.F2 = 2 * dbits - BI_FP;
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr, vv;
rr = "0".charCodeAt(0);
for (vv = 0; vv <= 9; ++vv) {
  BI_RC[rr++] = vv;
}
rr = "a".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
  BI_RC[rr++] = vv;
}
rr = "A".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
  BI_RC[rr++] = vv;
}
function int2char(a) {
  return BI_RM.charAt(a);
}
function intAt(b, a) {
  var d = BI_RC[b.charCodeAt(a)];
  return d == null ? -1 : d;
}
function bnpCopyTo(b) {
  for (var a = this.t - 1; a >= 0; --a) {
    b[a] = this[a];
  }
  b.t = this.t;
  b.s = this.s;
}
function bnpFromInt(a) {
  this.t = 1;
  this.s = a < 0 ? -1 : 0;
  if (a > 0) {
    this[0] = a;
  } else {
    if (a < -1) {
      this[0] = a + this.DV;
    } else {
      this.t = 0;
    }
  }
}
function nbv(a) {
  var b = nbi();
  b.fromInt(a);
  return b;
}
function bnpFromString(h, c) {
  var e;
  if (c == 16) {
    e = 4;
  } else {
    if (c == 8) {
      e = 3;
    } else {
      if (c == 256) {
        e = 8;
      } else {
        if (c == 2) {
          e = 1;
        } else {
          if (c == 32) {
            e = 5;
          } else {
            if (c == 4) {
              e = 2;
            } else {
              this.fromRadix(h, c);
              return;
            }
          }
        }
      }
    }
  }
  this.t = 0;
  this.s = 0;
  var g = h.length,
    d = false,
    f = 0;
  while (--g >= 0) {
    var a = e == 8 ? h[g] & 255 : intAt(h, g);
    if (a < 0) {
      if (h.charAt(g) == "-") {
        d = true;
      }
      continue;
    }
    d = false;
    if (f == 0) {
      this[this.t++] = a;
    } else {
      if (f + e > this.DB) {
        this[this.t - 1] |= (a & (1 << this.DB - f) - 1) << f;
        this[this.t++] = a >> this.DB - f;
      } else {
        this[this.t - 1] |= a << f;
      }
    }
    f += e;
    if (f >= this.DB) {
      f -= this.DB;
    }
  }
  if (e == 8 && (h[0] & 128) != 0) {
    this.s = -1;
    if (f > 0) {
      this[this.t - 1] |= (1 << this.DB - f) - 1 << f;
    }
  }
  this.clamp();
  if (d) {
    BigInteger.ZERO.subTo(this, this);
  }
}
function bnpClamp() {
  var a = this.s & this.DM;
  while (this.t > 0 && this[this.t - 1] == a) {
    --this.t;
  }
}
function bnToString(c) {
  if (this.s < 0) {
    return "-" + this.negate().toString(c);
  }
  var e;
  if (c == 16) {
    e = 4;
  } else {
    if (c == 8) {
      e = 3;
    } else {
      if (c == 2) {
        e = 1;
      } else {
        if (c == 32) {
          e = 5;
        } else {
          if (c == 4) {
            e = 2;
          } else {
            return this.toRadix(c);
          }
        }
      }
    }
  }
  var g = (1 << e) - 1,
    l,
    a = false,
    h = "",
    f = this.t;
  var j = this.DB - f * this.DB % e;
  if (f-- > 0) {
    if (j < this.DB && (l = this[f] >> j) > 0) {
      a = true;
      h = int2char(l);
    }
    while (f >= 0) {
      if (j < e) {
        l = (this[f] & (1 << j) - 1) << e - j;
        l |= this[--f] >> (j += this.DB - e);
      } else {
        l = this[f] >> (j -= e) & g;
        if (j <= 0) {
          j += this.DB;
          --f;
        }
      }
      if (l > 0) {
        a = true;
      }
      if (a) {
        h += int2char(l);
      }
    }
  }
  return a ? h : "0";
}
function bnNegate() {
  var a = nbi();
  BigInteger.ZERO.subTo(this, a);
  return a;
}
function bnAbs() {
  return this.s < 0 ? this.negate() : this;
}
function bnCompareTo(b) {
  var d = this.s - b.s;
  if (d != 0) {
    return d;
  }
  var c = this.t;
  d = c - b.t;
  if (d != 0) {
    return this.s < 0 ? -d : d;
  }
  while (--c >= 0) {
    if ((d = this[c] - b[c]) != 0) {
      return d;
    }
  }
  return 0;
}
function nbits(a) {
  var c = 1,
    b;
  if ((b = a >>> 16) != 0) {
    a = b;
    c += 16;
  }
  if ((b = a >> 8) != 0) {
    a = b;
    c += 8;
  }
  if ((b = a >> 4) != 0) {
    a = b;
    c += 4;
  }
  if ((b = a >> 2) != 0) {
    a = b;
    c += 2;
  }
  if ((b = a >> 1) != 0) {
    a = b;
    c += 1;
  }
  return c;
}
function bnBitLength() {
  if (this.t <= 0) {
    return 0;
  }
  return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
}
function bnpDLShiftTo(c, b) {
  var a;
  for (a = this.t - 1; a >= 0; --a) {
    b[a + c] = this[a];
  }
  for (a = c - 1; a >= 0; --a) {
    b[a] = 0;
  }
  b.t = this.t + c;
  b.s = this.s;
}
function bnpDRShiftTo(c, b) {
  for (var a = c; a < this.t; ++a) {
    b[a - c] = this[a];
  }
  b.t = Math.max(this.t - c, 0);
  b.s = this.s;
}
function bnpLShiftTo(j, e) {
  var b = j % this.DB;
  var a = this.DB - b;
  var g = (1 << a) - 1;
  var f = Math.floor(j / this.DB),
    h = this.s << b & this.DM,
    d;
  for (d = this.t - 1; d >= 0; --d) {
    e[d + f + 1] = this[d] >> a | h;
    h = (this[d] & g) << b;
  }
  for (d = f - 1; d >= 0; --d) {
    e[d] = 0;
  }
  e[f] = h;
  e.t = this.t + f + 1;
  e.s = this.s;
  e.clamp();
}
function bnpRShiftTo(g, d) {
  d.s = this.s;
  var e = Math.floor(g / this.DB);
  if (e >= this.t) {
    d.t = 0;
    return;
  }
  var b = g % this.DB;
  var a = this.DB - b;
  var f = (1 << b) - 1;
  d[0] = this[e] >> b;
  for (var c = e + 1; c < this.t; ++c) {
    d[c - e - 1] |= (this[c] & f) << a;
    d[c - e] = this[c] >> b;
  }
  if (b > 0) {
    d[this.t - e - 1] |= (this.s & f) << a;
  }
  d.t = this.t - e;
  d.clamp();
}
function bnpSubTo(d, f) {
  var e = 0,
    g = 0,
    b = Math.min(d.t, this.t);
  while (e < b) {
    g += this[e] - d[e];
    f[e++] = g & this.DM;
    g >>= this.DB;
  }
  if (d.t < this.t) {
    g -= d.s;
    while (e < this.t) {
      g += this[e];
      f[e++] = g & this.DM;
      g >>= this.DB;
    }
    g += this.s;
  } else {
    g += this.s;
    while (e < d.t) {
      g -= d[e];
      f[e++] = g & this.DM;
      g >>= this.DB;
    }
    g -= d.s;
  }
  f.s = g < 0 ? -1 : 0;
  if (g < -1) {
    f[e++] = this.DV + g;
  } else {
    if (g > 0) {
      f[e++] = g;
    }
  }
  f.t = e;
  f.clamp();
}
function bnpMultiplyTo(c, e) {
  var b = this.abs(),
    f = c.abs();
  var d = b.t;
  e.t = d + f.t;
  while (--d >= 0) {
    e[d] = 0;
  }
  for (d = 0; d < f.t; ++d) {
    e[d + b.t] = b.am(0, f[d], e, d, 0, b.t);
  }
  e.s = 0;
  e.clamp();
  if (this.s != c.s) {
    BigInteger.ZERO.subTo(e, e);
  }
}
function bnpSquareTo(d) {
  var a = this.abs();
  var b = d.t = 2 * a.t;
  while (--b >= 0) {
    d[b] = 0;
  }
  for (b = 0; b < a.t - 1; ++b) {
    var e = a.am(b, a[b], d, 2 * b, 0, 1);
    if ((d[b + a.t] += a.am(b + 1, 2 * a[b], d, 2 * b + 1, e, a.t - b - 1)) >= a.DV) {
      d[b + a.t] -= a.DV;
      d[b + a.t + 1] = 1;
    }
  }
  if (d.t > 0) {
    d[d.t - 1] += a.am(b, a[b], d, 2 * b, 0, 1);
  }
  d.s = 0;
  d.clamp();
}
function bnpDivRemTo(n, h, g) {
  var w = n.abs();
  if (w.t <= 0) {
    return;
  }
  var k = this.abs();
  if (k.t < w.t) {
    if (h != null) {
      h.fromInt(0);
    }
    if (g != null) {
      this.copyTo(g);
    }
    return;
  }
  if (g == null) {
    g = nbi();
  }
  var d = nbi(),
    a = this.s,
    l = n.s;
  var v = this.DB - nbits(w[w.t - 1]);
  if (v > 0) {
    w.lShiftTo(v, d);
    k.lShiftTo(v, g);
  } else {
    w.copyTo(d);
    k.copyTo(g);
  }
  var p = d.t;
  var b = d[p - 1];
  if (b == 0) {
    return;
  }
  var o = b * (1 << this.F1) + (p > 1 ? d[p - 2] >> this.F2 : 0);
  var A = this.FV / o,
    z = (1 << this.F1) / o,
    x = 1 << this.F2;
  var u = g.t,
    s = u - p,
    f = h == null ? nbi() : h;
  d.dlShiftTo(s, f);
  if (g.compareTo(f) >= 0) {
    g[g.t++] = 1;
    g.subTo(f, g);
  }
  BigInteger.ONE.dlShiftTo(p, f);
  f.subTo(d, d);
  while (d.t < p) {
    d[d.t++] = 0;
  }
  while (--s >= 0) {
    var c = g[--u] == b ? this.DM : Math.floor(g[u] * A + (g[u - 1] + x) * z);
    if ((g[u] += d.am(0, c, g, s, 0, p)) < c) {
      d.dlShiftTo(s, f);
      g.subTo(f, g);
      while (g[u] < --c) {
        g.subTo(f, g);
      }
    }
  }
  if (h != null) {
    g.drShiftTo(p, h);
    if (a != l) {
      BigInteger.ZERO.subTo(h, h);
    }
  }
  g.t = p;
  g.clamp();
  if (v > 0) {
    g.rShiftTo(v, g);
  }
  if (a < 0) {
    BigInteger.ZERO.subTo(g, g);
  }
}
function bnMod(b) {
  var c = nbi();
  this.abs().divRemTo(b, null, c);
  if (this.s < 0 && c.compareTo(BigInteger.ZERO) > 0) {
    b.subTo(c, c);
  }
  return c;
}
function Classic(a) {
  this.m = a;
}
function cConvert(a) {
  if (a.s < 0 || a.compareTo(this.m) >= 0) {
    return a.mod(this.m);
  } else {
    return a;
  }
}
function cRevert(a) {
  return a;
}
function cReduce(a) {
  a.divRemTo(this.m, null, a);
}
function cMulTo(a, c, b) {
  a.multiplyTo(c, b);
  this.reduce(b);
}
function cSqrTo(a, b) {
  a.squareTo(b);
  this.reduce(b);
}
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
function bnpInvDigit() {
  if (this.t < 1) {
    return 0;
  }
  var a = this[0];
  if ((a & 1) == 0) {
    return 0;
  }
  var b = a & 3;
  b = b * (2 - (a & 15) * b) & 15;
  b = b * (2 - (a & 255) * b) & 255;
  b = b * (2 - ((a & 65535) * b & 65535)) & 65535;
  b = b * (2 - a * b % this.DV) % this.DV;
  return b > 0 ? this.DV - b : -b;
}
function Montgomery(a) {
  this.m = a;
  this.mp = a.invDigit();
  this.mpl = this.mp & 32767;
  this.mph = this.mp >> 15;
  this.um = (1 << a.DB - 15) - 1;
  this.mt2 = 2 * a.t;
}
function montConvert(a) {
  var b = nbi();
  a.abs().dlShiftTo(this.m.t, b);
  b.divRemTo(this.m, null, b);
  if (a.s < 0 && b.compareTo(BigInteger.ZERO) > 0) {
    this.m.subTo(b, b);
  }
  return b;
}
function montRevert(a) {
  var b = nbi();
  a.copyTo(b);
  this.reduce(b);
  return b;
}
function montReduce(a) {
  while (a.t <= this.mt2) {
    a[a.t++] = 0;
  }
  for (var c = 0; c < this.m.t; ++c) {
    var b = a[c] & 32767;
    var d = b * this.mpl + ((b * this.mph + (a[c] >> 15) * this.mpl & this.um) << 15) & a.DM;
    b = c + this.m.t;
    a[b] += this.m.am(0, d, a, c, 0, this.m.t);
    while (a[b] >= a.DV) {
      a[b] -= a.DV;
      a[++b]++;
    }
  }
  a.clamp();
  a.drShiftTo(this.m.t, a);
  if (a.compareTo(this.m) >= 0) {
    a.subTo(this.m, a);
  }
}
function montSqrTo(a, b) {
  a.squareTo(b);
  this.reduce(b);
}
function montMulTo(a, c, b) {
  a.multiplyTo(c, b);
  this.reduce(b);
}
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
function bnpIsEven() {
  return (this.t > 0 ? this[0] & 1 : this.s) == 0;
}
function bnpExp(h, j) {
  if (h > 4294967295 || h < 1) {
    return BigInteger.ONE;
  }
  var f = nbi(),
    a = nbi(),
    d = j.convert(this),
    c = nbits(h) - 1;
  d.copyTo(f);
  while (--c >= 0) {
    j.sqrTo(f, a);
    if ((h & 1 << c) > 0) {
      j.mulTo(a, d, f);
    } else {
      var b = f;
      f = a;
      a = b;
    }
  }
  return j.revert(f);
}
function bnModPowInt(b, a) {
  var c;
  if (b < 256 || a.isEven()) {
    c = new Classic(a);
  } else {
    c = new Montgomery(a);
  }
  return this.exp(b, c);
}
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
function bnClone() {
  var a = nbi();
  this.copyTo(a);
  return a;
}
function bnIntValue() {
  if (this.s < 0) {
    if (this.t == 1) {
      return this[0] - this.DV;
    } else {
      if (this.t == 0) {
        return -1;
      }
    }
  } else {
    if (this.t == 1) {
      return this[0];
    } else {
      if (this.t == 0) {
        return 0;
      }
    }
  }
  return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
}
function bnByteValue() {
  return this.t == 0 ? this.s : this[0] << 24 >> 24;
}
function bnShortValue() {
  return this.t == 0 ? this.s : this[0] << 16 >> 16;
}
function bnpChunkSize(a) {
  return Math.floor(Math.LN2 * this.DB / Math.log(a));
}
function bnSigNum() {
  if (this.s < 0) {
    return -1;
  } else {
    if (this.t <= 0 || this.t == 1 && this[0] <= 0) {
      return 0;
    } else {
      return 1;
    }
  }
}
function bnpToRadix(c) {
  if (c == null) {
    c = 10;
  }
  if (this.signum() == 0 || c < 2 || c > 36) {
    return "0";
  }
  var f = this.chunkSize(c);
  var e = Math.pow(c, f);
  var i = nbv(e),
    j = nbi(),
    h = nbi(),
    g = "";
  this.divRemTo(i, j, h);
  while (j.signum() > 0) {
    g = (e + h.intValue()).toString(c).substr(1) + g;
    j.divRemTo(i, j, h);
  }
  return h.intValue().toString(c) + g;
}
function bnpFromRadix(m, h) {
  this.fromInt(0);
  if (h == null) {
    h = 10;
  }
  var f = this.chunkSize(h);
  var g = Math.pow(h, f),
    e = false,
    a = 0,
    l = 0;
  for (var c = 0; c < m.length; ++c) {
    var k = intAt(m, c);
    if (k < 0) {
      if (m.charAt(c) == "-" && this.signum() == 0) {
        e = true;
      }
      continue;
    }
    l = h * l + k;
    if (++a >= f) {
      this.dMultiply(g);
      this.dAddOffset(l, 0);
      a = 0;
      l = 0;
    }
  }
  if (a > 0) {
    this.dMultiply(Math.pow(h, a));
    this.dAddOffset(l, 0);
  }
  if (e) {
    BigInteger.ZERO.subTo(this, this);
  }
}
function bnpFromNumber(f, e, h) {
  if ("number" == typeof e) {
    if (f < 2) {
      this.fromInt(1);
    } else {
      this.fromNumber(f, h);
      if (!this.testBit(f - 1)) {
        this.bitwiseTo(BigInteger.ONE.shiftLeft(f - 1), op_or, this);
      }
      if (this.isEven()) {
        this.dAddOffset(1, 0);
      }
      while (!this.isProbablePrime(e)) {
        this.dAddOffset(2, 0);
        if (this.bitLength() > f) {
          this.subTo(BigInteger.ONE.shiftLeft(f - 1), this);
        }
      }
    }
  } else {
    var d = new Array(),
      g = f & 7;
    d.length = (f >> 3) + 1;
    e.nextBytes(d);
    if (g > 0) {
      d[0] &= (1 << g) - 1;
    } else {
      d[0] = 0;
    }
    this.fromString(d, 256);
  }
}
function bnToByteArray() {
  var b = this.t,
    c = new Array();
  c[0] = this.s;
  var e = this.DB - b * this.DB % 8,
    f,
    a = 0;
  if (b-- > 0) {
    if (e < this.DB && (f = this[b] >> e) != (this.s & this.DM) >> e) {
      c[a++] = f | this.s << this.DB - e;
    }
    while (b >= 0) {
      if (e < 8) {
        f = (this[b] & (1 << e) - 1) << 8 - e;
        f |= this[--b] >> (e += this.DB - 8);
      } else {
        f = this[b] >> (e -= 8) & 255;
        if (e <= 0) {
          e += this.DB;
          --b;
        }
      }
      if ((f & 128) != 0) {
        f |= -256;
      }
      if (a == 0 && (this.s & 128) != (f & 128)) {
        ++a;
      }
      if (a > 0 || f != this.s) {
        c[a++] = f;
      }
    }
  }
  return c;
}
function bnEquals(b) {
  return this.compareTo(b) == 0;
}
function bnMin(b) {
  return this.compareTo(b) < 0 ? this : b;
}
function bnMax(b) {
  return this.compareTo(b) > 0 ? this : b;
}
function bnpBitwiseTo(c, h, e) {
  var d,
    g,
    b = Math.min(c.t, this.t);
  for (d = 0; d < b; ++d) {
    e[d] = h(this[d], c[d]);
  }
  if (c.t < this.t) {
    g = c.s & this.DM;
    for (d = b; d < this.t; ++d) {
      e[d] = h(this[d], g);
    }
    e.t = this.t;
  } else {
    g = this.s & this.DM;
    for (d = b; d < c.t; ++d) {
      e[d] = h(g, c[d]);
    }
    e.t = c.t;
  }
  e.s = h(this.s, c.s);
  e.clamp();
}
function op_and(a, b) {
  return a & b;
}
function bnAnd(b) {
  var c = nbi();
  this.bitwiseTo(b, op_and, c);
  return c;
}
function op_or(a, b) {
  return a | b;
}
function bnOr(b) {
  var c = nbi();
  this.bitwiseTo(b, op_or, c);
  return c;
}
function op_xor(a, b) {
  return a ^ b;
}
function bnXor(b) {
  var c = nbi();
  this.bitwiseTo(b, op_xor, c);
  return c;
}
function op_andnot(a, b) {
  return a & ~b;
}
function bnAndNot(b) {
  var c = nbi();
  this.bitwiseTo(b, op_andnot, c);
  return c;
}
function bnNot() {
  var b = nbi();
  for (var a = 0; a < this.t; ++a) {
    b[a] = this.DM & ~this[a];
  }
  b.t = this.t;
  b.s = ~this.s;
  return b;
}
function bnShiftLeft(b) {
  var a = nbi();
  if (b < 0) {
    this.rShiftTo(-b, a);
  } else {
    this.lShiftTo(b, a);
  }
  return a;
}
function bnShiftRight(b) {
  var a = nbi();
  if (b < 0) {
    this.lShiftTo(-b, a);
  } else {
    this.rShiftTo(b, a);
  }
  return a;
}
function lbit(a) {
  if (a == 0) {
    return -1;
  }
  var b = 0;
  if ((a & 65535) == 0) {
    a >>= 16;
    b += 16;
  }
  if ((a & 255) == 0) {
    a >>= 8;
    b += 8;
  }
  if ((a & 15) == 0) {
    a >>= 4;
    b += 4;
  }
  if ((a & 3) == 0) {
    a >>= 2;
    b += 2;
  }
  if ((a & 1) == 0) {
    ++b;
  }
  return b;
}
function bnGetLowestSetBit() {
  for (var a = 0; a < this.t; ++a) {
    if (this[a] != 0) {
      return a * this.DB + lbit(this[a]);
    }
  }
  if (this.s < 0) {
    return this.t * this.DB;
  }
  return -1;
}
function cbit(a) {
  var b = 0;
  while (a != 0) {
    a &= a - 1;
    ++b;
  }
  return b;
}
function bnBitCount() {
  var c = 0,
    a = this.s & this.DM;
  for (var b = 0; b < this.t; ++b) {
    c += cbit(this[b] ^ a);
  }
  return c;
}
function bnTestBit(b) {
  var a = Math.floor(b / this.DB);
  if (a >= this.t) {
    return this.s != 0;
  }
  return (this[a] & 1 << b % this.DB) != 0;
}
function bnpChangeBit(c, b) {
  var a = BigInteger.ONE.shiftLeft(c);
  this.bitwiseTo(a, b, a);
  return a;
}
function bnSetBit(a) {
  return this.changeBit(a, op_or);
}
function bnClearBit(a) {
  return this.changeBit(a, op_andnot);
}
function bnFlipBit(a) {
  return this.changeBit(a, op_xor);
}
function bnpAddTo(d, f) {
  var e = 0,
    g = 0,
    b = Math.min(d.t, this.t);
  while (e < b) {
    g += this[e] + d[e];
    f[e++] = g & this.DM;
    g >>= this.DB;
  }
  if (d.t < this.t) {
    g += d.s;
    while (e < this.t) {
      g += this[e];
      f[e++] = g & this.DM;
      g >>= this.DB;
    }
    g += this.s;
  } else {
    g += this.s;
    while (e < d.t) {
      g += d[e];
      f[e++] = g & this.DM;
      g >>= this.DB;
    }
    g += d.s;
  }
  f.s = g < 0 ? -1 : 0;
  if (g > 0) {
    f[e++] = g;
  } else {
    if (g < -1) {
      f[e++] = this.DV + g;
    }
  }
  f.t = e;
  f.clamp();
}
function bnAdd(b) {
  var c = nbi();
  this.addTo(b, c);
  return c;
}
function bnSubtract(b) {
  var c = nbi();
  this.subTo(b, c);
  return c;
}
function bnMultiply(b) {
  var c = nbi();
  this.multiplyTo(b, c);
  return c;
}
function bnSquare() {
  var a = nbi();
  this.squareTo(a);
  return a;
}
function bnDivide(b) {
  var c = nbi();
  this.divRemTo(b, c, null);
  return c;
}
function bnRemainder(b) {
  var c = nbi();
  this.divRemTo(b, null, c);
  return c;
}
function bnDivideAndRemainder(b) {
  var d = nbi(),
    c = nbi();
  this.divRemTo(b, d, c);
  return new Array(d, c);
}
function bnpDMultiply(a) {
  this[this.t] = this.am(0, a - 1, this, 0, 0, this.t);
  ++this.t;
  this.clamp();
}
function bnpDAddOffset(b, a) {
  if (b == 0) {
    return;
  }
  while (this.t <= a) {
    this[this.t++] = 0;
  }
  this[a] += b;
  while (this[a] >= this.DV) {
    this[a] -= this.DV;
    if (++a >= this.t) {
      this[this.t++] = 0;
    }
    ++this[a];
  }
}
function NullExp() {}
function nNop(a) {
  return a;
}
function nMulTo(a, c, b) {
  a.multiplyTo(c, b);
}
function nSqrTo(a, b) {
  a.squareTo(b);
}
NullExp.prototype.convert = nNop;
NullExp.prototype.revert = nNop;
NullExp.prototype.mulTo = nMulTo;
NullExp.prototype.sqrTo = nSqrTo;
function bnPow(a) {
  return this.exp(a, new NullExp());
}
function bnpMultiplyLowerTo(b, f, e) {
  var d = Math.min(this.t + b.t, f);
  e.s = 0;
  e.t = d;
  while (d > 0) {
    e[--d] = 0;
  }
  var c;
  for (c = e.t - this.t; d < c; ++d) {
    e[d + this.t] = this.am(0, b[d], e, d, 0, this.t);
  }
  for (c = Math.min(b.t, f); d < c; ++d) {
    this.am(0, b[d], e, d, 0, f - d);
  }
  e.clamp();
}
function bnpMultiplyUpperTo(b, e, d) {
  --e;
  var c = d.t = this.t + b.t - e;
  d.s = 0;
  while (--c >= 0) {
    d[c] = 0;
  }
  for (c = Math.max(e - this.t, 0); c < b.t; ++c) {
    d[this.t + c - e] = this.am(e - c, b[c], d, 0, 0, this.t + c - e);
  }
  d.clamp();
  d.drShiftTo(1, d);
}
function Barrett(a) {
  this.r2 = nbi();
  this.q3 = nbi();
  BigInteger.ONE.dlShiftTo(2 * a.t, this.r2);
  this.mu = this.r2.divide(a);
  this.m = a;
}
function barrettConvert(a) {
  if (a.s < 0 || a.t > 2 * this.m.t) {
    return a.mod(this.m);
  } else {
    if (a.compareTo(this.m) < 0) {
      return a;
    } else {
      var b = nbi();
      a.copyTo(b);
      this.reduce(b);
      return b;
    }
  }
}
function barrettRevert(a) {
  return a;
}
function barrettReduce(a) {
  a.drShiftTo(this.m.t - 1, this.r2);
  if (a.t > this.m.t + 1) {
    a.t = this.m.t + 1;
    a.clamp();
  }
  this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
  this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
  while (a.compareTo(this.r2) < 0) {
    a.dAddOffset(1, this.m.t + 1);
  }
  a.subTo(this.r2, a);
  while (a.compareTo(this.m) >= 0) {
    a.subTo(this.m, a);
  }
}
function barrettSqrTo(a, b) {
  a.squareTo(b);
  this.reduce(b);
}
function barrettMulTo(a, c, b) {
  a.multiplyTo(c, b);
  this.reduce(b);
}
Barrett.prototype.convert = barrettConvert;
Barrett.prototype.revert = barrettRevert;
Barrett.prototype.reduce = barrettReduce;
Barrett.prototype.mulTo = barrettMulTo;
Barrett.prototype.sqrTo = barrettSqrTo;
function bnModPow(q, f) {
  var o = q.bitLength(),
    h,
    b = nbv(1),
    v;
  if (o <= 0) {
    return b;
  } else {
    if (o < 18) {
      h = 1;
    } else {
      if (o < 48) {
        h = 3;
      } else {
        if (o < 144) {
          h = 4;
        } else {
          if (o < 768) {
            h = 5;
          } else {
            h = 6;
          }
        }
      }
    }
  }
  if (o < 8) {
    v = new Classic(f);
  } else {
    if (f.isEven()) {
      v = new Barrett(f);
    } else {
      v = new Montgomery(f);
    }
  }
  var p = new Array(),
    d = 3,
    s = h - 1,
    a = (1 << h) - 1;
  p[1] = v.convert(this);
  if (h > 1) {
    var A = nbi();
    v.sqrTo(p[1], A);
    while (d <= a) {
      p[d] = nbi();
      v.mulTo(A, p[d - 2], p[d]);
      d += 2;
    }
  }
  var l = q.t - 1,
    x,
    u = true,
    c = nbi(),
    y;
  o = nbits(q[l]) - 1;
  while (l >= 0) {
    if (o >= s) {
      x = q[l] >> o - s & a;
    } else {
      x = (q[l] & (1 << o + 1) - 1) << s - o;
      if (l > 0) {
        x |= q[l - 1] >> this.DB + o - s;
      }
    }
    d = h;
    while ((x & 1) == 0) {
      x >>= 1;
      --d;
    }
    if ((o -= d) < 0) {
      o += this.DB;
      --l;
    }
    if (u) {
      p[x].copyTo(b);
      u = false;
    } else {
      while (d > 1) {
        v.sqrTo(b, c);
        v.sqrTo(c, b);
        d -= 2;
      }
      if (d > 0) {
        v.sqrTo(b, c);
      } else {
        y = b;
        b = c;
        c = y;
      }
      v.mulTo(c, p[x], b);
    }
    while (l >= 0 && (q[l] & 1 << o) == 0) {
      v.sqrTo(b, c);
      y = b;
      b = c;
      c = y;
      if (--o < 0) {
        o = this.DB - 1;
        --l;
      }
    }
  }
  return v.revert(b);
}
function bnGCD(c) {
  var b = this.s < 0 ? this.negate() : this.clone();
  var h = c.s < 0 ? c.negate() : c.clone();
  if (b.compareTo(h) < 0) {
    var e = b;
    b = h;
    h = e;
  }
  var d = b.getLowestSetBit(),
    f = h.getLowestSetBit();
  if (f < 0) {
    return b;
  }
  if (d < f) {
    f = d;
  }
  if (f > 0) {
    b.rShiftTo(f, b);
    h.rShiftTo(f, h);
  }
  while (b.signum() > 0) {
    if ((d = b.getLowestSetBit()) > 0) {
      b.rShiftTo(d, b);
    }
    if ((d = h.getLowestSetBit()) > 0) {
      h.rShiftTo(d, h);
    }
    if (b.compareTo(h) >= 0) {
      b.subTo(h, b);
      b.rShiftTo(1, b);
    } else {
      h.subTo(b, h);
      h.rShiftTo(1, h);
    }
  }
  if (f > 0) {
    h.lShiftTo(f, h);
  }
  return h;
}
function bnpModInt(e) {
  if (e <= 0) {
    return 0;
  }
  var c = this.DV % e,
    b = this.s < 0 ? e - 1 : 0;
  if (this.t > 0) {
    if (c == 0) {
      b = this[0] % e;
    } else {
      for (var a = this.t - 1; a >= 0; --a) {
        b = (c * b + this[a]) % e;
      }
    }
  }
  return b;
}
function bnModInverse(f) {
  var j = f.isEven();
  if (this.isEven() && j || f.signum() == 0) {
    return BigInteger.ZERO;
  }
  var i = f.clone(),
    h = this.clone();
  var g = nbv(1),
    e = nbv(0),
    l = nbv(0),
    k = nbv(1);
  while (i.signum() != 0) {
    while (i.isEven()) {
      i.rShiftTo(1, i);
      if (j) {
        if (!g.isEven() || !e.isEven()) {
          g.addTo(this, g);
          e.subTo(f, e);
        }
        g.rShiftTo(1, g);
      } else {
        if (!e.isEven()) {
          e.subTo(f, e);
        }
      }
      e.rShiftTo(1, e);
    }
    while (h.isEven()) {
      h.rShiftTo(1, h);
      if (j) {
        if (!l.isEven() || !k.isEven()) {
          l.addTo(this, l);
          k.subTo(f, k);
        }
        l.rShiftTo(1, l);
      } else {
        if (!k.isEven()) {
          k.subTo(f, k);
        }
      }
      k.rShiftTo(1, k);
    }
    if (i.compareTo(h) >= 0) {
      i.subTo(h, i);
      if (j) {
        g.subTo(l, g);
      }
      e.subTo(k, e);
    } else {
      h.subTo(i, h);
      if (j) {
        l.subTo(g, l);
      }
      k.subTo(e, k);
    }
  }
  if (h.compareTo(BigInteger.ONE) != 0) {
    return BigInteger.ZERO;
  }
  if (k.compareTo(f) >= 0) {
    return k.subtract(f);
  }
  if (k.signum() < 0) {
    k.addTo(f, k);
  } else {
    return k;
  }
  if (k.signum() < 0) {
    return k.add(f);
  } else {
    return k;
  }
}
var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
function bnIsProbablePrime(e) {
  var d,
    b = this.abs();
  if (b.t == 1 && b[0] <= lowprimes[lowprimes.length - 1]) {
    for (d = 0; d < lowprimes.length; ++d) {
      if (b[0] == lowprimes[d]) {
        return true;
      }
    }
    return false;
  }
  if (b.isEven()) {
    return false;
  }
  d = 1;
  while (d < lowprimes.length) {
    var a = lowprimes[d],
      c = d + 1;
    while (c < lowprimes.length && a < lplim) {
      a *= lowprimes[c++];
    }
    a = b.modInt(a);
    while (d < c) {
      if (a % lowprimes[d++] == 0) {
        return false;
      }
    }
  }
  return b.millerRabin(e);
}
function bnpMillerRabin(f) {
  var g = this.subtract(BigInteger.ONE);
  var c = g.getLowestSetBit();
  if (c <= 0) {
    return false;
  }
  var h = g.shiftRight(c);
  f = f + 1 >> 1;
  if (f > lowprimes.length) {
    f = lowprimes.length;
  }
  var b = nbi();
  for (var e = 0; e < f; ++e) {
    b.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
    var l = b.modPow(h, this);
    if (l.compareTo(BigInteger.ONE) != 0 && l.compareTo(g) != 0) {
      var d = 1;
      while (d++ < c && l.compareTo(g) != 0) {
        l = l.modPowInt(2, this);
        if (l.compareTo(BigInteger.ONE) == 0) {
          return false;
        }
      }
      if (l.compareTo(g) != 0) {
        return false;
      }
    }
  }
  return true;
}
BigInteger.prototype.chunkSize = bnpChunkSize;
BigInteger.prototype.toRadix = bnpToRadix;
BigInteger.prototype.fromRadix = bnpFromRadix;
BigInteger.prototype.fromNumber = bnpFromNumber;
BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
BigInteger.prototype.changeBit = bnpChangeBit;
BigInteger.prototype.addTo = bnpAddTo;
BigInteger.prototype.dMultiply = bnpDMultiply;
BigInteger.prototype.dAddOffset = bnpDAddOffset;
BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
BigInteger.prototype.modInt = bnpModInt;
BigInteger.prototype.millerRabin = bnpMillerRabin;
BigInteger.prototype.clone = bnClone;
BigInteger.prototype.intValue = bnIntValue;
BigInteger.prototype.byteValue = bnByteValue;
BigInteger.prototype.shortValue = bnShortValue;
BigInteger.prototype.signum = bnSigNum;
BigInteger.prototype.toByteArray = bnToByteArray;
BigInteger.prototype.equals = bnEquals;
BigInteger.prototype.min = bnMin;
BigInteger.prototype.max = bnMax;
BigInteger.prototype.and = bnAnd;
BigInteger.prototype.or = bnOr;
BigInteger.prototype.xor = bnXor;
BigInteger.prototype.andNot = bnAndNot;
BigInteger.prototype.not = bnNot;
BigInteger.prototype.shiftLeft = bnShiftLeft;
BigInteger.prototype.shiftRight = bnShiftRight;
BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
BigInteger.prototype.bitCount = bnBitCount;
BigInteger.prototype.testBit = bnTestBit;
BigInteger.prototype.setBit = bnSetBit;
BigInteger.prototype.clearBit = bnClearBit;
BigInteger.prototype.flipBit = bnFlipBit;
BigInteger.prototype.add = bnAdd;
BigInteger.prototype.subtract = bnSubtract;
BigInteger.prototype.multiply = bnMultiply;
BigInteger.prototype.divide = bnDivide;
BigInteger.prototype.remainder = bnRemainder;
BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
BigInteger.prototype.modPow = bnModPow;
BigInteger.prototype.modInverse = bnModInverse;
BigInteger.prototype.pow = bnPow;
BigInteger.prototype.gcd = bnGCD;
BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
BigInteger.prototype.square = bnSquare;
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
function Arcfour() {
  this.i = 0;
  this.j = 0;
  this.S = new Array();
}
function ARC4init(d) {
  var c, a, b;
  for (c = 0; c < 256; ++c) {
    this.S[c] = c;
  }
  a = 0;
  for (c = 0; c < 256; ++c) {
    a = a + this.S[c] + d[c % d.length] & 255;
    b = this.S[c];
    this.S[c] = this.S[a];
    this.S[a] = b;
  }
  this.i = 0;
  this.j = 0;
}
function ARC4next() {
  var a;
  this.i = this.i + 1 & 255;
  this.j = this.j + this.S[this.i] & 255;
  a = this.S[this.i];
  this.S[this.i] = this.S[this.j];
  this.S[this.j] = a;
  return this.S[a + this.S[this.i] & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
function prng_newstate() {
  return new Arcfour();
}
var rng_psize = 256;
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
var rng_state;
var rng_pool;
var rng_pptr;
function rng_seed_int(a) {
  rng_pool[rng_pptr++] ^= a & 255;
  rng_pool[rng_pptr++] ^= a >> 8 & 255;
  rng_pool[rng_pptr++] ^= a >> 16 & 255;
  rng_pool[rng_pptr++] ^= a >> 24 & 255;
  if (rng_pptr >= rng_psize) {
    rng_pptr -= rng_psize;
  }
}
function rng_seed_time() {
  rng_seed_int(new Date().getTime());
}
if (rng_pool == null) {
  rng_pool = new Array();
  rng_pptr = 0;
  var t;
  if (window !== undefined && (window.crypto !== undefined || window.msCrypto !== undefined)) {
    var crypto = window.crypto || window.msCrypto;
    if (crypto.getRandomValues) {
      var ua = new Uint8Array(32);
      crypto.getRandomValues(ua);
      for (t = 0; t < 32; ++t) {
        rng_pool[rng_pptr++] = ua[t];
      }
    } else {
      if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
        var z = window.crypto.random(32);
        for (t = 0; t < z.length; ++t) {
          rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
        }
      }
    }
  }
  while (rng_pptr < rng_psize) {
    t = Math.floor(65536 * Math.random());
    rng_pool[rng_pptr++] = t >>> 8;
    rng_pool[rng_pptr++] = t & 255;
  }
  rng_pptr = 0;
  rng_seed_time();
}
function rng_get_byte() {
  if (rng_state == null) {
    rng_seed_time();
    rng_state = prng_newstate();
    rng_state.init(rng_pool);
    for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
      rng_pool[rng_pptr] = 0;
    }
    rng_pptr = 0;
  }
  return rng_state.next();
}
function rng_get_bytes(b) {
  var a;
  for (a = 0; a < b.length; ++a) {
    b[a] = rng_get_byte();
  }
}
function SecureRandom() {}
SecureRandom.prototype.nextBytes = rng_get_bytes;
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
function parseBigInt(b, a) {
  return new BigInteger(b, a);
}
function linebrk(c, d) {
  var a = "";
  var b = 0;
  while (b + d < c.length) {
    a += c.substring(b, b + d) + "\n";
    b += d;
  }
  return a + c.substring(b, c.length);
}
function byte2Hex(a) {
  if (a < 16) {
    return "0" + a.toString(16);
  } else {
    return a.toString(16);
  }
}
function pkcs1pad2(e, h) {
  if (h < e.length + 11) {
    throw "Message too long for RSA";
    return null;
  }
  var g = new Array();
  var d = e.length - 1;
  while (d >= 0 && h > 0) {
    var f = e.charCodeAt(d--);
    if (f < 128) {
      g[--h] = f;
    } else {
      if (f > 127 && f < 2048) {
        g[--h] = f & 63 | 128;
        g[--h] = f >> 6 | 192;
      } else {
        g[--h] = f & 63 | 128;
        g[--h] = f >> 6 & 63 | 128;
        g[--h] = f >> 12 | 224;
      }
    }
  }
  g[--h] = 0;
  var b = new SecureRandom();
  var a = new Array();
  while (h > 2) {
    a[0] = 0;
    while (a[0] == 0) {
      b.nextBytes(a);
    }
    g[--h] = a[0];
  }
  g[--h] = 2;
  g[--h] = 0;
  return new BigInteger(g);
}
function oaep_mgf1_arr(c, a, e) {
  var b = "",
    d = 0;
  while (b.length < a) {
    b += e(String.fromCharCode.apply(String, c.concat([(d & 4278190080) >> 24, (d & 16711680) >> 16, (d & 65280) >> 8, d & 255])));
    d += 1;
  }
  return b;
}
function oaep_pad(q, a, f, l) {
  var c = KJUR.crypto.MessageDigest;
  var o = KJUR.crypto.Util;
  var b = null;
  if (!f) {
    f = "sha1";
  }
  if (typeof f === "string") {
    b = c.getCanonicalAlgName(f);
    l = c.getHashLength(b);
    f = function (i) {
      return hextorstr(o.hashHex(rstrtohex(i), b));
    };
  }
  if (q.length + 2 * l + 2 > a) {
    throw "Message too long for RSA";
  }
  var k = "",
    e;
  for (e = 0; e < a - q.length - 2 * l - 2; e += 1) {
    k += "\x00";
  }
  var h = f("") + k + "\x01" + q;
  var g = new Array(l);
  new SecureRandom().nextBytes(g);
  var j = oaep_mgf1_arr(g, h.length, f);
  var p = [];
  for (e = 0; e < h.length; e += 1) {
    p[e] = h.charCodeAt(e) ^ j.charCodeAt(e);
  }
  var m = oaep_mgf1_arr(p, g.length, f);
  var d = [0];
  for (e = 0; e < g.length; e += 1) {
    d[e + 1] = g[e] ^ m.charCodeAt(e);
  }
  return new BigInteger(d.concat(p));
}
function RSAKey() {
  this.n = null;
  this.e = 0;
  this.d = null;
  this.p = null;
  this.q = null;
  this.dmp1 = null;
  this.dmq1 = null;
  this.coeff = null;
}
function RSASetPublic(b, a) {
  this.isPublic = true;
  this.isPrivate = false;
  if (typeof b !== "string") {
    this.n = b;
    this.e = a;
  } else {
    if (b != null && a != null && b.length > 0 && a.length > 0) {
      this.n = parseBigInt(b, 16);
      this.e = parseInt(a, 16);
    } else {
      throw "Invalid RSA public key";
    }
  }
}
function RSADoPublic(a) {
  return a.modPowInt(this.e, this.n);
}
RSAKey.prototype.doPublic = RSADoPublic;
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.type = "RSA";
/*! (c) Tom Wu, Kenji Urushima | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
function pkcs1unpad2(g, j) {
  var a = g.toByteArray();
  var f = 0;
  while (f < a.length && a[f] == 0) {
    ++f;
  }
  if (a.length - f != j - 1 || a[f] != 2) {
    return null;
  }
  ++f;
  while (a[f] != 0) {
    if (++f >= a.length) {
      return null;
    }
  }
  var e = "";
  while (++f < a.length) {
    var h = a[f] & 255;
    if (h < 128) {
      e += String.fromCharCode(h);
    } else {
      if (h > 191 && h < 224) {
        e += String.fromCharCode((h & 31) << 6 | a[f + 1] & 63);
        ++f;
      } else {
        e += String.fromCharCode((h & 15) << 12 | (a[f + 1] & 63) << 6 | a[f + 2] & 63);
        f += 2;
      }
    }
  }
  return e;
}
function oaep_mgf1_str(c, a, e) {
  var b = "",
    d = 0;
  while (b.length < a) {
    b += e(c + String.fromCharCode.apply(String, [(d & 4278190080) >> 24, (d & 16711680) >> 16, (d & 65280) >> 8, d & 255]));
    d += 1;
  }
  return b;
}
function oaep_unpad(o, b, g, p) {
  var e = KJUR.crypto.MessageDigest;
  var r = KJUR.crypto.Util;
  var c = null;
  if (!g) {
    g = "sha1";
  }
  if (typeof g === "string") {
    c = e.getCanonicalAlgName(g);
    p = e.getHashLength(c);
    g = function (d) {
      return hextorstr(r.hashHex(rstrtohex(d), c));
    };
  }
  o = o.toByteArray();
  var h;
  for (h = 0; h < o.length; h += 1) {
    o[h] &= 255;
  }
  while (o.length < b) {
    o.unshift(0);
  }
  o = String.fromCharCode.apply(String, o);
  if (o.length < 2 * p + 2) {
    throw "Cipher too short";
  }
  var f = o.substr(1, p);
  var s = o.substr(p + 1);
  var q = oaep_mgf1_str(s, p, g);
  var k = [],
    h;
  for (h = 0; h < f.length; h += 1) {
    k[h] = f.charCodeAt(h) ^ q.charCodeAt(h);
  }
  var l = oaep_mgf1_str(String.fromCharCode.apply(String, k), o.length - p, g);
  var j = [];
  for (h = 0; h < s.length; h += 1) {
    j[h] = s.charCodeAt(h) ^ l.charCodeAt(h);
  }
  j = String.fromCharCode.apply(String, j);
  if (j.substr(0, p) !== g("")) {
    throw "Hash mismatch";
  }
  j = j.substr(p);
  var a = j.indexOf("\x01");
  var m = a != -1 ? j.substr(0, a).lastIndexOf("\x00") : -1;
  if (m + 1 != a) {
    throw "Malformed data";
  }
  return j.substr(a + 1);
}
function RSASetPrivate(c, a, b) {
  this.isPrivate = true;
  if (typeof c !== "string") {
    this.n = c;
    this.e = a;
    this.d = b;
  } else {
    if (c != null && a != null && c.length > 0 && a.length > 0) {
      this.n = parseBigInt(c, 16);
      this.e = parseInt(a, 16);
      this.d = parseBigInt(b, 16);
    } else {
      throw "Invalid RSA private key";
    }
  }
}
function RSASetPrivateEx(g, d, e, c, b, a, h, f) {
  this.isPrivate = true;
  this.isPublic = false;
  if (g == null) {
    throw "RSASetPrivateEx N == null";
  }
  if (d == null) {
    throw "RSASetPrivateEx E == null";
  }
  if (g.length == 0) {
    throw "RSASetPrivateEx N.length == 0";
  }
  if (d.length == 0) {
    throw "RSASetPrivateEx E.length == 0";
  }
  if (g != null && d != null && g.length > 0 && d.length > 0) {
    this.n = parseBigInt(g, 16);
    this.e = parseInt(d, 16);
    this.d = parseBigInt(e, 16);
    this.p = parseBigInt(c, 16);
    this.q = parseBigInt(b, 16);
    this.dmp1 = parseBigInt(a, 16);
    this.dmq1 = parseBigInt(h, 16);
    this.coeff = parseBigInt(f, 16);
  } else {
    throw "Invalid RSA private key in RSASetPrivateEx";
  }
}
function RSAGenerate(b, l) {
  var a = new SecureRandom();
  var g = b >> 1;
  this.e = parseInt(l, 16);
  var c = new BigInteger(l, 16);
  var d = b / 2 - 100;
  var k = BigInteger.ONE.shiftLeft(d);
  for (;;) {
    for (;;) {
      this.p = new BigInteger(b - g, 1, a);
      if (this.p.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
        break;
      }
    }
    for (;;) {
      this.q = new BigInteger(g, 1, a);
      if (this.q.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
        break;
      }
    }
    if (this.p.compareTo(this.q) <= 0) {
      var j = this.p;
      this.p = this.q;
      this.q = j;
    }
    var h = this.q.subtract(this.p).abs();
    if (h.bitLength() < d || h.compareTo(k) <= 0) {
      continue;
    }
    var i = this.p.subtract(BigInteger.ONE);
    var e = this.q.subtract(BigInteger.ONE);
    var f = i.multiply(e);
    if (f.gcd(c).compareTo(BigInteger.ONE) == 0) {
      this.n = this.p.multiply(this.q);
      if (this.n.bitLength() == b) {
        this.d = c.modInverse(f);
        this.dmp1 = this.d.mod(i);
        this.dmq1 = this.d.mod(e);
        this.coeff = this.q.modInverse(this.p);
        break;
      }
    }
  }
  this.isPrivate = true;
}
function RSADoPrivate(a) {
  if (this.p == null || this.q == null) {
    return a.modPow(this.d, this.n);
  }
  var c = a.mod(this.p).modPow(this.dmp1, this.p);
  var b = a.mod(this.q).modPow(this.dmq1, this.q);
  while (c.compareTo(b) < 0) {
    c = c.add(this.p);
  }
  return c.subtract(b).multiply(this.coeff).mod(this.p).multiply(this.q).add(b);
}
RSAKey.prototype.doPrivate = RSADoPrivate;
RSAKey.prototype.setPrivate = RSASetPrivate;
RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
RSAKey.prototype.generate = RSAGenerate;
/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
 */
function ECFieldElementFp(b, a) {
  this.x = a;
  this.q = b;
}
function feFpEquals(a) {
  if (a == this) {
    return true;
  }
  return this.q.equals(a.q) && this.x.equals(a.x);
}
function feFpToBigInteger() {
  return this.x;
}
function feFpNegate() {
  return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
}
function feFpAdd(a) {
  return new ECFieldElementFp(this.q, this.x.add(a.toBigInteger()).mod(this.q));
}
function feFpSubtract(a) {
  return new ECFieldElementFp(this.q, this.x.subtract(a.toBigInteger()).mod(this.q));
}
function feFpMultiply(a) {
  return new ECFieldElementFp(this.q, this.x.multiply(a.toBigInteger()).mod(this.q));
}
function feFpSquare() {
  return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
}
function feFpDivide(a) {
  return new ECFieldElementFp(this.q, this.x.multiply(a.toBigInteger().modInverse(this.q)).mod(this.q));
}
ECFieldElementFp.prototype.equals = feFpEquals;
ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
ECFieldElementFp.prototype.negate = feFpNegate;
ECFieldElementFp.prototype.add = feFpAdd;
ECFieldElementFp.prototype.subtract = feFpSubtract;
ECFieldElementFp.prototype.multiply = feFpMultiply;
ECFieldElementFp.prototype.square = feFpSquare;
ECFieldElementFp.prototype.divide = feFpDivide;
ECFieldElementFp.prototype.sqrt = function () {
  return new ECFieldElementFp(this.q, this.x.sqrt().mod(this.q));
};
function ECPointFp(c, a, d, b) {
  this.curve = c;
  this.x = a;
  this.y = d;
  if (b == null) {
    this.z = BigInteger.ONE;
  } else {
    this.z = b;
  }
  this.zinv = null;
}
function pointFpGetX() {
  if (this.zinv == null) {
    this.zinv = this.z.modInverse(this.curve.q);
  }
  return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
}
function pointFpGetY() {
  if (this.zinv == null) {
    this.zinv = this.z.modInverse(this.curve.q);
  }
  return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
}
function pointFpEquals(a) {
  if (a == this) {
    return true;
  }
  if (this.isInfinity()) {
    return a.isInfinity();
  }
  if (a.isInfinity()) {
    return this.isInfinity();
  }
  var c, b;
  c = a.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(a.z)).mod(this.curve.q);
  if (!c.equals(BigInteger.ZERO)) {
    return false;
  }
  b = a.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(a.z)).mod(this.curve.q);
  return b.equals(BigInteger.ZERO);
}
function pointFpIsInfinity() {
  if (this.x == null && this.y == null) {
    return true;
  }
  return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
}
function pointFpNegate() {
  return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
}
function pointFpAdd(l) {
  if (this.isInfinity()) {
    return l;
  }
  if (l.isInfinity()) {
    return this;
  }
  var p = l.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(l.z)).mod(this.curve.q);
  var o = l.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(l.z)).mod(this.curve.q);
  if (BigInteger.ZERO.equals(o)) {
    if (BigInteger.ZERO.equals(p)) {
      return this.twice();
    }
    return this.curve.getInfinity();
  }
  var j = new BigInteger("3");
  var e = this.x.toBigInteger();
  var n = this.y.toBigInteger();
  var c = l.x.toBigInteger();
  var k = l.y.toBigInteger();
  var m = o.square();
  var i = m.multiply(o);
  var d = e.multiply(m);
  var g = p.square().multiply(this.z);
  var a = g.subtract(d.shiftLeft(1)).multiply(l.z).subtract(i).multiply(o).mod(this.curve.q);
  var h = d.multiply(j).multiply(p).subtract(n.multiply(i)).subtract(g.multiply(p)).multiply(l.z).add(p.multiply(i)).mod(this.curve.q);
  var f = i.multiply(this.z).multiply(l.z).mod(this.curve.q);
  return new ECPointFp(this.curve, this.curve.fromBigInteger(a), this.curve.fromBigInteger(h), f);
}
function pointFpTwice() {
  if (this.isInfinity()) {
    return this;
  }
  if (this.y.toBigInteger().signum() == 0) {
    return this.curve.getInfinity();
  }
  var g = new BigInteger("3");
  var c = this.x.toBigInteger();
  var h = this.y.toBigInteger();
  var e = h.multiply(this.z);
  var j = e.multiply(h).mod(this.curve.q);
  var i = this.curve.a.toBigInteger();
  var k = c.square().multiply(g);
  if (!BigInteger.ZERO.equals(i)) {
    k = k.add(this.z.square().multiply(i));
  }
  k = k.mod(this.curve.q);
  var b = k.square().subtract(c.shiftLeft(3).multiply(j)).shiftLeft(1).multiply(e).mod(this.curve.q);
  var f = k.multiply(g).multiply(c).subtract(j.shiftLeft(1)).shiftLeft(2).multiply(j).subtract(k.square().multiply(k)).mod(this.curve.q);
  var d = e.square().multiply(e).shiftLeft(3).mod(this.curve.q);
  return new ECPointFp(this.curve, this.curve.fromBigInteger(b), this.curve.fromBigInteger(f), d);
}
function pointFpMultiply(d) {
  if (this.isInfinity()) {
    return this;
  }
  if (d.signum() == 0) {
    return this.curve.getInfinity();
  }
  var m = d;
  var l = m.multiply(new BigInteger("3"));
  var b = this.negate();
  var j = this;
  var q = this.curve.q.subtract(d);
  var o = q.multiply(new BigInteger("3"));
  var c = new ECPointFp(this.curve, this.x, this.y);
  var a = c.negate();
  var g;
  for (g = l.bitLength() - 2; g > 0; --g) {
    j = j.twice();
    var n = l.testBit(g);
    var f = m.testBit(g);
    if (n != f) {
      j = j.add(n ? this : b);
    }
  }
  for (g = o.bitLength() - 2; g > 0; --g) {
    c = c.twice();
    var p = o.testBit(g);
    var r = q.testBit(g);
    if (p != r) {
      c = c.add(p ? c : a);
    }
  }
  return j;
}
function pointFpMultiplyTwo(c, a, b) {
  var d;
  if (c.bitLength() > b.bitLength()) {
    d = c.bitLength() - 1;
  } else {
    d = b.bitLength() - 1;
  }
  var f = this.curve.getInfinity();
  var e = this.add(a);
  while (d >= 0) {
    f = f.twice();
    if (c.testBit(d)) {
      if (b.testBit(d)) {
        f = f.add(e);
      } else {
        f = f.add(this);
      }
    } else {
      if (b.testBit(d)) {
        f = f.add(a);
      }
    }
    --d;
  }
  return f;
}
ECPointFp.prototype.getX = pointFpGetX;
ECPointFp.prototype.getY = pointFpGetY;
ECPointFp.prototype.equals = pointFpEquals;
ECPointFp.prototype.isInfinity = pointFpIsInfinity;
ECPointFp.prototype.negate = pointFpNegate;
ECPointFp.prototype.add = pointFpAdd;
ECPointFp.prototype.twice = pointFpTwice;
ECPointFp.prototype.multiply = pointFpMultiply;
ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
function ECCurveFp(e, d, c) {
  this.q = e;
  this.a = this.fromBigInteger(d);
  this.b = this.fromBigInteger(c);
  this.infinity = new ECPointFp(this, null, null);
}
function curveFpGetQ() {
  return this.q;
}
function curveFpGetA() {
  return this.a;
}
function curveFpGetB() {
  return this.b;
}
function curveFpEquals(a) {
  if (a == this) {
    return true;
  }
  return this.q.equals(a.q) && this.a.equals(a.a) && this.b.equals(a.b);
}
function curveFpGetInfinity() {
  return this.infinity;
}
function curveFpFromBigInteger(a) {
  return new ECFieldElementFp(this.q, a);
}
function curveFpDecodePointHex(m) {
  switch (parseInt(m.substr(0, 2), 16)) {
    case 0:
      return this.infinity;
    case 2:
    case 3:
      var c = m.substr(0, 2);
      var l = m.substr(2);
      var j = this.fromBigInteger(new BigInteger(k, 16));
      var i = this.getA();
      var h = this.getB();
      var e = j.square().add(i).multiply(j).add(h);
      var g = e.sqrt();
      if (c == "03") {
        g = g.negate();
      }
      return new ECPointFp(this, j, g);
    case 4:
    case 6:
    case 7:
      var d = (m.length - 2) / 2;
      var k = m.substr(2, d);
      var f = m.substr(d + 2, d);
      return new ECPointFp(this, this.fromBigInteger(new BigInteger(k, 16)), this.fromBigInteger(new BigInteger(f, 16)));
    default:
      return null;
  }
}
ECCurveFp.prototype.getQ = curveFpGetQ;
ECCurveFp.prototype.getA = curveFpGetA;
ECCurveFp.prototype.getB = curveFpGetB;
ECCurveFp.prototype.equals = curveFpEquals;
ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib
 */
ECFieldElementFp.prototype.getByteLength = function () {
  return Math.floor((this.toBigInteger().bitLength() + 7) / 8);
};
ECPointFp.prototype.getEncoded = function (c) {
  var d = function (h, f) {
    var g = h.toByteArrayUnsigned();
    if (f < g.length) {
      g = g.slice(g.length - f);
    } else {
      while (f > g.length) {
        g.unshift(0);
      }
    }
    return g;
  };
  var a = this.getX().toBigInteger();
  var e = this.getY().toBigInteger();
  var b = d(a, 32);
  if (c) {
    if (e.isEven()) {
      b.unshift(2);
    } else {
      b.unshift(3);
    }
  } else {
    b.unshift(4);
    b = b.concat(d(e, 32));
  }
  return b;
};
ECPointFp.decodeFrom = function (g, c) {
  var f = c[0];
  var e = c.length - 1;
  var d = c.slice(1, 1 + e / 2);
  var b = c.slice(1 + e / 2, 1 + e);
  d.unshift(0);
  b.unshift(0);
  var a = new BigInteger(d);
  var h = new BigInteger(b);
  return new ECPointFp(g, g.fromBigInteger(a), g.fromBigInteger(h));
};
ECPointFp.decodeFromHex = function (g, c) {
  var f = c.substr(0, 2);
  var e = c.length - 2;
  var d = c.substr(2, e / 2);
  var b = c.substr(2 + e / 2, e / 2);
  var a = new BigInteger(d, 16);
  var h = new BigInteger(b, 16);
  return new ECPointFp(g, g.fromBigInteger(a), g.fromBigInteger(h));
};
ECPointFp.prototype.add2D = function (c) {
  if (this.isInfinity()) {
    return c;
  }
  if (c.isInfinity()) {
    return this;
  }
  if (this.x.equals(c.x)) {
    if (this.y.equals(c.y)) {
      return this.twice();
    }
    return this.curve.getInfinity();
  }
  var g = c.x.subtract(this.x);
  var e = c.y.subtract(this.y);
  var a = e.divide(g);
  var d = a.square().subtract(this.x).subtract(c.x);
  var f = a.multiply(this.x.subtract(d)).subtract(this.y);
  return new ECPointFp(this.curve, d, f);
};
ECPointFp.prototype.twice2D = function () {
  if (this.isInfinity()) {
    return this;
  }
  if (this.y.toBigInteger().signum() == 0) {
    return this.curve.getInfinity();
  }
  var b = this.curve.fromBigInteger(BigInteger.valueOf(2));
  var e = this.curve.fromBigInteger(BigInteger.valueOf(3));
  var a = this.x.square().multiply(e).add(this.curve.a).divide(this.y.multiply(b));
  var c = a.square().subtract(this.x.multiply(b));
  var d = a.multiply(this.x.subtract(c)).subtract(this.y);
  return new ECPointFp(this.curve, c, d);
};
ECPointFp.prototype.multiply2D = function (b) {
  if (this.isInfinity()) {
    return this;
  }
  if (b.signum() == 0) {
    return this.curve.getInfinity();
  }
  var g = b;
  var f = g.multiply(new BigInteger("3"));
  var l = this.negate();
  var d = this;
  var c;
  for (c = f.bitLength() - 2; c > 0; --c) {
    d = d.twice();
    var a = f.testBit(c);
    var j = g.testBit(c);
    if (a != j) {
      d = d.add2D(a ? this : l);
    }
  }
  return d;
};
ECPointFp.prototype.isOnCurve = function () {
  var d = this.getX().toBigInteger();
  var i = this.getY().toBigInteger();
  var f = this.curve.getA().toBigInteger();
  var c = this.curve.getB().toBigInteger();
  var h = this.curve.getQ();
  var e = i.multiply(i).mod(h);
  var g = d.multiply(d).multiply(d).add(f.multiply(d)).add(c).mod(h);
  return e.equals(g);
};
ECPointFp.prototype.toString = function () {
  return "(" + this.getX().toBigInteger().toString() + "," + this.getY().toBigInteger().toString() + ")";
};
ECPointFp.prototype.validate = function () {
  var c = this.curve.getQ();
  if (this.isInfinity()) {
    throw new Error("Point is at infinity.");
  }
  var a = this.getX().toBigInteger();
  var b = this.getY().toBigInteger();
  if (a.compareTo(BigInteger.ONE) < 0 || a.compareTo(c.subtract(BigInteger.ONE)) > 0) {
    throw new Error("x coordinate out of bounds");
  }
  if (b.compareTo(BigInteger.ONE) < 0 || b.compareTo(c.subtract(BigInteger.ONE)) > 0) {
    throw new Error("y coordinate out of bounds");
  }
  if (!this.isOnCurve()) {
    throw new Error("Point is not on the curve.");
  }
  if (this.multiply(c).isInfinity()) {
    throw new Error("Point is not a scalar multiple of G.");
  }
  return true;
};
/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval
 */
var jsonParse = function () {
  var e = "(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)";
  var j = '(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
  var i = '(?:"' + j + '*")';
  var d = new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|" + e + "|" + i + ")", "g");
  var k = new RegExp("\\\\(?:([^u])|u(.{4}))", "g");
  var g = {
    '"': '"',
    "/": "/",
    "\\": "\\",
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t"
  };
  function h(l, m, n) {
    return m ? g[m] : String.fromCharCode(parseInt(n, 16));
  }
  var c = new String("");
  var a = "\\";
  var f = {
    "{": Object,
    "[": Array
  };
  var b = Object.hasOwnProperty;
  return function (u, q) {
    var p = u.match(d);
    var x;
    var v = p[0];
    var l = false;
    if ("{" === v) {
      x = {};
    } else {
      if ("[" === v) {
        x = [];
      } else {
        x = [];
        l = true;
      }
    }
    var t;
    var r = [x];
    for (var o = 1 - l, m = p.length; o < m; ++o) {
      v = p[o];
      var w;
      switch (v.charCodeAt(0)) {
        default:
          w = r[0];
          w[t || w.length] = +v;
          t = void 0;
          break;
        case 34:
          v = v.substring(1, v.length - 1);
          if (v.indexOf(a) !== -1) {
            v = v.replace(k, h);
          }
          w = r[0];
          if (!t) {
            if (w instanceof Array) {
              t = w.length;
            } else {
              t = v || c;
              break;
            }
          }
          w[t] = v;
          t = void 0;
          break;
        case 91:
          w = r[0];
          r.unshift(w[t || w.length] = []);
          t = void 0;
          break;
        case 93:
          r.shift();
          break;
        case 102:
          w = r[0];
          w[t || w.length] = false;
          t = void 0;
          break;
        case 110:
          w = r[0];
          w[t || w.length] = null;
          t = void 0;
          break;
        case 116:
          w = r[0];
          w[t || w.length] = true;
          t = void 0;
          break;
        case 123:
          w = r[0];
          r.unshift(w[t || w.length] = {});
          t = void 0;
          break;
        case 125:
          r.shift();
          break;
      }
    }
    if (l) {
      if (r.length !== 1) {
        throw new Error();
      }
      x = x[0];
    } else {
      if (r.length) {
        throw new Error();
      }
    }
    if (q) {
      var s = function (C, B) {
        var D = C[B];
        if (D && typeof D === "object") {
          var n = null;
          for (var z in D) {
            if (b.call(D, z) && D !== C) {
              var y = s(D, z);
              if (y !== void 0) {
                D[z] = y;
              } else {
                if (!n) {
                  n = [];
                }
                n.push(z);
              }
            }
          }
          if (n) {
            for (var A = n.length; --A >= 0;) {
              delete D[n[A]];
            }
          }
        }
        return q.call(C, B, D);
      };
      x = s({
        "": x
      }, "");
    }
    return x;
  };
}();
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
KJUR.asn1.ASN1Util = new function () {
  this.integerToByteHex = function (a) {
    var b = a.toString(16);
    if (b.length % 2 == 1) {
      b = "0" + b;
    }
    return b;
  };
  this.bigIntToMinTwosComplementsHex = function (a) {
    return twoscompl(a);
  };
  this.getPEMStringFromHex = function (a, b) {
    return hextopem(a, b);
  };
  this.newObject = function (k) {
    var F = KJUR,
      o = F.asn1,
      v = o.ASN1Object,
      B = o.DERBoolean,
      e = o.DERInteger,
      t = o.DERBitString,
      h = o.DEROctetString,
      x = o.DERNull,
      y = o.DERObjectIdentifier,
      m = o.DEREnumerated,
      g = o.DERUTF8String,
      f = o.DERNumericString,
      A = o.DERPrintableString,
      w = o.DERTeletexString,
      q = o.DERIA5String,
      E = o.DERUTCTime,
      j = o.DERGeneralizedTime,
      b = o.DERVisibleString,
      l = o.DERBMPString,
      n = o.DERSequence,
      c = o.DERSet,
      s = o.DERTaggedObject,
      p = o.ASN1Util.newObject;
    if (k instanceof o.ASN1Object) {
      return k;
    }
    var u = Object.keys(k);
    if (u.length != 1) {
      throw new Error("key of param shall be only one.");
    }
    var H = u[0];
    if (":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":" + H + ":") == -1) {
      throw new Error("undefined key: " + H);
    }
    if (H == "bool") {
      return new B(k[H]);
    }
    if (H == "int") {
      return new e(k[H]);
    }
    if (H == "bitstr") {
      return new t(k[H]);
    }
    if (H == "octstr") {
      return new h(k[H]);
    }
    if (H == "null") {
      return new x(k[H]);
    }
    if (H == "oid") {
      return new y(k[H]);
    }
    if (H == "enum") {
      return new m(k[H]);
    }
    if (H == "utf8str") {
      return new g(k[H]);
    }
    if (H == "numstr") {
      return new f(k[H]);
    }
    if (H == "prnstr") {
      return new A(k[H]);
    }
    if (H == "telstr") {
      return new w(k[H]);
    }
    if (H == "ia5str") {
      return new q(k[H]);
    }
    if (H == "utctime") {
      return new E(k[H]);
    }
    if (H == "gentime") {
      return new j(k[H]);
    }
    if (H == "visstr") {
      return new b(k[H]);
    }
    if (H == "bmpstr") {
      return new l(k[H]);
    }
    if (H == "asn1") {
      return new v(k[H]);
    }
    if (H == "seq") {
      var d = k[H];
      var G = [];
      for (var z = 0; z < d.length; z++) {
        var D = p(d[z]);
        G.push(D);
      }
      return new n({
        array: G
      });
    }
    if (H == "set") {
      var d = k[H];
      var G = [];
      for (var z = 0; z < d.length; z++) {
        var D = p(d[z]);
        G.push(D);
      }
      return new c({
        array: G
      });
    }
    if (H == "tag") {
      var C = k[H];
      if (Object.prototype.toString.call(C) === "[object Array]" && C.length == 3) {
        var r = p(C[2]);
        return new s({
          tag: C[0],
          explicit: C[1],
          obj: r
        });
      } else {
        return new s(C);
      }
    }
  };
  this.jsonToASN1HEX = function (b) {
    var a = this.newObject(b);
    return a.tohex();
  };
}();
KJUR.asn1.ASN1Util.oidHexToInt = function (a) {
  var j = "";
  var k = parseInt(a.substr(0, 2), 16);
  var d = Math.floor(k / 40);
  var c = k % 40;
  var j = d + "." + c;
  var e = "";
  for (var f = 2; f < a.length; f += 2) {
    var g = parseInt(a.substr(f, 2), 16);
    var h = ("00000000" + g.toString(2)).slice(-8);
    e = e + h.substr(1, 7);
    if (h.substr(0, 1) == "0") {
      var b = new BigInteger(e, 2);
      j = j + "." + b.toString(10);
      e = "";
    }
  }
  return j;
};
KJUR.asn1.ASN1Util.oidIntToHex = function (f) {
  var e = function (a) {
    var k = a.toString(16);
    if (k.length == 1) {
      k = "0" + k;
    }
    return k;
  };
  var d = function (o) {
    var n = "";
    var k = new BigInteger(o, 10);
    var a = k.toString(2);
    var l = 7 - a.length % 7;
    if (l == 7) {
      l = 0;
    }
    var q = "";
    for (var m = 0; m < l; m++) {
      q += "0";
    }
    a = q + a;
    for (var m = 0; m < a.length - 1; m += 7) {
      var p = a.substr(m, 7);
      if (m != a.length - 7) {
        p = "1" + p;
      }
      n += e(parseInt(p, 2));
    }
    return n;
  };
  if (!f.match(/^[0-9.]+$/)) {
    throw "malformed oid string: " + f;
  }
  var g = "";
  var b = f.split(".");
  var j = parseInt(b[0]) * 40 + parseInt(b[1]);
  g += e(j);
  b.splice(0, 2);
  for (var c = 0; c < b.length; c++) {
    g += d(b[c]);
  }
  return g;
};
KJUR.asn1.ASN1Object = function (e) {
  var c = true;
  var b = null;
  var d = "00";
  var f = "00";
  var a = "";
  this.params = null;
  this.getLengthHexFromValue = function () {
    if (typeof this.hV == "undefined" || this.hV == null) {
      throw new Error("this.hV is null or undefined");
    }
    if (this.hV.length % 2 == 1) {
      throw new Error("value hex must be even length: n=" + a.length + ",v=" + this.hV);
    }
    var j = this.hV.length / 2;
    var i = j.toString(16);
    if (i.length % 2 == 1) {
      i = "0" + i;
    }
    if (j < 128) {
      return i;
    } else {
      var h = i.length / 2;
      if (h > 15) {
        throw new Error("ASN.1 length too long to represent by 8x: n = " + j.toString(16));
      }
      var g = 128 + h;
      return g.toString(16) + i;
    }
  };
  this.tohex = function () {
    if (this.hTLV == null || this.isModified) {
      this.hV = this.getFreshValueHex();
      this.hL = this.getLengthHexFromValue();
      this.hTLV = this.hT + this.hL + this.hV;
      this.isModified = false;
    }
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.getValueHex = function () {
    this.tohex();
    return this.hV;
  };
  this.getFreshValueHex = function () {
    return "";
  };
  this.setByParam = function (g) {
    this.params = g;
  };
  if (e != undefined) {
    if (e.tlv != undefined) {
      this.hTLV = e.tlv;
      this.isModified = false;
    }
  }
};
KJUR.asn1.DERAbstractString = function (c) {
  KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  var b = null;
  var a = null;
  this.getString = function () {
    return this.s;
  };
  this.setString = function (d) {
    this.hTLV = null;
    this.isModified = true;
    this.s = d;
    this.hV = utf8tohex(this.s).toLowerCase();
  };
  this.setStringHex = function (d) {
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = d;
  };
  this.getFreshValueHex = function () {
    return this.hV;
  };
  if (typeof c != "undefined") {
    if (typeof c == "string") {
      this.setString(c);
    } else {
      if (typeof c.str != "undefined") {
        this.setString(c.str);
      } else {
        if (typeof c.hex != "undefined") {
          this.setStringHex(c.hex);
        }
      }
    }
  }
};
extendClass(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractTime = function (c) {
  KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  var b = null;
  var a = null;
  this.localDateToUTC = function (g) {
    var e = g.getTime() + g.getTimezoneOffset() * 60000;
    var f = new Date(e);
    return f;
  };
  this.formatDate = function (m, o, e) {
    var g = this.zeroPadding;
    var n = this.localDateToUTC(m);
    var p = String(n.getFullYear());
    if (o == "utc") {
      p = p.substr(2, 2);
    }
    var l = g(String(n.getMonth() + 1), 2);
    var q = g(String(n.getDate()), 2);
    var h = g(String(n.getHours()), 2);
    var i = g(String(n.getMinutes()), 2);
    var j = g(String(n.getSeconds()), 2);
    var r = p + l + q + h + i + j;
    if (e === true) {
      var f = n.getMilliseconds();
      if (f != 0) {
        var k = g(String(f), 3);
        k = k.replace(/[0]+$/, "");
        r = r + "." + k;
      }
    }
    return r + "Z";
  };
  this.zeroPadding = function (e, d) {
    if (e.length >= d) {
      return e;
    }
    return new Array(d - e.length + 1).join("0") + e;
  };
  this.setByParam = function (d) {
    this.hV = null;
    this.hTLV = null;
    this.params = d;
  };
  this.getString = function () {
    return undefined;
  };
  this.setString = function (d) {
    this.hTLV = null;
    this.isModified = true;
    if (this.params == undefined) {
      this.params = {};
    }
    this.params.str = d;
  };
  this.setByDate = function (d) {
    this.hTLV = null;
    this.isModified = true;
    if (this.params == undefined) {
      this.params = {};
    }
    this.params.date = d;
  };
  this.setByDateValue = function (h, j, e, d, f, g) {
    var i = new Date(Date.UTC(h, j - 1, e, d, f, g, 0));
    this.setByDate(i);
  };
  this.getFreshValueHex = function () {
    return this.hV;
  };
};
extendClass(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractStructured = function (b) {
  KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  var a = null;
  this.setByASN1ObjectArray = function (c) {
    this.hTLV = null;
    this.isModified = true;
    this.asn1Array = c;
  };
  this.appendASN1Object = function (c) {
    this.hTLV = null;
    this.isModified = true;
    this.asn1Array.push(c);
  };
  this.asn1Array = new Array();
  if (typeof b != "undefined") {
    if (typeof b.array != "undefined") {
      this.asn1Array = b.array;
    }
  }
};
extendClass(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBoolean = function (a) {
  KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  this.hT = "01";
  if (a == false) {
    this.hTLV = "010100";
  } else {
    this.hTLV = "0101ff";
  }
};
extendClass(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
KJUR.asn1.DERInteger = function (b) {
  KJUR.asn1.DERInteger.superclass.constructor.call(this);
  this.hT = "02";
  this.params = null;
  var a = twoscompl;
  this.setByBigInteger = function (c) {
    this.isModified = true;
    this.params = {
      bigint: c
    };
  };
  this.setByInteger = function (c) {
    this.isModified = true;
    this.params = c;
  };
  this.setValueHex = function (c) {
    this.isModified = true;
    this.params = {
      hex: c
    };
  };
  this.getFreshValueHex = function () {
    var d = this.params;
    var c = null;
    if (d == null) {
      throw new Error("value not set");
    }
    if (typeof d == "object" && d.hex != undefined) {
      this.hV = d.hex;
      return this.hV;
    }
    if (typeof d == "number") {
      c = new BigInteger(String(d), 10);
    } else {
      if (d["int"] != undefined) {
        c = new BigInteger(String(d["int"]), 10);
      } else {
        if (d.bigint != undefined) {
          c = d.bigint;
        } else {
          throw new Error("wrong parameter");
        }
      }
    }
    this.hV = a(c);
    return this.hV;
  };
  if (b != undefined) {
    this.params = b;
  }
};
extendClass(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBitString = function (b) {
  if (b !== undefined && typeof b.obj !== "undefined") {
    var a = KJUR.asn1.ASN1Util.newObject(b.obj);
    b.hex = "00" + a.tohex();
  }
  KJUR.asn1.DERBitString.superclass.constructor.call(this);
  this.hT = "03";
  this.setHexValueIncludingUnusedBits = function (c) {
    this.hTLV = null;
    this.isModified = true;
    this.hV = c;
  };
  this.setUnusedBitsAndHexValue = function (c, e) {
    if (c < 0 || 7 < c) {
      throw "unused bits shall be from 0 to 7: u = " + c;
    }
    var d = "0" + c;
    this.hTLV = null;
    this.isModified = true;
    this.hV = d + e;
  };
  this.setByBinaryString = function (e) {
    e = e.replace(/0+$/, "");
    var f = 8 - e.length % 8;
    if (f == 8) {
      f = 0;
    }
    e += "0000000".substr(0, f);
    var j = "";
    for (var g = 0; g < e.length - 1; g += 8) {
      var d = e.substr(g, 8);
      var c = parseInt(d, 2).toString(16);
      if (c.length == 1) {
        c = "0" + c;
      }
      j += c;
    }
    this.hTLV = null;
    this.isModified = true;
    this.hV = "0" + f + j;
  };
  this.setByBooleanArray = function (e) {
    var d = "";
    for (var c = 0; c < e.length; c++) {
      if (e[c] == true) {
        d += "1";
      } else {
        d += "0";
      }
    }
    this.setByBinaryString(d);
  };
  this.newFalseArray = function (e) {
    var c = new Array(e);
    for (var d = 0; d < e; d++) {
      c[d] = false;
    }
    return c;
  };
  this.getFreshValueHex = function () {
    return this.hV;
  };
  if (typeof b != "undefined") {
    if (typeof b == "string" && b.toLowerCase().match(/^[0-9a-f]+$/)) {
      this.setHexValueIncludingUnusedBits(b);
    } else {
      if (typeof b.hex != "undefined") {
        this.setHexValueIncludingUnusedBits(b.hex);
      } else {
        if (typeof b.bin != "undefined") {
          this.setByBinaryString(b.bin);
        } else {
          if (typeof b.array != "undefined") {
            this.setByBooleanArray(b.array);
          }
        }
      }
    }
  }
};
extendClass(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
KJUR.asn1.DEROctetString = function (b) {
  if (b !== undefined && typeof b.obj !== "undefined") {
    var a = KJUR.asn1.ASN1Util.newObject(b.obj);
    b.hex = a.tohex();
  }
  KJUR.asn1.DEROctetString.superclass.constructor.call(this, b);
  this.hT = "04";
};
extendClass(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNull = function () {
  KJUR.asn1.DERNull.superclass.constructor.call(this);
  this.hT = "05";
  this.hTLV = "0500";
};
extendClass(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
KJUR.asn1.DERObjectIdentifier = function (a) {
  KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  this.hT = "06";
  this.setValueHex = function (b) {
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = b;
  };
  this.setValueOidString = function (b) {
    var c = oidtohex(b);
    if (c == null) {
      throw new Error("malformed oid string: " + b);
    }
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = c;
  };
  this.setValueName = function (c) {
    var b = KJUR.asn1.x509.OID.name2oid(c);
    if (b !== "") {
      this.setValueOidString(b);
    } else {
      throw new Error("DERObjectIdentifier oidName undefined: " + c);
    }
  };
  this.setValueNameOrOid = function (b) {
    if (b.match(/^[0-2].[0-9.]+$/)) {
      this.setValueOidString(b);
    } else {
      this.setValueName(b);
    }
  };
  this.getFreshValueHex = function () {
    return this.hV;
  };
  this.setByParam = function (b) {
    if (typeof b === "string") {
      this.setValueNameOrOid(b);
    } else {
      if (b.oid !== undefined) {
        this.setValueNameOrOid(b.oid);
      } else {
        if (b.name !== undefined) {
          this.setValueNameOrOid(b.name);
        } else {
          if (b.hex !== undefined) {
            this.setValueHex(b.hex);
          }
        }
      }
    }
  };
  if (a !== undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.DEREnumerated = function (a) {
  KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
  this.hT = "0a";
  this.setByBigInteger = function (b) {
    this.hTLV = null;
    this.isModified = true;
    this.hV = twoscompl(b);
  };
  this.setByInteger = function (c) {
    var b = new BigInteger(String(c), 10);
    this.setByBigInteger(b);
  };
  this.setValueHex = function (b) {
    this.hV = b;
  };
  this.getFreshValueHex = function () {
    return this.hV;
  };
  if (typeof a != "undefined") {
    if (typeof a["int"] != "undefined") {
      this.setByInteger(a["int"]);
    } else {
      if (typeof a == "number") {
        this.setByInteger(a);
      } else {
        if (typeof a.hex != "undefined") {
          this.setValueHex(a.hex);
        }
      }
    }
  }
};
extendClass(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
KJUR.asn1.DERUTF8String = function (a) {
  KJUR.asn1.DERUTF8String.superclass.constructor.call(this, a);
  this.hT = "0c";
};
extendClass(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNumericString = function (a) {
  KJUR.asn1.DERNumericString.superclass.constructor.call(this, a);
  this.hT = "12";
};
extendClass(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERPrintableString = function (a) {
  KJUR.asn1.DERPrintableString.superclass.constructor.call(this, a);
  this.hT = "13";
};
extendClass(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERTeletexString = function (a) {
  KJUR.asn1.DERTeletexString.superclass.constructor.call(this, a);
  this.hT = "14";
};
extendClass(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERIA5String = function (a) {
  KJUR.asn1.DERIA5String.superclass.constructor.call(this, a);
  this.hT = "16";
};
extendClass(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERVisibleString = function (a) {
  KJUR.asn1.DERIA5String.superclass.constructor.call(this, a);
  this.hT = "1a";
};
extendClass(KJUR.asn1.DERVisibleString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERBMPString = function (a) {
  KJUR.asn1.DERBMPString.superclass.constructor.call(this, a);
  this.hT = "1e";
};
extendClass(KJUR.asn1.DERBMPString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERUTCTime = function (a) {
  KJUR.asn1.DERUTCTime.superclass.constructor.call(this, a);
  this.hT = "17";
  this.params = undefined;
  this.getFreshValueHex = function () {
    var d = this.params;
    if (this.params == undefined) {
      d = {
        date: new Date()
      };
    }
    if (typeof d == "string") {
      if (d.match(/^[0-9]{12}Z$/) || d.match(/^[0-9]{12}\.[0-9]+Z$/)) {
        this.hV = stohex(d);
      } else {
        throw new Error("malformed string for UTCTime: " + d);
      }
    } else {
      if (d.str != undefined) {
        this.hV = stohex(d.str);
      } else {
        if (d.date == undefined && d.millis == true) {
          var c = new Date();
          this.hV = stohex(this.formatDate(c, "utc", true));
        } else {
          if (d.date != undefined && d.date instanceof Date) {
            var b = d.millis === true;
            this.hV = stohex(this.formatDate(d.date, "utc", b));
          } else {
            if (d instanceof Date) {
              this.hV = stohex(this.formatDate(d, "utc"));
            }
          }
        }
      }
    }
    if (this.hV == undefined) {
      throw new Error("parameter not specified properly for UTCTime");
    }
    return this.hV;
  };
  if (a != undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERGeneralizedTime = function (a) {
  KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, a);
  this.hT = "18";
  this.params = a;
  this.getFreshValueHex = function () {
    var d = this.params;
    if (this.params == undefined) {
      d = {
        date: new Date()
      };
    }
    if (typeof d == "string") {
      if (d.match(/^[0-9]{14}Z$/) || d.match(/^[0-9]{14}\.[0-9]+Z$/)) {
        this.hV = stohex(d);
      } else {
        throw new Error("malformed string for GeneralizedTime: " + d);
      }
    } else {
      if (d.str != undefined) {
        this.hV = stohex(d.str);
      } else {
        if (d.date == undefined && d.millis == true) {
          var c = new Date();
          this.hV = stohex(this.formatDate(c, "gen", true));
        } else {
          if (d.date != undefined && d.date instanceof Date) {
            var b = d.millis === true;
            this.hV = stohex(this.formatDate(d.date, "gen", b));
          } else {
            if (d instanceof Date) {
              this.hV = stohex(this.formatDate(d, "gen"));
            }
          }
        }
      }
    }
    if (this.hV == undefined) {
      throw new Error("parameter not specified properly for GeneralizedTime");
    }
    return this.hV;
  };
  if (a != undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERSequence = function (a) {
  KJUR.asn1.DERSequence.superclass.constructor.call(this, a);
  this.hT = "30";
  this.getFreshValueHex = function () {
    var c = "";
    for (var b = 0; b < this.asn1Array.length; b++) {
      var d = this.asn1Array[b];
      c += d.tohex();
    }
    this.hV = c;
    return this.hV;
  };
};
extendClass(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERSet = function (a) {
  KJUR.asn1.DERSet.superclass.constructor.call(this, a);
  this.hT = "31";
  this.sortFlag = true;
  this.getFreshValueHex = function () {
    var b = new Array();
    for (var c = 0; c < this.asn1Array.length; c++) {
      var d = this.asn1Array[c];
      b.push(d.tohex());
    }
    if (this.sortFlag == true) {
      b.sort();
    }
    this.hV = b.join("");
    return this.hV;
  };
  if (typeof a != "undefined") {
    if (typeof a.sortflag != "undefined" && a.sortflag == false) {
      this.sortFlag = false;
    }
  }
};
extendClass(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERTaggedObject = function (f) {
  KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  var d = KJUR.asn1,
    e = ASN1HEX,
    a = e.getV,
    c = e.isASN1HEX,
    b = d.ASN1Util.newObject;
  this.hT = "a0";
  this.hV = "";
  this.isExplicit = true;
  this.asn1Object = null;
  this.params = {
    tag: "a0",
    explicit: true
  };
  this.setASN1Object = function (g, h, i) {
    this.params = {
      tag: h,
      explicit: g,
      obj: i
    };
  };
  this.getFreshValueHex = function () {
    var h = this.params;
    if (h.explicit == undefined) {
      h.explicit = true;
    }
    if (h.tage != undefined) {
      h.tag = h.tage;
      h.explicit = true;
    }
    if (h.tagi != undefined) {
      h.tag = h.tagi;
      h.explicit = false;
    }
    if (h.str != undefined) {
      this.hV = utf8tohex(h.str);
    } else {
      if (h.hex != undefined) {
        this.hV = h.hex;
      } else {
        if (h.obj != undefined) {
          var g;
          if (h.obj instanceof d.ASN1Object) {
            g = h.obj.tohex();
          } else {
            if (typeof h.obj == "object") {
              g = b(h.obj).tohex();
            }
          }
          if (h.explicit) {
            this.hV = g;
          } else {
            this.hV = a(g, 0);
          }
        } else {
          throw new Error("str, hex nor obj not specified");
        }
      }
    }
    if (h.tag == undefined) {
      h.tag = "a0";
    }
    this.hT = h.tag;
    this.hTLV = null;
    this.isModified = true;
    return this.hV;
  };
  this.setByParam = function (g) {
    this.params = g;
  };
  if (f !== undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
var ASN1HEX = new function () {}();
ASN1HEX.getLblen = function (c, a) {
  if (c.substr(a + 2, 1) != "8") {
    return 1;
  }
  var b = parseInt(c.substr(a + 3, 1));
  if (b == 0) {
    return -1;
  }
  if (0 < b && b < 10) {
    return b + 1;
  }
  return -2;
};
ASN1HEX.getL = function (c, b) {
  var a = ASN1HEX.getLblen(c, b);
  if (a < 1) {
    return "";
  }
  return c.substr(b + 2, a * 2);
};
ASN1HEX.getVblen = function (d, a) {
  var c, b;
  c = ASN1HEX.getL(d, a);
  if (c == "") {
    return -1;
  }
  if (c.substr(0, 1) === "8") {
    b = new BigInteger(c.substr(2), 16);
  } else {
    b = new BigInteger(c, 16);
  }
  return b.intValue();
};
ASN1HEX.getVidx = function (c, b) {
  var a = ASN1HEX.getLblen(c, b);
  if (a < 0) {
    return a;
  }
  return b + (a + 1) * 2;
};
ASN1HEX.getV = function (d, a) {
  var c = ASN1HEX.getVidx(d, a);
  var b = ASN1HEX.getVblen(d, a);
  return d.substr(c, b * 2);
};
ASN1HEX.getTLV = function (b, a) {
  return b.substr(a, 2) + ASN1HEX.getL(b, a) + ASN1HEX.getV(b, a);
};
ASN1HEX.getTLVblen = function (b, a) {
  return 2 + ASN1HEX.getLblen(b, a) * 2 + ASN1HEX.getVblen(b, a) * 2;
};
ASN1HEX.getNextSiblingIdx = function (d, a) {
  var c = ASN1HEX.getVidx(d, a);
  var b = ASN1HEX.getVblen(d, a);
  return c + b * 2;
};
ASN1HEX.getChildIdx = function (e, k) {
  var l = ASN1HEX;
  var j = [];
  var c, f, g;
  c = l.getVidx(e, k);
  f = l.getVblen(e, k) * 2;
  if (e.substr(k, 2) == "03") {
    c += 2;
    f -= 2;
  }
  g = 0;
  var d = c;
  while (g <= f) {
    var b = l.getTLVblen(e, d);
    g += b;
    if (g <= f) {
      j.push(d);
    }
    d += b;
    if (g >= f) {
      break;
    }
  }
  return j;
};
ASN1HEX.getNthChildIdx = function (d, b, e) {
  var c = ASN1HEX.getChildIdx(d, b);
  return c[e];
};
ASN1HEX.getIdxbyList = function (e, d, c, i) {
  var g = ASN1HEX;
  var f, b;
  if (c.length == 0) {
    if (i !== undefined) {
      if (e.substr(d, 2) !== i) {
        return -1;
      }
    }
    return d;
  }
  f = c.shift();
  b = g.getChildIdx(e, d);
  if (f >= b.length) {
    return -1;
  }
  return g.getIdxbyList(e, b[f], c, i);
};
ASN1HEX.getIdxbyListEx = function (f, k, b, g) {
  var m = ASN1HEX;
  var d, l;
  if (b.length == 0) {
    if (g !== undefined) {
      if (f.substr(k, 2) !== g) {
        return -1;
      }
    }
    return k;
  }
  d = b.shift();
  l = m.getChildIdx(f, k);
  var j = 0;
  for (var e = 0; e < l.length; e++) {
    var c = f.substr(l[e], 2);
    if (typeof d == "number" && !m.isContextTag(c) && j == d || typeof d == "string" && m.isContextTag(c, d)) {
      return m.getIdxbyListEx(f, l[e], b, g);
    }
    if (!m.isContextTag(c)) {
      j++;
    }
  }
  return -1;
};
ASN1HEX.getTLVbyList = function (d, c, b, f) {
  var e = ASN1HEX;
  var a = e.getIdxbyList(d, c, b, f);
  if (a == -1) {
    return null;
  }
  if (a >= d.length) {
    return null;
  }
  return e.getTLV(d, a);
};
ASN1HEX.getTLVbyListEx = function (d, c, b, f) {
  var e = ASN1HEX;
  var a = e.getIdxbyListEx(d, c, b, f);
  if (a == -1) {
    return null;
  }
  return e.getTLV(d, a);
};
ASN1HEX.getVbyList = function (e, c, b, g, i) {
  var f = ASN1HEX;
  var a, d;
  a = f.getIdxbyList(e, c, b, g);
  if (a == -1) {
    return null;
  }
  if (a >= e.length) {
    return null;
  }
  d = f.getV(e, a);
  if (i === true) {
    d = d.substr(2);
  }
  return d;
};
ASN1HEX.getVbyListEx = function (b, e, a, d, f) {
  var j = ASN1HEX;
  var g, c, i;
  g = j.getIdxbyListEx(b, e, a, d);
  if (g == -1) {
    return null;
  }
  i = j.getV(b, g);
  if (b.substr(g, 2) == "03" && f !== false) {
    i = i.substr(2);
  }
  return i;
};
ASN1HEX.getInt = function (e, b, f) {
  if (f == undefined) {
    f = -1;
  }
  try {
    var c = e.substr(b, 2);
    if (c != "02" && c != "03") {
      return f;
    }
    var a = ASN1HEX.getV(e, b);
    if (c == "02") {
      return parseInt(a, 16);
    } else {
      return bitstrtoint(a);
    }
  } catch (d) {
    return f;
  }
};
ASN1HEX.getOID = function (c, a, d) {
  if (d == undefined) {
    d = null;
  }
  try {
    if (c.substr(a, 2) != "06") {
      return d;
    }
    var e = ASN1HEX.getV(c, a);
    return hextooid(e);
  } catch (b) {
    return d;
  }
};
ASN1HEX.getOIDName = function (d, a, f) {
  if (f == undefined) {
    f = null;
  }
  try {
    var e = ASN1HEX.getOID(d, a, f);
    if (e == f) {
      return f;
    }
    var b = KJUR.asn1.x509.OID.oid2name(e);
    if (b == "") {
      return e;
    }
    return b;
  } catch (c) {
    return f;
  }
};
ASN1HEX.getString = function (d, b, e) {
  if (e == undefined) {
    e = null;
  }
  try {
    var a = ASN1HEX.getV(d, b);
    return hextorstr(a);
  } catch (c) {
    return e;
  }
};
ASN1HEX.hextooidstr = function (e) {
  var h = function (b, a) {
    if (b.length >= a) {
      return b;
    }
    return new Array(a - b.length + 1).join("0") + b;
  };
  var l = [];
  var o = e.substr(0, 2);
  var f = parseInt(o, 16);
  l[0] = new String(Math.floor(f / 40));
  l[1] = new String(f % 40);
  var m = e.substr(2);
  var k = [];
  for (var g = 0; g < m.length / 2; g++) {
    k.push(parseInt(m.substr(g * 2, 2), 16));
  }
  var j = [];
  var d = "";
  for (var g = 0; g < k.length; g++) {
    if (k[g] & 128) {
      d = d + h((k[g] & 127).toString(2), 7);
    } else {
      d = d + h((k[g] & 127).toString(2), 7);
      j.push(new String(parseInt(d, 2)));
      d = "";
    }
  }
  var n = l.join(".");
  if (j.length > 0) {
    n = n + "." + j.join(".");
  }
  return n;
};
ASN1HEX.dump = function (t, c, l, g) {
  var p = ASN1HEX;
  var j = p.getV;
  var y = p.dump;
  var w = p.getChildIdx;
  var e = t;
  if (t instanceof KJUR.asn1.ASN1Object) {
    e = t.tohex();
  }
  var q = function (A, i) {
    if (A.length <= i * 2) {
      return A;
    } else {
      var v = A.substr(0, i) + "..(total " + A.length / 2 + "bytes).." + A.substr(A.length - i, i);
      return v;
    }
  };
  if (c === undefined) {
    c = {
      ommit_long_octet: 32
    };
  }
  if (l === undefined) {
    l = 0;
  }
  if (g === undefined) {
    g = "";
  }
  var x = c.ommit_long_octet;
  var z = e.substr(l, 2);
  if (z == "01") {
    var h = j(e, l);
    if (h == "00") {
      return g + "BOOLEAN FALSE\n";
    } else {
      return g + "BOOLEAN TRUE\n";
    }
  }
  if (z == "02") {
    var h = j(e, l);
    return g + "INTEGER " + q(h, x) + "\n";
  }
  if (z == "03") {
    var h = j(e, l);
    if (p.isASN1HEX(h.substr(2))) {
      var k = g + "BITSTRING, encapsulates\n";
      k = k + y(h.substr(2), c, 0, g + "  ");
      return k;
    } else {
      return g + "BITSTRING " + q(h, x) + "\n";
    }
  }
  if (z == "04") {
    var h = j(e, l);
    if (p.isASN1HEX(h)) {
      var k = g + "OCTETSTRING, encapsulates\n";
      k = k + y(h, c, 0, g + "  ");
      return k;
    } else {
      return g + "OCTETSTRING " + q(h, x) + "\n";
    }
  }
  if (z == "05") {
    return g + "NULL\n";
  }
  if (z == "06") {
    var m = j(e, l);
    var b = KJUR.asn1.ASN1Util.oidHexToInt(m);
    var o = KJUR.asn1.x509.OID.oid2name(b);
    var a = b.replace(/\./g, " ");
    if (o != "") {
      return g + "ObjectIdentifier " + o + " (" + a + ")\n";
    } else {
      return g + "ObjectIdentifier (" + a + ")\n";
    }
  }
  if (z == "0a") {
    return g + "ENUMERATED " + parseInt(j(e, l)) + "\n";
  }
  if (z == "0c") {
    return g + "UTF8String '" + hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "13") {
    return g + "PrintableString '" + hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "14") {
    return g + "TeletexString '" + hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "16") {
    return g + "IA5String '" + hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "17") {
    return g + "UTCTime " + hextoutf8(j(e, l)) + "\n";
  }
  if (z == "18") {
    return g + "GeneralizedTime " + hextoutf8(j(e, l)) + "\n";
  }
  if (z == "1a") {
    return g + "VisualString '" + hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "1e") {
    return g + "BMPString '" + ucs2hextoutf8(j(e, l)) + "'\n";
  }
  if (z == "30") {
    if (e.substr(l, 4) == "3000") {
      return g + "SEQUENCE {}\n";
    }
    var k = g + "SEQUENCE\n";
    var d = w(e, l);
    var f = c;
    if ((d.length == 2 || d.length == 3) && e.substr(d[0], 2) == "06" && e.substr(d[d.length - 1], 2) == "04") {
      var o = p.oidname(j(e, d[0]));
      var r = JSON.parse(JSON.stringify(c));
      r.x509ExtName = o;
      f = r;
    }
    for (var u = 0; u < d.length; u++) {
      k = k + y(e, f, d[u], g + "  ");
    }
    return k;
  }
  if (z == "31") {
    var k = g + "SET\n";
    var d = w(e, l);
    for (var u = 0; u < d.length; u++) {
      k = k + y(e, c, d[u], g + "  ");
    }
    return k;
  }
  var z = parseInt(z, 16);
  if ((z & 128) != 0) {
    var n = z & 31;
    if ((z & 32) != 0) {
      var k = g + "[" + n + "]\n";
      var d = w(e, l);
      for (var u = 0; u < d.length; u++) {
        k = k + y(e, c, d[u], g + "  ");
      }
      return k;
    } else {
      var h = j(e, l);
      if (ASN1HEX.isASN1HEX(h)) {
        var k = g + "[" + n + "]\n";
        k = k + y(h, c, 0, g + "  ");
        return k;
      } else {
        if (h.substr(0, 8) == "68747470") {
          h = hextoutf8(h);
        } else {
          if (c.x509ExtName === "subjectAltName" && n == 2) {
            h = hextoutf8(h);
          }
        }
      }
      var k = g + "[" + n + "] " + h + "\n";
      return k;
    }
  }
  return g + "UNKNOWN(" + z + ") " + j(e, l) + "\n";
};
ASN1HEX.parse = function (x) {
  var t = ASN1HEX,
    f = t.parse,
    a = t.isASN1HEX,
    l = t.getV,
    b = t.getTLV,
    y = t.getChildIdx,
    i = KJUR.asn1,
    e = i.ASN1Util.oidHexToInt,
    B = i.x509.OID.oid2name,
    k = hextoutf8,
    n = ucs2hextoutf8,
    q = iso88591hextoutf8;
  var c = {
    "0c": "utf8str",
    "12": "numstr",
    "13": "prnstr",
    "14": "telstr",
    "16": "ia5str",
    "17": "utctime",
    "18": "gentime",
    "1a": "visstr",
    "1e": "bmpstr",
    "30": "seq",
    "31": "set"
  };
  var u = function (H) {
    var D = [];
    var E = y(H, 0);
    for (var G = 0; G < E.length; G++) {
      var s = E[G];
      var d = b(H, s);
      var F = f(d);
      D.push(F);
    }
    return D;
  };
  var C = x.substr(0, 2);
  var j = {};
  var p = l(x, 0);
  if (C == "01") {
    if (x == "0101ff") {
      return {
        bool: true
      };
    }
    return {
      bool: false
    };
  } else {
    if (C == "02") {
      return {
        "int": {
          hex: p
        }
      };
    } else {
      if (C == "03") {
        try {
          if (p.substr(0, 2) != "00") {
            throw "not encap";
          }
          var v = p.substr(2);
          if (!a(v)) {
            throw "not encap";
          }
          return {
            bitstr: {
              obj: f(v)
            }
          };
        } catch (z) {
          var m = null;
          if (p.length <= 10) {
            m = bitstrtobinstr(p);
          }
          if (m == null) {
            return {
              bitstr: {
                hex: p
              }
            };
          } else {
            return {
              bitstr: {
                bin: m
              }
            };
          }
        }
      } else {
        if (C == "04") {
          try {
            if (!a(p)) {
              throw "not encap";
            }
            return {
              octstr: {
                obj: f(p)
              }
            };
          } catch (z) {
            return {
              octstr: {
                hex: p
              }
            };
          }
        } else {
          if (C == "05") {
            return {
              "null": ""
            };
          } else {
            if (C == "06") {
              var g = e(p);
              var r = B(g);
              if (r == "") {
                return {
                  oid: g
                };
              } else {
                return {
                  oid: r
                };
              }
            } else {
              if (C == "0a") {
                if (p.length > 4) {
                  return {
                    "enum": {
                      hex: p
                    }
                  };
                } else {
                  return {
                    "enum": parseInt(p, 16)
                  };
                }
              } else {
                if (C == "30" || C == "31") {
                  j[c[C]] = u(x);
                  return j;
                } else {
                  if (C == "14") {
                    var o = q(p);
                    j[c[C]] = {
                      str: o
                    };
                    return j;
                  } else {
                    if (C == "1e") {
                      var o = n(p);
                      j[c[C]] = {
                        str: o
                      };
                      return j;
                    } else {
                      if (":0c:12:13:16:17:18:1a:".indexOf(C) != -1) {
                        var o = k(p);
                        j[c[C]] = {
                          str: o
                        };
                        return j;
                      } else {
                        if (C.match(/^8[0-9]$/)) {
                          var o = k(p);
                          if (o == null | o == "") {
                            return {
                              tag: {
                                tag: C,
                                explicit: false,
                                hex: p
                              }
                            };
                          } else {
                            if (o.match(/[\x00-\x1F\x7F-\x9F]/) != null || o.match(/[\u0000-\u001F\u0080–\u009F]/) != null) {
                              return {
                                tag: {
                                  tag: C,
                                  explicit: false,
                                  hex: p
                                }
                              };
                            } else {
                              return {
                                tag: {
                                  tag: C,
                                  explicit: false,
                                  str: o
                                }
                              };
                            }
                          }
                        } else {
                          if (C.match(/^a[0-9]$/)) {
                            try {
                              if (!a(p)) {
                                throw new Error("not encap");
                              }
                              return {
                                tag: {
                                  tag: C,
                                  explicit: true,
                                  obj: f(p)
                                }
                              };
                            } catch (z) {
                              return {
                                tag: {
                                  tag: C,
                                  explicit: true,
                                  hex: p
                                }
                              };
                            }
                          } else {
                            var A = new KJUR.asn1.ASN1Object();
                            A.hV = p;
                            var w = A.getLengthHexFromValue();
                            return {
                              asn1: {
                                tlv: C + w + p
                              }
                            };
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
};
ASN1HEX.isContextTag = function (c, b) {
  c = c.toLowerCase();
  var f, e;
  try {
    f = parseInt(c, 16);
  } catch (d) {
    return -1;
  }
  if (b === undefined) {
    if ((f & 192) == 128) {
      return true;
    } else {
      return false;
    }
  }
  try {
    var a = b.match(/^\[[0-9]+\]$/);
    if (a == null) {
      return false;
    }
    e = parseInt(b.substr(1, b.length - 1), 10);
    if (e > 31) {
      return false;
    }
    if ((f & 192) == 128 && (f & 31) == e) {
      return true;
    }
    return false;
  } catch (d) {
    return false;
  }
};
ASN1HEX.isASN1HEX = function (e) {
  var d = ASN1HEX;
  if (e.length % 2 == 1) {
    return false;
  }
  var c = d.getVblen(e, 0);
  var b = e.substr(0, 2);
  var f = d.getL(e, 0);
  var a = e.length - b.length - f.length;
  if (a == c * 2) {
    return true;
  }
  return false;
};
ASN1HEX.checkStrictDER = function (g, o, d, c, r) {
  var s = ASN1HEX;
  if (d === undefined) {
    if (typeof g != "string") {
      throw new Error("not hex string");
    }
    g = g.toLowerCase();
    if (!KJUR.lang.String.isHex(g)) {
      throw new Error("not hex string");
    }
    d = g.length;
    c = g.length / 2;
    if (c < 128) {
      r = 1;
    } else {
      r = Math.ceil(c.toString(16)) + 1;
    }
  }
  var k = s.getL(g, o);
  if (k.length > r * 2) {
    throw new Error("L of TLV too long: idx=" + o);
  }
  var n = s.getVblen(g, o);
  if (n > c) {
    throw new Error("value of L too long than hex: idx=" + o);
  }
  var q = s.getTLV(g, o);
  var f = q.length - 2 - s.getL(g, o).length;
  if (f !== n * 2) {
    throw new Error("V string length and L's value not the same:" + f + "/" + n * 2);
  }
  if (o === 0) {
    if (g.length != q.length) {
      throw new Error("total length and TLV length unmatch:" + g.length + "!=" + q.length);
    }
  }
  var b = g.substr(o, 2);
  if (b === "02") {
    var a = s.getVidx(g, o);
    if (g.substr(a, 2) == "00" && g.charCodeAt(a + 2) < 56) {
      throw new Error("not least zeros for DER INTEGER");
    }
  }
  if (parseInt(b, 16) & 32) {
    var p = s.getVblen(g, o);
    var m = 0;
    var l = s.getChildIdx(g, o);
    for (var e = 0; e < l.length; e++) {
      var j = s.getTLV(g, l[e]);
      m += j.length;
      s.checkStrictDER(g, l[e], d, c, r);
    }
    if (p * 2 != m) {
      throw new Error("sum of children's TLV length and L unmatch: " + p * 2 + "!=" + m);
    }
  }
};
ASN1HEX.oidname = function (a) {
  var c = KJUR.asn1;
  if (KJUR.lang.String.isHex(a)) {
    a = c.ASN1Util.oidHexToInt(a);
  }
  var b = c.x509.OID.oid2name(a);
  if (b === "") {
    b = a;
  }
  return b;
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
if (typeof KJUR.asn1.x509 == "undefined" || !KJUR.asn1.x509) {
  KJUR.asn1.x509 = {};
}
KJUR.asn1.x509.Certificate = function (h) {
  KJUR.asn1.x509.Certificate.superclass.constructor.call(this);
  var d = KJUR,
    c = d.asn1,
    f = c.DERBitString,
    b = c.DERSequence,
    g = c.x509,
    a = g.TBSCertificate,
    e = g.AlgorithmIdentifier;
  this.params = undefined;
  this.setByParam = function (i) {
    this.params = i;
  };
  this.sign = function () {
    var l = this.params;
    var k = l.sigalg;
    if (l.sigalg.name != undefined) {
      k = l.sigalg.name;
    }
    var i = l.tbsobj.tohex();
    var j = new KJUR.crypto.Signature({
      alg: k
    });
    j.init(l.cakey);
    j.updateHex(i);
    l.sighex = j.sign();
  };
  this.getPEM = function () {
    return hextopem(this.tohex(), "CERTIFICATE");
  };
  this.tohex = function () {
    var k = this.params;
    if (k.tbsobj == undefined || k.tbsobj == null) {
      k.tbsobj = new a(k);
    }
    if (k.sighex == undefined && k.cakey != undefined) {
      this.sign();
    }
    if (k.sighex == undefined) {
      throw new Error("sighex or cakey parameter not defined");
    }
    var i = [];
    i.push(k.tbsobj);
    i.push(new e({
      name: k.sigalg
    }));
    i.push(new f({
      hex: "00" + k.sighex
    }));
    var j = new b({
      array: i
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (h != undefined) {
    this.params = h;
  }
};
extendClass(KJUR.asn1.x509.Certificate, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.TBSCertificate = function (f) {
  KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);
  var b = KJUR,
    i = b.asn1,
    d = i.x509,
    c = i.DERTaggedObject,
    h = i.DERInteger,
    g = i.DERSequence,
    l = d.AlgorithmIdentifier,
    e = d.Time,
    a = d.X500Name,
    j = d.Extensions,
    k = d.SubjectPublicKeyInfo;
  this.params = null;
  this.setByParam = function (m) {
    this.params = m;
  };
  this.tohex = function () {
    var n = [];
    var q = this.params;
    if (q.version != undefined || q.version != 1) {
      var m = 2;
      if (q.version != undefined) {
        m = q.version - 1;
      }
      var p = new c({
        obj: new h({
          "int": m
        })
      });
      n.push(p);
    }
    n.push(new h(q.serial));
    n.push(new l({
      name: q.sigalg
    }));
    n.push(new a(q.issuer));
    n.push(new g({
      array: [new e(q.notbefore), new e(q.notafter)]
    }));
    n.push(new a(q.subject));
    n.push(new k(KEYUTIL.getKey(q.sbjpubkey)));
    if (q.ext !== undefined && q.ext.length > 0) {
      n.push(new c({
        tag: "a3",
        obj: new j(q.ext)
      }));
    }
    var o = new KJUR.asn1.DERSequence({
      array: n
    });
    return o.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.x509.TBSCertificate, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Extensions = function (d) {
  KJUR.asn1.x509.Extensions.superclass.constructor.call(this);
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    e = b.x509;
  this.aParam = [];
  this.setByParam = function (f) {
    this.aParam = f;
  };
  this.tohex = function () {
    var f = [];
    for (var h = 0; h < this.aParam.length; h++) {
      var l = this.aParam[h];
      var k = l.extname;
      var j = null;
      if (l.extn != undefined) {
        j = new e.PrivateExtension(l);
      } else {
        if (k == "subjectKeyIdentifier") {
          j = new e.SubjectKeyIdentifier(l);
        } else {
          if (k == "keyUsage") {
            j = new e.KeyUsage(l);
          } else {
            if (k == "subjectAltName") {
              j = new e.SubjectAltName(l);
            } else {
              if (k == "issuerAltName") {
                j = new e.IssuerAltName(l);
              } else {
                if (k == "basicConstraints") {
                  j = new e.BasicConstraints(l);
                } else {
                  if (k == "nameConstraints") {
                    j = new e.NameConstraints(l);
                  } else {
                    if (k == "cRLDistributionPoints") {
                      j = new e.CRLDistributionPoints(l);
                    } else {
                      if (k == "certificatePolicies") {
                        j = new e.CertificatePolicies(l);
                      } else {
                        if (k == "policyMappings") {
                          j = new e.PolicyMappings(l);
                        } else {
                          if (k == "policyConstraints") {
                            j = new e.PolicyConstraints(l);
                          } else {
                            if (k == "inhibitAnyPolicy") {
                              j = new e.InhibitAnyPolicy(l);
                            } else {
                              if (k == "authorityKeyIdentifier") {
                                j = new e.AuthorityKeyIdentifier(l);
                              } else {
                                if (k == "extKeyUsage") {
                                  j = new e.ExtKeyUsage(l);
                                } else {
                                  if (k == "authorityInfoAccess") {
                                    j = new e.AuthorityInfoAccess(l);
                                  } else {
                                    if (k == "cRLNumber") {
                                      j = new e.CRLNumber(l);
                                    } else {
                                      if (k == "cRLReason") {
                                        j = new e.CRLReason(l);
                                      } else {
                                        if (k == "ocspNonce") {
                                          j = new e.OCSPNonce(l);
                                        } else {
                                          if (k == "ocspNoCheck") {
                                            j = new e.OCSPNoCheck(l);
                                          } else {
                                            if (k == "adobeTimeStamp") {
                                              j = new e.AdobeTimeStamp(l);
                                            } else {
                                              if (k == "subjectDirectoryAttributes") {
                                                j = new e.SubjectDirectoryAttributes(l);
                                              } else {
                                                throw new Error("extension not supported:" + JSON.stringify(l));
                                              }
                                            }
                                          }
                                        }
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (j != null) {
        f.push(j);
      }
    }
    var g = new a({
      array: f
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d != undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.x509.Extensions, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Extension = function (d) {
  KJUR.asn1.x509.Extension.superclass.constructor.call(this);
  var f = null,
    a = KJUR,
    e = a.asn1,
    h = e.DERObjectIdentifier,
    i = e.DEROctetString,
    b = e.DERBitString,
    g = e.DERBoolean,
    c = e.DERSequence;
  this.tohex = function () {
    var m = new h({
      oid: this.oid
    });
    var l = new i({
      hex: this.getExtnValueHex()
    });
    var k = new Array();
    k.push(m);
    if (this.critical) {
      k.push(new g());
    }
    k.push(l);
    var j = new c({
      array: k
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.critical = false;
  if (d !== undefined) {
    if (d.critical !== undefined) {
      this.critical = d.critical;
    }
  }
};
extendClass(KJUR.asn1.x509.Extension, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.KeyUsage = function (c) {
  KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this, c);
  var b = Error;
  var a = {
    digitalSignature: 0,
    nonRepudiation: 1,
    keyEncipherment: 2,
    dataEncipherment: 3,
    keyAgreement: 4,
    keyCertSign: 5,
    cRLSign: 6,
    encipherOnly: 7,
    decipherOnly: 8
  };
  this.getExtnValueHex = function () {
    var d = this.getBinValue();
    this.asn1ExtnValue = new KJUR.asn1.DERBitString({
      bin: d
    });
    return this.asn1ExtnValue.tohex();
  };
  this.getBinValue = function () {
    var d = this.params;
    if (typeof d != "object" || typeof d.names != "object" && typeof d.bin != "string") {
      throw new b("parameter not yet set");
    }
    if (d.names != undefined) {
      return namearraytobinstr(d.names, a);
    } else {
      if (d.bin != undefined) {
        return d.bin;
      } else {
        throw new b("parameter not set properly");
      }
    }
  };
  this.oid = "2.5.29.15";
  if (c !== undefined) {
    this.params = c;
  }
};
extendClass(KJUR.asn1.x509.KeyUsage, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.BasicConstraints = function (g) {
  KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this, g);
  var c = KJUR.asn1,
    e = c.DERBoolean,
    f = c.DERInteger,
    b = c.DERSequence;
  var a = false;
  var d = -1;
  this.getExtnValueHex = function () {
    var i = new Array();
    if (this.cA) {
      i.push(new e());
    }
    if (this.pathLen > -1) {
      i.push(new f({
        "int": this.pathLen
      }));
    }
    var h = new b({
      array: i
    });
    this.asn1ExtnValue = h;
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.19";
  this.cA = false;
  this.pathLen = -1;
  if (g !== undefined) {
    if (g.cA !== undefined) {
      this.cA = g.cA;
    }
    if (g.pathLen !== undefined) {
      this.pathLen = g.pathLen;
    }
  }
};
extendClass(KJUR.asn1.x509.BasicConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRLDistributionPoints = function (d) {
  KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this, d);
  var b = KJUR,
    a = b.asn1,
    c = a.x509;
  this.getExtnValueHex = function () {
    return this.asn1ExtnValue.tohex();
  };
  this.setByDPArray = function (e) {
    var f = [];
    for (var g = 0; g < e.length; g++) {
      if (e[g] instanceof KJUR.asn1.ASN1Object) {
        f.push(e[g]);
      } else {
        var h = new c.DistributionPoint(e[g]);
        f.push(h);
      }
    }
    this.asn1ExtnValue = new a.DERSequence({
      array: f
    });
  };
  this.setByOneURI = function (f) {
    var e = new c.DistributionPoint({
      fulluri: f
    });
    this.setByDPArray([e]);
  };
  this.oid = "2.5.29.31";
  if (d !== undefined) {
    if (d.array !== undefined) {
      this.setByDPArray(d.array);
    } else {
      if (d.uri !== undefined) {
        this.setByOneURI(d.uri);
      }
    }
  }
};
extendClass(KJUR.asn1.x509.CRLDistributionPoints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.DistributionPoint = function (e) {
  KJUR.asn1.x509.DistributionPoint.superclass.constructor.call(this);
  var a = null,
    c = KJUR,
    b = c.asn1,
    d = b.x509.DistributionPointName;
  this.tohex = function () {
    var f = new b.DERSequence();
    if (this.asn1DP != null) {
      var g = new b.DERTaggedObject({
        explicit: true,
        tag: "a0",
        obj: this.asn1DP
      });
      f.appendASN1Object(g);
    }
    this.hTLV = f.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    if (e.dpobj !== undefined) {
      this.asn1DP = e.dpobj;
    } else {
      if (e.dpname !== undefined) {
        this.asn1DP = new d(e.dpname);
      } else {
        if (e.fulluri !== undefined) {
          this.asn1DP = new d({
            full: [{
              uri: e.fulluri
            }]
          });
        }
      }
    }
  }
};
extendClass(KJUR.asn1.x509.DistributionPoint, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.DistributionPointName = function (h) {
  KJUR.asn1.x509.DistributionPointName.superclass.constructor.call(this);
  var g = null,
    d = null,
    a = null,
    f = null,
    c = KJUR,
    b = c.asn1,
    e = b.DERTaggedObject;
  this.tohex = function () {
    if (this.type != "full") {
      throw new Error("currently type shall be 'full': " + this.type);
    }
    this.asn1Obj = new e({
      explicit: false,
      tag: this.tag,
      obj: this.asn1V
    });
    this.hTLV = this.asn1Obj.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (h !== undefined) {
    if (b.x509.GeneralNames.prototype.isPrototypeOf(h)) {
      this.type = "full";
      this.tag = "a0";
      this.asn1V = h;
    } else {
      if (h.full !== undefined) {
        this.type = "full";
        this.tag = "a0";
        this.asn1V = new b.x509.GeneralNames(h.full);
      } else {
        throw new Error("This class supports GeneralNames only as argument");
      }
    }
  }
};
extendClass(KJUR.asn1.x509.DistributionPointName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CertificatePolicies = function (f) {
  KJUR.asn1.x509.CertificatePolicies.superclass.constructor.call(this, f);
  var c = KJUR,
    b = c.asn1,
    e = b.x509,
    a = b.DERSequence,
    d = e.PolicyInformation;
  this.params = null;
  this.getExtnValueHex = function () {
    var j = [];
    for (var h = 0; h < this.params.array.length; h++) {
      j.push(new d(this.params.array[h]));
    }
    var g = new a({
      array: j
    });
    this.asn1ExtnValue = g;
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.32";
  if (f !== undefined) {
    this.params = f;
  }
};
extendClass(KJUR.asn1.x509.CertificatePolicies, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PolicyInformation = function (d) {
  KJUR.asn1.x509.PolicyInformation.superclass.constructor.call(this, d);
  var c = KJUR.asn1,
    b = c.DERSequence,
    e = c.DERObjectIdentifier,
    a = c.x509.PolicyQualifierInfo;
  this.params = null;
  this.tohex = function () {
    if (this.params.policyoid === undefined && this.params.array === undefined) {
      throw new Error("parameter oid and array missing");
    }
    var f = [new e(this.params.policyoid)];
    if (this.params.array !== undefined) {
      var j = [];
      for (var h = 0; h < this.params.array.length; h++) {
        j.push(new a(this.params.array[h]));
      }
      if (j.length > 0) {
        f.push(new b({
          array: j
        }));
      }
    }
    var g = new b({
      array: f
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d !== undefined) {
    this.params = d;
  }
};
extendClass(KJUR.asn1.x509.PolicyInformation, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.PolicyQualifierInfo = function (e) {
  KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this, e);
  var c = KJUR.asn1,
    b = c.DERSequence,
    d = c.DERIA5String,
    f = c.DERObjectIdentifier,
    a = c.x509.UserNotice;
  this.params = null;
  this.tohex = function () {
    if (this.params.cps !== undefined) {
      var g = new b({
        array: [new f({
          oid: "1.3.6.1.5.5.7.2.1"
        }), new d({
          str: this.params.cps
        })]
      });
      return g.tohex();
    }
    if (this.params.unotice != undefined) {
      var g = new b({
        array: [new f({
          oid: "1.3.6.1.5.5.7.2.2"
        }), new a(this.params.unotice)]
      });
      return g.tohex();
    }
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.PolicyQualifierInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.UserNotice = function (e) {
  KJUR.asn1.x509.UserNotice.superclass.constructor.call(this, e);
  var a = KJUR.asn1.DERSequence,
    d = KJUR.asn1.DERInteger,
    c = KJUR.asn1.x509.DisplayText,
    b = KJUR.asn1.x509.NoticeReference;
  this.params = null;
  this.tohex = function () {
    var f = [];
    if (this.params.noticeref !== undefined) {
      f.push(new b(this.params.noticeref));
    }
    if (this.params.exptext !== undefined) {
      f.push(new c(this.params.exptext));
    }
    var g = new a({
      array: f
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.UserNotice, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.NoticeReference = function (d) {
  KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this, d);
  var a = KJUR.asn1.DERSequence,
    c = KJUR.asn1.DERInteger,
    b = KJUR.asn1.x509.DisplayText;
  this.params = null;
  this.tohex = function () {
    var f = [];
    if (this.params.org !== undefined) {
      f.push(new b(this.params.org));
    }
    if (this.params.noticenum !== undefined) {
      var h = [];
      var e = this.params.noticenum;
      for (var j = 0; j < e.length; j++) {
        h.push(new c(e[j]));
      }
      f.push(new a({
        array: h
      }));
    }
    if (f.length == 0) {
      throw new Error("parameter is empty");
    }
    var g = new a({
      array: f
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d !== undefined) {
    this.params = d;
  }
};
extendClass(KJUR.asn1.x509.NoticeReference, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.DisplayText = function (a) {
  KJUR.asn1.x509.DisplayText.superclass.constructor.call(this, a);
  this.hT = "0c";
  if (a !== undefined) {
    if (a.type === "ia5") {
      this.hT = "16";
    } else {
      if (a.type === "vis") {
        this.hT = "1a";
      } else {
        if (a.type === "bmp") {
          this.hT = "1e";
        }
      }
    }
  }
};
extendClass(KJUR.asn1.x509.DisplayText, KJUR.asn1.DERAbstractString);
KJUR.asn1.x509.PolicyMappings = function (e) {
  KJUR.asn1.x509.PolicyMappings.superclass.constructor.call(this, e);
  var c = KJUR,
    b = c.asn1,
    d = b.x509,
    a = b.ASN1Util.newObject;
  this.params = null;
  this.getExtnValueHex = function () {
    var j = this.params;
    var f = [];
    for (var g = 0; g < j.array.length; g++) {
      var h = j.array[g];
      f.push({
        seq: [{
          oid: h[0]
        }, {
          oid: h[1]
        }]
      });
    }
    this.asn1ExtnValue = a({
      seq: f
    });
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.33";
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.PolicyMappings, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PolicyConstraints = function (e) {
  KJUR.asn1.x509.PolicyConstraints.superclass.constructor.call(this, e);
  var c = KJUR,
    b = c.asn1,
    d = b.x509,
    a = b.ASN1Util.newObject;
  this.params = null;
  this.getExtnValueHex = function () {
    var g = this.params;
    var f = [];
    if (g.reqexp != undefined) {
      f.push({
        tag: {
          tagi: "80",
          obj: {
            "int": g.reqexp
          }
        }
      });
    }
    if (g.inhibit != undefined) {
      f.push({
        tag: {
          tagi: "81",
          obj: {
            "int": g.inhibit
          }
        }
      });
    }
    this.asn1ExtnValue = a({
      seq: f
    });
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.36";
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.PolicyConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.InhibitAnyPolicy = function (e) {
  KJUR.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this, e);
  var c = KJUR,
    b = c.asn1,
    d = b.x509,
    a = b.ASN1Util.newObject;
  this.params = null;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = a({
      "int": this.params.skip
    });
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.54";
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.InhibitAnyPolicy, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.NameConstraints = function (f) {
  KJUR.asn1.x509.NameConstraints.superclass.constructor.call(this, f);
  var c = KJUR,
    b = c.asn1,
    e = b.x509,
    a = b.ASN1Util.newObject,
    d = e.GeneralSubtree;
  this.params = null;
  this.getExtnValueHex = function () {
    var l = this.params;
    var g = [];
    if (l.permit != undefined && l.permit.length != undefined) {
      var k = [];
      for (var h = 0; h < l.permit.length; h++) {
        k.push(new d(l.permit[h]));
      }
      g.push({
        tag: {
          tagi: "a0",
          obj: {
            seq: k
          }
        }
      });
    }
    if (l.exclude != undefined && l.exclude.length != undefined) {
      var j = [];
      for (var h = 0; h < l.exclude.length; h++) {
        j.push(new d(l.exclude[h]));
      }
      g.push({
        tag: {
          tagi: "a1",
          obj: {
            seq: j
          }
        }
      });
    }
    this.asn1ExtnValue = a({
      seq: g
    });
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.30";
  if (f !== undefined) {
    this.params = f;
  }
};
extendClass(KJUR.asn1.x509.NameConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.GeneralSubtree = function (e) {
  KJUR.asn1.x509.GeneralSubtree.superclass.constructor.call(this);
  var b = KJUR.asn1,
    d = b.x509,
    c = d.GeneralName,
    a = b.ASN1Util.newObject;
  this.params = null;
  this.setByParam = function (f) {
    this.params = f;
  };
  this.tohex = function () {
    var h = this.params;
    var f = [new c(h)];
    if (h.min != undefined) {
      f.push({
        tag: {
          tagi: "80",
          obj: {
            "int": h.min
          }
        }
      });
    }
    if (h.max != undefined) {
      f.push({
        tag: {
          tagi: "81",
          obj: {
            "int": h.max
          }
        }
      });
    }
    var g = a({
      seq: f
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.x509.GeneralSubtree, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.ExtKeyUsage = function (c) {
  KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this, c);
  var b = KJUR,
    a = b.asn1;
  this.setPurposeArray = function (d) {
    this.asn1ExtnValue = new a.DERSequence();
    for (var e = 0; e < d.length; e++) {
      var f = new a.DERObjectIdentifier(d[e]);
      this.asn1ExtnValue.appendASN1Object(f);
    }
  };
  this.getExtnValueHex = function () {
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.37";
  if (c !== undefined) {
    if (c.array !== undefined) {
      this.setPurposeArray(c.array);
    }
  }
};
extendClass(KJUR.asn1.x509.ExtKeyUsage, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AuthorityKeyIdentifier = function (f) {
  KJUR.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this, f);
  var b = KJUR,
    a = b.asn1,
    d = a.DERTaggedObject,
    e = a.x509.GeneralNames,
    c = b.crypto.Util.isKey;
  this.asn1KID = null;
  this.asn1CertIssuer = null;
  this.asn1CertSN = null;
  this.getExtnValueHex = function () {
    var h = new Array();
    if (this.asn1KID) {
      h.push(new d({
        explicit: false,
        tag: "80",
        obj: this.asn1KID
      }));
    }
    if (this.asn1CertIssuer) {
      h.push(new d({
        explicit: false,
        tag: "a1",
        obj: new e([{
          dn: this.asn1CertIssuer
        }])
      }));
    }
    if (this.asn1CertSN) {
      h.push(new d({
        explicit: false,
        tag: "82",
        obj: this.asn1CertSN
      }));
    }
    var g = new a.DERSequence({
      array: h
    });
    this.asn1ExtnValue = g;
    return this.asn1ExtnValue.tohex();
  };
  this.setKIDByParam = function (i) {
    if (i.str !== undefined || i.hex !== undefined) {
      this.asn1KID = new KJUR.asn1.DEROctetString(i);
    } else {
      if (typeof i === "object" && KJUR.crypto.Util.isKey(i) || typeof i === "string" && i.indexOf("BEGIN ") != -1) {
        var h = i;
        if (typeof i === "string") {
          h = KEYUTIL.getKey(i);
        }
        var g = KEYUTIL.getKeyID(h);
        this.asn1KID = new KJUR.asn1.DEROctetString({
          hex: g
        });
      }
    }
  };
  this.setCertIssuerByParam = function (g) {
    if (g.str !== undefined || g.ldapstr !== undefined || g.hex !== undefined || g.certsubject !== undefined || g.certissuer !== undefined) {
      this.asn1CertIssuer = new KJUR.asn1.x509.X500Name(g);
    } else {
      if (typeof g === "string" && g.indexOf("BEGIN ") != -1 && g.indexOf("CERTIFICATE") != -1) {
        this.asn1CertIssuer = new KJUR.asn1.x509.X500Name({
          certissuer: g
        });
      }
    }
  };
  this.setCertSNByParam = function (i) {
    if (i.str !== undefined || i.bigint !== undefined || i.hex !== undefined) {
      this.asn1CertSN = new KJUR.asn1.DERInteger(i);
    } else {
      if (typeof i === "string" && i.indexOf("BEGIN ") != -1 && i.indexOf("CERTIFICATE")) {
        var g = new X509();
        g.readCertPEM(i);
        var h = g.getSerialNumberHex();
        this.asn1CertSN = new KJUR.asn1.DERInteger({
          hex: h
        });
      }
    }
  };
  this.oid = "2.5.29.35";
  if (f !== undefined) {
    if (f.kid !== undefined) {
      this.setKIDByParam(f.kid);
    }
    if (f.issuer !== undefined) {
      this.setCertIssuerByParam(f.issuer);
    }
    if (f.sn !== undefined) {
      this.setCertSNByParam(f.sn);
    }
    if (f.issuersn !== undefined && typeof f.issuersn === "string" && f.issuersn.indexOf("BEGIN ") != -1 && f.issuersn.indexOf("CERTIFICATE")) {
      this.setCertSNByParam(f.issuersn);
      this.setCertIssuerByParam(f.issuersn);
    }
  }
};
extendClass(KJUR.asn1.x509.AuthorityKeyIdentifier, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectKeyIdentifier = function (d) {
  KJUR.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this, d);
  var b = KJUR,
    a = b.asn1,
    c = a.DEROctetString;
  this.asn1KID = null;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = this.asn1KID;
    return this.asn1ExtnValue.tohex();
  };
  this.setKIDByParam = function (g) {
    if (g.str !== undefined || g.hex !== undefined) {
      this.asn1KID = new c(g);
    } else {
      if (typeof g === "object" && KJUR.crypto.Util.isKey(g) || typeof g === "string" && g.indexOf("BEGIN") != -1) {
        var f = g;
        if (typeof g === "string") {
          f = KEYUTIL.getKey(g);
        }
        var e = KEYUTIL.getKeyID(f);
        this.asn1KID = new KJUR.asn1.DEROctetString({
          hex: e
        });
      }
    }
  };
  this.oid = "2.5.29.14";
  if (d !== undefined) {
    if (d.kid !== undefined) {
      this.setKIDByParam(d.kid);
    }
  }
};
extendClass(KJUR.asn1.x509.SubjectKeyIdentifier, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AuthorityInfoAccess = function (a) {
  KJUR.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this, a);
  this.setAccessDescriptionArray = function (k) {
    var d = new Array(),
      b = KJUR,
      g = b.asn1,
      c = g.DERSequence,
      j = g.DERObjectIdentifier,
      l = g.x509.GeneralName;
    for (var f = 0; f < k.length; f++) {
      var e;
      var h = k[f];
      if (h.ocsp !== undefined) {
        e = new c({
          array: [new j({
            oid: "1.3.6.1.5.5.7.48.1"
          }), new l({
            uri: h.ocsp
          })]
        });
      } else {
        if (h.caissuer !== undefined) {
          e = new c({
            array: [new j({
              oid: "1.3.6.1.5.5.7.48.2"
            }), new l({
              uri: h.caissuer
            })]
          });
        } else {
          throw new Error("unknown AccessMethod parameter: " + JSON.stringify(h));
        }
      }
      d.push(e);
    }
    this.asn1ExtnValue = new c({
      array: d
    });
  };
  this.getExtnValueHex = function () {
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "1.3.6.1.5.5.7.1.1";
  if (a !== undefined) {
    if (a.array !== undefined) {
      this.setAccessDescriptionArray(a.array);
    }
  }
};
extendClass(KJUR.asn1.x509.AuthorityInfoAccess, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectAltName = function (a) {
  KJUR.asn1.x509.SubjectAltName.superclass.constructor.call(this, a);
  this.setNameArray = function (b) {
    this.asn1ExtnValue = new KJUR.asn1.x509.GeneralNames(b);
  };
  this.getExtnValueHex = function () {
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.17";
  if (a !== undefined) {
    if (a.array !== undefined) {
      this.setNameArray(a.array);
    }
  }
};
extendClass(KJUR.asn1.x509.SubjectAltName, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.IssuerAltName = function (a) {
  KJUR.asn1.x509.IssuerAltName.superclass.constructor.call(this, a);
  this.setNameArray = function (b) {
    this.asn1ExtnValue = new KJUR.asn1.x509.GeneralNames(b);
  };
  this.getExtnValueHex = function () {
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.18";
  if (a !== undefined) {
    if (a.array !== undefined) {
      this.setNameArray(a.array);
    }
  }
};
extendClass(KJUR.asn1.x509.IssuerAltName, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectDirectoryAttributes = function (e) {
  KJUR.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this, e);
  var c = KJUR.asn1,
    a = c.DERSequence,
    b = c.ASN1Util.newObject,
    d = c.x509.OID.name2oid;
  this.params = null;
  this.getExtnValueHex = function () {
    var f = [];
    for (var j = 0; j < this.params.array.length; j++) {
      var l = this.params.array[j];
      if (l.attr != undefined && l.array != undefined) {
        var k = {
          seq: [{
            oid: l.attr
          }, {
            set: l.array
          }]
        };
        f.push(b(k));
        continue;
      }
      var h = {
        seq: [{
          oid: "1.2.3.4"
        }, {
          set: [{
            utf8str: "DE"
          }]
        }]
      };
      if (l.attr == "dateOfBirth") {
        h.seq[0].oid = d(l.attr);
        h.seq[1].set[0] = {
          gentime: l.str
        };
      } else {
        if (l.attr == "placeOfBirth") {
          h.seq[0].oid = d(l.attr);
          h.seq[1].set[0] = {
            utf8str: l.str
          };
        } else {
          if (l.attr == "gender") {
            h.seq[0].oid = d(l.attr);
            h.seq[1].set[0] = {
              prnstr: l.str
            };
          } else {
            if (l.attr == "countryOfCitizenship") {
              h.seq[0].oid = d(l.attr);
              h.seq[1].set[0] = {
                prnstr: l.str
              };
            } else {
              if (l.attr == "countryOfResidence") {
                h.seq[0].oid = d(l.attr);
                h.seq[1].set[0] = {
                  prnstr: l.str
                };
              } else {
                throw new Error("unsupported attribute: " + l.attr);
              }
            }
          }
        }
      }
      f.push(new b(h));
    }
    var g = new a({
      array: f
    });
    this.asn1ExtnValue = g;
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.9";
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.x509.SubjectDirectoryAttributes, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PrivateExtension = function (f) {
  KJUR.asn1.x509.PrivateExtension.superclass.constructor.call(this, f);
  var c = KJUR,
    e = c.lang.String.isHex,
    b = c.asn1,
    d = b.x509.OID.name2oid,
    a = b.ASN1Util.newObject;
  this.params = null;
  this.setByParam = function (g) {
    this.oid = d(g.extname);
    this.params = g;
  };
  this.getExtnValueHex = function () {
    if (this.params.extname == undefined || this.params.extn == undefined) {
      throw new Error("extname or extnhex not specified");
    }
    var h = this.params.extn;
    if (typeof h == "string" && e(h)) {
      return h;
    } else {
      if (typeof h == "object") {
        try {
          return a(h).tohex();
        } catch (g) {}
      }
    }
    throw new Error("unsupported extn value");
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.x509.PrivateExtension, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRL = function (g) {
  KJUR.asn1.x509.CRL.superclass.constructor.call(this);
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    e = b.DERBitString,
    f = b.x509,
    d = f.AlgorithmIdentifier,
    h = f.TBSCertList;
  this.params = undefined;
  this.setByParam = function (i) {
    this.params = i;
  };
  this.sign = function () {
    var j = new h(this.params).tohex();
    var k = new KJUR.crypto.Signature({
      alg: this.params.sigalg
    });
    k.init(this.params.cakey);
    k.updateHex(j);
    var i = k.sign();
    this.params.sighex = i;
  };
  this.getPEM = function () {
    return hextopem(this.tohex(), "X509 CRL");
  };
  this.tohex = function () {
    var k = this.params;
    if (k.tbsobj == undefined) {
      k.tbsobj = new h(k);
    }
    if (k.sighex == undefined && k.cakey != undefined) {
      this.sign();
    }
    if (k.sighex == undefined) {
      throw new Error("sighex or cakey parameter not defined");
    }
    var i = [];
    i.push(k.tbsobj);
    i.push(new d({
      name: k.sigalg
    }));
    i.push(new e({
      hex: "00" + k.sighex
    }));
    var j = new a({
      array: i
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.params = g;
  }
};
extendClass(KJUR.asn1.x509.CRL, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.TBSCertList = function (f) {
  KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);
  var b = KJUR,
    i = b.asn1,
    h = i.DERInteger,
    g = i.DERSequence,
    c = i.DERTaggedObject,
    k = i.DERObjectIdentifier,
    d = i.x509,
    l = d.AlgorithmIdentifier,
    e = d.Time,
    j = d.Extensions,
    a = d.X500Name;
  this.params = null;
  this.setByParam = function (m) {
    this.params = m;
  };
  this.getRevCertSequence = function () {
    var m = [];
    var n = this.params.revcert;
    for (var o = 0; o < n.length; o++) {
      var p = [new h(n[o].sn), new e(n[o].date)];
      if (n[o].ext != undefined) {
        p.push(new j(n[o].ext));
      }
      m.push(new g({
        array: p
      }));
    }
    return new g({
      array: m
    });
  };
  this.tohex = function () {
    var n = [];
    var r = this.params;
    if (r.version != undefined) {
      var m = r.version - 1;
      var p = new h({
        "int": m
      });
      n.push(p);
    }
    n.push(new l({
      name: r.sigalg
    }));
    n.push(new a(r.issuer));
    n.push(new e(r.thisupdate));
    if (r.nextupdate != undefined) {
      n.push(new e(r.nextupdate));
    }
    if (r.revcert != undefined) {
      n.push(this.getRevCertSequence());
    }
    if (r.ext != undefined) {
      var q = new j(r.ext);
      n.push(new c({
        tag: "a0",
        explicit: true,
        obj: q
      }));
    }
    var o = new g({
      array: n
    });
    return o.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.x509.TBSCertList, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CRLEntry = function (e) {
  KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);
  var d = null,
    c = null,
    b = KJUR,
    a = b.asn1;
  this.setCertSerial = function (f) {
    this.sn = new a.DERInteger(f);
  };
  this.setRevocationDate = function (f) {
    this.time = new a.x509.Time(f);
  };
  this.tohex = function () {
    var f = new a.DERSequence({
      array: [this.sn, this.time]
    });
    this.TLV = f.tohex();
    return this.TLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    if (e.time !== undefined) {
      this.setRevocationDate(e.time);
    }
    if (e.sn !== undefined) {
      this.setCertSerial(e.sn);
    }
  }
};
extendClass(KJUR.asn1.x509.CRLEntry, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CRLNumber = function (a) {
  KJUR.asn1.x509.CRLNumber.superclass.constructor.call(this, a);
  this.params = undefined;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = new KJUR.asn1.DERInteger(this.params.num);
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.20";
  if (a != undefined) {
    this.params = a;
  }
};
extendClass(KJUR.asn1.x509.CRLNumber, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRLReason = function (a) {
  KJUR.asn1.x509.CRLReason.superclass.constructor.call(this, a);
  this.params = undefined;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = new KJUR.asn1.DEREnumerated(this.params.code);
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "2.5.29.21";
  if (a != undefined) {
    this.params = a;
  }
};
extendClass(KJUR.asn1.x509.CRLReason, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.OCSPNonce = function (a) {
  KJUR.asn1.x509.OCSPNonce.superclass.constructor.call(this, a);
  this.params = undefined;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = new KJUR.asn1.DEROctetString(this.params);
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "1.3.6.1.5.5.7.48.1.2";
  if (a != undefined) {
    this.params = a;
  }
};
extendClass(KJUR.asn1.x509.OCSPNonce, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.OCSPNoCheck = function (a) {
  KJUR.asn1.x509.OCSPNoCheck.superclass.constructor.call(this, a);
  this.params = undefined;
  this.getExtnValueHex = function () {
    this.asn1ExtnValue = new KJUR.asn1.DERNull();
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "1.3.6.1.5.5.7.48.1.5";
  if (a != undefined) {
    this.params = a;
  }
};
extendClass(KJUR.asn1.x509.OCSPNoCheck, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AdobeTimeStamp = function (g) {
  KJUR.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this, g);
  var c = KJUR,
    b = c.asn1,
    f = b.DERInteger,
    d = b.DERBoolean,
    a = b.DERSequence,
    e = b.x509.GeneralName;
  this.params = null;
  this.getExtnValueHex = function () {
    var i = this.params;
    var h = [new f(1)];
    h.push(new e({
      uri: i.uri
    }));
    if (i.reqauth != undefined) {
      h.push(new d(i.reqauth));
    }
    this.asn1ExtnValue = new a({
      array: h
    });
    return this.asn1ExtnValue.tohex();
  };
  this.oid = "1.2.840.113583.1.1.9.1";
  if (g !== undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.x509.AdobeTimeStamp, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.X500Name = function (f) {
  KJUR.asn1.x509.X500Name.superclass.constructor.call(this);
  this.asn1Array = [];
  this.paramArray = [];
  this.sRule = "utf8";
  var c = KJUR,
    b = c.asn1,
    e = b.x509,
    d = e.RDN,
    a = pemtohex;
  this.setByString = function (g, l) {
    if (l !== undefined) {
      this.sRule = l;
    }
    var k = g.split("/");
    k.shift();
    var j = [];
    for (var m = 0; m < k.length; m++) {
      if (k[m].match(/^[^=]+=.+$/)) {
        j.push(k[m]);
      } else {
        var h = j.length - 1;
        j[h] = j[h] + "/" + k[m];
      }
    }
    for (var m = 0; m < j.length; m++) {
      this.asn1Array.push(new d({
        str: j[m],
        rule: this.sRule
      }));
    }
  };
  this.setByLdapString = function (g, h) {
    if (h !== undefined) {
      this.sRule = h;
    }
    var i = e.X500Name.ldapToCompat(g);
    this.setByString(i, h);
  };
  this.setByObject = function (j, i) {
    if (i !== undefined) {
      this.sRule = i;
    }
    for (var g in j) {
      if (j.hasOwnProperty(g)) {
        var h = new d({
          str: g + "=" + j[g],
          rule: this.sRule
        });
        this.asn1Array ? this.asn1Array.push(h) : this.asn1Array = [h];
      }
    }
  };
  this.setByParam = function (h) {
    if (h.rule !== undefined) {
      this.sRule = h.rule;
    }
    if (h.array !== undefined) {
      this.paramArray = h.array;
    } else {
      if (h.str !== undefined) {
        this.setByString(h.str);
      } else {
        if (h.ldapstr !== undefined) {
          this.setByLdapString(h.ldapstr);
        } else {
          if (h.hex !== undefined) {
            this.hTLV = h.hex;
          } else {
            if (h.certissuer !== undefined) {
              var g = new X509();
              g.readCertPEM(h.certissuer);
              this.hTLV = g.getIssuerHex();
            } else {
              if (h.certsubject !== undefined) {
                var g = new X509();
                g.readCertPEM(h.certsubject);
                this.hTLV = g.getSubjectHex();
              } else {
                if (typeof h === "object" && h.certsubject === undefined && h.certissuer === undefined) {
                  this.setByObject(h);
                }
              }
            }
          }
        }
      }
    }
  };
  this.tohex = function () {
    if (typeof this.hTLV == "string") {
      return this.hTLV;
    }
    if (this.asn1Array.length == 0 && this.paramArray.length > 0) {
      for (var g = 0; g < this.paramArray.length; g++) {
        var k = {
          array: this.paramArray[g]
        };
        if (this.sRule != "utf8") {
          k.rule = this.sRule;
        }
        var h = new d(k);
        this.asn1Array.push(h);
      }
    }
    var j = new b.DERSequence({
      array: this.asn1Array
    });
    this.hTLV = j.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.x509.X500Name, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.X500Name.compatToLDAP = function (d) {
  if (d.substr(0, 1) !== "/") {
    throw "malformed input";
  }
  var b = "";
  d = d.substr(1);
  var c = d.split("/");
  c.reverse();
  c = c.map(function (a) {
    return a.replace(/,/, "\\,");
  });
  return c.join(",");
};
KJUR.asn1.x509.X500Name.onelineToLDAP = function (a) {
  return KJUR.asn1.x509.X500Name.compatToLDAP(a);
};
KJUR.asn1.x509.X500Name.ldapToCompat = function (g) {
  var c = g.split(",");
  var e = false;
  var b = [];
  for (var f = 0; c.length > 0; f++) {
    var h = c.shift();
    if (e === true) {
      var d = b.pop();
      var j = (d + "," + h).replace(/\\,/g, ",");
      b.push(j);
      e = false;
    } else {
      b.push(h);
    }
    if (h.substr(-1, 1) === "\\") {
      e = true;
    }
  }
  b = b.map(function (a) {
    return a.replace("/", "\\/");
  });
  b.reverse();
  return "/" + b.join("/");
};
KJUR.asn1.x509.X500Name.ldapToOneline = function (a) {
  return KJUR.asn1.x509.X500Name.ldapToCompat(a);
};
KJUR.asn1.x509.RDN = function (b) {
  KJUR.asn1.x509.RDN.superclass.constructor.call(this);
  this.asn1Array = [];
  this.paramArray = [];
  this.sRule = "utf8";
  var a = KJUR.asn1.x509.AttributeTypeAndValue;
  this.setByParam = function (c) {
    if (c.rule !== undefined) {
      this.sRule = c.rule;
    }
    if (c.str !== undefined) {
      this.addByMultiValuedString(c.str);
    }
    if (c.array !== undefined) {
      this.paramArray = c.array;
    }
  };
  this.addByString = function (c) {
    this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({
      str: c,
      rule: this.sRule
    }));
  };
  this.addByMultiValuedString = function (e) {
    var c = KJUR.asn1.x509.RDN.parseString(e);
    for (var d = 0; d < c.length; d++) {
      this.addByString(c[d]);
    }
  };
  this.tohex = function () {
    if (this.asn1Array.length == 0 && this.paramArray.length > 0) {
      for (var d = 0; d < this.paramArray.length; d++) {
        var f = this.paramArray[d];
        if (f.rule !== undefined && this.sRule != "utf8") {
          f.rule = this.sRule;
        }
        var c = new a(f);
        this.asn1Array.push(c);
      }
    }
    var e = new KJUR.asn1.DERSet({
      array: this.asn1Array
    });
    this.TLV = e.tohex();
    return this.TLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (b !== undefined) {
    this.setByParam(b);
  }
};
extendClass(KJUR.asn1.x509.RDN, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.RDN.parseString = function (m) {
  var j = m.split(/\+/);
  var h = false;
  var c = [];
  for (var g = 0; j.length > 0; g++) {
    var k = j.shift();
    if (h === true) {
      var f = c.pop();
      var d = (f + "+" + k).replace(/\\\+/g, "+");
      c.push(d);
      h = false;
    } else {
      c.push(k);
    }
    if (k.substr(-1, 1) === "\\") {
      h = true;
    }
  }
  var l = false;
  var b = [];
  for (var g = 0; c.length > 0; g++) {
    var k = c.shift();
    if (l === true) {
      var e = b.pop();
      if (k.match(/"$/)) {
        var d = (e + "+" + k).replace(/^([^=]+)="(.*)"$/, "$1=$2");
        b.push(d);
        l = false;
      } else {
        b.push(e + "+" + k);
      }
    } else {
      b.push(k);
    }
    if (k.match(/^[^=]+="/)) {
      l = true;
    }
  }
  return b;
};
KJUR.asn1.x509.AttributeTypeAndValue = function (c) {
  KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this);
  this.sRule = "utf8";
  this.sType = null;
  this.sValue = null;
  this.dsType = null;
  var a = KJUR,
    g = a.asn1,
    d = g.DERSequence,
    l = g.DERUTF8String,
    i = g.DERPrintableString,
    h = g.DERTeletexString,
    b = g.DERIA5String,
    e = g.DERVisibleString,
    k = g.DERBMPString,
    f = a.lang.String.isMail,
    j = a.lang.String.isPrintable;
  this.setByParam = function (o) {
    if (o.rule !== undefined) {
      this.sRule = o.rule;
    }
    if (o.ds !== undefined) {
      this.dsType = o.ds;
    }
    if (o.value === undefined && o.str !== undefined) {
      var n = o.str;
      var m = n.match(/^([^=]+)=(.+)$/);
      if (m) {
        this.sType = m[1];
        this.sValue = m[2];
      } else {
        throw new Error("malformed attrTypeAndValueStr: " + attrTypeAndValueStr);
      }
    } else {
      this.sType = o.type;
      this.sValue = o.value;
    }
  };
  this.setByString = function (n, o) {
    if (o !== undefined) {
      this.sRule = o;
    }
    var m = n.match(/^([^=]+)=(.+)$/);
    if (m) {
      this.setByAttrTypeAndValueStr(m[1], m[2]);
    } else {
      throw new Error("malformed attrTypeAndValueStr: " + attrTypeAndValueStr);
    }
  };
  this._getDsType = function () {
    var o = this.sType;
    var n = this.sValue;
    var m = this.sRule;
    if (m === "prn") {
      if (o == "CN" && f(n)) {
        return "ia5";
      }
      if (j(n)) {
        return "prn";
      }
      return "utf8";
    } else {
      if (m === "utf8") {
        if (o == "CN" && f(n)) {
          return "ia5";
        }
        if (o == "C") {
          return "prn";
        }
        return "utf8";
      }
    }
    return "utf8";
  };
  this.setByAttrTypeAndValueStr = function (o, n, m) {
    if (m !== undefined) {
      this.sRule = m;
    }
    this.sType = o;
    this.sValue = n;
  };
  this.getValueObj = function (n, m) {
    if (n == "utf8") {
      return new l({
        str: m
      });
    }
    if (n == "prn") {
      return new i({
        str: m
      });
    }
    if (n == "tel") {
      return new h({
        str: m
      });
    }
    if (n == "ia5") {
      return new b({
        str: m
      });
    }
    if (n == "vis") {
      return new e({
        str: m
      });
    }
    if (n == "bmp") {
      return new k({
        str: m
      });
    }
    throw new Error("unsupported directory string type: type=" + n + " value=" + m);
  };
  this.tohex = function () {
    if (this.dsType == null) {
      this.dsType = this._getDsType();
    }
    var n = KJUR.asn1.x509.OID.atype2obj(this.sType);
    var m = this.getValueObj(this.dsType, this.sValue);
    var p = new d({
      array: [n, m]
    });
    this.TLV = p.tohex();
    return this.TLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (c !== undefined) {
    this.setByParam(c);
  }
};
extendClass(KJUR.asn1.x509.AttributeTypeAndValue, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.SubjectPublicKeyInfo = function (f) {
  KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);
  var l = null,
    k = null,
    a = KJUR,
    j = a.asn1,
    i = j.DERInteger,
    b = j.DERBitString,
    m = j.DERObjectIdentifier,
    e = j.DERSequence,
    h = j.ASN1Util.newObject,
    d = j.x509,
    o = d.AlgorithmIdentifier,
    g = a.crypto,
    n = g.ECDSA,
    c = g.DSA;
  this.getASN1Object = function () {
    if (this.asn1AlgId == null || this.asn1SubjPKey == null) {
      throw "algId and/or subjPubKey not set";
    }
    var p = new e({
      array: [this.asn1AlgId, this.asn1SubjPKey]
    });
    return p;
  };
  this.tohex = function () {
    var p = this.getASN1Object();
    this.hTLV = p.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setPubKey = function (q) {
    try {
      if (q instanceof RSAKey) {
        var u = h({
          seq: [{
            "int": {
              bigint: q.n
            }
          }, {
            "int": {
              "int": q.e
            }
          }]
        });
        var s = u.tohex();
        this.asn1AlgId = new o({
          name: "rsaEncryption"
        });
        this.asn1SubjPKey = new b({
          hex: "00" + s
        });
      }
    } catch (p) {}
    try {
      if (q instanceof KJUR.crypto.ECDSA) {
        var r = new m({
          name: q.curveName
        });
        this.asn1AlgId = new o({
          name: "ecPublicKey",
          asn1params: r
        });
        this.asn1SubjPKey = new b({
          hex: "00" + q.pubKeyHex
        });
      }
    } catch (p) {}
    try {
      if (q instanceof KJUR.crypto.DSA) {
        var r = new h({
          seq: [{
            "int": {
              bigint: q.p
            }
          }, {
            "int": {
              bigint: q.q
            }
          }, {
            "int": {
              bigint: q.g
            }
          }]
        });
        this.asn1AlgId = new o({
          name: "dsa",
          asn1params: r
        });
        var t = new i({
          bigint: q.y
        });
        this.asn1SubjPKey = new b({
          hex: "00" + t.tohex()
        });
      }
    } catch (p) {}
  };
  if (f !== undefined) {
    this.setPubKey(f);
  }
};
extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Time = function (f) {
  KJUR.asn1.x509.Time.superclass.constructor.call(this);
  var e = null,
    a = null,
    d = KJUR,
    c = d.asn1,
    b = c.DERUTCTime,
    g = c.DERGeneralizedTime;
  this.params = null;
  this.type = null;
  this.setTimeParams = function (h) {
    this.timeParams = h;
  };
  this.setByParam = function (h) {
    this.params = h;
  };
  this.getType = function (h) {
    if (h.match(/^[0-9]{12}Z$/)) {
      return "utc";
    }
    if (h.match(/^[0-9]{14}Z$/)) {
      return "gen";
    }
    if (h.match(/^[0-9]{12}\.[0-9]+Z$/)) {
      return "utc";
    }
    if (h.match(/^[0-9]{14}\.[0-9]+Z$/)) {
      return "gen";
    }
    return null;
  };
  this.tohex = function () {
    var i = this.params;
    var h = null;
    if (typeof i == "string") {
      i = {
        str: i
      };
    }
    if (i != null && i.str && (i.type == null || i.type == undefined)) {
      i.type = this.getType(i.str);
    }
    if (i != null && i.str) {
      if (i.type == "utc") {
        h = new b(i.str);
      }
      if (i.type == "gen") {
        h = new g(i.str);
      }
    } else {
      if (this.type == "gen") {
        h = new g();
      } else {
        h = new b();
      }
    }
    if (h == null) {
      throw new Error("wrong setting for Time");
    }
    this.TLV = h.tohex();
    return this.TLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
KJUR.asn1.x509.Time_bak = function (f) {
  KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);
  var e = null,
    a = null,
    d = KJUR,
    c = d.asn1,
    b = c.DERUTCTime,
    g = c.DERGeneralizedTime;
  this.setTimeParams = function (h) {
    this.timeParams = h;
  };
  this.tohex = function () {
    var h = null;
    if (this.timeParams != null) {
      if (this.type == "utc") {
        h = new b(this.timeParams);
      } else {
        h = new g(this.timeParams);
      }
    } else {
      if (this.type == "utc") {
        h = new b();
      } else {
        h = new g();
      }
    }
    this.TLV = h.tohex();
    return this.TLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.type = "utc";
  if (f !== undefined) {
    if (f.type !== undefined) {
      this.type = f.type;
    } else {
      if (f.str !== undefined) {
        if (f.str.match(/^[0-9]{12}Z$/)) {
          this.type = "utc";
        }
        if (f.str.match(/^[0-9]{14}Z$/)) {
          this.type = "gen";
        }
      }
    }
    this.timeParams = f;
  }
};
extendClass(KJUR.asn1.x509.Time, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.AlgorithmIdentifier = function (e) {
  KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this);
  this.nameAlg = null;
  this.asn1Alg = null;
  this.asn1Params = null;
  this.paramEmpty = false;
  var b = KJUR,
    a = b.asn1,
    c = a.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;
  this.tohex = function () {
    if (this.nameAlg === null && this.asn1Alg === null) {
      throw new Error("algorithm not specified");
    }
    if (this.nameAlg !== null) {
      var f = null;
      for (var h in c) {
        if (h === this.nameAlg) {
          f = c[h];
        }
      }
      if (f !== null) {
        this.hTLV = f;
        return this.hTLV;
      }
    }
    if (this.nameAlg !== null && this.asn1Alg === null) {
      this.asn1Alg = a.x509.OID.name2obj(this.nameAlg);
    }
    var g = [this.asn1Alg];
    if (this.asn1Params !== null) {
      g.push(this.asn1Params);
    }
    var i = new a.DERSequence({
      array: g
    });
    this.hTLV = i.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    if (e.name !== undefined) {
      this.nameAlg = e.name;
    }
    if (e.asn1params !== undefined) {
      this.asn1Params = e.asn1params;
    }
    if (e.paramempty !== undefined) {
      this.paramEmpty = e.paramempty;
    }
  }
  if (this.asn1Params === null && this.paramEmpty === false && this.nameAlg !== null) {
    if (this.nameAlg.name !== undefined) {
      this.nameAlg = this.nameAlg.name;
    }
    var d = this.nameAlg.toLowerCase();
    if (d.substr(-7, 7) !== "withdsa" && d.substr(-9, 9) !== "withecdsa") {
      this.asn1Params = new a.DERNull();
    }
  }
};
extendClass(KJUR.asn1.x509.AlgorithmIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV = {
  SHAwithRSAandMGF1: "300d06092a864886f70d01010a3000",
  SHA256withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",
  SHA384withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",
  SHA512withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"
};
KJUR.asn1.x509.GeneralName = function (f) {
  KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);
  var l = {
      rfc822: "81",
      dns: "82",
      dn: "a4",
      uri: "86",
      ip: "87",
      otherName: "a0"
    },
    b = KJUR,
    h = b.asn1,
    d = h.x509,
    a = d.X500Name,
    g = d.OtherName,
    e = h.DERIA5String,
    i = h.DERPrintableString,
    k = h.DEROctetString,
    c = h.DERTaggedObject,
    m = h.ASN1Object,
    j = Error;
  this.params = null;
  this.setByParam = function (n) {
    this.params = n;
  };
  this.tohex = function () {
    var p = this.params;
    var A, y, q;
    var y = false;
    if (p.other !== undefined) {
      A = "a0", q = new g(p.other);
    } else {
      if (p.rfc822 !== undefined) {
        A = "81";
        q = new e({
          str: p.rfc822
        });
      } else {
        if (p.dns !== undefined) {
          A = "82";
          q = new e({
            str: p.dns
          });
        } else {
          if (p.dn !== undefined) {
            A = "a4";
            y = true;
            if (typeof p.dn === "string") {
              q = new a({
                str: p.dn
              });
            } else {
              if (p.dn instanceof KJUR.asn1.x509.X500Name) {
                q = p.dn;
              } else {
                q = new a(p.dn);
              }
            }
          } else {
            if (p.ldapdn !== undefined) {
              A = "a4";
              y = true;
              q = new a({
                ldapstr: p.ldapdn
              });
            } else {
              if (p.certissuer !== undefined || p.certsubj !== undefined) {
                A = "a4";
                y = true;
                var n, o;
                var z = null;
                if (p.certsubj !== undefined) {
                  n = false;
                  o = p.certsubj;
                } else {
                  n = true;
                  o = p.certissuer;
                }
                if (o.match(/^[0-9A-Fa-f]+$/)) {
                  z == o;
                }
                if (o.indexOf("-----BEGIN ") != -1) {
                  z = pemtohex(o);
                }
                if (z == null) {
                  throw new Error("certsubj/certissuer not cert");
                }
                var w = new X509();
                w.hex = z;
                var s;
                if (n) {
                  s = w.getIssuerHex();
                } else {
                  s = w.getSubjectHex();
                }
                q = new m();
                q.hTLV = s;
              } else {
                if (p.uri !== undefined) {
                  A = "86";
                  q = new e({
                    str: p.uri
                  });
                } else {
                  if (p.ip !== undefined) {
                    A = "87";
                    var v;
                    var t = p.ip;
                    try {
                      if (t.match(/^[0-9a-f]+$/)) {
                        var r = t.length;
                        if (r == 8 || r == 16 || r == 32 || r == 64) {
                          v = t;
                        } else {
                          throw "err";
                        }
                      } else {
                        v = iptohex(t);
                      }
                    } catch (u) {
                      throw new j("malformed IP address: " + p.ip + ":" + u.message);
                    }
                    q = new k({
                      hex: v
                    });
                  } else {
                    throw new j("improper params");
                  }
                }
              }
            }
          }
        }
      }
    }
    var B = new c({
      tag: A,
      explicit: y,
      obj: q
    });
    return B.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.x509.GeneralName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.GeneralNames = function (d) {
  KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);
  var a = null,
    c = KJUR,
    b = c.asn1;
  this.setByParamArray = function (g) {
    for (var e = 0; e < g.length; e++) {
      var f = new b.x509.GeneralName(g[e]);
      this.asn1Array.push(f);
    }
  };
  this.tohex = function () {
    var e = new b.DERSequence({
      array: this.asn1Array
    });
    return e.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.asn1Array = new Array();
  if (typeof d != "undefined") {
    this.setByParamArray(d);
  }
};
extendClass(KJUR.asn1.x509.GeneralNames, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.OtherName = function (g) {
  KJUR.asn1.x509.OtherName.superclass.constructor.call(this);
  var f = null,
    e = null,
    d = KJUR,
    c = d.asn1,
    h = c.DERObjectIdentifier,
    a = c.DERSequence,
    b = c.ASN1Util.newObject;
  this.params = null;
  this.setByParam = function (i) {
    this.params = i;
  };
  this.tohex = function () {
    var k = this.params;
    if (k.oid == undefined || k.value == undefined) {
      throw new Error("oid or value not specified");
    }
    var l = new h({
      oid: k.oid
    });
    var i = b({
      tag: {
        tag: "a0",
        explicit: true,
        obj: k.value
      }
    });
    var j = new a({
      array: [l, i]
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g !== undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.x509.OtherName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.OID = new function () {
  var a = KJUR.asn1.DERObjectIdentifier;
  this.name2oidList = {
    "aes128-CBC": "2.16.840.1.101.3.4.1.2",
    "aes256-CBC": "2.16.840.1.101.3.4.1.42",
    sha1: "1.3.14.3.2.26",
    sha256: "2.16.840.1.101.3.4.2.1",
    sha384: "2.16.840.1.101.3.4.2.2",
    sha512: "2.16.840.1.101.3.4.2.3",
    sha224: "2.16.840.1.101.3.4.2.4",
    md5: "1.2.840.113549.2.5",
    md2: "1.3.14.7.2.2.1",
    ripemd160: "1.3.36.3.2.1",
    hmacWithSHA1: "1.2.840.113549.2.7",
    hmacWithSHA224: "1.2.840.113549.2.8",
    hmacWithSHA256: "1.2.840.113549.2.9",
    hmacWithSHA384: "1.2.840.113549.2.10",
    hmacWithSHA512: "1.2.840.113549.2.11",
    MD2withRSA: "1.2.840.113549.1.1.2",
    MD4withRSA: "1.2.840.113549.1.1.3",
    MD5withRSA: "1.2.840.113549.1.1.4",
    SHA1withRSA: "1.2.840.113549.1.1.5",
    "pkcs1-MGF": "1.2.840.113549.1.1.8",
    rsaPSS: "1.2.840.113549.1.1.10",
    SHA224withRSA: "1.2.840.113549.1.1.14",
    SHA256withRSA: "1.2.840.113549.1.1.11",
    SHA384withRSA: "1.2.840.113549.1.1.12",
    SHA512withRSA: "1.2.840.113549.1.1.13",
    SHA1withECDSA: "1.2.840.10045.4.1",
    SHA224withECDSA: "1.2.840.10045.4.3.1",
    SHA256withECDSA: "1.2.840.10045.4.3.2",
    SHA384withECDSA: "1.2.840.10045.4.3.3",
    SHA512withECDSA: "1.2.840.10045.4.3.4",
    dsa: "1.2.840.10040.4.1",
    SHA1withDSA: "1.2.840.10040.4.3",
    SHA224withDSA: "2.16.840.1.101.3.4.3.1",
    SHA256withDSA: "2.16.840.1.101.3.4.3.2",
    rsaEncryption: "1.2.840.113549.1.1.1",
    commonName: "2.5.4.3",
    countryName: "2.5.4.6",
    localityName: "2.5.4.7",
    stateOrProvinceName: "2.5.4.8",
    streetAddress: "2.5.4.9",
    organizationName: "2.5.4.10",
    organizationalUnitName: "2.5.4.11",
    domainComponent: "0.9.2342.19200300.100.1.25",
    userId: "0.9.2342.19200300.100.1.1",
    surname: "2.5.4.4",
    givenName: "2.5.4.42",
    title: "2.5.4.12",
    distinguishedName: "2.5.4.49",
    emailAddress: "1.2.840.113549.1.9.1",
    description: "2.5.4.13",
    businessCategory: "2.5.4.15",
    postalCode: "2.5.4.17",
    uniqueIdentifier: "2.5.4.45",
    organizationIdentifier: "2.5.4.97",
    jurisdictionOfIncorporationL: "1.3.6.1.4.1.311.60.2.1.1",
    jurisdictionOfIncorporationSP: "1.3.6.1.4.1.311.60.2.1.2",
    jurisdictionOfIncorporationC: "1.3.6.1.4.1.311.60.2.1.3",
    subjectDirectoryAttributes: "2.5.29.9",
    subjectKeyIdentifier: "2.5.29.14",
    keyUsage: "2.5.29.15",
    subjectAltName: "2.5.29.17",
    issuerAltName: "2.5.29.18",
    basicConstraints: "2.5.29.19",
    cRLNumber: "2.5.29.20",
    cRLReason: "2.5.29.21",
    nameConstraints: "2.5.29.30",
    cRLDistributionPoints: "2.5.29.31",
    certificatePolicies: "2.5.29.32",
    anyPolicy: "2.5.29.32.0",
    policyMappings: "2.5.29.33",
    authorityKeyIdentifier: "2.5.29.35",
    policyConstraints: "2.5.29.36",
    extKeyUsage: "2.5.29.37",
    inhibitAnyPolicy: "2.5.29.54",
    authorityInfoAccess: "1.3.6.1.5.5.7.1.1",
    ocsp: "1.3.6.1.5.5.7.48.1",
    ocspBasic: "1.3.6.1.5.5.7.48.1.1",
    ocspNonce: "1.3.6.1.5.5.7.48.1.2",
    ocspNoCheck: "1.3.6.1.5.5.7.48.1.5",
    caIssuers: "1.3.6.1.5.5.7.48.2",
    anyExtendedKeyUsage: "2.5.29.37.0",
    serverAuth: "1.3.6.1.5.5.7.3.1",
    clientAuth: "1.3.6.1.5.5.7.3.2",
    codeSigning: "1.3.6.1.5.5.7.3.3",
    emailProtection: "1.3.6.1.5.5.7.3.4",
    timeStamping: "1.3.6.1.5.5.7.3.8",
    ocspSigning: "1.3.6.1.5.5.7.3.9",
    smtpUTF8Mailbox: "1.3.6.1.5.5.7.8.9",
    dateOfBirth: "1.3.6.1.5.5.7.9.1",
    placeOfBirth: "1.3.6.1.5.5.7.9.2",
    gender: "1.3.6.1.5.5.7.9.3",
    countryOfCitizenship: "1.3.6.1.5.5.7.9.4",
    countryOfResidence: "1.3.6.1.5.5.7.9.5",
    ecPublicKey: "1.2.840.10045.2.1",
    "P-256": "1.2.840.10045.3.1.7",
    secp256r1: "1.2.840.10045.3.1.7",
    secp256k1: "1.3.132.0.10",
    secp384r1: "1.3.132.0.34",
    secp521r1: "1.3.132.0.35",
    pkcs5PBES2: "1.2.840.113549.1.5.13",
    pkcs5PBKDF2: "1.2.840.113549.1.5.12",
    "des-EDE3-CBC": "1.2.840.113549.3.7",
    data: "1.2.840.113549.1.7.1",
    "signed-data": "1.2.840.113549.1.7.2",
    "enveloped-data": "1.2.840.113549.1.7.3",
    "digested-data": "1.2.840.113549.1.7.5",
    "encrypted-data": "1.2.840.113549.1.7.6",
    "authenticated-data": "1.2.840.113549.1.9.16.1.2",
    tstinfo: "1.2.840.113549.1.9.16.1.4",
    signingCertificate: "1.2.840.113549.1.9.16.2.12",
    timeStampToken: "1.2.840.113549.1.9.16.2.14",
    signaturePolicyIdentifier: "1.2.840.113549.1.9.16.2.15",
    etsArchiveTimeStamp: "1.2.840.113549.1.9.16.2.27",
    signingCertificateV2: "1.2.840.113549.1.9.16.2.47",
    etsArchiveTimeStampV2: "1.2.840.113549.1.9.16.2.48",
    extensionRequest: "1.2.840.113549.1.9.14",
    contentType: "1.2.840.113549.1.9.3",
    messageDigest: "1.2.840.113549.1.9.4",
    signingTime: "1.2.840.113549.1.9.5",
    counterSignature: "1.2.840.113549.1.9.6",
    archiveTimeStampV3: "0.4.0.1733.2.4",
    pdfRevocationInfoArchival: "1.2.840.113583.1.1.8",
    adobeTimeStamp: "1.2.840.113583.1.1.9.1",
    smimeMailboxLegacy: "2.23.140.1.5.1.1",
    smimeMailboxMulti: "2.23.140.1.5.1.2",
    smimeMailboxStrict: "2.23.140.1.5.1.3",
    smimeOrganizationLegacy: "2.23.140.1.5.2.1",
    smimeOrganizationMulti: "2.23.140.1.5.2.2",
    smimeOrganizationStrict: "2.23.140.1.5.2.3",
    smimeSponsorLegacy: "2.23.140.1.5.3.1",
    smimeSponsorMulti: "2.23.140.1.5.3.2",
    smimeSponsorStrict: "2.23.140.1.5.3.3",
    smimeIndividualLegacy: "2.23.140.1.5.4.1",
    smimeIndividualMulti: "2.23.140.1.5.4.2",
    smimeIndividualStrict: "2.23.140.1.5.4.3"
  };
  this.atype2oidList = {
    CN: "2.5.4.3",
    L: "2.5.4.7",
    ST: "2.5.4.8",
    O: "2.5.4.10",
    OU: "2.5.4.11",
    C: "2.5.4.6",
    STREET: "2.5.4.9",
    DC: "0.9.2342.19200300.100.1.25",
    UID: "0.9.2342.19200300.100.1.1",
    SN: "2.5.4.4",
    T: "2.5.4.12",
    GN: "2.5.4.42",
    DN: "2.5.4.49",
    E: "1.2.840.113549.1.9.1",
    description: "2.5.4.13",
    businessCategory: "2.5.4.15",
    postalCode: "2.5.4.17",
    serialNumber: "2.5.4.5",
    uniqueIdentifier: "2.5.4.45",
    organizationIdentifier: "2.5.4.97",
    jurisdictionOfIncorporationL: "1.3.6.1.4.1.311.60.2.1.1",
    jurisdictionOfIncorporationSP: "1.3.6.1.4.1.311.60.2.1.2",
    jurisdictionOfIncorporationC: "1.3.6.1.4.1.311.60.2.1.3"
  };
  this.objCache = {};
  this.name2obj = function (b) {
    if (typeof this.objCache[b] != "undefined") {
      return this.objCache[b];
    }
    if (typeof this.name2oidList[b] == "undefined") {
      throw "Name of ObjectIdentifier not defined: " + b;
    }
    var c = this.name2oidList[b];
    var d = new a({
      oid: c
    });
    this.objCache[b] = d;
    return d;
  };
  this.atype2obj = function (b) {
    if (this.objCache[b] !== undefined) {
      return this.objCache[b];
    }
    var c;
    if (b.match(/^\d+\.\d+\.[0-9.]+$/)) {
      c = b;
    } else {
      if (this.atype2oidList[b] !== undefined) {
        c = this.atype2oidList[b];
      } else {
        if (this.name2oidList[b] !== undefined) {
          c = this.name2oidList[b];
        } else {
          throw new Error("AttributeType name undefined: " + b);
        }
      }
    }
    var d = new a({
      oid: c
    });
    this.objCache[b] = d;
    return d;
  };
  this.registerOIDs = function (b) {
    if (!this.checkOIDs(b)) {
      return;
    }
    for (var c in b) {
      this.name2oidList[c] = b[c];
    }
  };
  this.checkOIDs = function (b) {
    try {
      var d = Object.keys(b);
      if (d.length == 0) {
        return false;
      }
      d.map(function (g, e, h) {
        var f = this[g];
        if (!f.match(/^[0-2]\.[0-9.]+$/)) {
          throw new Error("value is not OID");
        }
      }, b);
      return true;
    } catch (c) {
      return false;
    }
  };
}();
KJUR.asn1.x509.OID.oid2name = function (b) {
  var c = KJUR.asn1.x509.OID.name2oidList;
  for (var a in c) {
    if (c[a] == b) {
      return a;
    }
  }
  return "";
};
KJUR.asn1.x509.OID.oid2atype = function (b) {
  var c = KJUR.asn1.x509.OID.atype2oidList;
  for (var a in c) {
    if (c[a] == b) {
      return a;
    }
  }
  return b;
};
KJUR.asn1.x509.OID.name2oid = function (a) {
  if (a.match(/^[0-9.]+$/)) {
    return a;
  }
  var b = KJUR.asn1.x509.OID.name2oidList;
  if (b[a] === undefined) {
    return "";
  }
  return b[a];
};
KJUR.asn1.x509.X509Util = {};
KJUR.asn1.x509.X509Util.newCertPEM = function (e) {
  var d = KJUR.asn1.x509,
    b = d.TBSCertificate,
    a = d.Certificate;
  var c = new a(e);
  return c.getPEM();
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
if (typeof KJUR.asn1.cms == "undefined" || !KJUR.asn1.cms) {
  KJUR.asn1.cms = {};
}
KJUR.asn1.cms.Attribute = function (f) {
  var e = Error,
    d = KJUR,
    c = d.asn1,
    b = c.DERSequence,
    a = c.DERSet,
    g = c.DERObjectIdentifier;
  this.params = null;
  this.typeOid = null;
  this.setByParam = function (h) {
    this.params = h;
  };
  this.getValueArray = function () {
    throw new e("not yet implemented abstract");
  };
  this.tohex = function () {
    var j = new g({
      oid: this.typeOid
    });
    var h = new a({
      array: this.getValueArray()
    });
    var i = new b({
      array: [j, h]
    });
    return i.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
};
extendClass(KJUR.asn1.cms.Attribute, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.ContentType = function (c) {
  var b = KJUR,
    a = b.asn1;
  a.cms.ContentType.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.3";
  this.getValueArray = function () {
    var d = new a.DERObjectIdentifier(this.params.type);
    return [d];
  };
  if (c != undefined) {
    this.setByParam(c);
  }
};
extendClass(KJUR.asn1.cms.ContentType, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.MessageDigest = function (e) {
  var b = KJUR,
    a = b.asn1,
    c = a.DEROctetString,
    d = a.cms;
  d.MessageDigest.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.4";
  this.getValueArray = function () {
    var f = new c(this.params);
    return [f];
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cms.MessageDigest, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.SigningTime = function (c) {
  var b = KJUR,
    a = b.asn1;
  a.cms.SigningTime.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.5";
  this.getValueArray = function () {
    var d = new a.x509.Time(this.params);
    return [d];
  };
  if (c != undefined) {
    this.setByParam(c);
  }
};
extendClass(KJUR.asn1.cms.SigningTime, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.SigningCertificate = function (h) {
  var e = Error,
    d = KJUR,
    c = d.asn1,
    b = c.DERSequence,
    g = c.cms,
    a = g.ESSCertID,
    f = d.crypto;
  g.SigningCertificate.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.16.2.12";
  this.getValueArray = function () {
    if (this.params == null || this.params == undefined || this.params.array == undefined) {
      throw new e("parameter 'array' not specified");
    }
    var o = this.params.array;
    var k = [];
    for (var l = 0; l < o.length; l++) {
      var n = o[l];
      if (h.hasis == false && typeof n == "string" && (n.indexOf("-----BEGIN") != -1 || ASN1HEX.isASN1HEX(n))) {
        n = {
          cert: n
        };
      }
      if (n.hasis != false && h.hasis == false) {
        n.hasis = false;
      }
      k.push(new a(n));
    }
    var j = new b({
      array: k
    });
    var m = new b({
      array: [j]
    });
    return [m];
  };
  if (h != undefined) {
    this.setByParam(h);
  }
};
extendClass(KJUR.asn1.cms.SigningCertificate, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.ESSCertID = function (g) {
  KJUR.asn1.cms.ESSCertID.superclass.constructor.call(this);
  var d = Error,
    c = KJUR,
    b = c.asn1,
    f = b.DEROctetString,
    a = b.DERSequence,
    e = b.cms.IssuerSerial;
  this.params = null;
  this.getCertHash = function (k, h) {
    if (k.hash != undefined) {
      return k.hash;
    }
    if (typeof k == "string" && k.indexOf("-----BEGIN") == -1 && !ASN1HEX.isASN1HEX(k)) {
      return k;
    }
    var i;
    if (typeof k == "string") {
      i = k;
    } else {
      if (k.cert != undefined) {
        i = k.cert;
      } else {
        throw new d("hash nor cert unspecified");
      }
    }
    var j;
    if (i.indexOf("-----BEGIN") != -1) {
      j = pemtohex(i);
    } else {
      j = i;
    }
    if (typeof k == "string") {
      if (k.indexOf("-----BEGIN") != -1) {
        j = pemtohex(k);
      } else {
        if (ASN1HEX.isASN1HEX(k)) {
          j = k;
        }
      }
    }
    var l;
    if (k.alg != undefined) {
      l = k.alg;
    } else {
      if (h != undefined) {
        l = h;
      } else {
        throw new d("hash alg unspecified");
      }
    }
    return c.crypto.Util.hashHex(j, l);
  };
  this.tohex = function () {
    var k = this.params;
    var j = this.getCertHash(k, "sha1");
    var h = [];
    h.push(new f({
      hex: j
    }));
    if (typeof k == "string" && k.indexOf("-----BEGIN") != -1 || k.cert != undefined && k.hasis != false || k.issuer != undefined && k.serial != undefined) {
      h.push(new e(k));
    }
    var i = new a({
      array: h
    });
    return i.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cms.ESSCertID, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SigningCertificateV2 = function (d) {
  var h = Error,
    a = KJUR,
    g = a.asn1,
    e = g.DERSequence,
    b = g.x509,
    i = g.cms,
    c = i.ESSCertIDv2,
    f = a.crypto;
  i.SigningCertificateV2.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.16.2.47";
  this.getValueArray = function () {
    if (this.params == null || this.params == undefined || this.params.array == undefined) {
      throw new h("parameter 'array' not specified");
    }
    var o = this.params.array;
    var l = [];
    for (var m = 0; m < o.length; m++) {
      var n = o[m];
      if ((d.alg != undefined || d.hasis == false) && typeof n == "string" && (n.indexOf("-----BEGIN") != -1 || ASN1HEX.isASN1HEX(n))) {
        n = {
          cert: n
        };
      }
      if (n.alg == undefined && d.alg != undefined) {
        n.alg = d.alg;
      }
      if (n.hasis != false && d.hasis == false) {
        n.hasis = false;
      }
      l.push(new c(n));
    }
    var k = new e({
      array: l
    });
    var j = new e({
      array: [k]
    });
    return [j];
  };
  if (d != undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.cms.SigningCertificateV2, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.ESSCertIDv2 = function (h) {
  KJUR.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);
  var d = Error,
    c = KJUR,
    b = c.asn1,
    f = b.DEROctetString,
    a = b.DERSequence,
    e = b.cms.IssuerSerial,
    g = b.x509.AlgorithmIdentifier;
  this.params = null;
  this.tohex = function () {
    var l = this.params;
    var k = this.getCertHash(l, "sha256");
    var i = [];
    if (l.alg != undefined && l.alg != "sha256") {
      i.push(new g({
        name: l.alg
      }));
    }
    i.push(new f({
      hex: k
    }));
    if (typeof l == "string" && l.indexOf("-----BEGIN") != -1 || l.cert != undefined && l.hasis != false || l.issuer != undefined && l.serial != undefined) {
      i.push(new e(l));
    }
    var j = new a({
      array: i
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (h != undefined) {
    this.setByParam(h);
  }
};
extendClass(KJUR.asn1.cms.ESSCertIDv2, KJUR.asn1.cms.ESSCertID);
KJUR.asn1.cms.IssuerSerial = function (e) {
  var i = Error,
    c = KJUR,
    h = c.asn1,
    g = h.DERInteger,
    f = h.DERSequence,
    j = h.cms,
    d = h.x509,
    a = d.GeneralNames,
    b = X509;
  j.IssuerSerial.superclass.constructor.call(this);
  this.setByParam = function (k) {
    this.params = k;
  };
  this.tohex = function () {
    var p = this.params;
    var l, r;
    if (typeof p == "string" && p.indexOf("-----BEGIN") != -1 || p.cert != undefined) {
      var n;
      if (p.cert != undefined) {
        n = p.cert;
      } else {
        n = p;
      }
      var k = new b();
      k.readCertPEM(n);
      l = k.getIssuer();
      r = {
        hex: k.getSerialNumberHex()
      };
    } else {
      if (p.issuer != undefined && p.serial) {
        l = p.issuer;
        r = p.serial;
      } else {
        throw new i("cert or issuer and serial parameter not specified");
      }
    }
    var q = new a([{
      dn: l
    }]);
    var o = new g(r);
    var m = new f({
      array: [q, o]
    });
    return m.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cms.IssuerSerial, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignerIdentifier = function (f) {
  var c = KJUR,
    i = c.asn1,
    h = i.DERInteger,
    g = i.DERSequence,
    l = i.cms,
    k = l.IssuerAndSerialNumber,
    d = l.SubjectKeyIdentifier,
    e = i.x509,
    a = e.X500Name,
    b = X509,
    j = Error;
  l.SignerIdentifier.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var o = this.params;
    if (o.type == "isssn") {
      var m = new k(o);
      return m.tohex();
    } else {
      if (o.type == "skid") {
        var n = new d(o);
        return n.tohex();
      } else {
        throw new Error("wrong property for isssn or skid");
      }
    }
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.cms.SignerIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.IssuerAndSerialNumber = function (e) {
  var c = KJUR,
    h = c.asn1,
    g = h.DERInteger,
    f = h.DERSequence,
    j = h.cms,
    d = h.x509,
    a = d.X500Name,
    b = X509,
    i = Error;
  j.IssuerAndSerialNumber.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var p = this.params;
    var l, r;
    if (typeof p == "string" && p.indexOf("-----BEGIN") != -1 || p.cert != undefined) {
      var n;
      if (p.cert != undefined) {
        n = p.cert;
      } else {
        n = p;
      }
      var k = new b();
      k.readCertPEM(n);
      l = k.getIssuer();
      r = {
        hex: k.getSerialNumberHex()
      };
    } else {
      if (p.issuer != undefined && p.serial) {
        l = p.issuer;
        r = p.serial;
      } else {
        throw new i("cert or issuer and serial parameter not specified");
      }
    }
    var q = new a(l);
    var o = new g(r);
    var m = new f({
      array: [q, o]
    });
    return m.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (k) {
    this.params = k;
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cms.IssuerAndSerialNumber, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SubjectKeyIdentifier = function (g) {
  var d = KJUR,
    k = d.asn1,
    i = k.DERInteger,
    h = k.DERSequence,
    j = k.ASN1Util.newObject,
    m = k.cms,
    f = m.IssuerAndSerialName,
    c = m.SubjectKeyIdentifier,
    e = k.x509,
    a = e.X500Name,
    b = X509,
    l = Error;
  m.SubjectKeyIdentifier.superclass.constructor.call(this);
  this.tohex = function () {
    var r = this.params;
    if (r.cert == undefined && r.skid == undefined) {
      throw new l("property cert nor skid undefined");
    }
    var q;
    if (r.cert != undefined) {
      var n = new b(r.cert);
      var o = n.getExtSubjectKeyIdentifier();
      q = o.kid.hex;
    } else {
      if (r.skid != undefined) {
        q = r.skid;
      }
    }
    var p = j({
      tag: {
        tage: "a0",
        obj: {
          octstr: {
            hex: q
          }
        }
      }
    });
    return p.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cms.SubjectKeyIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.AttributeList = function (f) {
  var d = Error,
    c = KJUR,
    b = c.asn1,
    a = b.DERSet,
    e = b.cms;
  e.AttributeList.superclass.constructor.call(this);
  this.params = null;
  this.hTLV = null;
  this.setByParam = function (g) {
    this.params = g;
  };
  this.tohex = function () {
    var o = this.params;
    if (this.hTLV != null) {
      return this.hTLV;
    }
    var m = true;
    if (o.sortflag != undefined) {
      m = o.sortflag;
    }
    var j = o.array;
    var g = [];
    for (var l = 0; l < j.length; l++) {
      var n = j[l];
      var k = n.attr;
      if (k == "contentType") {
        g.push(new e.ContentType(n));
      } else {
        if (k == "messageDigest") {
          g.push(new e.MessageDigest(n));
        } else {
          if (k == "signingTime") {
            g.push(new e.SigningTime(n));
          } else {
            if (k == "signingCertificate") {
              g.push(new e.SigningCertificate(n));
            } else {
              if (k == "signingCertificateV2") {
                g.push(new e.SigningCertificateV2(n));
              } else {
                if (k == "signaturePolicyIdentifier") {
                  g.push(new KJUR.asn1.cades.SignaturePolicyIdentifier(n));
                } else {
                  if (k == "signatureTimeStamp" || k == "timeStampToken") {
                    g.push(new KJUR.asn1.cades.SignatureTimeStamp(n));
                  } else {
                    throw new d("unknown attr: " + k);
                  }
                }
              }
            }
          }
        }
      }
    }
    var h = new a({
      array: g,
      sortflag: m
    });
    this.hTLV = h.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.cms.AttributeList, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignerInfo = function (q) {
  var n = Error,
    r = KJUR,
    i = r.asn1,
    c = i.DERInteger,
    f = i.DEROctetString,
    h = i.DERSequence,
    m = i.DERTaggedObject,
    k = i.cms,
    p = k.SignerIdentifier,
    l = k.AttributeList,
    g = k.ContentType,
    e = k.EncapsulatedContentInfo,
    d = k.MessageDigest,
    j = k.SignedData,
    a = i.x509,
    s = a.AlgorithmIdentifier,
    b = r.crypto,
    o = KEYUTIL;
  k.SignerInfo.superclass.constructor.call(this);
  this.params = null;
  this.sign = function () {
    var y = this.params;
    var x = y.sigalg;
    var u = new l(y.sattrs).tohex();
    var v = o.getKey(y.signkey);
    var w = new b.Signature({
      alg: x
    });
    w.init(v);
    w.updateHex(u);
    var t = w.sign();
    y.sighex = t;
  };
  this.tohex = function () {
    var w = this.params;
    var t = [];
    t.push(new c({
      "int": w.version
    }));
    t.push(new p(w.id));
    t.push(new s({
      name: w.hashalg
    }));
    if (w.sattrs != undefined) {
      var x = new l(w.sattrs);
      try {
        t.push(new m({
          tag: "a0",
          explicit: false,
          obj: x
        }));
      } catch (v) {
        throw new n("si sattr error: " + v);
      }
    }
    if (w.sigalgfield != undefined) {
      t.push(new s({
        name: w.sigalgfield
      }));
    } else {
      t.push(new s({
        name: w.sigalg
      }));
    }
    if (w.sighex == undefined && w.signkey != undefined) {
      this.sign();
    }
    t.push(new f({
      hex: w.sighex
    }));
    if (w.uattrs != undefined) {
      var x = new l(w.uattrs);
      try {
        t.push(new m({
          tag: "a1",
          explicit: false,
          obj: x
        }));
      } catch (v) {
        throw new n("si uattr error: " + v);
      }
    }
    var u = new h({
      array: t
    });
    return u.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (q != undefined) {
    this.setByParam(q);
  }
};
extendClass(KJUR.asn1.cms.SignerInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.EncapsulatedContentInfo = function (g) {
  var c = KJUR,
    b = c.asn1,
    e = b.DERTaggedObject,
    a = b.DERSequence,
    h = b.DERObjectIdentifier,
    d = b.DEROctetString,
    f = b.cms;
  f.EncapsulatedContentInfo.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var m = this.params;
    var i = [];
    i.push(new h(m.type));
    if (m.content != undefined && (m.content.hex != undefined || m.content.str != undefined) && m.isDetached != true) {
      var k = new d(m.content);
      var l = new e({
        tag: "a0",
        explicit: true,
        obj: k
      });
      i.push(l);
    }
    var j = new a({
      array: i
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (i) {
    this.params = i;
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cms.EncapsulatedContentInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.ContentInfo = function (g) {
  var c = KJUR,
    b = c.asn1,
    d = b.DERTaggedObject,
    a = b.DERSequence,
    h = b.DERObjectIdentifier,
    f = b.x509,
    e = f.OID.name2obj;
  KJUR.asn1.cms.ContentInfo.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var l = this.params;
    var i = [];
    i.push(new h(l.type));
    var k = new d({
      tag: "a0",
      explicit: true,
      obj: l.obj
    });
    i.push(k);
    var j = new a({
      array: i
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (i) {
    this.params = i;
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cms.ContentInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignedData = function (e) {
  var j = Error,
    a = KJUR,
    h = a.asn1,
    m = h.ASN1Object,
    g = h.DERInteger,
    p = h.DERSet,
    f = h.DERSequence,
    b = h.DERTaggedObject,
    o = h.cms,
    l = o.EncapsulatedContentInfo,
    d = o.SignerInfo,
    q = o.ContentInfo,
    k = o.CertificateSet,
    i = o.RevocationInfoChoices,
    c = h.x509,
    n = c.AlgorithmIdentifier;
  KJUR.asn1.cms.SignedData.superclass.constructor.call(this);
  this.params = null;
  this.checkAndFixParam = function () {
    var r = this.params;
    this._setDigestAlgs(r);
    this._setContentTypeByEContent(r);
    this._setMessageDigestByEContent(r);
    this._setSignerInfoVersion(r);
    this._setSignedDataVersion(r);
  };
  this._setDigestAlgs = function (v) {
    var u = {};
    var t = v.sinfos;
    for (var r = 0; r < t.length; r++) {
      var s = t[r];
      u[s.hashalg] = 1;
    }
    v.hashalgs = Object.keys(u).sort();
  };
  this._setContentTypeByEContent = function (w) {
    var u = w.econtent.type;
    var v = w.sinfos;
    for (var r = 0; r < v.length; r++) {
      var t = v[r];
      var s = this._getAttrParamByName(t, "contentType");
      s.type = u;
    }
  };
  this._setMessageDigestByEContent = function (r) {
    var v = r.econtent;
    var y = r.econtent.type;
    var x = v.content.hex;
    if (x == undefined && v.type == "data" && v.content.str != undefined) {
      x = rstrtohex(v.content.str);
    }
    var A = r.sinfos;
    for (var u = 0; u < A.length; u++) {
      var t = A[u];
      var s = t.hashalg;
      var z = this._getAttrParamByName(t, "messageDigest");
      var w = KJUR.crypto.Util.hashHex(x, s);
      z.hex = w;
    }
  };
  this._getAttrParamByName = function (t, s) {
    var u = t.sattrs.array;
    for (var r = 0; r < u.length; r++) {
      if (u[r].attr == s) {
        return u[r];
      }
    }
  };
  this._setSignerInfoVersion = function (v) {
    var t = v.sinfos;
    for (var r = 0; r < t.length; r++) {
      var s = t[r];
      var u = 1;
      if (s.id.type == "skid") {
        u = 3;
      }
      s.version = u;
    }
  };
  this._setSignedDataVersion = function (s) {
    var r = this._getSignedDataVersion(s);
    s.version = r;
  };
  this._getSignedDataVersion = function (w) {
    if (w.revinfos != undefined) {
      var r = w.revinfos;
      for (var t = 0; t < r.length; t++) {
        var s = r[t];
        if (s.ocsp != undefined) {
          return 5;
        }
      }
    }
    var v = w.sinfos;
    for (var t = 0; t < v.length; t++) {
      var u = w.sinfos[t];
      if (u.version == 3) {
        return 3;
      }
    }
    if (w.econtent.type != "data") {
      return 3;
    }
    return 1;
  };
  this.tohex = function () {
    var y = this.params;
    if (this.getEncodedHexPrepare != undefined) {
      this.getEncodedHexPrepare();
    }
    if (y.fixed != true) {
      this.checkAndFixParam();
    }
    var r = [];
    r.push(new g({
      "int": y.version
    }));
    var w = [];
    for (var v = 0; v < y.hashalgs.length; v++) {
      var t = y.hashalgs[v];
      w.push(new n({
        name: t
      }));
    }
    r.push(new p({
      array: w
    }));
    r.push(new l(y.econtent));
    if (y.certs != undefined) {
      r.push(new k(y.certs));
    }
    if (y.revinfos != undefined) {
      r.push(new i(y.revinfos));
    }
    var u = [];
    for (var v = 0; v < y.sinfos.length; v++) {
      var x = y.sinfos[v];
      u.push(new d(x));
    }
    r.push(new p({
      array: u
    }));
    var s = new f({
      array: r
    });
    return s.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.getContentInfo = function () {
    var r = new q({
      type: "signed-data",
      obj: this
    });
    return r;
  };
  this.getContentInfoEncodedHex = function () {
    return this.getContentInfo().tohex();
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cms.SignedData, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.CertificateSet = function (f) {
  KJUR.asn1.cms.CertificateSet.superclass.constructor.call(this);
  var c = Error,
    b = KJUR.asn1,
    e = b.DERTaggedObject,
    a = b.DERSet,
    d = b.ASN1Object;
  this.params = null;
  this.tohex = function () {
    var j = this.params;
    var p = [];
    var q;
    if (j instanceof Array) {
      q = j;
    } else {
      if (j.array != undefined) {
        q = j.array;
      } else {
        throw new c("cert array not specified");
      }
    }
    for (var k = 0; k < q.length; k++) {
      var l = q[k];
      var n = pemtohex(l);
      var g = new d();
      g.hTLV = n;
      p.push(g);
    }
    var m = {
      array: p
    };
    if (j.sortflag == false) {
      m.sortflag = false;
    }
    var o = new a(m);
    var h = new e({
      tag: "a0",
      explicit: false,
      obj: o
    });
    return h.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.cms.CertificateSet, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.RevocationInfoChoices = function (a) {
  KJUR.asn1.cms.RevocationInfoChoices.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var e = this.params;
    if (!e instanceof Array) {
      throw new Error("params is not array");
    }
    var b = [];
    for (var c = 0; c < e.length; c++) {
      b.push(new KJUR.asn1.cms.RevocationInfoChoice(e[c]));
    }
    var d = KJUR.asn1.ASN1Util.newObject({
      tag: {
        tagi: "a1",
        obj: {
          set: b
        }
      }
    });
    return d.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (a != undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.cms.RevocationInfoChoices, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.RevocationInfoChoice = function (a) {
  KJUR.asn1.cms.RevocationInfoChoice.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var d = this.params;
    if (d.crl != undefined && typeof d.crl == "string") {
      var b = d.crl;
      if (d.crl.indexOf("-----BEGIN") != -1) {
        b = pemtohex(d.crl);
      }
      return b;
    } else {
      if (d.ocsp != undefined) {
        var c = KJUR.asn1.ASN1Util.newObject({
          tag: {
            tagi: "a1",
            obj: new KJUR.asn1.cms.OtherRevocationFormat(d)
          }
        });
        return c.tohex();
      } else {
        throw new Error("property crl or ocsp undefined");
      }
    }
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (a != undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.cms.RevocationInfoChoice, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.OtherRevocationFormat = function (f) {
  KJUR.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);
  var d = Error,
    c = KJUR,
    b = c.asn1,
    a = b.ASN1Util.newObject,
    e = c.lang.String.isHex;
  this.params = null;
  this.tohex = function () {
    var h = this.params;
    if (h.ocsp == undefined) {
      throw new d("property ocsp not specified");
    }
    if (!e(h.ocsp) || !ASN1HEX.isASN1HEX(h.ocsp)) {
      throw new d("ocsp value not ASN.1 hex string");
    }
    var g = a({
      seq: [{
        oid: "1.3.6.1.5.5.7.16.2"
      }, {
        asn1: {
          tlv: h.ocsp
        }
      }]
    });
    return g.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.cms.OtherRevocationFormat, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.CMSUtil = new function () {}();
KJUR.asn1.cms.CMSUtil.newSignedData = function (a) {
  return new KJUR.asn1.cms.SignedData(a);
};
KJUR.asn1.cms.CMSUtil.verifySignedData = function (n) {
  var C = KJUR,
    p = C.asn1,
    s = p.cms,
    D = s.SignerInfo,
    q = s.SignedData,
    y = s.SigningTime,
    b = s.SigningCertificate,
    d = s.SigningCertificateV2,
    A = p.cades,
    u = A.SignaturePolicyIdentifier,
    i = C.lang.String.isHex,
    v = ASN1HEX,
    h = v.getVbyList,
    a = v.getTLVbyList,
    t = v.getIdxbyList,
    z = v.getChildIdx,
    c = v.getTLV,
    B = v.oidname,
    j = C.crypto.Util.hashHex;
  if (n.cms === undefined && !i(n.cms)) {}
  var E = n.cms;
  var g = function (J, H) {
    var G;
    for (var I = 3; I < 6; I++) {
      G = t(J, 0, [1, 0, I]);
      if (G !== undefined) {
        var F = J.substr(G, 2);
        if (F === "a0") {
          H.certsIdx = G;
        }
        if (F === "a1") {
          H.revinfosIdx = G;
        }
        if (F === "31") {
          H.signerinfosIdx = G;
        }
      }
    }
  };
  var l = function (I, F) {
    var H = F.signerinfosIdx;
    if (H === undefined) {
      return;
    }
    var L = z(I, H);
    F.signerInfoIdxList = L;
    for (var G = 0; G < L.length; G++) {
      var K = L[G];
      var J = {
        idx: K
      };
      k(I, J);
      F.signerInfos.push(J);
    }
  };
  var k = function (I, J) {
    var F = J.idx;
    J.signerid_issuer1 = a(I, F, [1, 0], "30");
    J.signerid_serial1 = h(I, F, [1, 1], "02");
    J.hashalg = B(h(I, F, [2, 0], "06"));
    var H = t(I, F, [3], "a0");
    J.idxSignedAttrs = H;
    f(I, J, H);
    var G = z(I, F);
    var K = G.length;
    if (K < 6) {
      throw "malformed SignerInfo";
    }
    J.sigalg = B(h(I, F, [K - 2, 0], "06"));
    J.sigval = h(I, F, [K - 1], "04");
  };
  var f = function (L, M, F) {
    var J = z(L, F);
    M.signedAttrIdxList = J;
    for (var K = 0; K < J.length; K++) {
      var I = J[K];
      var G = h(L, I, [0], "06");
      var H;
      if (G === "2a864886f70d010905") {
        H = hextoutf8(h(L, I, [1, 0]));
        M.saSigningTime = H;
      } else {
        if (G === "2a864886f70d010904") {
          H = h(L, I, [1, 0], "04");
          M.saMessageDigest = H;
        }
      }
    }
  };
  var w = function (G, F) {
    if (h(G, 0, [0], "06") !== "2a864886f70d010702") {
      return F;
    }
    F.cmsType = "signedData";
    F.econtent = h(G, 0, [1, 0, 2, 1, 0]);
    g(G, F);
    F.signerInfos = [];
    l(G, F);
  };
  var o = function (J, F) {
    var G = F.parse.signerInfos;
    var L = G.length;
    var K = true;
    for (var I = 0; I < L; I++) {
      var H = G[I];
      e(J, F, H, I);
      if (!H.isValid) {
        K = false;
      }
    }
    F.isValid = K;
  };
  var x = function (F, Q, J, P) {
    var N = Q.parse.certsIdx;
    var H;
    if (Q.certs === undefined) {
      H = [];
      Q.certkeys = [];
      var K = z(F, N);
      for (var I = 0; I < K.length; I++) {
        var M = c(F, K[I]);
        var O = new X509();
        O.readCertHex(M);
        H[I] = O;
        Q.certkeys[I] = O.getPublicKey();
      }
      Q.certs = H;
    } else {
      H = Q.certs;
    }
    Q.cccc = H.length;
    Q.cccci = K.length;
    for (var I = 0; I < H.length; I++) {
      var L = O.getIssuerHex();
      var G = O.getSerialNumberHex();
      if (J.signerid_issuer1 === L && J.signerid_serial1 === G) {
        J.certkey_idx = I;
      }
    }
  };
  var e = function (F, R, I, N) {
    I.verifyDetail = {};
    var Q = I.verifyDetail;
    var K = R.parse.econtent;
    var G = I.hashalg;
    var L = I.saMessageDigest;
    Q.validMessageDigest = false;
    if (j(K, G) === L) {
      Q.validMessageDigest = true;
    }
    x(F, R, I, N);
    Q.validSignatureValue = false;
    var H = I.sigalg;
    var M = "31" + c(F, I.idxSignedAttrs).substr(2);
    I.signedattrshex = M;
    var J = R.certs[I.certkey_idx].getPublicKey();
    var P = new KJUR.crypto.Signature({
      alg: H
    });
    P.init(J);
    P.updateHex(M);
    var O = P.verify(I.sigval);
    Q.validSignatureValue_isValid = O;
    if (O === true) {
      Q.validSignatureValue = true;
    }
    I.isValid = false;
    if (Q.validMessageDigest && Q.validSignatureValue) {
      I.isValid = true;
    }
  };
  var m = function () {};
  var r = {
    isValid: false,
    parse: {}
  };
  w(E, r.parse);
  o(E, r);
  return r;
};
KJUR.asn1.cms.CMSParser = function () {
  var g = Error,
    a = X509,
    h = new a(),
    l = ASN1HEX,
    i = l.getV,
    b = l.getTLV,
    f = l.getIdxbyList,
    c = l.getTLVbyList,
    d = l.getTLVbyListEx,
    e = l.getVbyList,
    k = l.getVbyListEx,
    j = l.getChildIdx;
  this.getCMSSignedData = function (m) {
    var o = c(m, 0, [1, 0]);
    var n = this.getSignedData(o);
    return n;
  };
  this.getSignedData = function (o) {
    var q = j(o, 0);
    var v = {};
    var p = i(o, q[0]);
    var n = parseInt(p, 16);
    v.version = n;
    var r = b(o, q[1]);
    v.hashalgs = this.getHashAlgArray(r);
    var t = b(o, q[2]);
    v.econtent = this.getEContent(t);
    var m = d(o, 0, ["[0]"]);
    if (m != null) {
      v.certs = this.getCertificateSet(m);
    }
    var u = d(o, 0, ["[1]"]);
    if (u != null) {}
    var s = d(o, 0, [3]);
    v.sinfos = this.getSignerInfos(s);
    return v;
  };
  this.getHashAlgArray = function (s) {
    var q = j(s, 0);
    var m = new a();
    var n = [];
    for (var r = 0; r < q.length; r++) {
      var p = b(s, q[r]);
      var o = m.getAlgorithmIdentifierName(p);
      n.push(o);
    }
    return n;
  };
  this.getEContent = function (m) {
    var n = {};
    var p = e(m, 0, [0]);
    var o = e(m, 0, [1, 0]);
    n.type = KJUR.asn1.x509.OID.oid2name(ASN1HEX.hextooidstr(p));
    n.content = {
      hex: o
    };
    return n;
  };
  this.getSignerInfos = function (p) {
    var r = [];
    var m = j(p, 0);
    for (var n = 0; n < m.length; n++) {
      var o = b(p, m[n]);
      var q = this.getSignerInfo(o);
      r.push(q);
    }
    return r;
  };
  this.getSignerInfo = function (s) {
    var y = {};
    var u = j(s, 0);
    var q = l.getInt(s, u[0], -1);
    if (q != -1) {
      y.version = q;
    }
    var t = b(s, u[1]);
    var p = this.getIssuerAndSerialNumber(t);
    y.id = p;
    var z = b(s, u[2]);
    var n = h.getAlgorithmIdentifierName(z);
    y.hashalg = n;
    var w = d(s, 0, ["[0]"]);
    if (w != null) {
      var A = this.getAttributeList(w);
      y.sattrs = A;
    }
    var m = d(s, 0, [3]);
    var x = h.getAlgorithmIdentifierName(m);
    y.sigalg = x;
    var o = k(s, 0, [4]);
    y.sighex = o;
    var r = d(s, 0, ["[1]"]);
    if (r != null) {
      var v = this.getAttributeList(r);
      y.uattrs = v;
    }
    return y;
  };
  this.getSignerIdentifier = function (m) {
    if (m.substr(0, 2) == "30") {
      return this.getIssuerAndSerialNumber(m);
    } else {
      throw new Error("SKID of signerIdentifier not supported");
    }
  };
  this.getIssuerAndSerialNumber = function (n) {
    var o = {
      type: "isssn"
    };
    var m = j(n, 0);
    var p = b(n, m[0]);
    o.issuer = h.getX500Name(p);
    var q = i(n, m[1]);
    o.serial = {
      hex: q
    };
    return o;
  };
  this.getAttributeList = function (q) {
    var m = [];
    var n = j(q, 0);
    for (var o = 0; o < n.length; o++) {
      var p = b(q, n[o]);
      var r = this.getAttribute(p);
      m.push(r);
    }
    return {
      array: m
    };
  };
  this.getAttribute = function (p) {
    var t = {};
    var q = j(p, 0);
    var o = l.getOID(p, q[0]);
    var m = KJUR.asn1.x509.OID.oid2name(o);
    t.attr = m;
    var r = b(p, q[1]);
    var u = j(r, 0);
    if (u.length == 1) {
      t.valhex = b(r, u[0]);
    } else {
      var s = [];
      for (var n = 0; n < u.length; n++) {
        s.push(b(r, u[n]));
      }
      t.valhex = s;
    }
    if (m == "contentType") {
      this.setContentType(t);
    } else {
      if (m == "messageDigest") {
        this.setMessageDigest(t);
      } else {
        if (m == "signingTime") {
          this.setSigningTime(t);
        } else {
          if (m == "signingCertificate") {
            this.setSigningCertificate(t);
          } else {
            if (m == "signingCertificateV2") {
              this.setSigningCertificateV2(t);
            } else {
              if (m == "signaturePolicyIdentifier") {
                this.setSignaturePolicyIdentifier(t);
              }
            }
          }
        }
      }
    }
    return t;
  };
  this.setContentType = function (m) {
    var n = l.getOIDName(m.valhex, 0, null);
    if (n != null) {
      m.type = n;
      delete m.valhex;
    }
  };
  this.setSigningTime = function (o) {
    var n = i(o.valhex, 0);
    var m = hextoutf8(n);
    o.str = m;
    delete o.valhex;
  };
  this.setMessageDigest = function (m) {
    var n = i(m.valhex, 0);
    m.hex = n;
    delete m.valhex;
  };
  this.setSigningCertificate = function (n) {
    var q = j(n.valhex, 0);
    if (q.length > 0) {
      var m = b(n.valhex, q[0]);
      var p = j(m, 0);
      var t = [];
      for (var o = 0; o < p.length; o++) {
        var s = b(m, p[o]);
        var u = this.getESSCertID(s);
        t.push(u);
      }
      n.array = t;
    }
    if (q.length > 1) {
      var r = b(n.valhex, q[1]);
      n.polhex = r;
    }
    delete n.valhex;
  };
  this.setSignaturePolicyIdentifier = function (s) {
    var q = j(s.valhex, 0);
    if (q.length > 0) {
      var r = l.getOID(s.valhex, q[0]);
      s.oid = r;
    }
    if (q.length > 1) {
      var m = new a();
      var t = j(s.valhex, q[1]);
      var p = b(s.valhex, t[0]);
      var o = m.getAlgorithmIdentifierName(p);
      s.alg = o;
      var n = i(s.valhex, t[1]);
      s.hash = n;
    }
    delete s.valhex;
  };
  this.setSigningCertificateV2 = function (o) {
    var s = j(o.valhex, 0);
    if (s.length > 0) {
      var n = b(o.valhex, s[0]);
      var r = j(n, 0);
      var u = [];
      for (var q = 0; q < r.length; q++) {
        var m = b(n, r[q]);
        var p = this.getESSCertIDv2(m);
        u.push(p);
      }
      o.array = u;
    }
    if (s.length > 1) {
      var t = b(o.valhex, s[1]);
      o.polhex = t;
    }
    delete o.valhex;
  };
  this.getESSCertID = function (o) {
    var p = {};
    var n = j(o, 0);
    if (n.length > 0) {
      var q = i(o, n[0]);
      p.hash = q;
    }
    if (n.length > 1) {
      var m = b(o, n[1]);
      var r = this.getIssuerSerial(m);
      if (r.serial != undefined) {
        p.serial = r.serial;
      }
      if (r.issuer != undefined) {
        p.issuer = r.issuer;
      }
    }
    return p;
  };
  this.getESSCertIDv2 = function (q) {
    var s = {};
    var p = j(q, 0);
    if (p.length < 1 || 3 < p.length) {
      throw new g("wrong number of elements");
    }
    var r = 0;
    if (q.substr(p[0], 2) == "30") {
      var o = b(q, p[0]);
      s.alg = h.getAlgorithmIdentifierName(o);
      r++;
    } else {
      s.alg = "sha256";
    }
    var n = i(q, p[r]);
    s.hash = n;
    if (p.length > r + 1) {
      var m = b(q, p[r + 1]);
      var t = this.getIssuerSerial(m);
      s.issuer = t.issuer;
      s.serial = t.serial;
    }
    return s;
  };
  this.getIssuerSerial = function (q) {
    var r = {};
    var n = j(q, 0);
    var m = b(q, n[0]);
    var p = h.getGeneralNames(m);
    var o = p[0].dn;
    r.issuer = o;
    var s = i(q, n[1]);
    r.serial = {
      hex: s
    };
    return r;
  };
  this.getCertificateSet = function (p) {
    var n = j(p, 0);
    var m = [];
    for (var o = 0; o < n.length; o++) {
      var r = b(p, n[o]);
      if (r.substr(0, 2) == "30") {
        var q = hextopem(r, "CERTIFICATE");
        m.push(q);
      }
    }
    return {
      array: m,
      sortflag: false
    };
  };
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
if (typeof KJUR.asn1.tsp == "undefined" || !KJUR.asn1.tsp) {
  KJUR.asn1.tsp = {};
}
KJUR.asn1.tsp.TimeStampToken = function (d) {
  var c = KJUR,
    b = c.asn1,
    a = b.tsp;
  a.TimeStampToken.superclass.constructor.call(this);
  this.params = null;
  this.getEncodedHexPrepare = function () {
    var e = new a.TSTInfo(this.params.econtent.content);
    this.params.econtent.content.hex = e.tohex();
  };
  if (d != undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.tsp.TimeStampToken, KJUR.asn1.cms.SignedData);
KJUR.asn1.tsp.TSTInfo = function (f) {
  var m = Error,
    c = KJUR,
    j = c.asn1,
    g = j.DERSequence,
    i = j.DERInteger,
    l = j.DERBoolean,
    h = j.DERGeneralizedTime,
    n = j.DERObjectIdentifier,
    e = j.DERTaggedObject,
    k = j.tsp,
    d = k.MessageImprint,
    b = k.Accuracy,
    a = j.x509.X500Name,
    o = j.x509.GeneralName;
  k.TSTInfo.superclass.constructor.call(this);
  this.dVersion = new i({
    "int": 1
  });
  this.dPolicy = null;
  this.dMessageImprint = null;
  this.dSerial = null;
  this.dGenTime = null;
  this.dAccuracy = null;
  this.dOrdering = null;
  this.dNonce = null;
  this.dTsa = null;
  this.tohex = function () {
    var p = [this.dVersion];
    if (this.dPolicy == null) {
      throw new Error("policy shall be specified.");
    }
    p.push(this.dPolicy);
    if (this.dMessageImprint == null) {
      throw new Error("messageImprint shall be specified.");
    }
    p.push(this.dMessageImprint);
    if (this.dSerial == null) {
      throw new Error("serialNumber shall be specified.");
    }
    p.push(this.dSerial);
    if (this.dGenTime == null) {
      throw new Error("genTime shall be specified.");
    }
    p.push(this.dGenTime);
    if (this.dAccuracy != null) {
      p.push(this.dAccuracy);
    }
    if (this.dOrdering != null) {
      p.push(this.dOrdering);
    }
    if (this.dNonce != null) {
      p.push(this.dNonce);
    }
    if (this.dTsa != null) {
      p.push(this.dTsa);
    }
    var q = new g({
      array: p
    });
    this.hTLV = q.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    if (typeof f.policy == "string") {
      if (!f.policy.match(/^[0-9.]+$/)) {
        throw "policy shall be oid like 0.1.4.134";
      }
      this.dPolicy = new n({
        oid: f.policy
      });
    }
    if (f.messageImprint !== undefined) {
      this.dMessageImprint = new d(f.messageImprint);
    }
    if (f.serial !== undefined) {
      this.dSerial = new i(f.serial);
    }
    if (f.genTime !== undefined) {
      this.dGenTime = new h(f.genTime);
    }
    if (f.accuracy !== undefined) {
      this.dAccuracy = new b(f.accuracy);
    }
    if (f.ordering !== undefined && f.ordering == true) {
      this.dOrdering = new l();
    }
    if (f.nonce !== undefined) {
      this.dNonce = new i(f.nonce);
    }
    if (f.tsa !== undefined) {
      this.dTsa = new e({
        tag: "a0",
        explicit: true,
        obj: new o({
          dn: f.tsa
        })
      });
    }
  }
};
extendClass(KJUR.asn1.tsp.TSTInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.Accuracy = function (d) {
  var c = KJUR,
    b = c.asn1,
    a = b.ASN1Util.newObject;
  b.tsp.Accuracy.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var f = this.params;
    var e = [];
    if (f.seconds != undefined && typeof f.seconds == "number") {
      e.push({
        "int": f.seconds
      });
    }
    if (f.millis != undefined && typeof f.millis == "number") {
      e.push({
        tag: {
          tagi: "80",
          obj: {
            "int": f.millis
          }
        }
      });
    }
    if (f.micros != undefined && typeof f.micros == "number") {
      e.push({
        tag: {
          tagi: "81",
          obj: {
            "int": f.micros
          }
        }
      });
    }
    return a({
      seq: e
    }).tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d != undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.tsp.Accuracy, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.MessageImprint = function (g) {
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    d = b.DEROctetString,
    f = b.x509,
    e = f.AlgorithmIdentifier;
  b.tsp.MessageImprint.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var k = this.params;
    var j = new e({
      name: k.alg
    });
    var h = new d({
      hex: k.hash
    });
    var i = new a({
      array: [j, h]
    });
    return i.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g !== undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.tsp.MessageImprint, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.TimeStampReq = function (c) {
  var a = KJUR,
    f = a.asn1,
    d = f.DERSequence,
    e = f.DERInteger,
    h = f.DERBoolean,
    j = f.ASN1Object,
    i = f.DERObjectIdentifier,
    g = f.tsp,
    b = g.MessageImprint;
  g.TimeStampReq.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var m = this.params;
    var k = [];
    k.push(new e({
      "int": 1
    }));
    if (m.messageImprint instanceof KJUR.asn1.ASN1Object) {
      k.push(m.messageImprint);
    } else {
      k.push(new b(m.messageImprint));
    }
    if (m.policy != undefined) {
      k.push(new i(m.policy));
    }
    if (m.nonce != undefined) {
      k.push(new e(m.nonce));
    }
    if (m.certreq == true) {
      k.push(new h());
    }
    var l = new d({
      array: k
    });
    return l.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (c != undefined) {
    this.setByParam(c);
  }
};
extendClass(KJUR.asn1.tsp.TimeStampReq, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.TimeStampResp = function (g) {
  var e = KJUR,
    d = e.asn1,
    c = d.DERSequence,
    f = d.ASN1Object,
    a = d.tsp,
    b = a.PKIStatusInfo;
  a.TimeStampResp.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var j = this.params;
    var h = [];
    if (j.econtent != undefined || j.tst != undefined) {
      if (j.statusinfo != undefined) {
        h.push(new b(j.statusinfo));
      } else {
        h.push(new b("granted"));
      }
      if (j.econtent != undefined) {
        h.push(new a.TimeStampToken(j).getContentInfo());
      } else {
        if (j.tst instanceof d.ASN1Object) {
          h.push(j.tst);
        } else {
          throw new Error("improper member tst value");
        }
      }
    } else {
      if (j.statusinfo != undefined) {
        h.push(new b(j.statusinfo));
      } else {
        throw new Error("parameter for token nor statusinfo not specified");
      }
    }
    var i = new c({
      array: h
    });
    return i.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.tsp.TimeStampResp, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIStatusInfo = function (d) {
  var h = Error,
    a = KJUR,
    g = a.asn1,
    e = g.DERSequence,
    i = g.tsp,
    f = i.PKIStatus,
    c = i.PKIFreeText,
    b = i.PKIFailureInfo;
  i.PKIStatusInfo.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var l = this.params;
    var j = [];
    if (typeof l == "string") {
      j.push(new f(l));
    } else {
      if (l.status == undefined) {
        throw new h("property 'status' unspecified");
      }
      j.push(new f(l.status));
      if (l.statusstr != undefined) {
        j.push(new c(l.statusstr));
      }
      if (l.failinfo != undefined) {
        j.push(new b(l.failinfo));
      }
    }
    var k = new e({
      array: j
    });
    return k.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d != undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.tsp.PKIStatusInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIStatus = function (g) {
  var e = Error,
    d = KJUR,
    c = d.asn1,
    f = c.DERInteger,
    b = c.tsp;
  b.PKIStatus.superclass.constructor.call(this);
  var a = {
    granted: 0,
    grantedWithMods: 1,
    rejection: 2,
    waiting: 3,
    revocationWarning: 4,
    revocationNotification: 5
  };
  this.params = null;
  this.tohex = function () {
    var k = this.params;
    var h, j;
    if (typeof k == "string") {
      try {
        j = a[k];
      } catch (i) {
        throw new e("undefined name: " + k);
      }
    } else {
      if (typeof k == "number") {
        j = k;
      } else {
        throw new e("unsupported params");
      }
    }
    return new f({
      "int": j
    }).tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.tsp.PKIStatus, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIFreeText = function (g) {
  var f = Error,
    e = KJUR,
    d = e.asn1,
    b = d.DERSequence,
    c = d.DERUTF8String,
    a = d.tsp;
  a.PKIFreeText.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var l = this.params;
    if (!l instanceof Array) {
      throw new f("wrong params: not array");
    }
    var h = [];
    for (var k = 0; k < l.length; k++) {
      h.push(new c({
        str: l[k]
      }));
    }
    var j = new b({
      array: h
    });
    return j.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.tsp.PKIFreeText, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIFailureInfo = function (h) {
  var f = Error,
    e = KJUR,
    d = e.asn1,
    g = d.DERBitString,
    b = d.tsp,
    c = b.PKIFailureInfo;
  var a = {
    badAlg: 0,
    badRequest: 2,
    badDataFormat: 5,
    timeNotAvailable: 14,
    unacceptedPolicy: 15,
    unacceptedExtension: 16,
    addInfoNotAvailable: 17,
    systemFailure: 25
  };
  c.superclass.constructor.call(this);
  this.params = null;
  this.getBinValue = function () {
    var n = this.params;
    var m = 0;
    if (typeof n == "number" && 0 <= n && n <= 25) {
      m |= 1 << n;
      var k = m.toString(2);
      var l = "";
      for (var j = k.length - 1; j >= 0; j--) {
        l += k[j];
      }
      return l;
    } else {
      if (typeof n == "string" && a[n] != undefined) {
        return namearraytobinstr([n], a);
      } else {
        if (typeof n == "object" && n.length != undefined) {
          return namearraytobinstr(n, a);
        } else {
          throw new f("wrong params");
        }
      }
    }
    return;
  };
  this.tohex = function () {
    var j = this.params;
    var i = this.getBinValue();
    return new g({
      bin: i
    }).tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (h != undefined) {
    this.setByParam(h);
  }
};
extendClass(KJUR.asn1.tsp.PKIFailureInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.AbstractTSAAdapter = function (a) {
  this.getTSTHex = function (c, b) {
    throw "not implemented yet";
  };
};
KJUR.asn1.tsp.SimpleTSAAdapter = function (e) {
  var d = KJUR,
    c = d.asn1,
    a = c.tsp,
    b = d.crypto.Util.hashHex;
  a.SimpleTSAAdapter.superclass.constructor.call(this);
  this.params = null;
  this.serial = 0;
  this.getTSTHex = function (g, f) {
    var i = b(g, f);
    this.params.econtent.content.messageImprint = {
      alg: f,
      hash: i
    };
    this.params.econtent.content.serial = {
      "int": this.serial++
    };
    var h = Math.floor(Math.random() * 1000000000);
    this.params.econtent.content.nonce = {
      "int": h
    };
    var j = new a.TimeStampToken(this.params);
    return j.getContentInfoEncodedHex();
  };
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.tsp.SimpleTSAAdapter, KJUR.asn1.tsp.AbstractTSAAdapter);
KJUR.asn1.tsp.FixedTSAAdapter = function (e) {
  var d = KJUR,
    c = d.asn1,
    a = c.tsp,
    b = d.crypto.Util.hashHex;
  a.FixedTSAAdapter.superclass.constructor.call(this);
  this.params = null;
  this.getTSTHex = function (g, f) {
    var h = b(g, f);
    this.params.econtent.content.messageImprint = {
      alg: f,
      hash: h
    };
    var i = new a.TimeStampToken(this.params);
    return i.getContentInfoEncodedHex();
  };
  if (e !== undefined) {
    this.params = e;
  }
};
extendClass(KJUR.asn1.tsp.FixedTSAAdapter, KJUR.asn1.tsp.AbstractTSAAdapter);
KJUR.asn1.tsp.TSPUtil = new function () {}();
KJUR.asn1.tsp.TSPUtil.newTimeStampToken = function (a) {
  return new KJUR.asn1.tsp.TimeStampToken(a);
};
KJUR.asn1.tsp.TSPUtil.parseTimeStampReq = function (a) {
  var b = new KJUR.asn1.tsp.TSPParser();
  return b.getTimeStampReq(a);
};
KJUR.asn1.tsp.TSPUtil.parseMessageImprint = function (a) {
  var b = new KJUR.asn1.tsp.TSPParser();
  return b.getMessageImprint(a);
};
KJUR.asn1.tsp.TSPParser = function () {
  var e = Error,
    a = X509,
    f = new a(),
    k = ASN1HEX,
    g = k.getV,
    b = k.getTLV,
    d = k.getIdxbyList,
    c = k.getTLVbyListEx,
    i = k.getChildIdx;
  var j = ["granted", "grantedWithMods", "rejection", "waiting", "revocationWarning", "revocationNotification"];
  var h = {
    0: "badAlg",
    2: "badRequest",
    5: "badDataFormat",
    14: "timeNotAvailable",
    15: "unacceptedPolicy",
    16: "unacceptedExtension",
    17: "addInfoNotAvailable",
    25: "systemFailure"
  };
  this.getResponse = function (n) {
    var l = i(n, 0);
    if (l.length == 1) {
      return this.getPKIStatusInfo(b(n, l[0]));
    } else {
      if (l.length > 1) {
        var o = this.getPKIStatusInfo(b(n, l[0]));
        var m = b(n, l[1]);
        var p = this.getToken(m);
        p.statusinfo = o;
        return p;
      }
    }
  };
  this.getToken = function (m) {
    var l = new KJUR.asn1.cms.CMSParser();
    var n = l.getCMSSignedData(m);
    this.setTSTInfo(n);
    return n;
  };
  this.setTSTInfo = function (l) {
    var o = l.econtent;
    if (o.type == "tstinfo") {
      var n = o.content.hex;
      var m = this.getTSTInfo(n);
      o.content = m;
    }
  };
  this.getTSTInfo = function (r) {
    var x = {};
    var s = i(r, 0);
    var p = g(r, s[1]);
    x.policy = hextooid(p);
    var o = b(r, s[2]);
    x.messageImprint = this.getMessageImprint(o);
    var u = g(r, s[3]);
    x.serial = {
      hex: u
    };
    var y = g(r, s[4]);
    x.genTime = {
      str: hextoutf8(y)
    };
    var q = 0;
    if (s.length > 5 && r.substr(s[5], 2) == "30") {
      var v = b(r, s[5]);
      x.accuracy = this.getAccuracy(v);
      q++;
    }
    if (s.length > 5 + q && r.substr(s[5 + q], 2) == "01") {
      var z = g(r, s[5 + q]);
      if (z == "ff") {
        x.ordering = true;
      }
      q++;
    }
    if (s.length > 5 + q && r.substr(s[5 + q], 2) == "02") {
      var n = g(r, s[5 + q]);
      x.nonce = {
        hex: n
      };
      q++;
    }
    if (s.length > 5 + q && r.substr(s[5 + q], 2) == "a0") {
      var m = b(r, s[5 + q]);
      m = "30" + m.substr(2);
      pGeneralNames = f.getGeneralNames(m);
      var t = pGeneralNames[0].dn;
      x.tsa = t;
      q++;
    }
    if (s.length > 5 + q && r.substr(s[5 + q], 2) == "a1") {
      var l = b(r, s[5 + q]);
      l = "30" + l.substr(2);
      var w = f.getExtParamArray(l);
      x.ext = w;
      q++;
    }
    return x;
  };
  this.getAccuracy = function (q) {
    var r = {};
    var o = i(q, 0);
    for (var p = 0; p < o.length; p++) {
      var m = q.substr(o[p], 2);
      var l = g(q, o[p]);
      var n = parseInt(l, 16);
      if (m == "02") {
        r.seconds = n;
      } else {
        if (m == "80") {
          r.millis = n;
        } else {
          if (m == "81") {
            r.micros = n;
          }
        }
      }
    }
    return r;
  };
  this.getMessageImprint = function (n) {
    if (n.substr(0, 2) != "30") {
      throw new Error("head of messageImprint hex shall be x30");
    }
    var s = {};
    var l = i(n, 0);
    var t = d(n, 0, [0, 0]);
    var o = g(n, t);
    var p = k.hextooidstr(o);
    var r = KJUR.asn1.x509.OID.oid2name(p);
    if (r == "") {
      throw new Error("hashAlg name undefined: " + p);
    }
    var m = r;
    var q = d(n, 0, [1]);
    s.alg = m;
    s.hash = g(n, q);
    return s;
  };
  this.getPKIStatusInfo = function (o) {
    var t = {};
    var r = i(o, 0);
    var n = 0;
    try {
      var l = g(o, r[0]);
      var p = parseInt(l, 16);
      t.status = j[p];
    } catch (s) {}
    if (r.length > 1 && o.substr(r[1], 2) == "30") {
      var m = b(o, r[1]);
      t.statusstr = this.getPKIFreeText(m);
      n++;
    }
    if (r.length > n && o.substr(r[1 + n], 2) == "03") {
      var q = b(o, r[1 + n]);
      t.failinfo = this.getPKIFailureInfo(q);
    }
    return t;
  };
  this.getPKIFreeText = function (n) {
    var o = [];
    var l = i(n, 0);
    for (var m = 0; m < l.length; m++) {
      o.push(k.getString(n, l[m]));
    }
    return o;
  };
  this.getPKIFailureInfo = function (l) {
    var m = k.getInt(l, 0);
    if (h[m] != undefined) {
      return h[m];
    } else {
      return m;
    }
  };
  this.getTimeStampReq = function (q) {
    var p = {};
    p.certreq = false;
    var s = i(q, 0);
    if (s.length < 2) {
      throw new Error("TimeStampReq must have at least 2 items");
    }
    var n = b(q, s[1]);
    p.messageImprint = KJUR.asn1.tsp.TSPUtil.parseMessageImprint(n);
    for (var o = 2; o < s.length; o++) {
      var m = s[o];
      var l = q.substr(m, 2);
      if (l == "06") {
        var r = g(q, m);
        p.policy = k.hextooidstr(r);
      }
      if (l == "02") {
        p.nonce = g(q, m);
      }
      if (l == "01") {
        p.certreq = true;
      }
    }
    return p;
  };
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
if (typeof KJUR.asn1.cades == "undefined" || !KJUR.asn1.cades) {
  KJUR.asn1.cades = {};
}
KJUR.asn1.cades.SignaturePolicyIdentifier = function (e) {
  var c = KJUR,
    b = c.asn1,
    a = b.cades,
    d = a.SignaturePolicyId;
  a.SignaturePolicyIdentifier.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.16.2.15";
  this.params = null;
  this.getValueArray = function () {
    return [new d(this.params)];
  };
  this.setByParam = function (f) {
    this.params = f;
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cades.SignaturePolicyIdentifier, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.SignaturePolicyId = function (e) {
  var a = KJUR,
    g = a.asn1,
    f = g.DERSequence,
    i = g.DERObjectIdentifier,
    d = g.x509,
    j = d.AlgorithmIdentifier,
    c = g.cades,
    h = c.SignaturePolicyId,
    b = c.OtherHashAlgAndValue;
  h.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var m = this.params;
    var k = [];
    k.push(new i(m.oid));
    k.push(new b(m));
    var l = new f({
      array: k
    });
    return l.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (k) {
    this.params = k;
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cades.SignaturePolicyId, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHashAlgAndValue = function (e) {
  var h = Error,
    a = KJUR,
    g = a.asn1,
    f = g.DERSequence,
    i = g.DEROctetString,
    d = g.x509,
    j = d.AlgorithmIdentifier,
    c = g.cades,
    b = c.OtherHashAlgAndValue;
  b.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var o = this.params;
    if (o.alg == undefined) {
      throw new h("property 'alg' not specified");
    }
    if (o.hash == undefined && o.cert == undefined) {
      throw new h("property 'hash' nor 'cert' not specified");
    }
    var m = null;
    if (o.hash != undefined) {
      m = o.hash;
    } else {
      if (o.cert != undefined) {
        if (typeof o.cert != "string") {
          throw new h("cert not string");
        }
        var n = o.cert;
        if (o.cert.indexOf("-----BEGIN") != -1) {
          n = pemtohex(o.cert);
        }
        m = KJUR.crypto.Util.hashHex(n, o.alg);
      }
    }
    var k = [];
    k.push(new j({
      name: o.alg
    }));
    k.push(new i({
      hex: m
    }));
    var l = new f({
      array: k
    });
    return l.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cades.OtherHashAlgAndValue, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHashValue = function (g) {
  KJUR.asn1.cades.OtherHashValue.superclass.constructor.call(this);
  var d = Error,
    c = KJUR,
    f = c.lang.String.isHex,
    b = c.asn1,
    e = b.DEROctetString,
    a = c.crypto.Util.hashHex;
  this.params = null;
  this.tohex = function () {
    var j = this.params;
    if (j.hash == undefined && j.cert == undefined) {
      throw new d("hash or cert not specified");
    }
    var h = null;
    if (j.hash != undefined) {
      h = j.hash;
    } else {
      if (j.cert != undefined) {
        if (typeof j.cert != "string") {
          throw new d("cert not string");
        }
        var i = j.cert;
        if (j.cert.indexOf("-----BEGIN") != -1) {
          i = pemtohex(j.cert);
        }
        h = KJUR.crypto.Util.hashHex(i, "sha1");
      }
    }
    return new e({
      hex: h
    }).tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cades.OtherHashValue, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.SignatureTimeStamp = function (h) {
  var d = Error,
    c = KJUR,
    f = c.lang.String.isHex,
    b = c.asn1,
    e = b.ASN1Object,
    g = b.x509,
    a = b.cades;
  a.SignatureTimeStamp.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.16.2.14";
  this.params = null;
  this.getValueArray = function () {
    var l = this.params;
    if (l.tst != undefined) {
      if (f(l.tst)) {
        var j = new e();
        j.hTLV = l.tst;
        return [j];
      } else {
        if (l.tst instanceof e) {
          return [l.tst];
        } else {
          throw new d("params.tst has wrong value");
        }
      }
    } else {
      if (l.res != undefined) {
        var k = l.res;
        if (k instanceof e) {
          k = k.tohex();
        }
        if (typeof k != "string" || !f(k)) {
          throw new d("params.res has wrong value");
        }
        var i = ASN1HEX.getTLVbyList(k, 0, [1]);
        var j = new e();
        j.hTLV = l.tst;
        return [j];
      }
    }
  };
  if (h != null) {
    this.setByParam(h);
  }
};
extendClass(KJUR.asn1.cades.SignatureTimeStamp, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.CompleteCertificateRefs = function (h) {
  var f = Error,
    e = KJUR,
    d = e.asn1,
    b = d.DERSequence,
    c = d.cades,
    a = c.OtherCertID,
    g = e.lang.String.isHex;
  c.CompleteCertificateRefs.superclass.constructor.call(this);
  this.typeOid = "1.2.840.113549.1.9.16.2.21";
  this.params = null;
  this.getValueArray = function () {
    var o = this.params;
    var k = [];
    for (var m = 0; m < o.array.length; m++) {
      var n = o.array[m];
      if (typeof n == "string") {
        if (n.indexOf("-----BEGIN") != -1) {
          n = {
            cert: n
          };
        } else {
          if (g(n)) {
            n = {
              hash: n
            };
          } else {
            throw new f("unsupported value: " + n);
          }
        }
      }
      if (o.alg != undefined && n.alg == undefined) {
        n.alg = o.alg;
      }
      if (o.hasis != undefined && n.hasis == undefined) {
        n.hasis = o.hasis;
      }
      var j = new a(n);
      k.push(j);
    }
    var l = new b({
      array: k
    });
    return [l];
  };
  if (h != undefined) {
    this.setByParam(h);
  }
};
extendClass(KJUR.asn1.cades.CompleteCertificateRefs, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.OtherCertID = function (e) {
  var a = KJUR,
    h = a.asn1,
    f = h.DERSequence,
    i = h.cms,
    g = i.IssuerSerial,
    c = h.cades,
    d = c.OtherHashValue,
    b = c.OtherHashAlgAndValue;
  c.OtherCertID.superclass.constructor.call(this);
  this.params = e;
  this.tohex = function () {
    var n = this.params;
    if (typeof n == "string") {
      if (n.indexOf("-----BEGIN") != -1) {
        n = {
          cert: n
        };
      } else {
        if (_isHex(n)) {
          n = {
            hash: n
          };
        }
      }
    }
    var j = [];
    var m = null;
    if (n.alg != undefined) {
      m = new b(n);
    } else {
      m = new d(n);
    }
    j.push(m);
    if (n.cert != undefined && n.hasis == true || n.issuer != undefined && n.serial != undefined) {
      var l = new g(n);
      j.push(l);
    }
    var k = new f({
      array: j
    });
    return k.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e != undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.cades.OtherCertID, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHash = function (g) {
  var i = Error,
    a = KJUR,
    h = a.asn1,
    j = h.cms,
    c = h.cades,
    b = c.OtherHashAlgAndValue,
    e = c.OtherHashValue,
    d = a.crypto.Util.hashHex,
    f = a.lang.String.isHex;
  c.OtherHash.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var l = this.params;
    if (typeof l == "string") {
      if (l.indexOf("-----BEGIN") != -1) {
        l = {
          cert: l
        };
      } else {
        if (f(l)) {
          l = {
            hash: l
          };
        }
      }
    }
    var k = null;
    if (l.alg != undefined) {
      k = new b(l);
    } else {
      k = new e(l);
    }
    return k.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g != undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.cades.OtherHash, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.CAdESUtil = new function () {}();
KJUR.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned = function (a) {
  var c = new KJUR.asn1.cms.CMSParser();
  var b = c.getCMSSignedData(a);
  return b;
};
KJUR.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned = function (g, q, c) {
  var p = ASN1HEX,
    s = p.getChildIdx,
    a = p.getTLV,
    l = p.getV,
    v = KJUR,
    h = v.asn1,
    n = h.ASN1Object,
    j = h.cms,
    k = j.AttributeList,
    w = j.SignerInfo;
  var o = {};
  var t = s(g, q);
  if (t.length != 6) {
    throw "not supported items for SignerInfo (!=6)";
  }
  var d = t.shift();
  o.version = a(g, d);
  var e = t.shift();
  o.si = a(g, e);
  var m = t.shift();
  o.digalg = a(g, m);
  var f = t.shift();
  o.sattrs = a(g, f);
  var i = t.shift();
  o.sigalg = a(g, i);
  var b = t.shift();
  o.sig = a(g, b);
  o.sigval = l(g, b);
  var u = null;
  o.obj = new w();
  u = new n();
  u.hTLV = o.version;
  o.obj.dCMSVersion = u;
  u = new n();
  u.hTLV = o.si;
  o.obj.dSignerIdentifier = u;
  u = new n();
  u.hTLV = o.digalg;
  o.obj.dDigestAlgorithm = u;
  u = new n();
  u.hTLV = o.sattrs;
  o.obj.dSignedAttrs = u;
  u = new n();
  u.hTLV = o.sigalg;
  o.obj.dSigAlg = u;
  u = new n();
  u.hTLV = o.sig;
  o.obj.dSig = u;
  o.obj.dUnsignedAttrs = new k();
  return o;
};
if (typeof KJUR.asn1.csr == "undefined" || !KJUR.asn1.csr) {
  KJUR.asn1.csr = {};
}
KJUR.asn1.csr.CertificationRequest = function (g) {
  var d = KJUR,
    c = d.asn1,
    e = c.DERBitString,
    b = c.DERSequence,
    a = c.csr,
    f = c.x509,
    h = a.CertificationRequestInfo;
  a.CertificationRequest.superclass.constructor.call(this);
  this.setByParam = function (i) {
    this.params = i;
  };
  this.sign = function () {
    var j = new h(this.params).tohex();
    var k = new KJUR.crypto.Signature({
      alg: this.params.sigalg
    });
    k.init(this.params.sbjprvkey);
    k.updateHex(j);
    var i = k.sign();
    this.params.sighex = i;
  };
  this.getPEM = function () {
    return hextopem(this.tohex(), "CERTIFICATE REQUEST");
  };
  this.tohex = function () {
    var l = this.params;
    var j = new KJUR.asn1.csr.CertificationRequestInfo(this.params);
    var m = new KJUR.asn1.x509.AlgorithmIdentifier({
      name: l.sigalg
    });
    if (l.sighex == undefined && l.sbjprvkey != undefined) {
      this.sign();
    }
    if (l.sighex == undefined) {
      throw new Error("sighex or sbjprvkey parameter not defined");
    }
    var k = new e({
      hex: "00" + l.sighex
    });
    var i = new b({
      array: [j, m, k]
    });
    return i.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (g !== undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.csr.CertificationRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.CertificationRequestInfo = function (f) {
  var b = KJUR,
    j = b.asn1,
    c = j.DERBitString,
    g = j.DERSequence,
    i = j.DERInteger,
    p = j.DERUTF8String,
    d = j.DERTaggedObject,
    h = j.ASN1Util.newObject,
    n = j.csr,
    e = j.x509,
    a = e.X500Name,
    l = e.Extensions,
    o = e.SubjectPublicKeyInfo,
    k = n.AttributeList;
  n.CertificationRequestInfo.superclass.constructor.call(this);
  this.params = null;
  this.setByParam = function (q) {
    if (q != undefined) {
      this.params = q;
    }
  };
  this.tohex = function () {
    var v = this.params;
    var r = [];
    r.push(new i({
      "int": 0
    }));
    r.push(new a(v.subject));
    r.push(new o(KEYUTIL.getKey(v.sbjpubkey)));
    if (v.attrs != undefined) {
      var u = m(v.attrs);
      var t = h({
        tag: {
          tage: "a0",
          obj: u
        }
      });
      r.push(t);
    } else {
      if (v.extreq != undefined) {
        var q = new l(v.extreq);
        var t = h({
          tag: {
            tage: "a0",
            obj: {
              seq: [{
                oid: "1.2.840.113549.1.9.14"
              }, {
                set: [q]
              }]
            }
          }
        });
        r.push(t);
      } else {
        r.push(new d({
          tag: "a0",
          explicit: false,
          obj: new p({
            str: ""
          })
        }));
      }
    }
    var s = new g({
      array: r
    });
    return s.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  function m(s) {
    var w = Error,
      v = KJUR.asn1.x509.Extensions;
    var y = [];
    for (var u = 0; u < s.length; u++) {
      var r = s[u];
      var x = r.attr;
      if (x == "extensionRequest") {
        var t = new v(r.ext);
        var q = {
          seq: [{
            oid: "1.2.840.113549.1.9.14"
          }, {
            set: [t]
          }]
        };
        y.push(q);
      } else {
        if (x == "unstructuredName") {
          var q = {
            seq: [{
              oid: "1.2.840.113549.1.9.2"
            }, {
              set: r.names
            }]
          };
          y.push(q);
        } else {
          if (x == "challengePassword") {
            var q = {
              seq: [{
                oid: "1.2.840.113549.1.9.7"
              }, {
                set: [{
                  utf8str: r.password
                }]
              }]
            };
            y.push(q);
          } else {
            throw new w("unknown CSR attribute");
          }
        }
      }
    }
    return {
      set: y
    };
  }
  if (f != undefined) {
    this.setByParam(f);
  }
};
extendClass(KJUR.asn1.csr.CertificationRequestInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.AttributeList = function (b) {
  function a(c) {}
};
extendClass(KJUR.asn1.csr.AttributeList, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.CSRUtil = new function () {}();
KJUR.asn1.csr.CSRUtil.newCSRPEM = function (e) {
  var b = KEYUTIL,
    a = KJUR.asn1.csr;
  var c = new a.CertificationRequest(e);
  var d = c.getPEM();
  return d;
};
KJUR.asn1.csr.CSRUtil.getParam = function (d, a) {
  var m = ASN1HEX,
    i = m.getV,
    j = m.getIdxbyList,
    b = m.getTLVbyList,
    o = m.getTLVbyListEx,
    n = m.getVbyListEx;
  var l = function (u) {
    var t = j(u, 0, [0, 3, 0, 0], "06");
    if (i(u, t) != "2a864886f70d01090e") {
      return null;
    }
    return b(u, 0, [0, 3, 0, 1, 0], "30");
  };
  var g = {};
  if (d.indexOf("-----BEGIN CERTIFICATE REQUEST") == -1) {
    throw new Error("argument is not PEM file");
  }
  var e = pemtohex(d, "CERTIFICATE REQUEST");
  if (a) {
    g.tbs = b(e, 0, [0]);
  }
  try {
    var p = o(e, 0, [0, 1]);
    if (p == "3000") {
      g.subject = {};
    } else {
      var f = new X509();
      g.subject = f.getX500Name(p);
    }
  } catch (q) {}
  var k = o(e, 0, [0, 2]);
  var r = KEYUTIL.getKey(k, null, "pkcs8pub");
  g.sbjpubkey = KEYUTIL.getPEM(r, "PKCS8PUB");
  var c = l(e);
  var f = new X509();
  if (c != null) {
    g.extreq = f.getExtParamArray(c);
  }
  try {
    var h = o(e, 0, [1], "30");
    var f = new X509();
    g.sigalg = f.getAlgorithmIdentifierName(h);
  } catch (q) {}
  try {
    var s = n(e, 0, [2]);
    g.sighex = s;
  } catch (q) {}
  return g;
};
KJUR.asn1.csr.CSRUtil.verifySignature = function (b) {
  try {
    var c = null;
    if (typeof b == "string" && b.indexOf("-----BEGIN CERTIFICATE REQUEST") != -1) {
      c = KJUR.asn1.csr.CSRUtil.getParam(b, true);
    } else {
      if (typeof b == "object" && b.sbjpubkey != undefined && b.sigalg != undefined && b.sighex != undefined && b.tbs != undefined) {
        c = b;
      }
    }
    if (c == null) {
      return false;
    }
    var d = new KJUR.crypto.Signature({
      alg: c.sigalg
    });
    d.init(c.sbjpubkey);
    d.updateHex(c.tbs);
    return d.verify(c.sighex);
  } catch (a) {
    alert(a);
    return false;
  }
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
  KJUR.asn1 = {};
}
if (typeof KJUR.asn1.ocsp == "undefined" || !KJUR.asn1.ocsp) {
  KJUR.asn1.ocsp = {};
}
KJUR.asn1.ocsp.DEFAULT_HASH = "sha1";
KJUR.asn1.ocsp.OCSPResponse = function (e) {
  KJUR.asn1.ocsp.OCSPResponse.superclass.constructor.call(this);
  var a = KJUR.asn1.DEREnumerated,
    b = KJUR.asn1.ASN1Util.newObject,
    c = KJUR.asn1.ocsp.ResponseBytes;
  var d = ["successful", "malformedRequest", "internalError", "tryLater", "_not_used_", "sigRequired", "unauthorized"];
  this.params = null;
  this._getStatusCode = function () {
    var f = this.params.resstatus;
    if (typeof f == "number") {
      return f;
    }
    if (typeof f != "string") {
      return -1;
    }
    return d.indexOf(f);
  };
  this.setByParam = function (f) {
    this.params = f;
  };
  this.tohex = function () {
    var h = this.params;
    var g = this._getStatusCode();
    if (g == -1) {
      throw new Error("responseStatus not supported: " + h.resstatus);
    }
    if (g != 0) {
      return b({
        seq: [{
          "enum": {
            "int": g
          }
        }]
      }).tohex();
    }
    var f = new c(h);
    return b({
      seq: [{
        "enum": {
          "int": 0
        }
      }, {
        tag: {
          tag: "a0",
          explicit: true,
          obj: f
        }
      }]
    }).tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.ocsp.OCSPResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponseBytes = function (e) {
  KJUR.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);
  var b = KJUR.asn1,
    a = b.DERSequence,
    f = b.DERObjectIdentifier,
    c = b.DEROctetString,
    d = b.ocsp.BasicOCSPResponse;
  this.params = null;
  this.setByParam = function (g) {
    this.params = g;
  };
  this.tohex = function () {
    var j = this.params;
    if (j.restype != "ocspBasic") {
      throw new Error("not supported responseType: " + j.restype);
    }
    var i = new d(j);
    var g = [];
    g.push(new f({
      name: "ocspBasic"
    }));
    g.push(new c({
      hex: i.tohex()
    }));
    var h = new a({
      array: g
    });
    return h.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.ocsp.ResponseBytes, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.BasicOCSPResponse = function (d) {
  KJUR.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);
  var i = Error,
    g = KJUR.asn1,
    j = g.ASN1Object,
    e = g.DERSequence,
    f = g.DERGeneralizedTime,
    c = g.DERTaggedObject,
    b = g.DERBitString,
    h = g.x509.Extensions,
    k = g.x509.AlgorithmIdentifier,
    l = g.ocsp,
    a = l.ResponderID;
  _SingleResponseList = l.SingleResponseList, _ResponseData = l.ResponseData;
  this.params = null;
  this.setByParam = function (m) {
    this.params = m;
  };
  this.sign = function () {
    var o = this.params;
    var m = o.tbsresp.tohex();
    var n = new KJUR.crypto.Signature({
      alg: o.sigalg
    });
    n.init(o.reskey);
    n.updateHex(m);
    o.sighex = n.sign();
  };
  this.tohex = function () {
    var t = this.params;
    if (t.tbsresp == undefined) {
      t.tbsresp = new _ResponseData(t);
    }
    if (t.sighex == undefined && t.reskey != undefined) {
      this.sign();
    }
    var n = [];
    n.push(t.tbsresp);
    n.push(new k({
      name: t.sigalg
    }));
    n.push(new b({
      hex: "00" + t.sighex
    }));
    if (t.certs != undefined && t.certs.length != undefined) {
      var m = [];
      for (var q = 0; q < t.certs.length; q++) {
        var s = t.certs[q];
        var r = null;
        if (ASN1HEX.isASN1HEX(s)) {
          r = s;
        } else {
          if (s.match(/-----BEGIN/)) {
            r = pemtohex(s);
          } else {
            throw new i("certs[" + q + "] not hex or PEM");
          }
        }
        m.push(new j({
          tlv: r
        }));
      }
      var p = new e({
        array: m
      });
      n.push(new c({
        tag: "a0",
        explicit: true,
        obj: p
      }));
    }
    var o = new e({
      array: n
    });
    return o.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (d !== undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.ocsp.BasicOCSPResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponseData = function (c) {
  KJUR.asn1.ocsp.ResponseData.superclass.constructor.call(this);
  var h = Error,
    f = KJUR.asn1,
    d = f.DERSequence,
    e = f.DERGeneralizedTime,
    b = f.DERTaggedObject,
    g = f.x509.Extensions,
    i = f.ocsp,
    a = i.ResponderID;
  _SingleResponseList = i.SingleResponseList;
  this.params = null;
  this.tohex = function () {
    var m = this.params;
    if (m.respid != undefined) {
      new h("respid not specified");
    }
    if (m.prodat != undefined) {
      new h("prodat not specified");
    }
    if (m.array != undefined) {
      new h("array not specified");
    }
    var j = [];
    j.push(new a(m.respid));
    j.push(new e(m.prodat));
    j.push(new _SingleResponseList(m.array));
    if (m.ext != undefined) {
      var l = new g(m.ext);
      j.push(new b({
        tag: "a1",
        explicit: true,
        obj: l
      }));
    }
    var k = new d({
      array: j
    });
    return k.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (j) {
    this.params = j;
  };
  if (c !== undefined) {
    this.setByParam(c);
  }
};
extendClass(KJUR.asn1.ocsp.ResponseData, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponderID = function (g) {
  KJUR.asn1.ocsp.ResponderID.superclass.constructor.call(this);
  var d = KJUR,
    c = d.asn1,
    b = c.ASN1Util.newObject,
    f = c.x509.X500Name,
    e = d.lang.String.isHex,
    a = Error;
  this.params = null;
  this.tohex = function () {
    var m = this.params;
    if (m.key != undefined) {
      var l = null;
      if (typeof m.key == "string") {
        if (e(m.key)) {
          l = m.key;
        }
        if (m.key.match(/-----BEGIN CERTIFICATE/)) {
          var h = new X509(m.key);
          var k = h.getExtSubjectKeyIdentifier();
          if (k != null) {
            l = k.kid.hex;
          }
        }
      } else {
        if (m.key instanceof X509) {
          var k = m.key.getExtSubjectKeyIdentifier();
          if (k != null) {
            l = k.kid.hex;
          }
        }
      }
      if (l == null) {
        throw new a("wrong key member value");
      }
      var j = b({
        tag: {
          tag: "a2",
          explicit: true,
          obj: {
            octstr: {
              hex: l
            }
          }
        }
      });
      return j.tohex();
    } else {
      if (m.name != undefined) {
        var i = null;
        if (typeof m.name == "string" && m.name.match(/-----BEGIN CERTIFICATE/)) {
          var h = new X509(m.name);
          i = h.getSubject();
        } else {
          if (m.name instanceof X509) {
            i = m.name.getSubject();
          } else {
            if (typeof m.name == "object" && (m.name.array != undefined || m.name.str != undefined)) {
              i = m.name;
            }
          }
        }
        if (i == null) {
          throw new a("wrong name member value");
        }
        var j = b({
          tag: {
            tag: "a1",
            explicit: true,
            obj: new f(i)
          }
        });
        return j.tohex();
      }
    }
    throw new a("key or name not specified");
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (h) {
    this.params = h;
  };
  if (g !== undefined) {
    this.setByParam(g);
  }
};
extendClass(KJUR.asn1.ocsp.ResponderID, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.SingleResponseList = function (d) {
  KJUR.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);
  var c = KJUR.asn1,
    b = c.DERSequence,
    a = c.ocsp.SingleResponse;
  this.params = null;
  this.tohex = function () {
    var h = this.params;
    if (typeof h != "object" || h.length == undefined) {
      throw new Error("params not specified properly");
    }
    var e = [];
    for (var g = 0; g < h.length; g++) {
      e.push(new a(h[g]));
    }
    var f = new b({
      array: e
    });
    return f.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (e) {
    this.params = e;
  };
  if (d !== undefined) {
    this.setByParam(d);
  }
};
extendClass(KJUR.asn1.ocsp.SingleResponseList, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.SingleResponse = function (e) {
  var k = Error,
    a = KJUR,
    i = a.asn1,
    f = i.DERSequence,
    g = i.DERGeneralizedTime,
    b = i.DERTaggedObject,
    l = i.ocsp,
    h = l.CertID,
    c = l.CertStatus,
    d = i.x509,
    j = d.Extensions;
  l.SingleResponse.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var q = this.params;
    var n = [];
    if (q.certid == undefined) {
      throw new k("certid unspecified");
    }
    if (q.status == undefined) {
      throw new k("status unspecified");
    }
    if (q.thisupdate == undefined) {
      throw new k("thisupdate unspecified");
    }
    n.push(new h(q.certid));
    n.push(new c(q.status));
    n.push(new g(q.thisupdate));
    if (q.nextupdate != undefined) {
      var m = new g(q.nextupdate);
      n.push(new b({
        tag: "a0",
        explicit: true,
        obj: m
      }));
    }
    if (q.ext != undefined) {
      var p = new j(q.ext);
      n.push(new b({
        tag: "a1",
        explicit: true,
        obj: p
      }));
    }
    var o = new f({
      array: n
    });
    return o.tohex();
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (m) {
    this.params = m;
  };
  if (e !== undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.ocsp.SingleResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.CertID = function (e) {
  var b = KJUR,
    i = b.asn1,
    l = i.DEROctetString,
    h = i.DERInteger,
    f = i.DERSequence,
    d = i.x509,
    m = d.AlgorithmIdentifier,
    n = i.ocsp,
    k = n.DEFAULT_HASH,
    g = b.crypto,
    c = g.Util.hashHex,
    a = X509,
    o = ASN1HEX,
    j = o.getVbyList;
  n.CertID.superclass.constructor.call(this);
  this.DEFAULT_HASH = "sha1";
  this.params = null;
  this.setByValue = function (s, r, p, q) {
    if (q == undefined) {
      q = this.DEFAULT_HASH;
    }
    this.params = {
      alg: q,
      issname: s,
      isskey: r,
      sbjsn: p
    };
  };
  this.setByCert = function (p, q, r) {
    if (r == undefined) {
      r = this.DEFAULT_HASH;
    }
    this.params = {
      alg: r,
      issuerCert: p,
      subjectCert: q
    };
  };
  this.getParamByCerts = function (y, x, t) {
    if (t == undefined) {
      t = this.DEFAULT_HASH;
    }
    var q = new a(y);
    var v = new a(x);
    var s = c(q.getSubjectHex(), t);
    var u = q.getPublicKeyHex();
    var p = c(j(u, 0, [1], "03", true), t);
    var w = v.getSerialNumberHex();
    var r = {
      alg: t,
      issname: s,
      isskey: p,
      sbjsn: w
    };
    return r;
  };
  this.tohex = function () {
    if (typeof this.params != "object") {
      throw new Error("params not set");
    }
    var s = this.params;
    var u, r, y, q;
    if (s.alg == undefined) {
      q = this.DEFAULT_HASH;
    } else {
      q = s.alg;
    }
    if (s.issuerCert != undefined && s.subjectCert != undefined) {
      var t = this.getParamByCerts(s.issuerCert, s.subjectCert, q);
      u = t.issname;
      r = t.isskey;
      y = t.sbjsn;
    } else {
      if (s.issname != undefined && s.isskey != undefined && s.sbjsn != undefined) {
        u = s.issname;
        r = s.isskey;
        y = s.sbjsn;
      } else {
        throw new Error("required param members not defined");
      }
    }
    var A = new m({
      name: q
    });
    var v = new l({
      hex: u
    });
    var x = new l({
      hex: r
    });
    var w = new h({
      hex: y
    });
    var z = new f({
      array: [A, v, x, w]
    });
    this.hTLV = z.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    this.setByParam(e);
  }
};
extendClass(KJUR.asn1.ocsp.CertID, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.CertStatus = function (a) {
  KJUR.asn1.ocsp.CertStatus.superclass.constructor.call(this);
  this.params = null;
  this.tohex = function () {
    var d = this.params;
    if (d.status == "good") {
      return "8000";
    }
    if (d.status == "unknown") {
      return "8200";
    }
    if (d.status == "revoked") {
      var c = [{
        gentime: {
          str: d.time
        }
      }];
      if (d.reason != undefined) {
        c.push({
          tag: {
            tag: "a0",
            explicit: true,
            obj: {
              "enum": {
                "int": d.reason
              }
            }
          }
        });
      }
      var b = {
        tag: "a1",
        explicit: false,
        obj: {
          seq: c
        }
      };
      return KJUR.asn1.ASN1Util.newObject({
        tag: b
      }).tohex();
    }
    throw new Error("bad status");
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  this.setByParam = function (b) {
    this.params = b;
  };
  if (a !== undefined) {
    this.setByParam(a);
  }
};
extendClass(KJUR.asn1.ocsp.CertStatus, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.Request = function (f) {
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    d = b.ocsp;
  d.Request.superclass.constructor.call(this);
  this.dReqCert = null;
  this.dExt = null;
  this.tohex = function () {
    var g = [];
    if (this.dReqCert === null) {
      throw "reqCert not set";
    }
    g.push(this.dReqCert);
    var h = new a({
      array: g
    });
    this.hTLV = h.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (typeof f !== "undefined") {
    var e = new d.CertID(f);
    this.dReqCert = e;
  }
};
extendClass(KJUR.asn1.ocsp.Request, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.TBSRequest = function (e) {
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    d = b.ocsp;
  d.TBSRequest.superclass.constructor.call(this);
  this.version = 0;
  this.dRequestorName = null;
  this.dRequestList = [];
  this.dRequestExt = null;
  this.setRequestListByParam = function (h) {
    var f = [];
    for (var g = 0; g < h.length; g++) {
      var j = new d.Request(h[0]);
      f.push(j);
    }
    this.dRequestList = f;
  };
  this.tohex = function () {
    var f = [];
    if (this.version !== 0) {
      throw "not supported version: " + this.version;
    }
    if (this.dRequestorName !== null) {
      throw "requestorName not supported";
    }
    var h = new a({
      array: this.dRequestList
    });
    f.push(h);
    if (this.dRequestExt !== null) {
      throw "requestExtensions not supported";
    }
    var g = new a({
      array: f
    });
    this.hTLV = g.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (e !== undefined) {
    if (e.reqList !== undefined) {
      this.setRequestListByParam(e.reqList);
    }
  }
};
extendClass(KJUR.asn1.ocsp.TBSRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.OCSPRequest = function (f) {
  var c = KJUR,
    b = c.asn1,
    a = b.DERSequence,
    d = b.ocsp;
  d.OCSPRequest.superclass.constructor.call(this);
  this.dTbsRequest = null;
  this.dOptionalSignature = null;
  this.tohex = function () {
    var g = [];
    if (this.dTbsRequest !== null) {
      g.push(this.dTbsRequest);
    } else {
      throw "tbsRequest not set";
    }
    if (this.dOptionalSignature !== null) {
      throw "optionalSignature not supported";
    }
    var h = new a({
      array: g
    });
    this.hTLV = h.tohex();
    return this.hTLV;
  };
  this.getEncodedHex = function () {
    return this.tohex();
  };
  if (f !== undefined) {
    if (f.reqList !== undefined) {
      var e = new d.TBSRequest(f);
      this.dTbsRequest = e;
    }
  }
};
extendClass(KJUR.asn1.ocsp.OCSPRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.OCSPUtil = {};
KJUR.asn1.ocsp.OCSPUtil.getRequestHex = function (a, b, h) {
  var d = KJUR,
    c = d.asn1,
    e = c.ocsp;
  if (h === undefined) {
    h = e.DEFAULT_HASH;
  }
  var g = {
    alg: h,
    issuerCert: a,
    subjectCert: b
  };
  var f = new e.OCSPRequest({
    reqList: [g]
  });
  return f.tohex();
};
KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo = function (b) {
  var m = ASN1HEX,
    c = m.getVbyList,
    k = m.getVbyListEx,
    e = m.getIdxbyList,
    d = m.getIdxbyListEx,
    g = m.getV;
  var n = {};
  try {
    var j = k(b, 0, [0], "0a");
    n.responseStatus = parseInt(j, 16);
  } catch (f) {}
  if (n.responseStatus !== 0) {
    return n;
  }
  try {
    var i = e(b, 0, [1, 0, 1, 0, 0, 2, 0, 1]);
    if (b.substr(i, 2) === "80") {
      n.certStatus = "good";
    } else {
      if (b.substr(i, 2) === "a1") {
        n.certStatus = "revoked";
        n.revocationTime = hextoutf8(c(b, i, [0]));
      } else {
        if (b.substr(i, 2) === "82") {
          n.certStatus = "unknown";
        }
      }
    }
  } catch (f) {}
  try {
    var a = e(b, 0, [1, 0, 1, 0, 0, 2, 0, 2]);
    n.thisUpdate = hextoutf8(g(b, a));
  } catch (f) {}
  try {
    var l = e(b, 0, [1, 0, 1, 0, 0, 2, 0, 3]);
    if (b.substr(l, 2) === "a0") {
      n.nextUpdate = hextoutf8(c(b, l, [0]));
    }
  } catch (f) {}
  return n;
};
KJUR.asn1.ocsp.OCSPParser = function () {
  var g = Error,
    a = X509,
    h = new a(),
    l = ASN1HEX,
    i = l.getV,
    b = l.getTLV,
    f = l.getIdxbyList,
    e = l.getVbyList,
    c = l.getTLVbyList,
    k = l.getVbyListEx,
    d = l.getTLVbyListEx,
    j = l.getChildIdx;
  this.getOCSPRequest = function (o) {
    var n = j(o, 0);
    if (n.length != 1 && n.length != 2) {
      throw new g("wrong number elements: " + n.length);
    }
    var m = this.getTBSRequest(b(o, n[0]));
    return m;
  };
  this.getTBSRequest = function (o) {
    var m = {};
    var n = d(o, 0, [0], "30");
    m.array = this.getRequestList(n);
    var p = d(o, 0, ["[2]", 0], "30");
    if (p != null) {
      m.ext = h.getExtParamArray(p);
    }
    return m;
  };
  this.getRequestList = function (p) {
    var m = [];
    var n = j(p, 0);
    for (var o = 0; o < n.length; o++) {
      var p = b(p, n[o]);
      m.push(this.getRequest(p));
    }
    return m;
  };
  this.getRequest = function (n) {
    var m = j(n, 0);
    if (m.length != 1 && m.length != 2) {
      throw new g("wrong number elements: " + m.length);
    }
    var p = this.getCertID(b(n, m[0]));
    if (m.length == 2) {
      var o = f(n, 0, [1, 0]);
      p.ext = h.getExtParamArray(b(n, o));
    }
    return p;
  };
  this.getCertID = function (p) {
    var o = j(p, 0);
    if (o.length != 4) {
      throw new g("wrong number elements: " + o.length);
    }
    var n = new a();
    var m = {};
    m.alg = n.getAlgorithmIdentifierName(b(p, o[0]));
    m.issname = i(p, o[1]);
    m.isskey = i(p, o[2]);
    m.sbjsn = i(p, o[3]);
    return m;
  };
  this.getOCSPResponse = function (r) {
    var o = j(r, 0);
    var m;
    var q = i(r, o[0]);
    var p = parseInt(q);
    if (o.length == 1) {
      return {
        resstatus: p
      };
    }
    var n = c(r, 0, [1, 0]);
    m = this.getResponseBytes(n);
    m.resstatus = p;
    return m;
  };
  this.getResponseBytes = function (p) {
    var o = j(p, 0);
    var n;
    var q = c(p, 0, [1, 0]);
    n = this.getBasicOCSPResponse(q);
    var m = i(p, o[0]);
    n.restype = KJUR.asn1.x509.OID.oid2name(hextooid(m));
    return n;
  };
  this.getBasicOCSPResponse = function (q) {
    var t = j(q, 0);
    var v;
    v = this.getResponseData(b(q, t[0]));
    var u = new X509();
    v.alg = u.getAlgorithmIdentifierName(b(q, t[1]));
    var n = i(q, t[2]);
    v.sighex = n.substr(2);
    var m = k(q, 0, ["[0]"]);
    if (m != null) {
      var r = j(m, 0);
      var o = [];
      for (var p = 0; p < r.length; p++) {
        var s = b(m, r[p]);
        o.push(s);
      }
      v.certs = o;
    }
    return v;
  };
  this.getResponseData = function (q) {
    var p = j(q, 0);
    var r = p.length;
    var o = {};
    var n = 0;
    if (q.substr(p[0], 2) == "a0") {
      n++;
    }
    o.respid = this.getResponderID(b(q, p[n++]));
    var t = i(q, p[n++]);
    o.prodat = hextoutf8(t);
    o.array = this.getSingleResponseList(b(q, p[n++]));
    if (q.substr(p[r - 1], 2) == "a1") {
      var s = c(q, p[r - 1], [0]);
      var m = new X509();
      o.ext = m.getExtParamArray(s);
    }
    return o;
  };
  this.getResponderID = function (o) {
    var n = {};
    if (o.substr(0, 2) == "a2") {
      var p = e(o, 0, [0]);
      n.key = p;
    }
    if (o.substr(0, 2) == "a1") {
      var q = c(o, 0, [0]);
      var m = new X509();
      n.name = m.getX500Name(q);
    }
    return n;
  };
  this.getSingleResponseList = function (q) {
    var n = j(q, 0);
    var m = [];
    for (var o = 0; o < n.length; o++) {
      var r = this.getSingleResponse(b(q, n[o]));
      m.push(r);
    }
    return m;
  };
  this.getSingleResponse = function (p) {
    var t = j(p, 0);
    var v = {};
    var r = this.getCertID(b(p, t[0]));
    v.certid = r;
    var u = this.getCertStatus(b(p, t[1]));
    v.status = u;
    if (p.substr(t[2], 2) == "18") {
      var q = i(p, t[2]);
      v.thisupdate = hextoutf8(q);
    }
    for (var o = 3; o < t.length; o++) {
      if (p.substr(t[o], 2) == "a0") {
        var m = e(p, t[o], [0], "18");
        v.nextupdate = hextoutf8(m);
      }
      if (p.substr(t[o], 2) == "a1") {
        var s = new X509();
        var n = c(p, 0, [o, 0]);
        v.ext = s.getExtParamArray(n);
      }
    }
    return v;
  };
  this.getCertStatus = function (p) {
    var m = {};
    if (p == "8000") {
      return {
        status: "good"
      };
    }
    if (p == "8200") {
      return {
        status: "unknown"
      };
    }
    if (p.substr(0, 2) == "a1") {
      m.status = "revoked";
      var o = e(p, 0, [0]);
      var n = hextoutf8(o);
      m.time = n;
    }
    return m;
  };
};
var KJUR;
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.lang == "undefined" || !KJUR.lang) {
  KJUR.lang = {};
}
KJUR.lang.String = function () {};
function Base64x() {}
function stoBA(d) {
  var b = new Array();
  for (var c = 0; c < d.length; c++) {
    b[c] = d.charCodeAt(c);
  }
  return b;
}
function BAtos(b) {
  var d = "";
  for (var c = 0; c < b.length; c++) {
    d = d + String.fromCharCode(b[c]);
  }
  return d;
}
function BAtohex(b) {
  var e = "";
  for (var d = 0; d < b.length; d++) {
    var c = b[d].toString(16);
    if (c.length == 1) {
      c = "0" + c;
    }
    e = e + c;
  }
  return e;
}
function stohex(a) {
  return BAtohex(stoBA(a));
}
function stob64(a) {
  return hex2b64(stohex(a));
}
function stob64u(a) {
  return b64tob64u(hex2b64(stohex(a)));
}
function b64utos(a) {
  return BAtos(b64toBA(b64utob64(a)));
}
function b64tob64u(a) {
  a = a.replace(/\=/g, "");
  a = a.replace(/\+/g, "-");
  a = a.replace(/\//g, "_");
  return a;
}
function b64utob64(a) {
  if (a.length % 4 == 2) {
    a = a + "==";
  } else {
    if (a.length % 4 == 3) {
      a = a + "=";
    }
  }
  a = a.replace(/-/g, "+");
  a = a.replace(/_/g, "/");
  return a;
}
function hextob64u(a) {
  if (a.length % 2 == 1) {
    a = "0" + a;
  }
  return b64tob64u(hex2b64(a));
}
function b64utohex(a) {
  return b64tohex(b64utob64(a));
}
var utf8tob64u, b64utoutf8;
if (typeof Buffer === "function") {
  utf8tob64u = function (a) {
    return b64tob64u(Buffer.from(a, "utf8").toString("base64"));
  };
  b64utoutf8 = function (a) {
    return Buffer.from(b64utob64(a), "base64").toString("utf8");
  };
} else {
  utf8tob64u = function (a) {
    return hextob64u(uricmptohex(encodeURIComponentAll(a)));
  };
  b64utoutf8 = function (a) {
    return decodeURIComponent(hextouricmp(b64utohex(a)));
  };
}
function utf8tob64(a) {
  return hex2b64(uricmptohex(encodeURIComponentAll(a)));
}
function b64toutf8(a) {
  return decodeURIComponent(hextouricmp(b64tohex(a)));
}
function utf8tohex(a) {
  return uricmptohex(encodeURIComponentAll(a)).toLowerCase();
}
function hextoutf8(b) {
  try {
    return decodeURIComponent(hextouricmp(b));
  } catch (a) {
    return null;
  }
}
function iso88591hextoutf8(a) {
  return hextoutf8(iso88591hextoutf8hex(a));
}
function utf8toiso88591hex(a) {
  return utf8hextoiso88591hex(utf8tohex(a));
}
function iso88591hextoutf8hex(e) {
  var c = e.match(/.{1,2}/g);
  var b = [];
  for (var d = 0; d < c.length; d++) {
    var f = parseInt(c[d], 16);
    if (161 <= f && f <= 191) {
      b.push("c2");
      b.push(c[d]);
    } else {
      if (192 <= f && f <= 255) {
        b.push("c3");
        b.push((f - 64).toString(16));
      } else {
        b.push(c[d]);
      }
    }
  }
  return b.join("");
}
function utf8hextoiso88591hex(f) {
  var c = f.match(/.{1,2}/g);
  var b = [];
  for (var e = 0; e < c.length; e++) {
    if (c[e] == "c2") {
      e++;
      b.push(c[e]);
    } else {
      if (c[e] == "c3") {
        e++;
        var d = c[e];
        var g = parseInt(c[e], 16) + 64;
        b.push(g.toString(16));
      } else {
        b.push(c[e]);
      }
    }
  }
  return b.join("");
}
function hextorstr(c) {
  var b = "";
  for (var a = 0; a < c.length - 1; a += 2) {
    b += String.fromCharCode(parseInt(c.substr(a, 2), 16));
  }
  return b;
}
function rstrtohex(c) {
  var a = "";
  for (var b = 0; b < c.length; b++) {
    a += ("0" + c.charCodeAt(b).toString(16)).slice(-2);
  }
  return a;
}
function hextob64(a) {
  return hex2b64(a);
}
function hextob64nl(a) {
  return foldnl(hextob64(a), 64);
}
function foldnl(a, b) {
  a = a.replace(new RegExp("(.{" + b + "})", "g"), "$1\r\n");
  a = a.replace(/\s+$/, "");
  return a;
}
function b64nltohex(b) {
  var a = b.replace(/[^0-9A-Za-z\/+=]*/g, "");
  var c = b64tohex(a);
  return c;
}
function b64topem(b, a) {
  return "-----BEGIN " + a + "-----\r\n" + foldnl(b, 64) + "\r\n-----END " + a + "-----\r\n";
}
function hextopem(a, b) {
  return "-----BEGIN " + b + "-----\r\n" + foldnl(hextob64(a), 64) + "\r\n-----END " + b + "-----\r\n";
}
function pemtohex(a, b) {
  if (a.indexOf("-----BEGIN ") == -1) {
    throw new Error("can't find PEM header");
  }
  if (b !== undefined) {
    a = a.replace(new RegExp("^[^]*-----BEGIN " + b + "-----"), "");
    a = a.replace(new RegExp("-----END " + b + "-----[^]*$"), "");
  } else {
    a = a.replace(/^[^]*-----BEGIN [^-]+-----/, "");
    a = a.replace(/-----END [^-]+-----[^]*$/, "");
  }
  return b64nltohex(a);
}
function pemtob64(a) {
  if (a.indexOf("-----BEGIN ") == -1 || a.indexOf("-----END ") == -1) {
    return null;
  }
  a = a.replace(/^[\s\S]*?-----BEGIN [^-]+-----/m, "");
  a = a.replace(/-----END [\s\S]+$/m, "");
  a = a.replace(/\s+/g, "");
  return a.match(/^[0-9a-zA-Z+/=]+$/) ? a : null;
}
function hextoArrayBuffer(d) {
  if (d.length % 2 != 0) {
    throw "input is not even length";
  }
  if (d.match(/^[0-9A-Fa-f]+$/) == null) {
    throw "input is not hexadecimal";
  }
  var b = new ArrayBuffer(d.length / 2);
  var a = new DataView(b);
  for (var c = 0; c < d.length / 2; c++) {
    a.setUint8(c, parseInt(d.substr(c * 2, 2), 16));
  }
  return b;
}
function ArrayBuffertohex(b) {
  var d = "";
  var a = new DataView(b);
  for (var c = 0; c < b.byteLength; c++) {
    d += ("00" + a.getUint8(c).toString(16)).slice(-2);
  }
  return d;
}
function zulutomsec(n) {
  var l, j, m, e, f, i, b, k;
  var a, h, g, c;
  n = timetogen(n);
  c = n.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);
  if (c) {
    l = parseInt(c[1]);
    j = parseInt(c[2]) - 1;
    m = parseInt(c[3]);
    e = parseInt(c[4]);
    f = parseInt(c[5]);
    i = parseInt(c[6]);
    b = 0;
    h = c[7];
    if (h !== "") {
      g = (h.substr(1) + "00").substr(0, 3);
      b = parseInt(g);
    }
    return Date.UTC(l, j, m, e, f, i, b);
  }
  throw new Error("unsupported zulu format: " + n);
}
function msectozulu(b) {
  var h = new Date(b),
    i = ("0000" + h.getUTCFullYear()).slice(-4),
    c = ("00" + (h.getUTCMonth() + 1)).slice(-2),
    j = ("00" + h.getUTCDate()).slice(-2),
    e = ("00" + h.getUTCHours()).slice(-2),
    f = ("00" + h.getUTCMinutes()).slice(-2),
    g = ("00" + h.getUTCSeconds()).slice(-2),
    a = ("000" + h.getUTCMilliseconds()).slice(-3);
  a = a.replace(/0+$/, "");
  a = a != "" ? "." + a : a;
  return i + c + j + e + f + g + a + "Z";
}
function zulutosec(a) {
  return Math.round(zulutomsec(a) / 1000);
}
function zulutodate(a) {
  return new Date(zulutomsec(a));
}
function datetozulu(g, e, f) {
  var b;
  var a = g.getUTCFullYear();
  if (e) {
    if (a < 1950 || 2049 < a) {
      throw "not proper year for UTCTime: " + a;
    }
    b = ("" + a).slice(-2);
  } else {
    b = ("000" + a).slice(-4);
  }
  b += ("0" + (g.getUTCMonth() + 1)).slice(-2);
  b += ("0" + g.getUTCDate()).slice(-2);
  b += ("0" + g.getUTCHours()).slice(-2);
  b += ("0" + g.getUTCMinutes()).slice(-2);
  b += ("0" + g.getUTCSeconds()).slice(-2);
  if (f) {
    var c = g.getUTCMilliseconds();
    if (c !== 0) {
      c = ("00" + c).slice(-3);
      c = c.replace(/0+$/g, "");
      b += "." + c;
    }
  }
  b += "Z";
  return b;
}
function timetogen(a) {
  if (a.match(/^[0-9]{12}Z$/) || a.match(/^[0-9]{12}[.][0-9]*Z$/)) {
    return a.match(/^[0-4]/) ? "20" + a : "19" + a;
  }
  return a;
}
function uricmptohex(a) {
  return a.replace(/%/g, "");
}
function hextouricmp(a) {
  return a.replace(/(..)/g, "%$1");
}
function ipv6tohex(g) {
  var b = "malformed IPv6 address";
  if (!g.match(/^[0-9A-Fa-f:]+$/)) {
    throw b;
  }
  g = g.toLowerCase();
  var d = g.split(":").length - 1;
  if (d < 2) {
    throw b;
  }
  var e = ":".repeat(7 - d + 2);
  g = g.replace("::", e);
  var c = g.split(":");
  if (c.length != 8) {
    throw b;
  }
  for (var f = 0; f < 8; f++) {
    c[f] = ("0000" + c[f]).slice(-4);
  }
  return c.join("");
}
function hextoipv6(d) {
  if (!d.match(/^[0-9A-Fa-f]{32}$/)) {
    throw new Error("malformed IPv6 address: " + d);
  }
  d = d.toLowerCase();
  var b = d.match(/.{1,4}/g);
  b = b.map(function (a) {
    return a.replace(/^0+/, "");
  });
  b = b.map(function (a) {
    return a == "" ? "0" : a;
  });
  d = ":" + b.join(":") + ":";
  var c = d.match(/:(0:){2,}/g);
  if (c == null) {
    return d.slice(1, -1);
  }
  var e = c.sort().slice(-1)[0];
  d = d.replace(e.substr(0, e.length - 1), ":");
  if (d.substr(0, 2) != "::") {
    d = d.substr(1);
  }
  if (d.substr(-2, 2) != "::") {
    d = d.substr(0, d.length - 1);
  }
  return d;
}
function hextoip(b) {
  var c = new Error("malformed hex value");
  if (!b.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/)) {
    throw c;
  }
  if (b.length == 8) {
    var d;
    try {
      d = parseInt(b.substr(0, 2), 16) + "." + parseInt(b.substr(2, 2), 16) + "." + parseInt(b.substr(4, 2), 16) + "." + parseInt(b.substr(6, 2), 16);
      return d;
    } catch (a) {
      throw c;
    }
  } else {
    if (b.length == 16) {
      try {
        return hextoip(b.substr(0, 8)) + "/" + ipprefixlen(b.substr(8));
      } catch (a) {
        throw c;
      }
    } else {
      if (b.length == 32) {
        return hextoipv6(b);
      } else {
        if (b.length == 64) {
          try {
            return hextoipv6(b.substr(0, 32)) + "/" + ipprefixlen(b.substr(32));
          } catch (a) {
            throw c;
          }
          return;
        } else {
          return b;
        }
      }
    }
  }
}
function ipprefixlen(c) {
  var d = new Error("malformed mask");
  var a;
  try {
    a = new BigInteger(c, 16).toString(2);
  } catch (b) {
    throw d;
  }
  if (!a.match(/^1*0*$/)) {
    throw d;
  }
  return a.replace(/0+$/, "").length;
}
function iptohex(g) {
  var j = new Error("malformed IP address");
  g = g.toLowerCase(g);
  if (!g.match(/^[0-9a-f.:/]+$/)) {
    throw j;
  }
  if (g.match(/^[0-9.]+$/)) {
    var b = g.split(".");
    if (b.length !== 4) {
      throw j;
    }
    var h = "";
    try {
      for (var f = 0; f < 4; f++) {
        var k = parseInt(b[f]);
        h += ("0" + k.toString(16)).slice(-2);
      }
      return h;
    } catch (e) {
      throw j;
    }
  } else {
    if (g.match(/^[0-9.]+\/[0-9]+$/)) {
      var c = g.split("/");
      return iptohex(c[0]) + ipnetmask(parseInt(c[1]), 32);
    } else {
      if (g.match(/^[0-9a-f:]+$/) && g.indexOf(":") !== -1) {
        return ipv6tohex(g);
      } else {
        if (g.match(/^[0-9a-f:]+\/[0-9]+$/) && g.indexOf(":") !== -1) {
          var c = g.split("/");
          return ipv6tohex(c[0]) + ipnetmask(parseInt(c[1]), 128);
        } else {
          throw j;
        }
      }
    }
  }
}
function ipnetmask(d, c) {
  if (c == 32 && d == 0) {
    return "00000000";
  }
  if (c == 128 && d == 0) {
    return "00000000000000000000000000000000";
  }
  var a = Array(d + 1).join("1") + Array(c - d + 1).join("0");
  return new BigInteger(a, 2).toString(16);
}
function ucs2hextoutf8(d) {
  function e(f) {
    var h = parseInt(f.substr(0, 2), 16);
    var a = parseInt(f.substr(2), 16);
    if (h == 0 & a < 128) {
      return String.fromCharCode(a);
    }
    if (h < 8) {
      var j = 192 | (h & 7) << 3 | (a & 192) >> 6;
      var i = 128 | a & 63;
      return hextoutf8(j.toString(16) + i.toString(16));
    }
    var j = 224 | (h & 240) >> 4;
    var i = 128 | (h & 15) << 2 | (a & 192) >> 6;
    var g = 128 | a & 63;
    return hextoutf8(j.toString(16) + i.toString(16) + g.toString(16));
  }
  var c = d.match(/.{4}/g);
  var b = c.map(e);
  return b.join("");
}
function encodeURIComponentAll(a) {
  var d = encodeURIComponent(a);
  var b = "";
  for (var c = 0; c < d.length; c++) {
    if (d[c] == "%") {
      b = b + d.substr(c, 3);
      c = c + 2;
    } else {
      b = b + "%" + stohex(d[c]);
    }
  }
  return b;
}
function newline_toUnix(a) {
  a = a.replace(/\r\n/mg, "\n");
  return a;
}
function newline_toDos(a) {
  a = a.replace(/\r\n/mg, "\n");
  a = a.replace(/\n/mg, "\r\n");
  return a;
}
KJUR.lang.String.isInteger = function (a) {
  if (a.match(/^[0-9]+$/)) {
    return true;
  } else {
    if (a.match(/^-[0-9]+$/)) {
      return true;
    } else {
      return false;
    }
  }
};
KJUR.lang.String.isHex = function (a) {
  return ishex(a);
};
function ishex(a) {
  if (a.length % 2 == 0 && (a.match(/^[0-9a-f]+$/) || a.match(/^[0-9A-F]+$/))) {
    return true;
  } else {
    return false;
  }
}
KJUR.lang.String.isBase64 = function (a) {
  a = a.replace(/\s+/g, "");
  if (a.match(/^[0-9A-Za-z+\/]+={0,3}$/) && a.length % 4 == 0) {
    return true;
  } else {
    return false;
  }
};
KJUR.lang.String.isBase64URL = function (a) {
  if (a.match(/[+/=]/)) {
    return false;
  }
  a = b64utob64(a);
  return KJUR.lang.String.isBase64(a);
};
function isBase64URLDot(a) {
  if (a.match(/^[0-9A-Za-z-_.]+$/)) {
    return true;
  }
  return false;
}
KJUR.lang.String.isIntegerArray = function (a) {
  a = a.replace(/\s+/g, "");
  if (a.match(/^\[[0-9,]+\]$/)) {
    return true;
  } else {
    return false;
  }
};
KJUR.lang.String.isPrintable = function (a) {
  if (a.match(/^[0-9A-Za-z '()+,-./:=?]*$/) !== null) {
    return true;
  }
  return false;
};
KJUR.lang.String.isIA5 = function (a) {
  if (a.match(/^[\x20-\x21\x23-\x7f]*$/) !== null) {
    return true;
  }
  return false;
};
KJUR.lang.String.isMail = function (a) {
  if (a.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/) !== null) {
    return true;
  }
  return false;
};
function hextoposhex(a) {
  if (a.length % 2 == 1) {
    return "0" + a;
  }
  if (a.substr(0, 1) > "7") {
    return "00" + a;
  }
  return a;
}
function intarystrtohex(b) {
  b = b.replace(/^\s*\[\s*/, "");
  b = b.replace(/\s*\]\s*$/, "");
  b = b.replace(/\s*/g, "");
  try {
    var c = b.split(/,/).map(function (g, e, h) {
      var f = parseInt(g);
      if (f < 0 || 255 < f) {
        throw "integer not in range 0-255";
      }
      var d = ("00" + f.toString(16)).slice(-2);
      return d;
    }).join("");
    return c;
  } catch (a) {
    throw "malformed integer array string: " + a;
  }
}
var strdiffidx = function (c, a) {
  var d = c.length;
  if (c.length > a.length) {
    d = a.length;
  }
  for (var b = 0; b < d; b++) {
    if (c.charCodeAt(b) != a.charCodeAt(b)) {
      return b;
    }
  }
  if (c.length != a.length) {
    return d;
  }
  return -1;
};
function oidtohex(g) {
  var f = function (a) {
    var l = a.toString(16);
    if (l.length == 1) {
      l = "0" + l;
    }
    return l;
  };
  var e = function (p) {
    var o = "";
    var l = parseInt(p, 10);
    var a = l.toString(2);
    var m = 7 - a.length % 7;
    if (m == 7) {
      m = 0;
    }
    var r = "";
    for (var n = 0; n < m; n++) {
      r += "0";
    }
    a = r + a;
    for (var n = 0; n < a.length - 1; n += 7) {
      var q = a.substr(n, 7);
      if (n != a.length - 7) {
        q = "1" + q;
      }
      o += f(parseInt(q, 2));
    }
    return o;
  };
  try {
    if (!g.match(/^[0-9.]+$/)) {
      return null;
    }
    var j = "";
    var b = g.split(".");
    var k = parseInt(b[0], 10) * 40 + parseInt(b[1], 10);
    j += f(k);
    b.splice(0, 2);
    for (var d = 0; d < b.length; d++) {
      j += e(b[d]);
    }
    return j;
  } catch (c) {
    return null;
  }
}
function hextooid(g) {
  if (!ishex(g)) {
    return null;
  }
  try {
    var m = [];
    var p = g.substr(0, 2);
    var e = parseInt(p, 16);
    m[0] = new String(Math.floor(e / 40));
    m[1] = new String(e % 40);
    var n = g.substr(2);
    var l = [];
    for (var f = 0; f < n.length / 2; f++) {
      l.push(parseInt(n.substr(f * 2, 2), 16));
    }
    var k = [];
    var d = "";
    for (var f = 0; f < l.length; f++) {
      if (l[f] & 128) {
        d = d + strpad((l[f] & 127).toString(2), 7);
      } else {
        d = d + strpad((l[f] & 127).toString(2), 7);
        k.push(new String(parseInt(d, 2)));
        d = "";
      }
    }
    var o = m.join(".");
    if (k.length > 0) {
      o = o + "." + k.join(".");
    }
    return o;
  } catch (j) {
    return null;
  }
}
function inttohex(b) {
  var a = new BigInteger(String(b), 10);
  return twoscompl(a);
}
function twoscompl(b) {
  var g = b.toString(16);
  if (g.substr(0, 1) != "-") {
    if (g.length % 2 == 1) {
      g = "0" + g;
    } else {
      if (!g.match(/^[0-7]/)) {
        g = "00" + g;
      }
    }
    return g;
  }
  var a = g.substr(1);
  var f = a.length;
  if (f % 2 == 1) {
    f += 1;
  } else {
    if (!g.match(/^[0-7]/)) {
      f += 2;
    }
  }
  var j = "";
  for (var e = 0; e < f; e++) {
    j += "f";
  }
  var d = new BigInteger(j, 16);
  var c = d.xor(b).add(BigInteger.ONE);
  g = c.toString(16).replace(/^-/, "");
  return g;
}
var strpad = function (c, b, a) {
  if (a == undefined) {
    a = "0";
  }
  if (c.length >= b) {
    return c;
  }
  return new Array(b - c.length + 1).join(a) + c;
};
function bitstrtoint(e) {
  if (e.length % 2 != 0) {
    return -1;
  }
  e = e.toLowerCase();
  if (e.match(/^[0-9a-f]+$/) == null) {
    return -1;
  }
  try {
    var a = e.substr(0, 2);
    if (a == "00") {
      return parseInt(e.substr(2), 16);
    }
    var b = parseInt(a, 16);
    if (b > 7) {
      return -1;
    }
    var g = e.substr(2);
    var d = parseInt(g, 16).toString(2);
    if (d == "0") {
      d = "00000000";
    }
    d = d.slice(0, 0 - b);
    var f = parseInt(d, 2);
    if (f == NaN) {
      return -1;
    }
    return f;
  } catch (c) {
    return -1;
  }
}
function inttobitstr(e) {
  if (typeof e != "number") {
    return null;
  }
  if (e < 0) {
    return null;
  }
  var c = Number(e).toString(2);
  var b = 8 - c.length % 8;
  if (b == 8) {
    b = 0;
  }
  c = c + strpad("", b, "0");
  var d = parseInt(c, 2).toString(16);
  if (d.length % 2 == 1) {
    d = "0" + d;
  }
  var a = "0" + b;
  return a + d;
}
function bitstrtobinstr(g) {
  if (typeof g != "string") {
    return null;
  }
  if (g.length % 2 != 0) {
    return null;
  }
  if (!g.match(/^[0-9a-f]+$/)) {
    return null;
  }
  try {
    var c = parseInt(g.substr(0, 2), 16);
    if (c < 0 || 7 < c) {
      return null;
    }
    var j = g.substr(2);
    var f = "";
    for (var e = 0; e < j.length; e += 2) {
      var b = j.substr(e, 2);
      var a = parseInt(b, 16).toString(2);
      a = ("0000000" + a).slice(-8);
      f += a;
    }
    return f.substr(0, f.length - c);
  } catch (d) {
    return null;
  }
}
function binstrtobitstr(b) {
  if (typeof b != "string") {
    return null;
  }
  if (b.match(/^[01]+$/) == null) {
    return null;
  }
  try {
    var c = parseInt(b, 2);
    return inttobitstr(c);
  } catch (a) {
    return null;
  }
}
function namearraytobinstr(e, g) {
  var f = 0;
  for (var a = 0; a < e.length; a++) {
    f |= 1 << g[e[a]];
  }
  var b = f.toString(2);
  var c = "";
  for (var a = b.length - 1; a >= 0; a--) {
    c += b[a];
  }
  return c;
}
function aryval(e, c, d) {
  if (typeof e != "object") {
    return undefined;
  }
  var c = String(c).split(".");
  for (var b = 0; b < c.length && e; b++) {
    var a = c[b];
    if (a.match(/^[0-9]+$/)) {
      a = parseInt(a);
    }
    e = e[a];
  }
  return e || e === false ? e : d;
}
function extendClass(c, a) {
  var b = function () {};
  b.prototype = a.prototype;
  c.prototype = new b();
  c.prototype.constructor = c;
  c.superclass = a.prototype;
  if (a.prototype.constructor == Object.prototype.constructor) {
    a.prototype.constructor = a;
  }
}
;
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
  KJUR.crypto = {};
}
KJUR.crypto.Util = new function () {
  this.DIGESTINFOHEAD = {
    sha1: "3021300906052b0e03021a05000414",
    sha224: "302d300d06096086480165030402040500041c",
    sha256: "3031300d060960864801650304020105000420",
    sha384: "3041300d060960864801650304020205000430",
    sha512: "3051300d060960864801650304020305000440",
    md2: "3020300c06082a864886f70d020205000410",
    md5: "3020300c06082a864886f70d020505000410",
    ripemd160: "3021300906052b2403020105000414"
  };
  this.DEFAULTPROVIDER = {
    md5: "cryptojs",
    sha1: "cryptojs",
    sha224: "cryptojs",
    sha256: "cryptojs",
    sha384: "cryptojs",
    sha512: "cryptojs",
    ripemd160: "cryptojs",
    hmacmd5: "cryptojs",
    hmacsha1: "cryptojs",
    hmacsha224: "cryptojs",
    hmacsha256: "cryptojs",
    hmacsha384: "cryptojs",
    hmacsha512: "cryptojs",
    hmacripemd160: "cryptojs",
    MD5withRSA: "cryptojs/jsrsa",
    SHA1withRSA: "cryptojs/jsrsa",
    SHA224withRSA: "cryptojs/jsrsa",
    SHA256withRSA: "cryptojs/jsrsa",
    SHA384withRSA: "cryptojs/jsrsa",
    SHA512withRSA: "cryptojs/jsrsa",
    RIPEMD160withRSA: "cryptojs/jsrsa",
    MD5withECDSA: "cryptojs/jsrsa",
    SHA1withECDSA: "cryptojs/jsrsa",
    SHA224withECDSA: "cryptojs/jsrsa",
    SHA256withECDSA: "cryptojs/jsrsa",
    SHA384withECDSA: "cryptojs/jsrsa",
    SHA512withECDSA: "cryptojs/jsrsa",
    RIPEMD160withECDSA: "cryptojs/jsrsa",
    SHA1withDSA: "cryptojs/jsrsa",
    SHA224withDSA: "cryptojs/jsrsa",
    SHA256withDSA: "cryptojs/jsrsa",
    MD5withRSAandMGF1: "cryptojs/jsrsa",
    SHAwithRSAandMGF1: "cryptojs/jsrsa",
    SHA1withRSAandMGF1: "cryptojs/jsrsa",
    SHA224withRSAandMGF1: "cryptojs/jsrsa",
    SHA256withRSAandMGF1: "cryptojs/jsrsa",
    SHA384withRSAandMGF1: "cryptojs/jsrsa",
    SHA512withRSAandMGF1: "cryptojs/jsrsa",
    RIPEMD160withRSAandMGF1: "cryptojs/jsrsa"
  };
  this.CRYPTOJSMESSAGEDIGESTNAME = {
    md5: CryptoJS.algo.MD5,
    sha1: CryptoJS.algo.SHA1,
    sha224: CryptoJS.algo.SHA224,
    sha256: CryptoJS.algo.SHA256,
    sha384: CryptoJS.algo.SHA384,
    sha512: CryptoJS.algo.SHA512,
    ripemd160: CryptoJS.algo.RIPEMD160
  };
  this.getDigestInfoHex = function (a, b) {
    if (typeof this.DIGESTINFOHEAD[b] == "undefined") {
      throw "alg not supported in Util.DIGESTINFOHEAD: " + b;
    }
    return this.DIGESTINFOHEAD[b] + a;
  };
  this.getPaddedDigestInfoHex = function (h, a, j) {
    var c = this.getDigestInfoHex(h, a);
    var d = j / 4;
    if (c.length + 22 > d) {
      throw "key is too short for SigAlg: keylen=" + j + "," + a;
    }
    var b = "0001";
    var k = "00" + c;
    var g = "";
    var l = d - b.length - k.length;
    for (var f = 0; f < l; f += 2) {
      g += "ff";
    }
    var e = b + g + k;
    return e;
  };
  this.hashString = function (a, c) {
    var b = new KJUR.crypto.MessageDigest({
      alg: c
    });
    return b.digestString(a);
  };
  this.hashHex = function (b, c) {
    var a = new KJUR.crypto.MessageDigest({
      alg: c
    });
    return a.digestHex(b);
  };
  this.sha1 = function (a) {
    return this.hashString(a, "sha1");
  };
  this.sha256 = function (a) {
    return this.hashString(a, "sha256");
  };
  this.sha256Hex = function (a) {
    return this.hashHex(a, "sha256");
  };
  this.sha512 = function (a) {
    return this.hashString(a, "sha512");
  };
  this.sha512Hex = function (a) {
    return this.hashHex(a, "sha512");
  };
  this.isKey = function (a) {
    if (a instanceof RSAKey || a instanceof KJUR.crypto.DSA || a instanceof KJUR.crypto.ECDSA) {
      return true;
    } else {
      return false;
    }
  };
}();
KJUR.crypto.Util.md5 = function (a) {
  var b = new KJUR.crypto.MessageDigest({
    alg: "md5",
    prov: "cryptojs"
  });
  return b.digestString(a);
};
KJUR.crypto.Util.ripemd160 = function (a) {
  var b = new KJUR.crypto.MessageDigest({
    alg: "ripemd160",
    prov: "cryptojs"
  });
  return b.digestString(a);
};
KJUR.crypto.Util.SECURERANDOMGEN = new SecureRandom();
KJUR.crypto.Util.getRandomHexOfNbytes = function (b) {
  var a = new Array(b);
  KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(a);
  return BAtohex(a);
};
KJUR.crypto.Util.getRandomBigIntegerOfNbytes = function (a) {
  return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(a), 16);
};
KJUR.crypto.Util.getRandomHexOfNbits = function (d) {
  var c = d % 8;
  var a = (d - c) / 8;
  var b = new Array(a + 1);
  KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(b);
  b[0] = (255 << c & 255 ^ 255) & b[0];
  return BAtohex(b);
};
KJUR.crypto.Util.getRandomBigIntegerOfNbits = function (a) {
  return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(a), 16);
};
KJUR.crypto.Util.getRandomBigIntegerZeroToMax = function (b) {
  var a = b.bitLength();
  while (1) {
    var c = KJUR.crypto.Util.getRandomBigIntegerOfNbits(a);
    if (b.compareTo(c) != -1) {
      return c;
    }
  }
};
KJUR.crypto.Util.getRandomBigIntegerMinToMax = function (e, b) {
  var c = e.compareTo(b);
  if (c == 1) {
    throw "biMin is greater than biMax";
  }
  if (c == 0) {
    return e;
  }
  var a = b.subtract(e);
  var d = KJUR.crypto.Util.getRandomBigIntegerZeroToMax(a);
  return d.add(e);
};
KJUR.crypto.MessageDigest = function (c) {
  var b = null;
  var a = null;
  var d = null;
  this.setAlgAndProvider = function (g, f) {
    g = KJUR.crypto.MessageDigest.getCanonicalAlgName(g);
    if (g !== null && f === undefined) {
      f = KJUR.crypto.Util.DEFAULTPROVIDER[g];
    }
    if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g) != -1 && f == "cryptojs") {
      try {
        this.md = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g].create();
      } catch (e) {
        throw "setAlgAndProvider hash alg set fail alg=" + g + "/" + e;
      }
      this.updateString = function (h) {
        this.md.update(h);
      };
      this.updateHex = function (h) {
        var i = CryptoJS.enc.Hex.parse(h);
        this.md.update(i);
      };
      this.digest = function () {
        var h = this.md.finalize();
        return h.toString(CryptoJS.enc.Hex);
      };
      this.digestString = function (h) {
        this.updateString(h);
        return this.digest();
      };
      this.digestHex = function (h) {
        this.updateHex(h);
        return this.digest();
      };
    }
    if (":sha256:".indexOf(g) != -1 && f == "sjcl") {
      try {
        this.md = new sjcl.hash.sha256();
      } catch (e) {
        throw "setAlgAndProvider hash alg set fail alg=" + g + "/" + e;
      }
      this.updateString = function (h) {
        this.md.update(h);
      };
      this.updateHex = function (i) {
        var h = sjcl.codec.hex.toBits(i);
        this.md.update(h);
      };
      this.digest = function () {
        var h = this.md.finalize();
        return sjcl.codec.hex.fromBits(h);
      };
      this.digestString = function (h) {
        this.updateString(h);
        return this.digest();
      };
      this.digestHex = function (h) {
        this.updateHex(h);
        return this.digest();
      };
    }
  };
  this.updateString = function (e) {
    throw "updateString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
  };
  this.updateHex = function (e) {
    throw "updateHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
  };
  this.digest = function () {
    throw "digest() not supported for this alg/prov: " + this.algName + "/" + this.provName;
  };
  this.digestString = function (e) {
    throw "digestString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
  };
  this.digestHex = function (e) {
    throw "digestHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
  };
  if (c !== undefined) {
    if (c.alg !== undefined) {
      this.algName = c.alg;
      if (c.prov === undefined) {
        this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
      }
      this.setAlgAndProvider(this.algName, this.provName);
    }
  }
};
KJUR.crypto.MessageDigest.getCanonicalAlgName = function (a) {
  if (typeof a === "string") {
    a = a.toLowerCase();
    a = a.replace(/-/, "");
  }
  return a;
};
KJUR.crypto.MessageDigest.getHashLength = function (c) {
  var b = KJUR.crypto.MessageDigest;
  var a = b.getCanonicalAlgName(c);
  if (b.HASHLENGTH[a] === undefined) {
    throw "not supported algorithm: " + c;
  }
  return b.HASHLENGTH[a];
};
KJUR.crypto.MessageDigest.HASHLENGTH = {
  md5: 16,
  sha1: 20,
  sha224: 28,
  sha256: 32,
  sha384: 48,
  sha512: 64,
  ripemd160: 20
};
KJUR.crypto.Mac = function (d) {
  var f = null;
  var c = null;
  var a = null;
  var e = null;
  var b = null;
  this.setAlgAndProvider = function (k, i) {
    k = k.toLowerCase();
    if (k == null) {
      k = "hmacsha1";
    }
    k = k.toLowerCase();
    if (k.substr(0, 4) != "hmac") {
      throw "setAlgAndProvider unsupported HMAC alg: " + k;
    }
    if (i === undefined) {
      i = KJUR.crypto.Util.DEFAULTPROVIDER[k];
    }
    this.algProv = k + "/" + i;
    var g = k.substr(4);
    if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g) != -1 && i == "cryptojs") {
      try {
        var j = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g];
        this.mac = CryptoJS.algo.HMAC.create(j, this.pass);
      } catch (h) {
        throw "setAlgAndProvider hash alg set fail hashAlg=" + g + "/" + h;
      }
      this.updateString = function (l) {
        this.mac.update(l);
      };
      this.updateHex = function (l) {
        var m = CryptoJS.enc.Hex.parse(l);
        this.mac.update(m);
      };
      this.doFinal = function () {
        var l = this.mac.finalize();
        return l.toString(CryptoJS.enc.Hex);
      };
      this.doFinalString = function (l) {
        this.updateString(l);
        return this.doFinal();
      };
      this.doFinalHex = function (l) {
        this.updateHex(l);
        return this.doFinal();
      };
    }
  };
  this.updateString = function (g) {
    throw "updateString(str) not supported for this alg/prov: " + this.algProv;
  };
  this.updateHex = function (g) {
    throw "updateHex(hex) not supported for this alg/prov: " + this.algProv;
  };
  this.doFinal = function () {
    throw "digest() not supported for this alg/prov: " + this.algProv;
  };
  this.doFinalString = function (g) {
    throw "digestString(str) not supported for this alg/prov: " + this.algProv;
  };
  this.doFinalHex = function (g) {
    throw "digestHex(hex) not supported for this alg/prov: " + this.algProv;
  };
  this.setPassword = function (h) {
    if (typeof h == "string") {
      var g = h;
      if (h.length % 2 == 1 || !h.match(/^[0-9A-Fa-f]+$/)) {
        g = rstrtohex(h);
      }
      this.pass = CryptoJS.enc.Hex.parse(g);
      return;
    }
    if (typeof h != "object") {
      throw "KJUR.crypto.Mac unsupported password type: " + h;
    }
    var g = null;
    if (h.hex !== undefined) {
      if (h.hex.length % 2 != 0 || !h.hex.match(/^[0-9A-Fa-f]+$/)) {
        throw "Mac: wrong hex password: " + h.hex;
      }
      g = h.hex;
    }
    if (h.utf8 !== undefined) {
      g = utf8tohex(h.utf8);
    }
    if (h.rstr !== undefined) {
      g = rstrtohex(h.rstr);
    }
    if (h.b64 !== undefined) {
      g = b64tohex(h.b64);
    }
    if (h.b64u !== undefined) {
      g = b64utohex(h.b64u);
    }
    if (g == null) {
      throw "KJUR.crypto.Mac unsupported password type: " + h;
    }
    this.pass = CryptoJS.enc.Hex.parse(g);
  };
  if (d !== undefined) {
    if (d.pass !== undefined) {
      this.setPassword(d.pass);
    }
    if (d.alg !== undefined) {
      this.algName = d.alg;
      if (d.prov === undefined) {
        this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
      }
      this.setAlgAndProvider(this.algName, this.provName);
    }
  }
};
KJUR.crypto.Signature = function (o) {
  var q = null;
  var n = null;
  var r = null;
  var c = null;
  var l = null;
  var d = null;
  var k = null;
  var h = null;
  var p = null;
  var e = null;
  var b = -1;
  var g = null;
  var j = null;
  var a = null;
  var i = null;
  var f = null;
  this._setAlgNames = function () {
    var s = this.algName.match(/^(.+)with(.+)$/);
    if (s) {
      this.mdAlgName = s[1].toLowerCase();
      this.pubkeyAlgName = s[2].toLowerCase();
      if (this.pubkeyAlgName == "rsaandmgf1" && this.mdAlgName == "sha") {
        this.mdAlgName = "sha1";
      }
    }
  };
  this._zeroPaddingOfSignature = function (x, w) {
    var v = "";
    var t = w / 4 - x.length;
    for (var u = 0; u < t; u++) {
      v = v + "0";
    }
    return v + x;
  };
  this.setAlgAndProvider = function (u, t) {
    this._setAlgNames();
    if (t != "cryptojs/jsrsa") {
      throw new Error("provider not supported: " + t);
    }
    if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName) != -1) {
      try {
        this.md = new KJUR.crypto.MessageDigest({
          alg: this.mdAlgName
        });
      } catch (s) {
        throw new Error("setAlgAndProvider hash alg set fail alg=" + this.mdAlgName + "/" + s);
      }
      this.init = function (w, x) {
        var y = null;
        try {
          if (x === undefined) {
            y = KEYUTIL.getKey(w);
          } else {
            y = KEYUTIL.getKey(w, x);
          }
        } catch (v) {
          throw "init failed:" + v;
        }
        if (y.isPrivate === true) {
          this.prvKey = y;
          this.state = "SIGN";
        } else {
          if (y.isPublic === true) {
            this.pubKey = y;
            this.state = "VERIFY";
          } else {
            throw "init failed.:" + y;
          }
        }
      };
      this.updateString = function (v) {
        this.md.updateString(v);
      };
      this.updateHex = function (v) {
        this.md.updateHex(v);
      };
      this.sign = function () {
        this.sHashHex = this.md.digest();
        if (this.prvKey === undefined && this.ecprvhex !== undefined && this.eccurvename !== undefined && KJUR.crypto.ECDSA !== undefined) {
          this.prvKey = new KJUR.crypto.ECDSA({
            curve: this.eccurvename,
            prv: this.ecprvhex
          });
        }
        if (this.prvKey instanceof RSAKey && this.pubkeyAlgName === "rsaandmgf1") {
          this.hSign = this.prvKey.signWithMessageHashPSS(this.sHashHex, this.mdAlgName, this.pssSaltLen);
        } else {
          if (this.prvKey instanceof RSAKey && this.pubkeyAlgName === "rsa") {
            this.hSign = this.prvKey.signWithMessageHash(this.sHashHex, this.mdAlgName);
          } else {
            if (this.prvKey instanceof KJUR.crypto.ECDSA) {
              this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
            } else {
              if (this.prvKey instanceof KJUR.crypto.DSA) {
                this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
              } else {
                throw "Signature: unsupported private key alg: " + this.pubkeyAlgName;
              }
            }
          }
        }
        return this.hSign;
      };
      this.signString = function (v) {
        this.updateString(v);
        return this.sign();
      };
      this.signHex = function (v) {
        this.updateHex(v);
        return this.sign();
      };
      this.verify = function (v) {
        this.sHashHex = this.md.digest();
        if (this.pubKey === undefined && this.ecpubhex !== undefined && this.eccurvename !== undefined && KJUR.crypto.ECDSA !== undefined) {
          this.pubKey = new KJUR.crypto.ECDSA({
            curve: this.eccurvename,
            pub: this.ecpubhex
          });
        }
        if (this.pubKey instanceof RSAKey && this.pubkeyAlgName === "rsaandmgf1") {
          return this.pubKey.verifyWithMessageHashPSS(this.sHashHex, v, this.mdAlgName, this.pssSaltLen);
        } else {
          if (this.pubKey instanceof RSAKey && this.pubkeyAlgName === "rsa") {
            return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
          } else {
            if (KJUR.crypto.ECDSA !== undefined && this.pubKey instanceof KJUR.crypto.ECDSA) {
              return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
            } else {
              if (KJUR.crypto.DSA !== undefined && this.pubKey instanceof KJUR.crypto.DSA) {
                return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
              } else {
                throw "Signature: unsupported public key alg: " + this.pubkeyAlgName;
              }
            }
          }
        }
      };
    }
  };
  this.init = function (s, t) {
    throw "init(key, pass) not supported for this alg:prov=" + this.algProvName;
  };
  this.updateString = function (s) {
    throw "updateString(str) not supported for this alg:prov=" + this.algProvName;
  };
  this.updateHex = function (s) {
    throw "updateHex(hex) not supported for this alg:prov=" + this.algProvName;
  };
  this.sign = function () {
    throw "sign() not supported for this alg:prov=" + this.algProvName;
  };
  this.signString = function (s) {
    throw "digestString(str) not supported for this alg:prov=" + this.algProvName;
  };
  this.signHex = function (s) {
    throw "digestHex(hex) not supported for this alg:prov=" + this.algProvName;
  };
  this.verify = function (s) {
    throw "verify(hSigVal) not supported for this alg:prov=" + this.algProvName;
  };
  this.initParams = o;
  if (o !== undefined) {
    if (o.alg !== undefined) {
      this.algName = o.alg;
      if (o.prov === undefined) {
        this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
      } else {
        this.provName = o.prov;
      }
      this.algProvName = this.algName + ":" + this.provName;
      this.setAlgAndProvider(this.algName, this.provName);
      this._setAlgNames();
    }
    if (o.psssaltlen !== undefined) {
      this.pssSaltLen = o.psssaltlen;
    }
    if (o.prvkeypem !== undefined) {
      if (o.prvkeypas !== undefined) {
        throw "both prvkeypem and prvkeypas parameters not supported";
      } else {
        try {
          var q = KEYUTIL.getKey(o.prvkeypem);
          this.init(q);
        } catch (m) {
          throw "fatal error to load pem private key: " + m;
        }
      }
    }
  }
};
KJUR.crypto.Cipher = function (a) {};
KJUR.crypto.Cipher.encrypt = function (j, i, b, c) {
  if (aryval(c, "enclag") != undefined) {
    b = c.encalg;
  }
  if (typeof b == "string" && b.substr(-4) == "-CBC") {
    var g = i;
    var e = j;
    if (aryval(c, "key") != undefined) {
      g = c.key;
    }
    if (aryval(c, "enc") != undefined) {
      hEnc = c.enc;
    }
    var h = CryptoJS.enc.Hex.parse(g);
    var a = CryptoJS.enc.Hex.parse(e);
    var f = CryptoJS.enc.Hex.parse(c.iv);
    var d;
    if (b == "des-EDE3-CBC") {
      d = CryptoJS.TripleDES.encrypt(a, h, {
        iv: f
      });
    } else {
      if (b == "aes128-CBC" || b == "aes256-CBC") {
        d = CryptoJS.AES.encrypt(a, h, {
          iv: f
        });
      } else {
        throw new Error("unsupported algorithm: " + b);
      }
    }
    return d + "";
  } else {
    throw new Error("Cipher.encrypt: unsupported key or algorithm");
  }
};
KJUR.crypto.Cipher.decrypt = function (c, j, a, b) {
  if (aryval(b, "enclag") != undefined) {
    a = b.encalg;
  }
  if (typeof a == "string" && a.substr(-4) == "-CBC") {
    var h = j;
    var e = c;
    if (aryval(b, "key") != undefined) {
      h = b.key;
    }
    if (aryval(b, "enc") != undefined) {
      e = b.enc;
    }
    var i = CryptoJS.enc.Hex.parse(h);
    var f = CryptoJS.enc.Hex.parse(e);
    var g = CryptoJS.enc.Hex.parse(b.iv);
    var d;
    if (a == "des-EDE3-CBC") {
      d = CryptoJS.TripleDES.decrypt({
        ciphertext: f
      }, i, {
        iv: g
      });
    } else {
      if (a == "aes128-CBC" || a == "aes256-CBC") {
        d = CryptoJS.AES.decrypt({
          ciphertext: f
        }, i, {
          iv: g
        });
      } else {
        throw new Error("unsupported algorithm: " + a);
      }
    }
    return CryptoJS.enc.Hex.stringify(d);
  } else {
    throw new Error("Cipher.decrypt: unsupported key or algorithm");
  }
};
KJUR.crypto.OID = new function () {
  this.oidhex2name = {
    "2a864886f70d010101": "rsaEncryption",
    "2a8648ce3d0201": "ecPublicKey",
    "2a8648ce380401": "dsa",
    "2a8648ce3d030107": "secp256r1",
    "2b8104001f": "secp192k1",
    "2b81040021": "secp224r1",
    "2b8104000a": "secp256k1",
    "2b81040022": "secp384r1",
    "2b81040023": "secp521r1",
    "2a8648ce380403": "SHA1withDSA",
    "608648016503040301": "SHA224withDSA",
    "608648016503040302": "SHA256withDSA"
  };
}();
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
  KJUR.crypto = {};
}
KJUR.crypto.ECDSA = function (e) {
  var g = "secp256r1";
  var p = null;
  var b = null;
  var i = null;
  var j = Error,
    f = BigInteger,
    h = ECPointFp,
    m = KJUR.crypto.ECDSA,
    c = KJUR.crypto.ECParameterDB,
    d = m.getName,
    q = ASN1HEX,
    n = q.getVbyListEx,
    k = q.isASN1HEX;
  var a = new SecureRandom();
  var o = null;
  this.type = "EC";
  this.isPrivate = false;
  this.isPublic = false;
  function l(x, t, w, s) {
    var r = Math.max(t.bitLength(), s.bitLength());
    var y = x.add2D(w);
    var v = x.curve.getInfinity();
    for (var u = r - 1; u >= 0; --u) {
      v = v.twice2D();
      v.z = f.ONE;
      if (t.testBit(u)) {
        if (s.testBit(u)) {
          v = v.add2D(y);
        } else {
          v = v.add2D(x);
        }
      } else {
        if (s.testBit(u)) {
          v = v.add2D(w);
        }
      }
    }
    return v;
  }
  this.getBigRandom = function (r) {
    return new f(r.bitLength(), a).mod(r.subtract(f.ONE)).add(f.ONE);
  };
  this.setNamedCurve = function (r) {
    this.ecparams = c.getByName(r);
    this.prvKeyHex = null;
    this.pubKeyHex = null;
    this.curveName = r;
  };
  this.setPrivateKeyHex = function (r) {
    this.isPrivate = true;
    this.prvKeyHex = r;
  };
  this.setPublicKeyHex = function (r) {
    this.isPublic = true;
    this.pubKeyHex = r;
  };
  this.getPublicKeyXYHex = function () {
    var t = this.pubKeyHex;
    if (t.substr(0, 2) !== "04") {
      throw "this method supports uncompressed format(04) only";
    }
    var s = this.ecparams.keycharlen;
    if (t.length !== 2 + s * 2) {
      throw "malformed public key hex length";
    }
    var r = {};
    r.x = t.substr(2, s);
    r.y = t.substr(2 + s);
    return r;
  };
  this.getShortNISTPCurveName = function () {
    var r = this.curveName;
    if (r === "secp256r1" || r === "NIST P-256" || r === "P-256" || r === "prime256v1") {
      return "P-256";
    }
    if (r === "secp384r1" || r === "NIST P-384" || r === "P-384") {
      return "P-384";
    }
    if (r === "secp521r1" || r === "NIST P-521" || r === "P-521") {
      return "P-521";
    }
    return null;
  };
  this.generateKeyPairHex = function () {
    var s = this.ecparams.n;
    var u = this.getBigRandom(s);
    var r = this.ecparams.keycharlen;
    var t = ("0000000000" + u.toString(16)).slice(-r);
    this.setPrivateKeyHex(t);
    var v = this.generatePublicKeyHex();
    return {
      ecprvhex: t,
      ecpubhex: v
    };
  };
  this.generatePublicKeyHex = function () {
    var u = new f(this.prvKeyHex, 16);
    var w = this.ecparams.G.multiply(u);
    var t = w.getX().toBigInteger();
    var s = w.getY().toBigInteger();
    var r = this.ecparams.keycharlen;
    var y = ("0000000000" + t.toString(16)).slice(-r);
    var v = ("0000000000" + s.toString(16)).slice(-r);
    var x = "04" + y + v;
    this.setPublicKeyHex(x);
    return x;
  };
  this.signWithMessageHash = function (r) {
    return this.signHex(r, this.prvKeyHex);
  };
  this.signHex = function (x, u) {
    var A = new f(u, 16);
    var v = this.ecparams.n;
    var z = new f(x.substring(0, this.ecparams.keycharlen), 16);
    do {
      var w = this.getBigRandom(v);
      var B = this.ecparams.G;
      var y = B.multiply(w);
      var t = y.getX().toBigInteger().mod(v);
    } while (t.compareTo(f.ZERO) <= 0);
    var C = w.modInverse(v).multiply(z.add(A.multiply(t))).mod(v);
    return m.biRSSigToASN1Sig(t, C);
  };
  this.sign = function (w, B) {
    var z = B;
    var u = this.ecparams.n;
    var y = f.fromByteArrayUnsigned(w);
    do {
      var v = this.getBigRandom(u);
      var A = this.ecparams.G;
      var x = A.multiply(v);
      var t = x.getX().toBigInteger().mod(u);
    } while (t.compareTo(BigInteger.ZERO) <= 0);
    var C = v.modInverse(u).multiply(y.add(z.multiply(t))).mod(u);
    return this.serializeSig(t, C);
  };
  this.verifyWithMessageHash = function (s, r) {
    return this.verifyHex(s, r, this.pubKeyHex);
  };
  this.verifyHex = function (v, y, u) {
    try {
      var t, B;
      var w = m.parseSigHex(y);
      t = w.r;
      B = w.s;
      var x = h.decodeFromHex(this.ecparams.curve, u);
      var z = new f(v.substring(0, this.ecparams.keycharlen), 16);
      return this.verifyRaw(z, t, B, x);
    } catch (A) {
      return false;
    }
  };
  this.verify = function (z, A, u) {
    var w, t;
    if (Bitcoin.Util.isArray(A)) {
      var y = this.parseSig(A);
      w = y.r;
      t = y.s;
    } else {
      if ("object" === typeof A && A.r && A.s) {
        w = A.r;
        t = A.s;
      } else {
        throw "Invalid value for signature";
      }
    }
    var v;
    if (u instanceof ECPointFp) {
      v = u;
    } else {
      if (Bitcoin.Util.isArray(u)) {
        v = h.decodeFrom(this.ecparams.curve, u);
      } else {
        throw "Invalid format for pubkey value, must be byte array or ECPointFp";
      }
    }
    var x = f.fromByteArrayUnsigned(z);
    return this.verifyRaw(x, w, t, v);
  };
  this.verifyRaw = function (z, t, E, y) {
    var x = this.ecparams.n;
    var D = this.ecparams.G;
    if (t.compareTo(f.ONE) < 0 || t.compareTo(x) >= 0) {
      return false;
    }
    if (E.compareTo(f.ONE) < 0 || E.compareTo(x) >= 0) {
      return false;
    }
    var A = E.modInverse(x);
    var w = z.multiply(A).mod(x);
    var u = t.multiply(A).mod(x);
    var B = D.multiply(w).add(y.multiply(u));
    var C = B.getX().toBigInteger().mod(x);
    return C.equals(t);
  };
  this.serializeSig = function (v, u) {
    var w = v.toByteArraySigned();
    var t = u.toByteArraySigned();
    var x = [];
    x.push(2);
    x.push(w.length);
    x = x.concat(w);
    x.push(2);
    x.push(t.length);
    x = x.concat(t);
    x.unshift(x.length);
    x.unshift(48);
    return x;
  };
  this.parseSig = function (y) {
    var x;
    if (y[0] != 48) {
      throw new Error("Signature not a valid DERSequence");
    }
    x = 2;
    if (y[x] != 2) {
      throw new Error("First element in signature must be a DERInteger");
    }
    var w = y.slice(x + 2, x + 2 + y[x + 1]);
    x += 2 + y[x + 1];
    if (y[x] != 2) {
      throw new Error("Second element in signature must be a DERInteger");
    }
    var t = y.slice(x + 2, x + 2 + y[x + 1]);
    x += 2 + y[x + 1];
    var v = f.fromByteArrayUnsigned(w);
    var u = f.fromByteArrayUnsigned(t);
    return {
      r: v,
      s: u
    };
  };
  this.parseSigCompact = function (w) {
    if (w.length !== 65) {
      throw "Signature has the wrong length";
    }
    var t = w[0] - 27;
    if (t < 0 || t > 7) {
      throw "Invalid signature type";
    }
    var x = this.ecparams.n;
    var v = f.fromByteArrayUnsigned(w.slice(1, 33)).mod(x);
    var u = f.fromByteArrayUnsigned(w.slice(33, 65)).mod(x);
    return {
      r: v,
      s: u,
      i: t
    };
  };
  this.readPKCS5PrvKeyHex = function (u) {
    if (k(u) === false) {
      throw new Error("not ASN.1 hex string");
    }
    var r, t, v;
    try {
      r = n(u, 0, ["[0]", 0], "06");
      t = n(u, 0, [1], "04");
      try {
        v = n(u, 0, ["[1]", 0], "03");
      } catch (s) {}
    } catch (s) {
      throw new Error("malformed PKCS#1/5 plain ECC private key");
    }
    this.curveName = d(r);
    if (this.curveName === undefined) {
      throw "unsupported curve name";
    }
    this.setNamedCurve(this.curveName);
    this.setPublicKeyHex(v);
    this.setPrivateKeyHex(t);
    this.isPublic = false;
  };
  this.readPKCS8PrvKeyHex = function (v) {
    if (k(v) === false) {
      throw new j("not ASN.1 hex string");
    }
    var t, r, u, w;
    try {
      t = n(v, 0, [1, 0], "06");
      r = n(v, 0, [1, 1], "06");
      u = n(v, 0, [2, 0, 1], "04");
      try {
        w = n(v, 0, [2, 0, "[1]", 0], "03");
      } catch (s) {}
    } catch (s) {
      throw new j("malformed PKCS#8 plain ECC private key");
    }
    this.curveName = d(r);
    if (this.curveName === undefined) {
      throw new j("unsupported curve name");
    }
    this.setNamedCurve(this.curveName);
    this.setPublicKeyHex(w);
    this.setPrivateKeyHex(u);
    this.isPublic = false;
  };
  this.readPKCS8PubKeyHex = function (u) {
    if (k(u) === false) {
      throw new j("not ASN.1 hex string");
    }
    var t, r, v;
    try {
      t = n(u, 0, [0, 0], "06");
      r = n(u, 0, [0, 1], "06");
      v = n(u, 0, [1], "03");
    } catch (s) {
      throw new j("malformed PKCS#8 ECC public key");
    }
    this.curveName = d(r);
    if (this.curveName === null) {
      throw new j("unsupported curve name");
    }
    this.setNamedCurve(this.curveName);
    this.setPublicKeyHex(v);
  };
  this.readCertPubKeyHex = function (t, v) {
    if (k(t) === false) {
      throw new j("not ASN.1 hex string");
    }
    var r, u;
    try {
      r = n(t, 0, [0, 5, 0, 1], "06");
      u = n(t, 0, [0, 5, 1], "03");
    } catch (s) {
      throw new j("malformed X.509 certificate ECC public key");
    }
    this.curveName = d(r);
    if (this.curveName === null) {
      throw new j("unsupported curve name");
    }
    this.setNamedCurve(this.curveName);
    this.setPublicKeyHex(u);
  };
  if (e !== undefined) {
    if (e.curve !== undefined) {
      this.curveName = e.curve;
    }
  }
  if (this.curveName === undefined) {
    this.curveName = g;
  }
  this.setNamedCurve(this.curveName);
  if (e !== undefined) {
    if (e.prv !== undefined) {
      this.setPrivateKeyHex(e.prv);
    }
    if (e.pub !== undefined) {
      this.setPublicKeyHex(e.pub);
    }
  }
};
KJUR.crypto.ECDSA.parseSigHex = function (a) {
  var b = KJUR.crypto.ECDSA.parseSigHexInHexRS(a);
  var d = new BigInteger(b.r, 16);
  var c = new BigInteger(b.s, 16);
  return {
    r: d,
    s: c
  };
};
KJUR.crypto.ECDSA.parseSigHexInHexRS = function (f) {
  var j = ASN1HEX,
    i = j.getChildIdx,
    g = j.getV;
  j.checkStrictDER(f, 0);
  if (f.substr(0, 2) != "30") {
    throw new Error("signature is not a ASN.1 sequence");
  }
  var h = i(f, 0);
  if (h.length != 2) {
    throw new Error("signature shall have two elements");
  }
  var e = h[0];
  var d = h[1];
  if (f.substr(e, 2) != "02") {
    throw new Error("1st item not ASN.1 integer");
  }
  if (f.substr(d, 2) != "02") {
    throw new Error("2nd item not ASN.1 integer");
  }
  var c = g(f, e);
  var b = g(f, d);
  return {
    r: c,
    s: b
  };
};
KJUR.crypto.ECDSA.asn1SigToConcatSig = function (d) {
  var e = KJUR.crypto.ECDSA.parseSigHexInHexRS(d);
  var b = e.r;
  var a = e.s;
  if (b.length >= 130 && b.length <= 134) {
    if (b.length % 2 != 0) {
      throw Error("unknown ECDSA sig r length error");
    }
    if (a.length % 2 != 0) {
      throw Error("unknown ECDSA sig s length error");
    }
    if (b.substr(0, 2) == "00") {
      b = b.substr(2);
    }
    if (a.substr(0, 2) == "00") {
      a = a.substr(2);
    }
    var c = Math.max(b.length, a.length);
    b = ("000000" + b).slice(-c);
    a = ("000000" + a).slice(-c);
    return b + a;
  }
  if (b.substr(0, 2) == "00" && b.length % 32 == 2) {
    b = b.substr(2);
  }
  if (a.substr(0, 2) == "00" && a.length % 32 == 2) {
    a = a.substr(2);
  }
  if (b.length % 32 == 30) {
    b = "00" + b;
  }
  if (a.length % 32 == 30) {
    a = "00" + a;
  }
  if (b.length % 32 != 0) {
    throw Error("unknown ECDSA sig r length error");
  }
  if (a.length % 32 != 0) {
    throw Error("unknown ECDSA sig s length error");
  }
  return b + a;
};
KJUR.crypto.ECDSA.concatSigToASN1Sig = function (a) {
  if (a.length % 4 != 0) {
    throw Error("unknown ECDSA concatinated r-s sig length error");
  }
  var c = a.substr(0, a.length / 2);
  var b = a.substr(a.length / 2);
  return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(c, b);
};
KJUR.crypto.ECDSA.hexRSSigToASN1Sig = function (b, a) {
  var d = new BigInteger(b, 16);
  var c = new BigInteger(a, 16);
  return KJUR.crypto.ECDSA.biRSSigToASN1Sig(d, c);
};
KJUR.crypto.ECDSA.biRSSigToASN1Sig = function (f, d) {
  var c = KJUR.asn1;
  var b = new c.DERInteger({
    bigint: f
  });
  var a = new c.DERInteger({
    bigint: d
  });
  var e = new c.DERSequence({
    array: [b, a]
  });
  return e.tohex();
};
KJUR.crypto.ECDSA.getName = function (a) {
  if (a === "2b8104001f") {
    return "secp192k1";
  }
  if (a === "2a8648ce3d030107") {
    return "secp256r1";
  }
  if (a === "2b8104000a") {
    return "secp256k1";
  }
  if (a === "2b81040021") {
    return "secp224r1";
  }
  if (a === "2b81040022") {
    return "secp384r1";
  }
  if (a === "2b81040023") {
    return "secp521r1";
  }
  if ("|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(a) !== -1) {
    return "secp256r1";
  }
  if ("|secp256k1|".indexOf(a) !== -1) {
    return "secp256k1";
  }
  if ("|secp224r1|NIST P-224|P-224|".indexOf(a) !== -1) {
    return "secp224r1";
  }
  if ("|secp384r1|NIST P-384|P-384|".indexOf(a) !== -1) {
    return "secp384r1";
  }
  if ("|secp521r1|NIST P-521|P-521|".indexOf(a) !== -1) {
    return "secp521r1";
  }
  return null;
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
  KJUR.crypto = {};
}
KJUR.crypto.ECParameterDB = new function () {
  var b = {};
  var c = {};
  function a(d) {
    return new BigInteger(d, 16);
  }
  this.getByName = function (e) {
    var d = e;
    if (typeof c[d] != "undefined") {
      d = c[e];
    }
    if (typeof b[d] != "undefined") {
      return b[d];
    }
    throw "unregistered EC curve name: " + d;
  };
  this.regist = function (A, l, o, g, m, e, j, f, k, u, d, x) {
    b[A] = {};
    var s = a(o);
    var z = a(g);
    var y = a(m);
    var t = a(e);
    var w = a(j);
    var r = new ECCurveFp(s, z, y);
    var q = r.decodePointHex("04" + f + k);
    b[A]["name"] = A;
    b[A]["keylen"] = l;
    b[A]["keycharlen"] = Math.ceil(l / 8) * 2;
    b[A]["curve"] = r;
    b[A]["G"] = q;
    b[A]["n"] = t;
    b[A]["h"] = w;
    b[A]["oid"] = d;
    b[A]["info"] = x;
    for (var v = 0; v < u.length; v++) {
      c[u[v]] = A;
    }
  };
}();
KJUR.crypto.ECParameterDB.regist("secp128r1", 128, "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", "E87579C11079F43DD824993C2CEE5ED3", "FFFFFFFE0000000075A30D1B9038A115", "1", "161FF7528B899B2D0C28607CA52C5B86", "CF5AC8395BAFEB13C02DA292DDED7A83", [], "", "secp128r1 : SECG curve over a 128 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp160k1", 160, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", "0", "7", "0100000000000000000001B8FA16DFAB9ACA16B6B3", "1", "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", "938CF935318FDCED6BC28286531733C3F03C4FEE", [], "", "secp160k1 : SECG curve over a 160 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp160r1", 160, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", "0100000000000000000001F4C8F927AED3CA752257", "1", "4A96B5688EF573284664698968C38BB913CBFC82", "23A628553168947D59DCC912042351377AC5FB32", [], "", "secp160r1 : SECG curve over a 160 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp192k1", 192, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", "0", "3", "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", "1", "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", []);
KJUR.crypto.ECParameterDB.regist("secp192r1", 192, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", "1", "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811", []);
KJUR.crypto.ECParameterDB.regist("secp224r1", 224, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", "1", "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", []);
KJUR.crypto.ECParameterDB.regist("secp256k1", 256, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", "0", "7", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", "1", "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", []);
KJUR.crypto.ECParameterDB.regist("secp256r1", 256, "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", "1", "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", ["NIST P-256", "P-256", "prime256v1"]);
KJUR.crypto.ECParameterDB.regist("secp384r1", 384, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", "1", "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", "3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f", ["NIST P-384", "P-384"]);
KJUR.crypto.ECParameterDB.regist("secp521r1", 521, "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", "051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", "1", "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", "011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", ["NIST P-521", "P-521"]);
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
  KJUR.crypto = {};
}
KJUR.crypto.DSA = function () {
  var b = ASN1HEX,
    e = b.getVbyList,
    d = b.getVbyListEx,
    a = b.isASN1HEX,
    c = BigInteger;
  this.p = null;
  this.q = null;
  this.g = null;
  this.y = null;
  this.x = null;
  this.type = "DSA";
  this.isPrivate = false;
  this.isPublic = false;
  this.setPrivate = function (j, i, h, k, f) {
    this.isPrivate = true;
    this.p = j;
    this.q = i;
    this.g = h;
    this.y = k;
    this.x = f;
  };
  this.setPrivateHex = function (i, g, k, n, o) {
    var h, f, j, l, m;
    h = new BigInteger(i, 16);
    f = new BigInteger(g, 16);
    j = new BigInteger(k, 16);
    if (typeof n === "string" && n.length > 1) {
      l = new BigInteger(n, 16);
    } else {
      l = null;
    }
    m = new BigInteger(o, 16);
    this.setPrivate(h, f, j, l, m);
  };
  this.setPublic = function (i, h, f, j) {
    this.isPublic = true;
    this.p = i;
    this.q = h;
    this.g = f;
    this.y = j;
    this.x = null;
  };
  this.setPublicHex = function (k, j, i, l) {
    var g, f, m, h;
    g = new BigInteger(k, 16);
    f = new BigInteger(j, 16);
    m = new BigInteger(i, 16);
    h = new BigInteger(l, 16);
    this.setPublic(g, f, m, h);
  };
  this.signWithMessageHash = function (j) {
    var i = this.p;
    var h = this.q;
    var m = this.g;
    var o = this.y;
    var t = this.x;
    var l = KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE), h.subtract(BigInteger.ONE));
    var u = j.substr(0, h.bitLength() / 4);
    var n = new BigInteger(u, 16);
    var f = m.modPow(l, i).mod(h);
    var w = l.modInverse(h).multiply(n.add(t.multiply(f))).mod(h);
    var v = KJUR.asn1.ASN1Util.jsonToASN1HEX({
      seq: [{
        "int": {
          bigint: f
        }
      }, {
        "int": {
          bigint: w
        }
      }]
    });
    return v;
  };
  this.verifyWithMessageHash = function (m, l) {
    var j = this.p;
    var h = this.q;
    var o = this.g;
    var u = this.y;
    var n = this.parseASN1Signature(l);
    var f = n[0];
    var C = n[1];
    var B = m.substr(0, h.bitLength() / 4);
    var t = new BigInteger(B, 16);
    if (BigInteger.ZERO.compareTo(f) > 0 || f.compareTo(h) > 0) {
      throw "invalid DSA signature";
    }
    if (BigInteger.ZERO.compareTo(C) >= 0 || C.compareTo(h) > 0) {
      throw "invalid DSA signature";
    }
    var x = C.modInverse(h);
    var k = t.multiply(x).mod(h);
    var i = f.multiply(x).mod(h);
    var A = o.modPow(k, j).multiply(u.modPow(i, j)).mod(j).mod(h);
    return A.compareTo(f) == 0;
  };
  this.parseASN1Signature = function (f) {
    try {
      var i = new c(d(f, 0, [0], "02"), 16);
      var h = new c(d(f, 0, [1], "02"), 16);
      return [i, h];
    } catch (g) {
      throw new Error("malformed ASN.1 DSA signature");
    }
  };
  this.readPKCS5PrvKeyHex = function (j) {
    var k, i, g, l, m;
    if (a(j) === false) {
      throw new Error("not ASN.1 hex string");
    }
    try {
      k = d(j, 0, [1], "02");
      i = d(j, 0, [2], "02");
      g = d(j, 0, [3], "02");
      l = d(j, 0, [4], "02");
      m = d(j, 0, [5], "02");
    } catch (f) {
      throw new Error("malformed PKCS#1/5 plain DSA private key");
    }
    this.setPrivateHex(k, i, g, l, m);
  };
  this.readPKCS8PrvKeyHex = function (j) {
    var k, i, g, l;
    if (a(j) === false) {
      throw new Error("not ASN.1 hex string");
    }
    try {
      k = d(j, 0, [1, 1, 0], "02");
      i = d(j, 0, [1, 1, 1], "02");
      g = d(j, 0, [1, 1, 2], "02");
      l = d(j, 0, [2, 0], "02");
    } catch (f) {
      throw new Error("malformed PKCS#8 plain DSA private key");
    }
    this.setPrivateHex(k, i, g, null, l);
  };
  this.readPKCS8PubKeyHex = function (j) {
    var k, i, g, l;
    if (a(j) === false) {
      throw new Error("not ASN.1 hex string");
    }
    try {
      k = d(j, 0, [0, 1, 0], "02");
      i = d(j, 0, [0, 1, 1], "02");
      g = d(j, 0, [0, 1, 2], "02");
      l = d(j, 0, [1, 0], "02");
    } catch (f) {
      throw new Error("malformed PKCS#8 DSA public key");
    }
    this.setPublicHex(k, i, g, l);
  };
  this.readCertPubKeyHex = function (j, m) {
    var k, i, g, l;
    if (a(j) === false) {
      throw new Error("not ASN.1 hex string");
    }
    try {
      k = d(j, 0, [0, 5, 0, 1, 0], "02");
      i = d(j, 0, [0, 5, 0, 1, 1], "02");
      g = d(j, 0, [0, 5, 0, 1, 2], "02");
      l = d(j, 0, [0, 5, 1, 0], "02");
    } catch (f) {
      throw new Error("malformed X.509 certificate DSA public key");
    }
    this.setPublicHex(k, i, g, l);
  };
};
var KEYUTIL = function () {
  var d = function (p, r, q) {
    return k(CryptoJS.AES, p, r, q);
  };
  var e = function (p, r, q) {
    return k(CryptoJS.TripleDES, p, r, q);
  };
  var a = function (p, r, q) {
    return k(CryptoJS.DES, p, r, q);
  };
  var k = function (s, x, u, q) {
    var r = CryptoJS.enc.Hex.parse(x);
    var w = CryptoJS.enc.Hex.parse(u);
    var p = CryptoJS.enc.Hex.parse(q);
    var t = {};
    t.key = w;
    t.iv = p;
    t.ciphertext = r;
    var v = s.decrypt(t, w, {
      iv: p
    });
    return CryptoJS.enc.Hex.stringify(v);
  };
  var l = function (p, r, q) {
    return g(CryptoJS.AES, p, r, q);
  };
  var o = function (p, r, q) {
    return g(CryptoJS.TripleDES, p, r, q);
  };
  var f = function (p, r, q) {
    return g(CryptoJS.DES, p, r, q);
  };
  var g = function (t, y, v, q) {
    var s = CryptoJS.enc.Hex.parse(y);
    var x = CryptoJS.enc.Hex.parse(v);
    var p = CryptoJS.enc.Hex.parse(q);
    var w = t.encrypt(s, x, {
      iv: p
    });
    var r = CryptoJS.enc.Hex.parse(w.toString());
    var u = CryptoJS.enc.Base64.stringify(r);
    return u;
  };
  var i = {
    "AES-256-CBC": {
      proc: d,
      eproc: l,
      keylen: 32,
      ivlen: 16
    },
    "AES-192-CBC": {
      proc: d,
      eproc: l,
      keylen: 24,
      ivlen: 16
    },
    "AES-128-CBC": {
      proc: d,
      eproc: l,
      keylen: 16,
      ivlen: 16
    },
    "DES-EDE3-CBC": {
      proc: e,
      eproc: o,
      keylen: 24,
      ivlen: 8
    },
    "DES-CBC": {
      proc: a,
      eproc: f,
      keylen: 8,
      ivlen: 8
    }
  };
  var c = function (p) {
    return i[p]["proc"];
  };
  var m = function (p) {
    var r = CryptoJS.lib.WordArray.random(p);
    var q = CryptoJS.enc.Hex.stringify(r);
    return q;
  };
  var n = function (v) {
    var w = {};
    var q = v.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)", "m"));
    if (q) {
      w.cipher = q[1];
      w.ivsalt = q[2];
    }
    var p = v.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));
    if (p) {
      w.type = p[1];
    }
    var u = -1;
    var x = 0;
    if (v.indexOf("\r\n\r\n") != -1) {
      u = v.indexOf("\r\n\r\n");
      x = 2;
    }
    if (v.indexOf("\n\n") != -1) {
      u = v.indexOf("\n\n");
      x = 1;
    }
    var t = v.indexOf("-----END");
    if (u != -1 && t != -1) {
      var r = v.substring(u + x * 2, t - x);
      r = r.replace(/\s+/g, "");
      w.data = r;
    }
    return w;
  };
  var j = function (q, y, p) {
    var v = p.substring(0, 16);
    var t = CryptoJS.enc.Hex.parse(v);
    var r = CryptoJS.enc.Utf8.parse(y);
    var u = i[q]["keylen"] + i[q]["ivlen"];
    var x = "";
    var w = null;
    for (;;) {
      var s = CryptoJS.algo.MD5.create();
      if (w != null) {
        s.update(w);
      }
      s.update(r);
      s.update(t);
      w = s.finalize();
      x = x + CryptoJS.enc.Hex.stringify(w);
      if (x.length >= u * 2) {
        break;
      }
    }
    var z = {};
    z.keyhex = x.substr(0, i[q]["keylen"] * 2);
    z.ivhex = x.substr(i[q]["keylen"] * 2, i[q]["ivlen"] * 2);
    return z;
  };
  var b = function (p, v, r, w) {
    var s = CryptoJS.enc.Base64.parse(p);
    var q = CryptoJS.enc.Hex.stringify(s);
    var u = i[v]["proc"];
    var t = u(q, r, w);
    return t;
  };
  var h = function (p, s, q, u) {
    var r = i[s]["eproc"];
    var t = r(p, q, u);
    return t;
  };
  return {
    version: "1.0.0",
    parsePKCS5PEM: function (p) {
      return n(p);
    },
    getKeyAndUnusedIvByPasscodeAndIvsalt: function (q, p, r) {
      return j(q, p, r);
    },
    decryptKeyB64: function (p, r, q, s) {
      return b(p, r, q, s);
    },
    getDecryptedKeyHex: function (y, x) {
      var q = n(y);
      var t = q.type;
      var r = q.cipher;
      var p = q.ivsalt;
      var s = q.data;
      var w = j(r, x, p);
      var v = w.keyhex;
      var u = b(s, r, v, p);
      return u;
    },
    getEncryptedPKCS5PEMFromPrvKeyHex: function (x, s, A, t, r) {
      var p = "";
      if (typeof t == "undefined" || t == null) {
        t = "AES-256-CBC";
      }
      if (typeof i[t] == "undefined") {
        throw new Error("KEYUTIL unsupported algorithm: " + t);
      }
      if (typeof r == "undefined" || r == null) {
        var v = i[t]["ivlen"];
        var u = m(v);
        r = u.toUpperCase();
      }
      var z = j(t, A, r);
      var y = z.keyhex;
      var w = h(s, t, y, r);
      var q = w.replace(/(.{64})/g, "$1\r\n");
      var p = "-----BEGIN " + x + " PRIVATE KEY-----\r\n";
      p += "Proc-Type: 4,ENCRYPTED\r\n";
      p += "DEK-Info: " + t + "," + r + "\r\n";
      p += "\r\n";
      p += q;
      p += "\r\n-----END " + x + " PRIVATE KEY-----\r\n";
      return p;
    },
    getEncryptedPKCS8PEM: function (r, p, s) {
      var q = this.getEncryptedPKCS8Hex(r, p, s);
      return hextopem(q, "ENCRYPTED PRIVATE KEY");
    },
    getEncryptedPKCS8Hex: function (r, p, t) {
      var q;
      if (t == undefined || t == null) {
        q = {};
      } else {
        q = JSON.parse(JSON.stringify(t));
      }
      q.plain = r;
      this.initPBES2Param(q);
      this.encryptPBES2Param(q, p);
      var s = this.generatePBES2ASN1Param(q);
      return KJUR.asn1.ASN1Util.newObject(s).tohex();
    },
    initPBES2Param: function (p) {
      if (aryval(p, "encalg") == undefined) {
        p.encalg = "aes256-CBC";
      }
      if (aryval(p, "iter") == undefined) {
        p.iter = 2048;
      }
      if (aryval(p, "prf") == undefined) {
        p.prf = "hmacWithSHA256";
      }
      if (aryval(p, "salt") == undefined) {
        p.salt = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8));
      }
      if (aryval(p, "enciv") == undefined) {
        var q;
        if (p.encalg == "des-EDE3-CBC") {
          q = 8;
        }
        if (p.encalg == "aes128-CBC") {
          q = 16;
        }
        if (p.encalg == "aes256-CBC") {
          q = 16;
        }
        p.enciv = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(q));
      }
    },
    encryptPBES2Param: function (p, q) {
      var t = KEYUTIL.getDKFromPBES2Param(p, q);
      try {
        var s = KJUR.crypto.Cipher.encrypt(p.plain, t, p.encalg, {
          iv: p.enciv
        });
      } catch (r) {
        throw new Error("encrypt error: " + p.plain + " " + t + " " + p.encalg + " " + p.enciv);
      }
      p.enc = s;
    },
    generatePBES2ASN1Param: function (p) {
      var q = {
        seq: [{
          seq: [{
            oid: "pkcs5PBES2"
          }, {
            seq: [{
              seq: [{
                oid: "pkcs5PBKDF2"
              }, {
                seq: [{
                  octstr: {
                    hex: p.salt
                  }
                }, {
                  "int": {
                    hex: inttohex(p.iter)
                  }
                }]
              }]
            }, {
              seq: [{
                oid: p.encalg
              }, {
                octstr: {
                  hex: p.enciv
                }
              }]
            }]
          }]
        }, {
          octstr: {
            hex: p.enc
          }
        }]
      };
      if (p.prf != "hmacWithSHA1") {
        q.seq[0].seq[1].seq[0].seq[1].seq.push({
          seq: [{
            oid: p.prf
          }, {
            "null": ""
          }]
        });
      }
      return q;
    },
    parseHexOfEncryptedPKCS8: function (y) {
      var B = ASN1HEX;
      var z = B.getChildIdx;
      var w = B.getV;
      var t = {};
      var r = z(y, 0);
      if (r.length != 2) {
        throw new Error("malformed format: SEQUENCE(0).items != 2: " + r.length);
      }
      t.ciphertext = w(y, r[1]);
      var A = z(y, r[0]);
      if (A.length != 2) {
        throw new Error("malformed format: SEQUENCE(0.0).items != 2: " + A.length);
      }
      if (w(y, A[0]) != "2a864886f70d01050d") {
        throw new Error("this only supports pkcs5PBES2");
      }
      var p = z(y, A[1]);
      if (A.length != 2) {
        throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: " + p.length);
      }
      var q = z(y, p[1]);
      if (q.length != 2) {
        throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: " + q.length);
      }
      if (w(y, q[0]) != "2a864886f70d0307") {
        throw "this only supports TripleDES";
      }
      t.encryptionSchemeAlg = "TripleDES";
      t.encryptionSchemeIV = w(y, q[1]);
      var s = z(y, p[0]);
      if (s.length != 2) {
        throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: " + s.length);
      }
      if (w(y, s[0]) != "2a864886f70d01050c") {
        throw new Error("this only supports pkcs5PBKDF2");
      }
      var x = z(y, s[1]);
      if (x.length < 2) {
        throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: " + x.length);
      }
      t.pbkdf2Salt = w(y, x[0]);
      var u = w(y, x[1]);
      try {
        t.pbkdf2Iter = parseInt(u, 16);
      } catch (v) {
        throw new Error("malformed format pbkdf2Iter: " + u);
      }
      return t;
    },
    getPBKDF2KeyHexFromParam: function (u, p) {
      var t = CryptoJS.enc.Hex.parse(u.pbkdf2Salt);
      var q = u.pbkdf2Iter;
      var s = CryptoJS.PBKDF2(p, t, {
        keySize: 192 / 32,
        iterations: q
      });
      var r = CryptoJS.enc.Hex.stringify(s);
      return r;
    },
    _getPlainPKCS8HexFromEncryptedPKCS8PEM: function (x, y) {
      var r = pemtohex(x, "ENCRYPTED PRIVATE KEY");
      var p = this.parseHexOfEncryptedPKCS8(r);
      var u = KEYUTIL.getPBKDF2KeyHexFromParam(p, y);
      var v = {};
      v.ciphertext = CryptoJS.enc.Hex.parse(p.ciphertext);
      var t = CryptoJS.enc.Hex.parse(u);
      var s = CryptoJS.enc.Hex.parse(p.encryptionSchemeIV);
      var w = CryptoJS.TripleDES.decrypt(v, t, {
        iv: s
      });
      var q = CryptoJS.enc.Hex.stringify(w);
      return q;
    },
    parsePBES2: function (z) {
      var v = ASN1HEX.parse(z);
      if (aryval(v, "seq.0.seq.0.oid") != "pkcs5PBES2" || aryval(v, "seq.0.seq.1.seq.0.seq.0.oid") != "pkcs5PBKDF2") {
        throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");
      }
      var y = aryval(v, "seq.0.seq.1.seq.0.seq.1.seq");
      if (y == undefined) {
        throw new Error("PBKDF2 parameter not found");
      }
      var t = aryval(y, "0.octstr.hex");
      var p = aryval(y, "1.int.hex");
      var q = aryval(y, "2.seq.0.oid", "hmacWithSHA1");
      var x = -1;
      try {
        x = parseInt(p, 16);
      } catch (w) {
        throw new Error("iter not proper value");
      }
      var u = aryval(v, "seq.0.seq.1.seq.1.seq.0.oid");
      var s = aryval(v, "seq.0.seq.1.seq.1.seq.1.octstr.hex");
      var r = aryval(v, "seq.1.octstr.hex");
      if (u == undefined || s == undefined || r == undefined) {
        throw new Error("encalg, enciv or enc is undefined");
      }
      var A = {
        salt: t,
        iter: x,
        prf: q,
        encalg: u,
        enciv: s,
        enc: r
      };
      return A;
    },
    getDKFromPBES2Param: function (p, w) {
      var x = {
        hmacWithSHA1: CryptoJS.algo.SHA1,
        hmacWithSHA224: CryptoJS.algo.SHA224,
        hmacWithSHA256: CryptoJS.algo.SHA256,
        hmacWithSHA384: CryptoJS.algo.SHA384,
        hmacWithSHA512: CryptoJS.algo.SHA512
      };
      var q = {
        "des-EDE3-CBC": 192 / 32,
        "aes128-CBC": 128 / 32,
        "aes256-CBC": 256 / 32
      };
      var y = x[p.prf];
      if (y == undefined) {
        throw new Error("unsupported prf");
      }
      var r = q[p.encalg];
      if (r == undefined) {
        throw new Error("unsupported encalg");
      }
      var s = CryptoJS.enc.Hex.parse(p.salt);
      var u = p.iter;
      try {
        var v = CryptoJS.PBKDF2(w, s, {
          keySize: r,
          iterations: u,
          hasher: y
        });
        return CryptoJS.enc.Hex.stringify(v);
      } catch (t) {
        throw new Error("PBKDF2 error: " + t + " " + JSON.stringify(p) + " " + w);
      }
    },
    getPlainHexFromEncryptedPKCS8PEM: function (t, q) {
      if (t.indexOf("BEGIN ENCRYPTED PRIVATE KEY") == -1) {
        throw new Error("not Encrypted PKCS#8 PEM string");
      }
      var u = pemtohex(t);
      var p;
      try {
        p = KEYUTIL.parsePBES2(u);
      } catch (r) {
        throw new Error("malformed PBES2 format: " + r.message);
      }
      var s = KEYUTIL.getDKFromPBES2Param(p, q);
      return KJUR.crypto.Cipher.decrypt(p.enc, s, p.encalg, {
        iv: p.enciv
      });
    },
    getKeyFromEncryptedPKCS8PEM: function (s, q) {
      var p = this.getPlainHexFromEncryptedPKCS8PEM(s, q);
      var r = this.getKeyFromPlainPrivatePKCS8Hex(p);
      return r;
    },
    parsePlainPrivatePKCS8Hex: function (s) {
      var v = ASN1HEX;
      var u = v.getChildIdx;
      var t = v.getV;
      var q = {};
      q.algparam = null;
      if (s.substr(0, 2) != "30") {
        throw new Error("malformed plain PKCS8 private key(code:001)");
      }
      var r = u(s, 0);
      if (r.length < 3) {
        throw new Error("malformed plain PKCS8 private key(code:002)");
      }
      if (s.substr(r[1], 2) != "30") {
        throw new Error("malformed PKCS8 private key(code:003)");
      }
      var p = u(s, r[1]);
      if (p.length != 2) {
        throw new Error("malformed PKCS8 private key(code:004)");
      }
      if (s.substr(p[0], 2) != "06") {
        throw new Error("malformed PKCS8 private key(code:005)");
      }
      q.algoid = t(s, p[0]);
      if (s.substr(p[1], 2) == "06") {
        q.algparam = t(s, p[1]);
      }
      if (s.substr(r[2], 2) != "04") {
        throw new Error("malformed PKCS8 private key(code:006)");
      }
      q.keyidx = v.getVidx(s, r[2]);
      return q;
    },
    getKeyFromPlainPrivatePKCS8PEM: function (q) {
      var p = pemtohex(q, "PRIVATE KEY");
      var r = this.getKeyFromPlainPrivatePKCS8Hex(p);
      return r;
    },
    getKeyFromPlainPrivatePKCS8Hex: function (p) {
      var q = this.parsePlainPrivatePKCS8Hex(p);
      var r;
      if (q.algoid == "2a864886f70d010101") {
        r = new RSAKey();
      } else {
        if (q.algoid == "2a8648ce380401") {
          r = new KJUR.crypto.DSA();
        } else {
          if (q.algoid == "2a8648ce3d0201") {
            r = new KJUR.crypto.ECDSA();
          } else {
            throw new Error("unsupported private key algorithm");
          }
        }
      }
      r.readPKCS8PrvKeyHex(p);
      return r;
    },
    _getKeyFromPublicPKCS8Hex: function (q) {
      var p;
      var r = ASN1HEX.getVbyList(q, 0, [0, 0], "06");
      if (r === "2a864886f70d010101") {
        p = new RSAKey();
      } else {
        if (r === "2a8648ce380401") {
          p = new KJUR.crypto.DSA();
        } else {
          if (r === "2a8648ce3d0201") {
            p = new KJUR.crypto.ECDSA();
          } else {
            throw new Error("unsupported PKCS#8 public key hex");
          }
        }
      }
      p.readPKCS8PubKeyHex(q);
      return p;
    },
    parsePublicRawRSAKeyHex: function (r) {
      var u = ASN1HEX;
      var t = u.getChildIdx;
      var s = u.getV;
      var p = {};
      if (r.substr(0, 2) != "30") {
        throw new Error("malformed RSA key(code:001)");
      }
      var q = t(r, 0);
      if (q.length != 2) {
        throw new Error("malformed RSA key(code:002)");
      }
      if (r.substr(q[0], 2) != "02") {
        throw new Error("malformed RSA key(code:003)");
      }
      p.n = s(r, q[0]);
      if (r.substr(q[1], 2) != "02") {
        throw new Error("malformed RSA key(code:004)");
      }
      p.e = s(r, q[1]);
      return p;
    },
    parsePublicPKCS8Hex: function (t) {
      var v = ASN1HEX;
      var u = v.getChildIdx;
      var s = v.getV;
      var q = {};
      q.algparam = null;
      var r = u(t, 0);
      if (r.length != 2) {
        throw new Error("outer DERSequence shall have 2 elements: " + r.length);
      }
      var w = r[0];
      if (t.substr(w, 2) != "30") {
        throw new Error("malformed PKCS8 public key(code:001)");
      }
      var p = u(t, w);
      if (p.length != 2) {
        throw new Error("malformed PKCS8 public key(code:002)");
      }
      if (t.substr(p[0], 2) != "06") {
        throw new Error("malformed PKCS8 public key(code:003)");
      }
      q.algoid = s(t, p[0]);
      if (t.substr(p[1], 2) == "06") {
        q.algparam = s(t, p[1]);
      } else {
        if (t.substr(p[1], 2) == "30") {
          q.algparam = {};
          q.algparam.p = v.getVbyList(t, p[1], [0], "02");
          q.algparam.q = v.getVbyList(t, p[1], [1], "02");
          q.algparam.g = v.getVbyList(t, p[1], [2], "02");
        }
      }
      if (t.substr(r[1], 2) != "03") {
        throw new Error("malformed PKCS8 public key(code:004)");
      }
      q.key = s(t, r[1]).substr(2);
      return q;
    }
  };
}();
KEYUTIL.getKey = function (l, k, n) {
  var G = ASN1HEX,
    L = G.getChildIdx,
    v = G.getV,
    d = G.getVbyList,
    c = KJUR.crypto,
    i = c.ECDSA,
    C = c.DSA,
    w = RSAKey,
    M = pemtohex,
    F = KEYUTIL;
  if (typeof w != "undefined" && l instanceof w) {
    return l;
  }
  if (typeof i != "undefined" && l instanceof i) {
    return l;
  }
  if (typeof C != "undefined" && l instanceof C) {
    return l;
  }
  if (l.curve !== undefined && l.xy !== undefined && l.d === undefined) {
    return new i({
      pub: l.xy,
      curve: l.curve
    });
  }
  if (l.curve !== undefined && l.d !== undefined) {
    return new i({
      prv: l.d,
      curve: l.curve
    });
  }
  if (l.kty === undefined && l.n !== undefined && l.e !== undefined && l.d === undefined) {
    var P = new w();
    P.setPublic(l.n, l.e);
    return P;
  }
  if (l.kty === undefined && l.n !== undefined && l.e !== undefined && l.d !== undefined && l.p !== undefined && l.q !== undefined && l.dp !== undefined && l.dq !== undefined && l.co !== undefined && l.qi === undefined) {
    var P = new w();
    P.setPrivateEx(l.n, l.e, l.d, l.p, l.q, l.dp, l.dq, l.co);
    return P;
  }
  if (l.kty === undefined && l.n !== undefined && l.e !== undefined && l.d !== undefined && l.p === undefined) {
    var P = new w();
    P.setPrivate(l.n, l.e, l.d);
    return P;
  }
  if (l.p !== undefined && l.q !== undefined && l.g !== undefined && l.y !== undefined && l.x === undefined) {
    var P = new C();
    P.setPublic(l.p, l.q, l.g, l.y);
    return P;
  }
  if (l.p !== undefined && l.q !== undefined && l.g !== undefined && l.y !== undefined && l.x !== undefined) {
    var P = new C();
    P.setPrivate(l.p, l.q, l.g, l.y, l.x);
    return P;
  }
  if (l.kty === "RSA" && l.n !== undefined && l.e !== undefined && l.d === undefined) {
    var P = new w();
    P.setPublic(b64utohex(l.n), b64utohex(l.e));
    return P;
  }
  if (l.kty === "RSA" && l.n !== undefined && l.e !== undefined && l.d !== undefined && l.p !== undefined && l.q !== undefined && l.dp !== undefined && l.dq !== undefined && l.qi !== undefined) {
    var P = new w();
    P.setPrivateEx(b64utohex(l.n), b64utohex(l.e), b64utohex(l.d), b64utohex(l.p), b64utohex(l.q), b64utohex(l.dp), b64utohex(l.dq), b64utohex(l.qi));
    return P;
  }
  if (l.kty === "RSA" && l.n !== undefined && l.e !== undefined && l.d !== undefined) {
    var P = new w();
    P.setPrivate(b64utohex(l.n), b64utohex(l.e), b64utohex(l.d));
    return P;
  }
  if (l.kty === "EC" && l.crv !== undefined && l.x !== undefined && l.y !== undefined && l.d === undefined) {
    var j = new i({
      curve: l.crv
    });
    var t = j.ecparams.keycharlen;
    var B = ("0000000000" + b64utohex(l.x)).slice(-t);
    var z = ("0000000000" + b64utohex(l.y)).slice(-t);
    var u = "04" + B + z;
    j.setPublicKeyHex(u);
    return j;
  }
  if (l.kty === "EC" && l.crv !== undefined && l.x !== undefined && l.y !== undefined && l.d !== undefined) {
    var j = new i({
      curve: l.crv
    });
    var t = j.ecparams.keycharlen;
    var B = ("0000000000" + b64utohex(l.x)).slice(-t);
    var z = ("0000000000" + b64utohex(l.y)).slice(-t);
    var u = "04" + B + z;
    var b = ("0000000000" + b64utohex(l.d)).slice(-t);
    j.setPublicKeyHex(u);
    j.setPrivateKeyHex(b);
    return j;
  }
  if (n === "pkcs5prv") {
    var J = l,
      G = ASN1HEX,
      N,
      P;
    N = L(J, 0);
    if (N.length === 9) {
      P = new w();
      P.readPKCS5PrvKeyHex(J);
    } else {
      if (N.length === 6) {
        P = new C();
        P.readPKCS5PrvKeyHex(J);
      } else {
        if (N.length > 2 && J.substr(N[1], 2) === "04") {
          P = new i();
          P.readPKCS5PrvKeyHex(J);
        } else {
          throw new Error("unsupported PKCS#1/5 hexadecimal key");
        }
      }
    }
    return P;
  }
  if (n === "pkcs8prv") {
    var P = F.getKeyFromPlainPrivatePKCS8Hex(l);
    return P;
  }
  if (n === "pkcs8pub") {
    return F._getKeyFromPublicPKCS8Hex(l);
  }
  if (n === "x509pub") {
    return X509.getPublicKeyFromCertHex(l);
  }
  if (l.indexOf("-END CERTIFICATE-", 0) != -1 || l.indexOf("-END X509 CERTIFICATE-", 0) != -1 || l.indexOf("-END TRUSTED CERTIFICATE-", 0) != -1) {
    return X509.getPublicKeyFromCertPEM(l);
  }
  if (l.indexOf("-END PUBLIC KEY-") != -1) {
    var O = pemtohex(l, "PUBLIC KEY");
    return F._getKeyFromPublicPKCS8Hex(O);
  }
  if (l.indexOf("-END RSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
    var m = M(l, "RSA PRIVATE KEY");
    return F.getKey(m, null, "pkcs5prv");
  }
  if (l.indexOf("-END DSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
    var I = M(l, "DSA PRIVATE KEY");
    var E = d(I, 0, [1], "02");
    var D = d(I, 0, [2], "02");
    var K = d(I, 0, [3], "02");
    var r = d(I, 0, [4], "02");
    var s = d(I, 0, [5], "02");
    var P = new C();
    P.setPrivate(new BigInteger(E, 16), new BigInteger(D, 16), new BigInteger(K, 16), new BigInteger(r, 16), new BigInteger(s, 16));
    return P;
  }
  if (l.indexOf("-END EC PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
    var m = M(l, "EC PRIVATE KEY");
    return F.getKey(m, null, "pkcs5prv");
  }
  if (l.indexOf("-END PRIVATE KEY-") != -1) {
    return F.getKeyFromPlainPrivatePKCS8PEM(l);
  }
  if (l.indexOf("-END RSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
    var o = F.getDecryptedKeyHex(l, k);
    var H = new RSAKey();
    H.readPKCS5PrvKeyHex(o);
    return H;
  }
  if (l.indexOf("-END EC PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
    var I = F.getDecryptedKeyHex(l, k);
    var P = d(I, 0, [1], "04");
    var f = d(I, 0, [2, 0], "06");
    var A = d(I, 0, [3, 0], "03").substr(2);
    var e = "";
    if (KJUR.crypto.OID.oidhex2name[f] !== undefined) {
      e = KJUR.crypto.OID.oidhex2name[f];
    } else {
      throw new Error("undefined OID(hex) in KJUR.crypto.OID: " + f);
    }
    var j = new i({
      curve: e
    });
    j.setPublicKeyHex(A);
    j.setPrivateKeyHex(P);
    j.isPublic = false;
    return j;
  }
  if (l.indexOf("-END DSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
    var I = F.getDecryptedKeyHex(l, k);
    var E = d(I, 0, [1], "02");
    var D = d(I, 0, [2], "02");
    var K = d(I, 0, [3], "02");
    var r = d(I, 0, [4], "02");
    var s = d(I, 0, [5], "02");
    var P = new C();
    P.setPrivate(new BigInteger(E, 16), new BigInteger(D, 16), new BigInteger(K, 16), new BigInteger(r, 16), new BigInteger(s, 16));
    return P;
  }
  if (l.indexOf("-END ENCRYPTED PRIVATE KEY-") != -1) {
    return F.getKeyFromEncryptedPKCS8PEM(l, k);
  }
  throw new Error("not supported argument");
};
KEYUTIL.generateKeypair = function (a, c) {
  if (a == "RSA") {
    var b = c;
    var h = new RSAKey();
    h.generate(b, "10001");
    h.isPrivate = true;
    h.isPublic = true;
    var f = new RSAKey();
    var e = h.n.toString(16);
    var i = h.e.toString(16);
    f.setPublic(e, i);
    f.isPrivate = false;
    f.isPublic = true;
    var k = {};
    k.prvKeyObj = h;
    k.pubKeyObj = f;
    return k;
  } else {
    if (a == "EC") {
      var d = c;
      var g = new KJUR.crypto.ECDSA({
        curve: d
      });
      var j = g.generateKeyPairHex();
      var h = new KJUR.crypto.ECDSA({
        curve: d
      });
      h.setPublicKeyHex(j.ecpubhex);
      h.setPrivateKeyHex(j.ecprvhex);
      h.isPrivate = true;
      h.isPublic = false;
      var f = new KJUR.crypto.ECDSA({
        curve: d
      });
      f.setPublicKeyHex(j.ecpubhex);
      f.isPrivate = false;
      f.isPublic = true;
      var k = {};
      k.prvKeyObj = h;
      k.pubKeyObj = f;
      return k;
    } else {
      throw new Error("unknown algorithm: " + a);
    }
  }
};
KEYUTIL.getPEM = function (b, C, x, m, p, j) {
  var E = KJUR,
    k = E.asn1,
    y = k.DERObjectIdentifier,
    e = k.DERInteger,
    l = k.ASN1Util.newObject,
    a = k.x509,
    B = a.SubjectPublicKeyInfo,
    d = E.crypto,
    t = d.DSA,
    q = d.ECDSA,
    n = RSAKey;
  function z(s) {
    var G = l({
      seq: [{
        "int": 0
      }, {
        "int": {
          bigint: s.n
        }
      }, {
        "int": s.e
      }, {
        "int": {
          bigint: s.d
        }
      }, {
        "int": {
          bigint: s.p
        }
      }, {
        "int": {
          bigint: s.q
        }
      }, {
        "int": {
          bigint: s.dmp1
        }
      }, {
        "int": {
          bigint: s.dmq1
        }
      }, {
        "int": {
          bigint: s.coeff
        }
      }]
    });
    return G;
  }
  function A(G) {
    var s = l({
      seq: [{
        "int": 1
      }, {
        octstr: {
          hex: G.prvKeyHex
        }
      }, {
        tag: ["a0", true, {
          oid: {
            name: G.curveName
          }
        }]
      }, {
        tag: ["a1", true, {
          bitstr: {
            hex: "00" + G.pubKeyHex
          }
        }]
      }]
    });
    return s;
  }
  function w(s) {
    var G = l({
      seq: [{
        "int": 0
      }, {
        "int": {
          bigint: s.p
        }
      }, {
        "int": {
          bigint: s.q
        }
      }, {
        "int": {
          bigint: s.g
        }
      }, {
        "int": {
          bigint: s.y
        }
      }, {
        "int": {
          bigint: s.x
        }
      }]
    });
    return G;
  }
  if ((n !== undefined && b instanceof n || t !== undefined && b instanceof t || q !== undefined && b instanceof q) && b.isPublic == true && (C === undefined || C == "PKCS8PUB")) {
    var D = new B(b);
    var v = D.tohex();
    return hextopem(v, "PUBLIC KEY");
  }
  if (C == "PKCS1PRV" && n !== undefined && b instanceof n && (x === undefined || x == null) && b.isPrivate == true) {
    var D = z(b);
    var v = D.tohex();
    return hextopem(v, "RSA PRIVATE KEY");
  }
  if (C == "PKCS1PRV" && q !== undefined && b instanceof q && (x === undefined || x == null) && b.isPrivate == true) {
    var i = new y({
      name: b.curveName
    });
    var u = i.tohex();
    var h = A(b);
    var r = h.tohex();
    var o = "";
    o += hextopem(u, "EC PARAMETERS");
    o += hextopem(r, "EC PRIVATE KEY");
    return o;
  }
  if (C == "PKCS1PRV" && t !== undefined && b instanceof t && (x === undefined || x == null) && b.isPrivate == true) {
    var D = w(b);
    var v = D.tohex();
    return hextopem(v, "DSA PRIVATE KEY");
  }
  if (C == "PKCS5PRV" && n !== undefined && b instanceof n && x !== undefined && x != null && b.isPrivate == true) {
    var D = z(b);
    var v = D.tohex();
    if (m === undefined) {
      m = "DES-EDE3-CBC";
    }
    return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA", v, x, m, j);
  }
  if (C == "PKCS5PRV" && q !== undefined && b instanceof q && x !== undefined && x != null && b.isPrivate == true) {
    var D = A(b);
    var v = D.tohex();
    if (m === undefined) {
      m = "DES-EDE3-CBC";
    }
    return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC", v, x, m, j);
  }
  if (C == "PKCS5PRV" && t !== undefined && b instanceof t && x !== undefined && x != null && b.isPrivate == true) {
    var D = w(b);
    var v = D.tohex();
    if (m === undefined) {
      m = "DES-EDE3-CBC";
    }
    return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA", v, x, m, j);
  }
  var f = function (G, H) {
    if (typeof H == "string") {
      return KEYUTIL.getEncryptedPKCS8PEM(G, H);
    } else {
      if (typeof H == "object" && aryval(H, "passcode") != undefined) {
        var I = JSON.parse(JSON.stringify(H));
        var s = I.passcode;
        delete I.passcode;
        return KEYUTIL.getEncryptedPKCS8PEM(G, s, I);
      }
    }
  };
  if (C == "PKCS8PRV" && n != undefined && b instanceof n && b.isPrivate == true) {
    var g = z(b);
    var c = g.tohex();
    var D = l({
      seq: [{
        "int": 0
      }, {
        seq: [{
          oid: {
            name: "rsaEncryption"
          }
        }, {
          "null": true
        }]
      }, {
        octstr: {
          hex: c
        }
      }]
    });
    var v = D.tohex();
    if (x === undefined || x == null) {
      return hextopem(v, "PRIVATE KEY");
    } else {
      return f(v, x);
    }
  }
  if (C == "PKCS8PRV" && q !== undefined && b instanceof q && b.isPrivate == true) {
    var F = {
      seq: [{
        "int": 1
      }, {
        octstr: {
          hex: b.prvKeyHex
        }
      }]
    };
    if (typeof b.pubKeyHex == "string") {
      F.seq.push({
        tag: ["a1", true, {
          bitstr: {
            hex: "00" + b.pubKeyHex
          }
        }]
      });
    }
    var g = new l(F);
    var c = g.tohex();
    var D = l({
      seq: [{
        "int": 0
      }, {
        seq: [{
          oid: {
            name: "ecPublicKey"
          }
        }, {
          oid: {
            name: b.curveName
          }
        }]
      }, {
        octstr: {
          hex: c
        }
      }]
    });
    var v = D.tohex();
    if (x === undefined || x == null) {
      return hextopem(v, "PRIVATE KEY");
    } else {
      return f(v, x);
    }
  }
  if (C == "PKCS8PRV" && t !== undefined && b instanceof t && b.isPrivate == true) {
    var g = new e({
      bigint: b.x
    });
    var c = g.tohex();
    var D = l({
      seq: [{
        "int": 0
      }, {
        seq: [{
          oid: {
            name: "dsa"
          }
        }, {
          seq: [{
            "int": {
              bigint: b.p
            }
          }, {
            "int": {
              bigint: b.q
            }
          }, {
            "int": {
              bigint: b.g
            }
          }]
        }]
      }, {
        octstr: {
          hex: c
        }
      }]
    });
    var v = D.tohex();
    if (x === undefined || x == null) {
      return hextopem(v, "PRIVATE KEY");
    } else {
      return f(v, x);
    }
  }
  throw new Error("unsupported object nor format");
};
KEYUTIL.getKeyFromCSRPEM = function (b) {
  var a = pemtohex(b, "CERTIFICATE REQUEST");
  var c = KEYUTIL.getKeyFromCSRHex(a);
  return c;
};
KEYUTIL.getKeyFromCSRHex = function (a) {
  var c = KEYUTIL.parseCSRHex(a);
  var b = KEYUTIL.getKey(c.p8pubkeyhex, null, "pkcs8pub");
  return b;
};
KEYUTIL.parseCSRHex = function (d) {
  var i = ASN1HEX;
  var f = i.getChildIdx;
  var c = i.getTLV;
  var b = {};
  var g = d;
  if (g.substr(0, 2) != "30") {
    throw new Error("malformed CSR(code:001)");
  }
  var e = f(g, 0);
  if (e.length < 1) {
    throw new Error("malformed CSR(code:002)");
  }
  if (g.substr(e[0], 2) != "30") {
    throw new Error("malformed CSR(code:003)");
  }
  var a = f(g, e[0]);
  if (a.length < 3) {
    throw new Error("malformed CSR(code:004)");
  }
  b.p8pubkeyhex = c(g, a[2]);
  return b;
};
KEYUTIL.getKeyID = function (f) {
  var c = KEYUTIL;
  var e = ASN1HEX;
  if (typeof f === "string" && f.indexOf("BEGIN ") != -1) {
    f = c.getKey(f);
  }
  var d = pemtohex(c.getPEM(f));
  var b = e.getIdxbyList(d, 0, [1]);
  var a = e.getV(d, b).substring(2);
  return KJUR.crypto.Util.hashHex(a, "sha1");
};
KEYUTIL.getJWK = function (d, h, g, b, f) {
  var i;
  var k = {};
  var e;
  var c = KJUR.crypto.Util.hashHex;
  if (typeof d == "string") {
    i = KEYUTIL.getKey(d);
    if (d.indexOf("CERTIFICATE") != -1) {
      e = pemtohex(d);
    }
  } else {
    if (typeof d == "object") {
      if (d instanceof X509) {
        i = d.getPublicKey();
        e = d.hex;
      } else {
        i = d;
      }
    } else {
      throw new Error("unsupported keyinfo type");
    }
  }
  if (i instanceof RSAKey && i.isPrivate) {
    k.kty = "RSA";
    k.n = hextob64u(i.n.toString(16));
    k.e = hextob64u(i.e.toString(16));
    k.d = hextob64u(i.d.toString(16));
    k.p = hextob64u(i.p.toString(16));
    k.q = hextob64u(i.q.toString(16));
    k.dp = hextob64u(i.dmp1.toString(16));
    k.dq = hextob64u(i.dmq1.toString(16));
    k.qi = hextob64u(i.coeff.toString(16));
  } else {
    if (i instanceof RSAKey && i.isPublic) {
      k.kty = "RSA";
      k.n = hextob64u(i.n.toString(16));
      k.e = hextob64u(i.e.toString(16));
    } else {
      if (i instanceof KJUR.crypto.ECDSA && i.isPrivate) {
        var a = i.getShortNISTPCurveName();
        if (a !== "P-256" && a !== "P-384" && a !== "P-521") {
          throw new Error("unsupported curve name for JWT: " + a);
        }
        var j = i.getPublicKeyXYHex();
        k.kty = "EC";
        k.crv = a;
        k.x = hextob64u(j.x);
        k.y = hextob64u(j.y);
        k.d = hextob64u(i.prvKeyHex);
      } else {
        if (i instanceof KJUR.crypto.ECDSA && i.isPublic) {
          var a = i.getShortNISTPCurveName();
          if (a !== "P-256" && a !== "P-384" && a !== "P-521") {
            throw new Error("unsupported curve name for JWT: " + a);
          }
          var j = i.getPublicKeyXYHex();
          k.kty = "EC";
          k.crv = a;
          k.x = hextob64u(j.x);
          k.y = hextob64u(j.y);
        }
      }
    }
  }
  if (k.kty == undefined) {
    throw new Error("unsupported keyinfo");
  }
  if (!i.isPrivate && h != true) {
    k.kid = KJUR.jws.JWS.getJWKthumbprint(k);
  }
  if (e != undefined && g != true) {
    k.x5c = [hex2b64(e)];
  }
  if (e != undefined && b != true) {
    k.x5t = b64tob64u(hex2b64(c(e, "sha1")));
  }
  if (e != undefined && f != true) {
    k["x5t#S256"] = b64tob64u(hex2b64(c(e, "sha256")));
  }
  return k;
};
KEYUTIL.getJWKFromKey = function (a) {
  return KEYUTIL.getJWK(a, true, true, true, true);
};
RSAKey.getPosArrayOfChildrenFromHex = function (a) {
  return ASN1HEX.getChildIdx(a, 0);
};
RSAKey.getHexValueArrayOfChildrenFromHex = function (f) {
  var n = ASN1HEX;
  var i = n.getV;
  var k = RSAKey.getPosArrayOfChildrenFromHex(f);
  var e = i(f, k[0]);
  var j = i(f, k[1]);
  var b = i(f, k[2]);
  var c = i(f, k[3]);
  var h = i(f, k[4]);
  var g = i(f, k[5]);
  var m = i(f, k[6]);
  var l = i(f, k[7]);
  var d = i(f, k[8]);
  var k = new Array();
  k.push(e, j, b, c, h, g, m, l, d);
  return k;
};
RSAKey.prototype.readPrivateKeyFromPEMString = function (d) {
  var c = pemtohex(d);
  var b = RSAKey.getHexValueArrayOfChildrenFromHex(c);
  this.setPrivateEx(b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
};
RSAKey.prototype.readPKCS5PrvKeyHex = function (c) {
  var b = RSAKey.getHexValueArrayOfChildrenFromHex(c);
  this.setPrivateEx(b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
};
RSAKey.prototype.readPKCS8PrvKeyHex = function (e) {
  var c, i, k, b, a, f, d, j;
  var m = ASN1HEX;
  var l = m.getVbyListEx;
  if (m.isASN1HEX(e) === false) {
    throw new Error("not ASN.1 hex string");
  }
  try {
    c = l(e, 0, [2, 0, 1], "02");
    i = l(e, 0, [2, 0, 2], "02");
    k = l(e, 0, [2, 0, 3], "02");
    b = l(e, 0, [2, 0, 4], "02");
    a = l(e, 0, [2, 0, 5], "02");
    f = l(e, 0, [2, 0, 6], "02");
    d = l(e, 0, [2, 0, 7], "02");
    j = l(e, 0, [2, 0, 8], "02");
  } catch (g) {
    throw new Error("malformed PKCS#8 plain RSA private key");
  }
  this.setPrivateEx(c, i, k, b, a, f, d, j);
};
RSAKey.prototype.readPKCS5PubKeyHex = function (c) {
  var e = ASN1HEX;
  var b = e.getV;
  if (e.isASN1HEX(c) === false) {
    throw new Error("keyHex is not ASN.1 hex string");
  }
  var a = e.getChildIdx(c, 0);
  if (a.length !== 2 || c.substr(a[0], 2) !== "02" || c.substr(a[1], 2) !== "02") {
    throw new Error("wrong hex for PKCS#5 public key");
  }
  var f = b(c, a[0]);
  var d = b(c, a[1]);
  this.setPublic(f, d);
};
RSAKey.prototype.readPKCS8PubKeyHex = function (b) {
  var c = ASN1HEX;
  if (c.isASN1HEX(b) === false) {
    throw new Error("not ASN.1 hex string");
  }
  if (c.getTLVbyListEx(b, 0, [0, 0]) !== "06092a864886f70d010101") {
    throw new Error("not PKCS8 RSA public key");
  }
  var a = c.getTLVbyListEx(b, 0, [1, 0]);
  this.readPKCS5PubKeyHex(a);
};
RSAKey.prototype.readCertPubKeyHex = function (b, d) {
  var a, c;
  a = new X509();
  a.readCertHex(b);
  c = a.getPublicKeyHex();
  this.readPKCS8PubKeyHex(c);
};
var _RE_HEXDECONLY = new RegExp("[^0-9a-f]", "gi");
function _rsasign_getHexPaddedDigestInfoForString(d, e, a) {
  var b = function (f) {
    return KJUR.crypto.Util.hashString(f, a);
  };
  var c = b(d);
  return KJUR.crypto.Util.getPaddedDigestInfoHex(c, a, e);
}
function _zeroPaddingOfSignature(e, d) {
  var c = "";
  var a = d / 4 - e.length;
  for (var b = 0; b < a; b++) {
    c = c + "0";
  }
  return c + e;
}
RSAKey.prototype.sign = function (d, a) {
  var b = function (e) {
    return KJUR.crypto.Util.hashString(e, a);
  };
  var c = b(d);
  return this.signWithMessageHash(c, a);
};
RSAKey.prototype.signWithMessageHash = function (e, c) {
  var f = KJUR.crypto.Util.getPaddedDigestInfoHex(e, c, this.n.bitLength());
  var b = parseBigInt(f, 16);
  var d = this.doPrivate(b);
  var a = d.toString(16);
  return _zeroPaddingOfSignature(a, this.n.bitLength());
};
function pss_mgf1_str(c, a, e) {
  var b = "",
    d = 0;
  while (b.length < a) {
    b += hextorstr(e(rstrtohex(c + String.fromCharCode.apply(String, [(d & 4278190080) >> 24, (d & 16711680) >> 16, (d & 65280) >> 8, d & 255]))));
    d += 1;
  }
  return b;
}
RSAKey.prototype.signPSS = function (e, a, d) {
  var c = function (f) {
    return KJUR.crypto.Util.hashHex(f, a);
  };
  var b = c(rstrtohex(e));
  if (d === undefined) {
    d = -1;
  }
  return this.signWithMessageHashPSS(b, a, d);
};
RSAKey.prototype.signWithMessageHashPSS = function (l, a, k) {
  var b = hextorstr(l);
  var g = b.length;
  var m = this.n.bitLength() - 1;
  var c = Math.ceil(m / 8);
  var d;
  var o = function (i) {
    return KJUR.crypto.Util.hashHex(i, a);
  };
  if (k === -1 || k === undefined) {
    k = g;
  } else {
    if (k === -2) {
      k = c - g - 2;
    } else {
      if (k < -2) {
        throw new Error("invalid salt length");
      }
    }
  }
  if (c < g + k + 2) {
    throw new Error("data too long");
  }
  var f = "";
  if (k > 0) {
    f = new Array(k);
    new SecureRandom().nextBytes(f);
    f = String.fromCharCode.apply(String, f);
  }
  var n = hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00" + b + f)));
  var j = [];
  for (d = 0; d < c - k - g - 2; d += 1) {
    j[d] = 0;
  }
  var e = String.fromCharCode.apply(String, j) + "\x01" + f;
  var h = pss_mgf1_str(n, e.length, o);
  var q = [];
  for (d = 0; d < e.length; d += 1) {
    q[d] = e.charCodeAt(d) ^ h.charCodeAt(d);
  }
  var p = 65280 >> 8 * c - m & 255;
  q[0] &= ~p;
  for (d = 0; d < g; d++) {
    q.push(n.charCodeAt(d));
  }
  q.push(188);
  return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(q)).toString(16), this.n.bitLength());
};
function _rsasign_getDecryptSignatureBI(a, d, c) {
  var b = new RSAKey();
  b.setPublic(d, c);
  var e = b.doPublic(a);
  return e;
}
function _rsasign_getHexDigestInfoFromSig(a, c, b) {
  var e = _rsasign_getDecryptSignatureBI(a, c, b);
  var d = e.toString(16).replace(/^1f+00/, "");
  return d;
}
function _rsasign_getAlgNameAndHashFromHexDisgestInfo(f) {
  for (var e in KJUR.crypto.Util.DIGESTINFOHEAD) {
    var d = KJUR.crypto.Util.DIGESTINFOHEAD[e];
    var b = d.length;
    if (f.substring(0, b) == d) {
      var c = [e, f.substring(b)];
      return c;
    }
  }
  return [];
}
RSAKey.prototype.verify = function (f, l) {
  l = l.toLowerCase();
  if (l.match(/^[0-9a-f]+$/) == null) {
    return false;
  }
  var b = parseBigInt(l, 16);
  var k = this.n.bitLength();
  if (b.bitLength() > k) {
    return false;
  }
  var j = this.doPublic(b);
  var i = j.toString(16);
  if (i.length + 3 != k / 4) {
    return false;
  }
  var e = i.replace(/^1f+00/, "");
  var g = _rsasign_getAlgNameAndHashFromHexDisgestInfo(e);
  if (g.length == 0) {
    return false;
  }
  var d = g[0];
  var h = g[1];
  var a = function (m) {
    return KJUR.crypto.Util.hashString(m, d);
  };
  var c = a(f);
  return h == c;
};
RSAKey.prototype.verifyWithMessageHash = function (e, a) {
  if (a.length != Math.ceil(this.n.bitLength() / 4)) {
    return false;
  }
  var b = parseBigInt(a, 16);
  if (b.bitLength() > this.n.bitLength()) {
    return 0;
  }
  var h = this.doPublic(b);
  var g = h.toString(16).replace(/^1f+00/, "");
  var c = _rsasign_getAlgNameAndHashFromHexDisgestInfo(g);
  if (c.length == 0) {
    return false;
  }
  var d = c[0];
  var f = c[1];
  return f == e;
};
RSAKey.prototype.verifyPSS = function (c, b, a, f) {
  var e = function (g) {
    return KJUR.crypto.Util.hashHex(g, a);
  };
  var d = e(rstrtohex(c));
  if (f === undefined) {
    f = -1;
  }
  return this.verifyWithMessageHashPSS(d, b, a, f);
};
RSAKey.prototype.verifyWithMessageHashPSS = function (f, s, l, c) {
  if (s.length != Math.ceil(this.n.bitLength() / 4)) {
    return false;
  }
  var k = new BigInteger(s, 16);
  var r = function (i) {
    return KJUR.crypto.Util.hashHex(i, l);
  };
  var j = hextorstr(f);
  var h = j.length;
  var g = this.n.bitLength() - 1;
  var m = Math.ceil(g / 8);
  var q;
  if (c === -1 || c === undefined) {
    c = h;
  } else {
    if (c === -2) {
      c = m - h - 2;
    } else {
      if (c < -2) {
        throw new Error("invalid salt length");
      }
    }
  }
  if (m < h + c + 2) {
    throw new Error("data too long");
  }
  var a = this.doPublic(k).toByteArray();
  for (q = 0; q < a.length; q += 1) {
    a[q] &= 255;
  }
  while (a.length < m) {
    a.unshift(0);
  }
  if (a[m - 1] !== 188) {
    throw new Error("encoded message does not end in 0xbc");
  }
  a = String.fromCharCode.apply(String, a);
  var d = a.substr(0, m - h - 1);
  var e = a.substr(d.length, h);
  var p = 65280 >> 8 * m - g & 255;
  if ((d.charCodeAt(0) & p) !== 0) {
    throw new Error("bits beyond keysize not zero");
  }
  var n = pss_mgf1_str(e, d.length, r);
  var o = [];
  for (q = 0; q < d.length; q += 1) {
    o[q] = d.charCodeAt(q) ^ n.charCodeAt(q);
  }
  o[0] &= ~p;
  var b = m - h - c - 2;
  for (q = 0; q < b; q += 1) {
    if (o[q] !== 0) {
      throw new Error("leftmost octets not zero");
    }
  }
  if (o[b] !== 1) {
    throw new Error("0x01 marker not found");
  }
  return e === hextorstr(r(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00" + j + String.fromCharCode.apply(String, o.slice(-c)))));
};
RSAKey.SALT_LEN_HLEN = -1;
RSAKey.SALT_LEN_MAX = -2;
RSAKey.SALT_LEN_RECOVER = -2;
function X509(v) {
  var o = ASN1HEX,
    s = o.getChildIdx,
    k = o.getV,
    y = o.dump,
    j = o.parse,
    b = o.getTLV,
    c = o.getVbyList,
    p = o.getVbyListEx,
    a = o.getTLVbyList,
    q = o.getTLVbyListEx,
    l = o.getIdxbyList,
    f = o.getIdxbyListEx,
    n = o.getVidx,
    x = o.getInt,
    u = o.oidname,
    r = o.hextooidstr,
    d = X509,
    w = pemtohex,
    g,
    m = Error;
  try {
    g = KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;
  } catch (t) {}
  this.HEX2STAG = {
    "0c": "utf8",
    "13": "prn",
    "16": "ia5",
    "1a": "vis",
    "1e": "bmp"
  };
  this.hex = null;
  this.version = 0;
  this.foffset = 0;
  this.aExtInfo = null;
  this.getVersion = function () {
    if (this.hex === null || this.version !== 0) {
      return this.version;
    }
    var A = a(this.hex, 0, [0, 0]);
    if (A.substr(0, 2) == "a0") {
      var B = a(A, 0, [0]);
      var z = x(B, 0);
      if (z < 0 || 2 < z) {
        throw new Error("malformed version field");
      }
      this.version = z + 1;
      return this.version;
    } else {
      this.version = 1;
      this.foffset = -1;
      return 1;
    }
  };
  this.getSerialNumberHex = function () {
    return p(this.hex, 0, [0, 0], "02");
  };
  this.getSignatureAlgorithmField = function () {
    var z = q(this.hex, 0, [0, 1]);
    return this.getAlgorithmIdentifierName(z);
  };
  this.getAlgorithmIdentifierName = function (z) {
    for (var A in g) {
      if (z === g[A]) {
        return A;
      }
    }
    return u(p(z, 0, [0], "06"));
  };
  this.getIssuer = function (A, z) {
    return this.getX500Name(this.getIssuerHex(), A, z);
  };
  this.getIssuerHex = function () {
    return a(this.hex, 0, [0, 3 + this.foffset], "30");
  };
  this.getIssuerString = function () {
    var z = this.getIssuer();
    return z.str;
  };
  this.getSubject = function (A, z) {
    return this.getX500Name(this.getSubjectHex(), A, z);
  };
  this.getSubjectHex = function () {
    return a(this.hex, 0, [0, 5 + this.foffset], "30");
  };
  this.getSubjectString = function () {
    var z = this.getSubject();
    return z.str;
  };
  this.getNotBefore = function () {
    var z = c(this.hex, 0, [0, 4 + this.foffset, 0]);
    z = z.replace(/(..)/g, "%$1");
    z = decodeURIComponent(z);
    return z;
  };
  this.getNotAfter = function () {
    var z = c(this.hex, 0, [0, 4 + this.foffset, 1]);
    z = z.replace(/(..)/g, "%$1");
    z = decodeURIComponent(z);
    return z;
  };
  this.getPublicKeyHex = function () {
    return this.getSPKI();
  };
  this.getSPKI = function () {
    return a(this.hex, 0, [0, 6 + this.foffset], "30");
  };
  this.getSPKIValue = function () {
    var z = this.getSPKI();
    if (z == null) {
      return null;
    }
    return c(z, 0, [1], "03", true);
  };
  this.getPublicKeyIdx = function () {
    return l(this.hex, 0, [0, 6 + this.foffset], "30");
  };
  this.getPublicKeyContentIdx = function () {
    var z = this.getPublicKeyIdx();
    return l(this.hex, z, [1, 0], "30");
  };
  this.getPublicKey = function () {
    return KEYUTIL.getKey(this.getPublicKeyHex(), null, "pkcs8pub");
  };
  this.getSignatureAlgorithmName = function () {
    var z = a(this.hex, 0, [1], "30");
    return this.getAlgorithmIdentifierName(z);
  };
  this.getSignatureValueHex = function () {
    return c(this.hex, 0, [2], "03", true);
  };
  this.verifySignature = function (B) {
    var C = this.getSignatureAlgorithmField();
    var z = this.getSignatureValueHex();
    var A = a(this.hex, 0, [0], "30");
    var D = new KJUR.crypto.Signature({
      alg: C
    });
    D.init(B);
    D.updateHex(A);
    return D.verify(z);
  };
  this.parseExt = function (I) {
    var B, z, D;
    if (I === undefined) {
      D = this.hex;
      if (this.version !== 3) {
        return -1;
      }
      B = l(D, 0, [0, 7, 0], "30");
      z = s(D, B);
    } else {
      D = pemtohex(I);
      var E = l(D, 0, [0, 3, 0, 0], "06");
      if (k(D, E) != "2a864886f70d01090e") {
        this.aExtInfo = new Array();
        return;
      }
      B = l(D, 0, [0, 3, 0, 1, 0], "30");
      z = s(D, B);
      this.hex = D;
    }
    this.aExtInfo = new Array();
    for (var C = 0; C < z.length; C++) {
      var G = {};
      G.critical = false;
      var F = s(D, z[C]);
      var A = 0;
      if (F.length === 3) {
        G.critical = true;
        A = 1;
      }
      G.oid = o.hextooidstr(c(D, z[C], [0], "06"));
      var H = l(D, z[C], [1 + A]);
      G.vidx = n(D, H);
      this.aExtInfo.push(G);
    }
  };
  this.getExtInfo = function (B) {
    var z = this.aExtInfo;
    var C = B;
    if (!B.match(/^[0-9.]+$/)) {
      C = KJUR.asn1.x509.OID.name2oid(B);
    }
    if (C === "") {
      return undefined;
    }
    for (var A = 0; A < z.length; A++) {
      if (z[A].oid === C) {
        return z[A];
      }
    }
    return undefined;
  };
  this.getCriticalExtV = function (C, z, B) {
    if (z != undefined) {
      return [z, B];
    }
    var A = this.getExtInfo(C);
    if (A == undefined) {
      return [null, null];
    }
    return [b(this.hex, A.vidx), A.critical];
  };
  this.getExtBasicConstraints = function (A, E) {
    if (A === undefined && E === undefined) {
      var C = this.getExtInfo("basicConstraints");
      if (C === undefined) {
        return undefined;
      }
      A = b(this.hex, C.vidx);
      E = C.critical;
    }
    var z = {
      extname: "basicConstraints"
    };
    if (E) {
      z.critical = true;
    }
    if (A === "3000") {
      return z;
    }
    if (A === "30030101ff") {
      z.cA = true;
      return z;
    }
    if (A.substr(0, 12) === "30060101ff02") {
      var D = k(A, 10);
      var B = parseInt(D, 16);
      z.cA = true;
      z.pathLen = B;
      return z;
    }
    throw new Error("hExtV parse error: " + A);
  };
  this.getExtNameConstraints = function (I, G) {
    var A = this.getCriticalExtV("nameConstraints", I, G);
    I = A[0];
    G = A[1];
    if (I == null) {
      return undefined;
    }
    var K = {
      extname: "nameConstraints"
    };
    if (G) {
      K.critical = true;
    }
    var F = s(I, 0);
    for (var D = 0; D < F.length; D++) {
      var E = [];
      var B = s(I, F[D]);
      for (var C = 0; C < B.length; C++) {
        var H = b(I, B[C]);
        var z = this.getGeneralSubtree(H);
        E.push(z);
      }
      var J = I.substr(F[D], 2);
      if (J == "a0") {
        K.permit = E;
      } else {
        if (J == "a1") {
          K.exclude = E;
        }
      }
    }
    return K;
  };
  this.getGeneralSubtree = function (F) {
    var D = s(F, 0);
    var C = D.length;
    if (C < 1 || 2 < C) {
      throw new Error("wrong num elements");
    }
    var B = this.getGeneralName(b(F, D[0]));
    for (var E = 1; E < C; E++) {
      var A = F.substr(D[E], 2);
      var z = k(F, D[E]);
      var G = parseInt(z, 16);
      if (A == "80") {
        B.min = G;
      }
      if (A == "81") {
        B.max = G;
      }
    }
    return B;
  };
  this.getExtKeyUsage = function (A, C) {
    var B = this.getCriticalExtV("keyUsage", A, C);
    A = B[0];
    C = B[1];
    if (A == null) {
      return undefined;
    }
    var z = {
      extname: "keyUsage"
    };
    if (C) {
      z.critical = true;
    }
    z.names = this.getExtKeyUsageString(A).split(",");
    return z;
  };
  this.getExtKeyUsageBin = function (A) {
    if (A === undefined) {
      var B = this.getExtInfo("keyUsage");
      if (B === undefined) {
        return "";
      }
      A = b(this.hex, B.vidx);
    }
    if (A.length != 8 && A.length != 10) {
      throw new Error("malformed key usage value: " + A);
    }
    var z = "000000000000000" + parseInt(A.substr(6), 16).toString(2);
    if (A.length == 8) {
      z = z.slice(-8);
    }
    if (A.length == 10) {
      z = z.slice(-16);
    }
    z = z.replace(/0+$/, "");
    if (z == "") {
      z = "0";
    }
    return z;
  };
  this.getExtKeyUsageString = function (B) {
    var C = this.getExtKeyUsageBin(B);
    var z = new Array();
    for (var A = 0; A < C.length; A++) {
      if (C.substr(A, 1) == "1") {
        z.push(X509.KEYUSAGE_NAME[A]);
      }
    }
    return z.join(",");
  };
  this.getExtSubjectKeyIdentifier = function (B, D) {
    if (B === undefined && D === undefined) {
      var C = this.getExtInfo("subjectKeyIdentifier");
      if (C === undefined) {
        return undefined;
      }
      B = b(this.hex, C.vidx);
      D = C.critical;
    }
    var z = {
      extname: "subjectKeyIdentifier"
    };
    if (D) {
      z.critical = true;
    }
    var A = k(B, 0);
    z.kid = {
      hex: A
    };
    return z;
  };
  this.getExtAuthorityKeyIdentifier = function (F, D) {
    if (F === undefined && D === undefined) {
      var z = this.getExtInfo("authorityKeyIdentifier");
      if (z === undefined) {
        return undefined;
      }
      F = b(this.hex, z.vidx);
      D = z.critical;
    }
    var G = {
      extname: "authorityKeyIdentifier"
    };
    if (D) {
      G.critical = true;
    }
    var E = s(F, 0);
    for (var A = 0; A < E.length; A++) {
      var H = F.substr(E[A], 2);
      if (H === "80") {
        G.kid = {
          hex: k(F, E[A])
        };
      }
      if (H === "a1") {
        var C = b(F, E[A]);
        var B = this.getGeneralNames(C);
        G.issuer = B[0]["dn"];
      }
      if (H === "82") {
        G.sn = {
          hex: k(F, E[A])
        };
      }
    }
    return G;
  };
  this.getExtExtKeyUsage = function (C, E) {
    if (C === undefined && E === undefined) {
      var D = this.getExtInfo("extKeyUsage");
      if (D === undefined) {
        return undefined;
      }
      C = b(this.hex, D.vidx);
      E = D.critical;
    }
    var z = {
      extname: "extKeyUsage",
      array: []
    };
    if (E) {
      z.critical = true;
    }
    var A = s(C, 0);
    for (var B = 0; B < A.length; B++) {
      z.array.push(u(k(C, A[B])));
    }
    return z;
  };
  this.getExtExtKeyUsageName = function () {
    var D = this.getExtInfo("extKeyUsage");
    if (D === undefined) {
      return D;
    }
    var z = new Array();
    var C = b(this.hex, D.vidx);
    if (C === "") {
      return z;
    }
    var A = s(C, 0);
    for (var B = 0; B < A.length; B++) {
      z.push(u(k(C, A[B])));
    }
    return z;
  };
  this.getExtSubjectAltName = function (A, C) {
    if (A === undefined && C === undefined) {
      var B = this.getExtInfo("subjectAltName");
      if (B === undefined) {
        return undefined;
      }
      A = b(this.hex, B.vidx);
      C = B.critical;
    }
    var z = {
      extname: "subjectAltName",
      array: []
    };
    if (C) {
      z.critical = true;
    }
    z.array = this.getGeneralNames(A);
    return z;
  };
  this.getExtIssuerAltName = function (A, C) {
    if (A === undefined && C === undefined) {
      var B = this.getExtInfo("issuerAltName");
      if (B === undefined) {
        return undefined;
      }
      A = b(this.hex, B.vidx);
      C = B.critical;
    }
    var z = {
      extname: "issuerAltName",
      array: []
    };
    if (C) {
      z.critical = true;
    }
    z.array = this.getGeneralNames(A);
    return z;
  };
  this.getGeneralNames = function (D) {
    var B = s(D, 0);
    var z = [];
    for (var C = 0; C < B.length; C++) {
      var A = this.getGeneralName(b(D, B[C]));
      if (A !== undefined) {
        z.push(A);
      }
    }
    return z;
  };
  this.getGeneralName = function (A) {
    var z = A.substr(0, 2);
    var C = k(A, 0);
    var B = hextorstr(C);
    if (z == "81") {
      return {
        rfc822: B
      };
    }
    if (z == "82") {
      return {
        dns: B
      };
    }
    if (z == "86") {
      return {
        uri: B
      };
    }
    if (z == "87") {
      return {
        ip: hextoip(C)
      };
    }
    if (z == "a4") {
      return {
        dn: this.getX500Name(C)
      };
    }
    if (z == "a0") {
      return {
        other: this.getOtherName(A)
      };
    }
    return undefined;
  };
  this.getExtSubjectAltName2 = function () {
    var D, G, F;
    var E = this.getExtInfo("subjectAltName");
    if (E === undefined) {
      return E;
    }
    var z = new Array();
    var C = b(this.hex, E.vidx);
    var A = s(C, 0);
    for (var B = 0; B < A.length; B++) {
      F = C.substr(A[B], 2);
      D = k(C, A[B]);
      if (F === "81") {
        G = hextoutf8(D);
        z.push(["MAIL", G]);
      }
      if (F === "82") {
        G = hextoutf8(D);
        z.push(["DNS", G]);
      }
      if (F === "84") {
        G = X509.hex2dn(D, 0);
        z.push(["DN", G]);
      }
      if (F === "86") {
        G = hextoutf8(D);
        z.push(["URI", G]);
      }
      if (F === "87") {
        G = hextoip(D);
        z.push(["IP", G]);
      }
    }
    return z;
  };
  this.getExtCRLDistributionPoints = function (D, F) {
    if (D === undefined && F === undefined) {
      var E = this.getExtInfo("cRLDistributionPoints");
      if (E === undefined) {
        return undefined;
      }
      D = b(this.hex, E.vidx);
      F = E.critical;
    }
    var A = {
      extname: "cRLDistributionPoints",
      array: []
    };
    if (F) {
      A.critical = true;
    }
    var B = s(D, 0);
    for (var C = 0; C < B.length; C++) {
      var z = b(D, B[C]);
      A.array.push(this.getDistributionPoint(z));
    }
    return A;
  };
  this.getDistributionPoint = function (E) {
    var B = {};
    var C = s(E, 0);
    for (var D = 0; D < C.length; D++) {
      var A = E.substr(C[D], 2);
      var z = b(E, C[D]);
      if (A == "a0") {
        B.dpname = this.getDistributionPointName(z);
      }
    }
    return B;
  };
  this.getDistributionPointName = function (E) {
    var B = {};
    var C = s(E, 0);
    for (var D = 0; D < C.length; D++) {
      var A = E.substr(C[D], 2);
      var z = b(E, C[D]);
      if (A == "a0") {
        B.full = this.getGeneralNames(z);
      }
    }
    return B;
  };
  this.getExtCRLDistributionPointsURI = function () {
    var D = this.getExtCRLDistributionPoints();
    if (D == undefined) {
      return D;
    }
    var A = D.array;
    var z = [];
    for (var C = 0; C < A.length; C++) {
      try {
        if (A[C].dpname.full[0].uri != undefined) {
          z.push(A[C].dpname.full[0].uri);
        }
      } catch (B) {}
    }
    return z;
  };
  this.getExtAIAInfo = function () {
    var D = this.getExtInfo("authorityInfoAccess");
    if (D === undefined) {
      return D;
    }
    var z = {
      ocsp: [],
      caissuer: []
    };
    var A = s(this.hex, D.vidx);
    for (var B = 0; B < A.length; B++) {
      var E = c(this.hex, A[B], [0], "06");
      var C = c(this.hex, A[B], [1], "86");
      if (E === "2b06010505073001") {
        z.ocsp.push(hextoutf8(C));
      }
      if (E === "2b06010505073002") {
        z.caissuer.push(hextoutf8(C));
      }
    }
    return z;
  };
  this.getExtAuthorityInfoAccess = function (G, E) {
    if (G === undefined && E === undefined) {
      var z = this.getExtInfo("authorityInfoAccess");
      if (z === undefined) {
        return undefined;
      }
      G = b(this.hex, z.vidx);
      E = z.critical;
    }
    var H = {
      extname: "authorityInfoAccess",
      array: []
    };
    if (E) {
      H.critical = true;
    }
    var F = s(G, 0);
    for (var A = 0; A < F.length; A++) {
      var D = p(G, F[A], [0], "06");
      var B = c(G, F[A], [1], "86");
      var C = hextoutf8(B);
      if (D == "2b06010505073001") {
        H.array.push({
          ocsp: C
        });
      } else {
        if (D == "2b06010505073002") {
          H.array.push({
            caissuer: C
          });
        } else {
          throw new Error("unknown method: " + D);
        }
      }
    }
    return H;
  };
  this.getExtCertificatePolicies = function (D, G) {
    if (D === undefined && G === undefined) {
      var F = this.getExtInfo("certificatePolicies");
      if (F === undefined) {
        return undefined;
      }
      D = b(this.hex, F.vidx);
      G = F.critical;
    }
    var z = {
      extname: "certificatePolicies",
      array: []
    };
    if (G) {
      z.critical = true;
    }
    var A = s(D, 0);
    for (var B = 0; B < A.length; B++) {
      var E = b(D, A[B]);
      var C = this.getPolicyInformation(E);
      z.array.push(C);
    }
    return z;
  };
  this.getPolicyInformation = function (D) {
    var z = {};
    var F = c(D, 0, [0], "06");
    z.policyoid = u(F);
    var G = f(D, 0, [1], "30");
    if (G != -1) {
      z.array = [];
      var A = s(D, G);
      for (var B = 0; B < A.length; B++) {
        var E = b(D, A[B]);
        var C = this.getPolicyQualifierInfo(E);
        z.array.push(C);
      }
    }
    return z;
  };
  this.getOtherName = function (B) {
    var z = {};
    var A = s(B, 0);
    var D = c(B, A[0], [], "06");
    var C = c(B, A[1], []);
    z.oid = u(D);
    z.value = j(C);
    return z;
  };
  this.getPolicyQualifierInfo = function (A) {
    var z = {};
    var B = c(A, 0, [0], "06");
    if (B === "2b06010505070201") {
      var D = p(A, 0, [1], "16");
      z.cps = hextorstr(D);
    } else {
      if (B === "2b06010505070202") {
        var C = a(A, 0, [1], "30");
        z.unotice = this.getUserNotice(C);
      }
    }
    return z;
  };
  this.getUserNotice = function (B) {
    var D = null;
    var z = {};
    try {
      D = o.parse(B);
      var C = this._asn1ToUnotice(D);
      return C;
    } catch (A) {
      return undefined;
    }
  };
  this._asn1ToUnotice = function (E) {
    try {
      var z = {};
      var A = aryval(E, "seq");
      for (var C = 0; C < A.length; C++) {
        var D = this._asn1ToNoticeRef(A[C]);
        if (D != undefined) {
          z.noticeref = D;
        }
        var F = this.asn1ToDisplayText(A[C]);
        if (F != undefined) {
          z.exptext = F;
        }
      }
      if (Object.keys(z).length > 0) {
        return z;
      }
      return undefined;
    } catch (B) {
      return undefined;
    }
  };
  this._asn1ToNoticeRef = function (F) {
    try {
      var A = {};
      var B = aryval(F, "seq");
      for (var D = 0; D < B.length; D++) {
        var E = this._asn1ToNoticeNum(B[D]);
        if (E != undefined) {
          A.noticenum = E;
        }
        var z = this.asn1ToDisplayText(B[D]);
        if (z != undefined) {
          A.org = z;
        }
      }
      if (Object.keys(A).length > 0) {
        return A;
      }
      return undefined;
    } catch (C) {
      return undefined;
    }
  };
  this._asn1ToNoticeNum = function (E) {
    try {
      var A = aryval(E, "seq");
      var z = [];
      for (var C = 0; C < A.length; C++) {
        var D = A[C];
        z.push(parseInt(aryval(D, "int.hex"), 16));
      }
      return z;
    } catch (B) {
      return undefined;
    }
  };
  this.getDisplayText = function (A) {
    var B = {
      "0c": "utf8",
      "16": "ia5",
      "1a": "vis",
      "1e": "bmp"
    };
    var z = {};
    z.type = B[A.substr(0, 2)];
    z.str = hextorstr(k(A, 0));
    return z;
  };
  this.asn1ToDisplayText = function (z) {
    if (z.utf8str != undefined) {
      return {
        type: "utf8",
        str: z.utf8str.str
      };
    }
    if (z.ia5str != undefined) {
      return {
        type: "ia5",
        str: z.ia5str.str
      };
    }
    if (z.visstr != undefined) {
      return {
        type: "vis",
        str: z.visstr.str
      };
    }
    if (z.bmpstr != undefined) {
      return {
        type: "bmp",
        str: z.bmpstr.str
      };
    }
    if (z.prnstr != undefined) {
      return {
        type: "prn",
        str: z.prnstr.str
      };
    }
    return undefined;
  };
  this.getExtPolicyMappings = function (G, E) {
    var z = this.getCriticalExtV("policyMappings", G, E);
    G = z[0];
    E = z[1];
    if (G == null) {
      return undefined;
    }
    var I = {
      extname: "policyMappings"
    };
    if (E) {
      I.critical = true;
    }
    try {
      var A = j(G);
      var B = A.seq;
      var F = [];
      for (var C = 0; C < B.length; C++) {
        var H = B[C].seq;
        F.push([H[0].oid, H[1].oid]);
      }
      I.array = F;
    } catch (D) {
      throw new m("malformed policyMappings");
    }
    return I;
  };
  this.getExtPolicyConstraints = function (G, D) {
    var z = this.getCriticalExtV("policyConstraints", G, D);
    G = z[0];
    D = z[1];
    if (G == null) {
      return undefined;
    }
    var H = {
      extname: "policyConstraints"
    };
    if (D) {
      H.critical = true;
    }
    var A = j(G);
    try {
      var F = A.seq;
      for (var B = 0; B < F.length; B++) {
        var E = F[B].tag;
        if (E.explicit != false) {
          continue;
        }
        if (E.tag == "80") {
          H.reqexp = parseInt(E.hex, 16);
        }
        if (E.tag == "81") {
          H.inhibit = parseInt(E.hex, 16);
        }
      }
    } catch (C) {
      return new m("malformed policyConstraints value");
    }
    return H;
  };
  this.getExtInhibitAnyPolicy = function (A, D) {
    var C = this.getCriticalExtV("inhibitAnyPolicy", A, D);
    A = C[0];
    D = C[1];
    if (A == null) {
      return undefined;
    }
    var z = {
      extname: "inhibitAnyPolicy"
    };
    if (D) {
      z.critical = true;
    }
    var B = x(A, 0);
    if (B == -1) {
      return new m("wrong value");
    }
    z.skip = B;
    return z;
  };
  this.getExtCRLNumber = function (A, B) {
    var z = {
      extname: "cRLNumber"
    };
    if (B) {
      z.critical = true;
    }
    if (A.substr(0, 2) == "02") {
      z.num = {
        hex: k(A, 0)
      };
      return z;
    }
    throw new m("hExtV parse error: " + A);
  };
  this.getExtCRLReason = function (A, B) {
    var z = {
      extname: "cRLReason"
    };
    if (B) {
      z.critical = true;
    }
    if (A.substr(0, 2) == "0a") {
      z.code = parseInt(k(A, 0), 16);
      return z;
    }
    throw new Error("hExtV parse error: " + A);
  };
  this.getExtOcspNonce = function (A, C) {
    var z = {
      extname: "ocspNonce"
    };
    if (C) {
      z.critical = true;
    }
    var B = k(A, 0);
    z.hex = B;
    return z;
  };
  this.getExtOcspNoCheck = function (A, B) {
    var z = {
      extname: "ocspNoCheck"
    };
    if (B) {
      z.critical = true;
    }
    return z;
  };
  this.getExtAdobeTimeStamp = function (C, F) {
    if (C === undefined && F === undefined) {
      var E = this.getExtInfo("adobeTimeStamp");
      if (E === undefined) {
        return undefined;
      }
      C = b(this.hex, E.vidx);
      F = E.critical;
    }
    var z = {
      extname: "adobeTimeStamp"
    };
    if (F) {
      z.critical = true;
    }
    var B = s(C, 0);
    if (B.length > 1) {
      var G = b(C, B[1]);
      var A = this.getGeneralName(G);
      if (A.uri != undefined) {
        z.uri = A.uri;
      }
    }
    if (B.length > 2) {
      var D = b(C, B[2]);
      if (D == "0101ff") {
        z.reqauth = true;
      }
      if (D == "010100") {
        z.reqauth = false;
      }
    }
    return z;
  };
  this.getExtSubjectDirectoryAttributes = function (I, H) {
    if (I === undefined && H === undefined) {
      var B = this.getExtInfo("subjectDirectoryAttributes");
      if (B === undefined) {
        return undefined;
      }
      I = b(this.hex, B.vidx);
      H = B.critical;
    }
    var J = {
      extname: "subjectDirectoryAttributes"
    };
    if (H) {
      J.critical = true;
    }
    try {
      var z = j(I);
      var D = [];
      for (var E = 0; E < z.seq.length; E++) {
        var A = z.seq[E];
        var C = aryval(A, "seq.0.oid");
        var F = aryval(A, "seq.1.set");
        if (C == undefined || F == undefined) {
          throw "error";
        }
        D.push({
          attr: C,
          array: F
        });
      }
      J.array = D;
      return J;
    } catch (G) {
      throw new Error("malformed subjectDirectoryAttributes extension value");
    }
  };
  var e = function (E) {
    var z = {};
    try {
      var B = E.seq[0].oid;
      var D = KJUR.asn1.x509.OID.name2oid(B);
      z.type = KJUR.asn1.x509.OID.oid2atype(D);
      var A = E.seq[1];
      if (A.utf8str != undefined) {
        z.ds = "utf8";
        z.value = A.utf8str.str;
      } else {
        if (A.numstr != undefined) {
          z.ds = "num";
          z.value = A.numstr.str;
        } else {
          if (A.telstr != undefined) {
            z.ds = "tel";
            z.value = A.telstr.str;
          } else {
            if (A.prnstr != undefined) {
              z.ds = "prn";
              z.value = A.prnstr.str;
            } else {
              if (A.ia5str != undefined) {
                z.ds = "ia5";
                z.value = A.ia5str.str;
              } else {
                if (A.visstr != undefined) {
                  z.ds = "vis";
                  z.value = A.visstr.str;
                } else {
                  if (A.bmpstr != undefined) {
                    z.ds = "bmp";
                    z.value = A.bmpstr.str;
                  } else {
                    throw "error";
                  }
                }
              }
            }
          }
        }
      }
      return z;
    } catch (C) {
      throw new Erorr("improper ASN.1 parsed AttrTypeAndValue");
    }
  };
  var i = function (A) {
    try {
      return A.set.map(function (B) {
        return e(B);
      });
    } catch (z) {
      throw new Error("improper ASN.1 parsed RDN: " + z);
    }
  };
  var h = function (A) {
    try {
      return A.seq.map(function (B) {
        return i(B);
      });
    } catch (z) {
      throw new Error("improper ASN.1 parsed X500Name: " + z);
    }
  };
  this.getX500NameRule = function (z) {
    var G = true;
    var K = true;
    var J = false;
    var A = "";
    var D = "";
    var M = null;
    var H = [];
    for (var C = 0; C < z.length; C++) {
      var E = z[C];
      for (var B = 0; B < E.length; B++) {
        H.push(E[B]);
      }
    }
    for (var C = 0; C < H.length; C++) {
      var L = H[C];
      var N = L.ds;
      var I = L.value;
      var F = L.type;
      A += ":" + N;
      if (N != "prn" && N != "utf8" && N != "ia5") {
        return "mixed";
      }
      if (N == "ia5") {
        if (F != "CN") {
          return "mixed";
        } else {
          if (!KJUR.lang.String.isMail(I)) {
            return "mixed";
          } else {
            continue;
          }
        }
      }
      if (F == "C") {
        if (N == "prn") {
          continue;
        } else {
          return "mixed";
        }
      }
      D += ":" + N;
      if (M == null) {
        M = N;
      } else {
        if (M !== N) {
          return "mixed";
        }
      }
    }
    if (M == null) {
      return "prn";
    } else {
      return M;
    }
  };
  this.getAttrTypeAndValue = function (z) {
    var A = j(z);
    return e(A);
  };
  this.getRDN = function (z) {
    var A = j(z);
    return i(A);
  };
  this.getX500NameArray = function (z) {
    var A = j(z);
    return h(A);
  };
  this.getX500Name = function (C, E, D) {
    var A = this.getX500NameArray(C);
    var B = this.dnarraytostr(A);
    var z = {
      str: B
    };
    z.array = A;
    if (D == true) {
      z.hex = C;
    }
    if (E == true) {
      z.canon = this.c14nRDNArray(A);
    }
    return z;
  };
  this.readCertPEM = function (z) {
    this.readCertHex(w(z));
  };
  this.readCertHex = function (z) {
    this.hex = z;
    this.getVersion();
    try {
      l(this.hex, 0, [0, 7], "a3");
      this.parseExt();
    } catch (A) {}
  };
  this.getParam = function (A) {
    var z = {};
    if (A == undefined) {
      A = {};
    }
    z.version = this.getVersion();
    z.serial = {
      hex: this.getSerialNumberHex()
    };
    z.sigalg = this.getSignatureAlgorithmField();
    z.issuer = this.getIssuer(A.dncanon, A.dnhex);
    z.notbefore = this.getNotBefore();
    z.notafter = this.getNotAfter();
    z.subject = this.getSubject(A.dncanon, A.dnhex);
    z.sbjpubkey = hextopem(this.getPublicKeyHex(), "PUBLIC KEY");
    if (this.aExtInfo != undefined && this.aExtInfo.length > 0) {
      z.ext = this.getExtParamArray();
    }
    z.sighex = this.getSignatureValueHex();
    if (A.tbshex == true) {
      z.tbshex = a(this.hex, 0, [0]);
    }
    if (A.nodnarray == true) {
      delete z.issuer.array;
      delete z.subject.array;
    }
    return z;
  };
  this.getExtParamArray = function (A) {
    if (A == undefined) {
      var C = f(this.hex, 0, [0, "[3]"]);
      if (C != -1) {
        A = q(this.hex, 0, [0, "[3]", 0], "30");
      }
    }
    var z = [];
    var B = s(A, 0);
    for (var D = 0; D < B.length; D++) {
      var F = b(A, B[D]);
      var E = this.getExtParam(F);
      if (E != null) {
        z.push(E);
      }
    }
    return z;
  };
  this.getExtParam = function (A) {
    var I = {};
    var C = s(A, 0);
    var E = C.length;
    if (E != 2 && E != 3) {
      throw new Error("wrong number elements in Extension: " + E + " " + A);
    }
    var B = r(c(A, 0, [0], "06"));
    var G = false;
    if (E == 3 && a(A, 0, [1]) == "0101ff") {
      G = true;
    }
    var H = a(A, 0, [E - 1, 0]);
    var F = undefined;
    if (B == "2.5.29.14") {
      F = this.getExtSubjectKeyIdentifier(H, G);
    } else {
      if (B == "2.5.29.15") {
        F = this.getExtKeyUsage(H, G);
      } else {
        if (B == "2.5.29.17") {
          F = this.getExtSubjectAltName(H, G);
        } else {
          if (B == "2.5.29.18") {
            F = this.getExtIssuerAltName(H, G);
          } else {
            if (B == "2.5.29.19") {
              F = this.getExtBasicConstraints(H, G);
            } else {
              if (B == "2.5.29.30") {
                F = this.getExtNameConstraints(H, G);
              } else {
                if (B == "2.5.29.31") {
                  F = this.getExtCRLDistributionPoints(H, G);
                } else {
                  if (B == "2.5.29.32") {
                    F = this.getExtCertificatePolicies(H, G);
                  } else {
                    if (B == "2.5.29.33") {
                      F = this.getExtPolicyMappings(H, G);
                    } else {
                      if (B == "2.5.29.35") {
                        F = this.getExtAuthorityKeyIdentifier(H, G);
                      } else {
                        if (B == "2.5.29.36") {
                          F = this.getExtPolicyConstraints(H, G);
                        } else {
                          if (B == "2.5.29.37") {
                            F = this.getExtExtKeyUsage(H, G);
                          } else {
                            if (B == "2.5.29.54") {
                              F = this.getExtInhibitAnyPolicy(H, G);
                            } else {
                              if (B == "1.3.6.1.5.5.7.1.1") {
                                F = this.getExtAuthorityInfoAccess(H, G);
                              } else {
                                if (B == "2.5.29.20") {
                                  F = this.getExtCRLNumber(H, G);
                                } else {
                                  if (B == "2.5.29.21") {
                                    F = this.getExtCRLReason(H, G);
                                  } else {
                                    if (B == "2.5.29.9") {
                                      F = this.getExtSubjectDirectoryAttributes(H, G);
                                    } else {
                                      if (B == "1.3.6.1.5.5.7.48.1.2") {
                                        F = this.getExtOcspNonce(H, G);
                                      } else {
                                        if (B == "1.3.6.1.5.5.7.48.1.5") {
                                          F = this.getExtOcspNoCheck(H, G);
                                        } else {
                                          if (B == "1.2.840.113583.1.1.9.1") {
                                            F = this.getExtAdobeTimeStamp(H, G);
                                          } else {
                                            if (X509.EXT_PARSER[B] != undefined) {
                                              F = X509.EXT_PARSER[B](B, G, H);
                                            }
                                          }
                                        }
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    if (F != undefined) {
      return F;
    }
    var z = {
      extname: B,
      extn: H
    };
    try {
      z.extn = j(H);
    } catch (D) {}
    if (G) {
      z.critical = true;
    }
    return z;
  };
  this.findExt = function (A, B) {
    for (var z = 0; z < A.length; z++) {
      if (A[z].extname == B) {
        return A[z];
      }
    }
    return null;
  };
  this.updateExtCDPFullURI = function (D, z) {
    var C = this.findExt(D, "cRLDistributionPoints");
    if (C == null) {
      return;
    }
    if (C.array == undefined) {
      return;
    }
    var F = C.array;
    for (var B = 0; B < F.length; B++) {
      if (F[B].dpname == undefined) {
        continue;
      }
      if (F[B].dpname.full == undefined) {
        continue;
      }
      var G = F[B].dpname.full;
      for (var A = 0; A < G.length; A++) {
        var E = G[B];
        if (E.uri == undefined) {
          continue;
        }
        E.uri = z;
      }
    }
  };
  this.updateExtAIAOCSP = function (D, A) {
    var C = this.findExt(D, "authorityInfoAccess");
    if (C == null) {
      return;
    }
    if (C.array == undefined) {
      return;
    }
    var z = C.array;
    for (var B = 0; B < z.length; B++) {
      if (z[B].ocsp != undefined) {
        z[B].ocsp = A;
      }
    }
  };
  this.updateExtAIACAIssuer = function (D, A) {
    var C = this.findExt(D, "authorityInfoAccess");
    if (C == null) {
      return;
    }
    if (C.array == undefined) {
      return;
    }
    var z = C.array;
    for (var B = 0; B < z.length; B++) {
      if (z[B].caissuer != undefined) {
        z[B].caissuer = A;
      }
    }
  };
  this.dnarraytostr = function (B) {
    function z(C) {
      return C.map(function (D) {
        return A(D).replace(/\+/, "\\+");
      }).join("+");
    }
    function A(C) {
      return C.type + "=" + C.value;
    }
    return "/" + B.map(function (C) {
      return z(C).replace(/\//, "\\/");
    }).join("/");
  };
  this.setCanonicalizedDN = function (A) {
    var C;
    if (A.str != undefined && A.array == undefined) {
      var B = new KJUR.asn1.x509.X500Name({
        str: A.str
      });
      var z = B.tohex();
      C = this.getX500NameArray(z);
    } else {
      C = A.array;
    }
    if (A.canon == undefined) {
      A.canon = this.c14nRDNArray(C);
    }
  };
  this.c14nRDNArray = function (G) {
    var A = [];
    for (var C = 0; C < G.length; C++) {
      var E = G[C];
      var z = [];
      for (var B = 0; B < E.length; B++) {
        var D = E[B];
        var F = D.value;
        F = F.replace(/^\s*/, "");
        F = F.replace(/\s*$/, "");
        F = F.replace(/\s+/g, " ");
        F = F.toLowerCase();
        z.push(D.type.toLowerCase() + "=" + F);
      }
      A.push(z.join("+"));
    }
    return "/" + A.join("/");
  };
  this.getInfo = function () {
    var A = function (W) {
      var ac = "";
      var U = "    ";
      var Y = "\n";
      var Z = W.array;
      for (var X = 0; X < Z.length; X++) {
        var V = Z[X];
        if (V.dn != undefined) {
          ac += U + "dn: " + V.dn.str + Y;
        }
        if (V.ip != undefined) {
          ac += U + "ip: " + V.ip + Y;
        }
        if (V.rfc822 != undefined) {
          ac += U + "rfc822: " + V.rfc822 + Y;
        }
        if (V.dns != undefined) {
          ac += U + "dns: " + V.dns + Y;
        }
        if (V.uri != undefined) {
          ac += U + "uri: " + V.uri + Y;
        }
        if (V.other != undefined) {
          var ab = V.other.oid;
          var aa = JSON.stringify(V.other.value).replace(/\"/g, "");
          ac += U + "other: " + ab + "=" + aa + Y;
        }
      }
      ac = ac.replace(/\n$/, "");
      return ac;
    };
    var H = function (aa) {
      var Y = "";
      var U = aa.array;
      for (var X = 0; X < U.length; X++) {
        var Z = U[X];
        Y += "    policy oid: " + Z.policyoid + "\n";
        if (Z.array === undefined) {
          continue;
        }
        for (var W = 0; W < Z.array.length; W++) {
          var V = Z.array[W];
          if (V.cps !== undefined) {
            Y += "    cps: " + V.cps + "\n";
          }
        }
      }
      return Y;
    };
    var K = function (Y) {
      var X = "";
      var U = Y.array;
      for (var W = 0; W < U.length; W++) {
        var Z = U[W];
        try {
          if (Z.dpname.full[0].uri !== undefined) {
            X += "    " + Z.dpname.full[0].uri + "\n";
          }
        } catch (V) {}
        try {
          if (Z.dname.full[0].dn.hex !== undefined) {
            X += "    " + X509.hex2dn(Z.dpname.full[0].dn.hex) + "\n";
          }
        } catch (V) {}
      }
      return X;
    };
    var I = function (Y) {
      var X = "";
      var U = Y.array;
      for (var V = 0; V < U.length; V++) {
        var W = U[V];
        if (W.caissuer !== undefined) {
          X += "    caissuer: " + W.caissuer + "\n";
        }
        if (W.ocsp !== undefined) {
          X += "    ocsp: " + W.ocsp + "\n";
        }
      }
      return X;
    };
    var B = X509;
    var M, L, T;
    M = "Basic Fields\n";
    M += "  serial number: " + this.getSerialNumberHex() + "\n";
    M += "  signature algorithm: " + this.getSignatureAlgorithmField() + "\n";
    M += "  issuer: " + this.getIssuerString() + "\n";
    M += "  notBefore: " + this.getNotBefore() + "\n";
    M += "  notAfter: " + this.getNotAfter() + "\n";
    M += "  subject: " + this.getSubjectString() + "\n";
    M += "  subject public key info: \n";
    L = this.getPublicKey();
    M += "    key algorithm: " + L.type + "\n";
    if (L.type === "RSA") {
      M += "    n=" + hextoposhex(L.n.toString(16)).substr(0, 16) + "...\n";
      M += "    e=" + hextoposhex(L.e.toString(16)) + "\n";
    }
    T = this.aExtInfo;
    if (T !== undefined && T !== null) {
      M += "X509v3 Extensions:\n";
      for (var P = 0; P < T.length; P++) {
        var R = T[P];
        var z = KJUR.asn1.x509.OID.oid2name(R.oid);
        if (z === "") {
          z = R.oid;
        }
        var O = "";
        if (R.critical === true) {
          O = "CRITICAL";
        }
        M += "  " + z + " " + O + ":\n";
        if (z === "basicConstraints") {
          var C = this.getExtBasicConstraints();
          if (C.cA === undefined) {
            M += "    {}\n";
          } else {
            M += "    cA=true";
            if (C.pathLen !== undefined) {
              M += ", pathLen=" + C.pathLen;
            }
            M += "\n";
          }
        } else {
          if (z == "policyMappings") {
            var S = this.getExtPolicyMappings().array;
            var G = S.map(function (U) {
              var V = U;
              return V[0] + ":" + V[1];
            }).join(", ");
            M += "    " + G + "\n";
          } else {
            if (z == "policyConstraints") {
              var N = this.getExtPolicyConstraints();
              M += "    ";
              if (N.reqexp != undefined) {
                M += " reqexp=" + N.reqexp;
              }
              if (N.inhibit != undefined) {
                M += " inhibit=" + N.inhibit;
              }
              M += "\n";
            } else {
              if (z == "inhibitAnyPolicy") {
                var N = this.getExtInhibitAnyPolicy();
                M += "    skip=" + N.skip + "\n";
              } else {
                if (z == "keyUsage") {
                  M += "    " + this.getExtKeyUsageString() + "\n";
                } else {
                  if (z == "subjectKeyIdentifier") {
                    M += "    " + this.getExtSubjectKeyIdentifier().kid.hex + "\n";
                  } else {
                    if (z == "authorityKeyIdentifier") {
                      var D = this.getExtAuthorityKeyIdentifier();
                      if (D.kid !== undefined) {
                        M += "    kid=" + D.kid.hex + "\n";
                      }
                    } else {
                      if (z == "extKeyUsage") {
                        var Q = this.getExtExtKeyUsage().array;
                        M += "    " + Q.join(", ") + "\n";
                      } else {
                        if (z == "subjectAltName") {
                          var E = A(this.getExtSubjectAltName());
                          M += E + "\n";
                        } else {
                          if (z == "cRLDistributionPoints") {
                            var J = this.getExtCRLDistributionPoints();
                            M += K(J);
                          } else {
                            if (z == "authorityInfoAccess") {
                              var F = this.getExtAuthorityInfoAccess();
                              M += I(F);
                            } else {
                              if (z == "certificatePolicies") {
                                M += H(this.getExtCertificatePolicies());
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    M += "signature algorithm: " + this.getSignatureAlgorithmName() + "\n";
    M += "signature: " + this.getSignatureValueHex().substr(0, 16) + "...\n";
    return M;
  };
  if (typeof v == "string") {
    if (v.indexOf("-----BEGIN") != -1) {
      this.readCertPEM(v);
    } else {
      if (KJUR.lang.String.isHex(v)) {
        this.readCertHex(v);
      }
    }
  }
}
X509.EXT_PARSER = {};
X509.registExtParser = function (b, a) {
  X509.EXT_PARSER[b] = a;
};
X509.hex2dn = function (e, b) {
  if (b === undefined) {
    b = 0;
  }
  var a = new X509();
  var c = ASN1HEX.getTLV(e, b);
  var d = a.getX500Name(e);
  return d.str;
};
X509.hex2rdn = function (f, b) {
  if (b === undefined) {
    b = 0;
  }
  if (f.substr(b, 2) !== "31") {
    throw new Error("malformed RDN");
  }
  var c = new Array();
  var d = ASN1HEX.getChildIdx(f, b);
  for (var e = 0; e < d.length; e++) {
    c.push(X509.hex2attrTypeValue(f, d[e]));
  }
  c = c.map(function (a) {
    return a.replace("+", "\\+");
  });
  return c.join("+");
};
X509.hex2attrTypeValue = function (d, i) {
  var j = ASN1HEX;
  var h = j.getV;
  if (i === undefined) {
    i = 0;
  }
  if (d.substr(i, 2) !== "30") {
    throw new Error("malformed attribute type and value");
  }
  var g = j.getChildIdx(d, i);
  if (g.length !== 2 || d.substr(g[0], 2) !== "06") {
    "malformed attribute type and value";
  }
  var b = h(d, g[0]);
  var f = KJUR.asn1.ASN1Util.oidHexToInt(b);
  var e = KJUR.asn1.x509.OID.oid2atype(f);
  var a = h(d, g[1]);
  var c = hextorstr(a);
  return e + "=" + c;
};
X509.getPublicKeyFromCertHex = function (b) {
  var a = new X509();
  a.readCertHex(b);
  return a.getPublicKey();
};
X509.getPublicKeyFromCertPEM = function (b) {
  var a = new X509();
  a.readCertPEM(b);
  return a.getPublicKey();
};
X509.getPublicKeyInfoPropOfCertPEM = function (c) {
  var e = ASN1HEX;
  var g = e.getVbyList;
  var b = {};
  var a, f, d;
  b.algparam = null;
  a = new X509();
  a.readCertPEM(c);
  f = a.getPublicKeyHex();
  b.keyhex = g(f, 0, [1], "03").substr(2);
  b.algoid = g(f, 0, [0, 0], "06");
  if (b.algoid === "2a8648ce3d0201") {
    b.algparam = g(f, 0, [0, 1], "06");
  }
  return b;
};
X509.KEYUSAGE_NAME = ["digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly"];
var X509CRL = function (e) {
  var a = KJUR,
    f = a.lang.String.isHex,
    m = ASN1HEX,
    k = m.getV,
    b = m.getTLV,
    h = m.getVbyList,
    c = m.getTLVbyList,
    d = m.getTLVbyListEx,
    i = m.getIdxbyList,
    g = m.getIdxbyListEx,
    l = m.getChildIdx,
    j = new X509();
  this.hex = null;
  this.posSigAlg = null;
  this.posRevCert = null;
  this.parsed = null;
  this._setPos = function () {
    var o = i(this.hex, 0, [0, 0]);
    var n = this.hex.substr(o, 2);
    if (n == "02") {
      this.posSigAlg = 1;
    } else {
      if (n == "30") {
        this.posSigAlg = 0;
      } else {
        throw new Error("malformed 1st item of TBSCertList: " + n);
      }
    }
    var s = i(this.hex, 0, [0, this.posSigAlg + 3]);
    var r = this.hex.substr(s, 2);
    if (r == "17" || r == "18") {
      var q, p;
      q = i(this.hex, 0, [0, this.posSigAlg + 4]);
      this.posRevCert = null;
      if (q != -1) {
        p = this.hex.substr(q, 2);
        if (p == "30") {
          this.posRevCert = this.posSigAlg + 4;
        }
      }
    } else {
      if (r == "30") {
        this.posRevCert = this.posSigAlg + 3;
      } else {
        if (r == "a0") {
          this.posRevCert = null;
        } else {
          throw new Error("malformed nextUpdate or revCert tag: " + r);
        }
      }
    }
  };
  this.getVersion = function () {
    if (this.posSigAlg == 0) {
      return null;
    }
    return parseInt(h(this.hex, 0, [0, 0], "02"), 16) + 1;
  };
  this.getSignatureAlgorithmField = function () {
    var n = c(this.hex, 0, [0, this.posSigAlg], "30");
    return j.getAlgorithmIdentifierName(n);
  };
  this.getIssuer = function () {
    return j.getX500Name(this.getIssuerHex());
  };
  this.getIssuerHex = function () {
    return c(this.hex, 0, [0, this.posSigAlg + 1], "30");
  };
  this.getThisUpdate = function () {
    var n = h(this.hex, 0, [0, this.posSigAlg + 2]);
    return result = hextorstr(n);
  };
  this.getNextUpdate = function () {
    var o = i(this.hex, 0, [0, this.posSigAlg + 3]);
    var n = this.hex.substr(o, 2);
    if (n != "17" && n != "18") {
      return null;
    }
    return hextorstr(k(this.hex, o));
  };
  this.getRevCertArray = function () {
    if (this.posRevCert == null) {
      return null;
    }
    var o = [];
    var n = i(this.hex, 0, [0, this.posRevCert]);
    var p = l(this.hex, n);
    for (var q = 0; q < p.length; q++) {
      var r = b(this.hex, p[q]);
      o.push(this.getRevCert(r));
    }
    return o;
  };
  this.getRevCert = function (p) {
    var o = {};
    var n = l(p, 0);
    o.sn = {
      hex: h(p, 0, [0], "02")
    };
    o.date = hextorstr(h(p, 0, [1]));
    if (n.length == 3) {
      o.ext = j.getExtParamArray(c(p, 0, [2]));
    }
    return o;
  };
  this.findRevCert = function (p) {
    var n = new X509(p);
    var o = n.getSerialNumberHex();
    return this.findRevCertBySN(o);
  };
  this.findRevCertBySN = function (o) {
    if (this.parsed == null) {
      this.getParam();
    }
    if (this.parsed.revcert == null) {
      return null;
    }
    var n = this.parsed.revcert;
    for (var p = 0; p < n.length; p++) {
      if (o == n[p].sn.hex) {
        return n[p];
      }
    }
    return null;
  };
  this.getSignatureValueHex = function () {
    return h(this.hex, 0, [2], "03", true);
  };
  this.verifySignature = function (o) {
    var p = this.getSignatureAlgorithmField();
    var n = this.getSignatureValueHex();
    var q = c(this.hex, 0, [0], "30");
    var r = new KJUR.crypto.Signature({
      alg: p
    });
    r.init(o);
    r.updateHex(q);
    return r.verify(n);
  };
  this.getParam = function (r) {
    var n = {};
    var p = this.getVersion();
    if (p != null) {
      n.version = p;
    }
    n.sigalg = this.getSignatureAlgorithmField();
    n.issuer = this.getIssuer();
    n.thisupdate = this.getThisUpdate();
    var q = this.getNextUpdate();
    if (q != null) {
      n.nextupdate = q;
    }
    var t = this.getRevCertArray();
    if (t != null) {
      n.revcert = t;
    }
    var s = g(this.hex, 0, [0, "[0]"]);
    if (s != -1) {
      var o = d(this.hex, 0, [0, "[0]", 0]);
      n.ext = j.getExtParamArray(o);
    }
    n.sighex = this.getSignatureValueHex();
    this.parsed = n;
    if (typeof r == "object") {
      if (r.tbshex == true) {
        n.tbshex = c(this.hex, 0, [0]);
      }
      if (r.nodnarray == true) {
        delete n.issuer.array;
      }
    }
    return n;
  };
  if (typeof e == "string") {
    if (f(e)) {
      this.hex = e;
    } else {
      if (e.match(/-----BEGIN X509 CRL/)) {
        this.hex = pemtohex(e);
      }
    }
    this._setPos();
  }
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.jws == "undefined" || !KJUR.jws) {
  KJUR.jws = {};
}
KJUR.jws.JWS = function () {
  var b = KJUR,
    a = b.jws.JWS,
    c = a.isSafeJSONString;
  this.parseJWS = function (g, j) {
    if (this.parsedJWS !== undefined && (j || this.parsedJWS.sigvalH !== undefined)) {
      return;
    }
    var i = g.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
    if (i == null) {
      throw "JWS signature is not a form of 'Head.Payload.SigValue'.";
    }
    var k = i[1];
    var e = i[2];
    var l = i[3];
    var n = k + "." + e;
    this.parsedJWS = {};
    this.parsedJWS.headB64U = k;
    this.parsedJWS.payloadB64U = e;
    this.parsedJWS.sigvalB64U = l;
    this.parsedJWS.si = n;
    if (!j) {
      var h = b64utohex(l);
      var f = parseBigInt(h, 16);
      this.parsedJWS.sigvalH = h;
      this.parsedJWS.sigvalBI = f;
    }
    var d = b64utoutf8(k);
    var m = b64utoutf8(e);
    this.parsedJWS.headS = d;
    this.parsedJWS.payloadS = m;
    if (!c(d, this.parsedJWS, "headP")) {
      throw "malformed JSON string for JWS Head: " + d;
    }
  };
};
KJUR.jws.JWS.sign = function (j, w, z, A, a) {
  var x = KJUR,
    n = x.jws,
    r = n.JWS,
    h = r.readSafeJSONString,
    q = r.isSafeJSONString,
    d = x.crypto,
    l = d.ECDSA,
    p = d.Mac,
    c = d.Signature,
    u = JSON;
  var t, k, o;
  if (typeof w != "string" && typeof w != "object") {
    throw "spHeader must be JSON string or object: " + w;
  }
  if (typeof w == "object") {
    k = w;
    t = u.stringify(k);
  }
  if (typeof w == "string") {
    t = w;
    if (!q(t)) {
      throw "JWS Head is not safe JSON string: " + t;
    }
    k = h(t);
  }
  o = z;
  if (typeof z == "object") {
    o = u.stringify(z);
  }
  if ((j == "" || j == null) && k.alg !== undefined) {
    j = k.alg;
  }
  if (j != "" && j != null && k.alg === undefined) {
    k.alg = j;
    t = u.stringify(k);
  }
  if (j !== k.alg) {
    throw "alg and sHeader.alg doesn't match: " + j + "!=" + k.alg;
  }
  var s = null;
  if (r.jwsalg2sigalg[j] === undefined) {
    throw "unsupported alg name: " + j;
  } else {
    s = r.jwsalg2sigalg[j];
  }
  var e = utf8tob64u(t);
  var m = utf8tob64u(o);
  var b = e + "." + m;
  var y = "";
  if (s.substr(0, 4) == "Hmac") {
    if (A === undefined) {
      throw "mac key shall be specified for HS* alg";
    }
    var i = new p({
      alg: s,
      prov: "cryptojs",
      pass: A
    });
    i.updateString(b);
    y = i.doFinal();
  } else {
    if (s.indexOf("withECDSA") != -1) {
      var f = new c({
        alg: s
      });
      f.init(A, a);
      f.updateString(b);
      var g = f.sign();
      y = KJUR.crypto.ECDSA.asn1SigToConcatSig(g);
    } else {
      if (s != "none") {
        var f = new c({
          alg: s
        });
        f.init(A, a);
        f.updateString(b);
        y = f.sign();
      }
    }
  }
  var v = hextob64u(y);
  return b + "." + v;
};
KJUR.jws.JWS.verify = function (w, B, n) {
  var x = KJUR,
    q = x.jws,
    t = q.JWS,
    i = t.readSafeJSONString,
    e = x.crypto,
    p = e.ECDSA,
    s = e.Mac,
    d = e.Signature,
    m;
  if (typeof RSAKey !== undefined) {
    m = RSAKey;
  }
  if (!isBase64URLDot(w)) {
    return false;
  }
  var y = w.split(".");
  if (y.length !== 3) {
    return false;
  }
  var f = y[0];
  var r = y[1];
  var c = f + "." + r;
  var A = b64utohex(y[2]);
  var l = i(b64utoutf8(y[0]));
  var k = null;
  var z = null;
  if (l.alg === undefined) {
    throw "algorithm not specified in header";
  } else {
    k = l.alg;
    z = k.substr(0, 2);
  }
  if (n != null && Object.prototype.toString.call(n) === "[object Array]" && n.length > 0) {
    var b = ":" + n.join(":") + ":";
    if (b.indexOf(":" + k + ":") == -1) {
      throw "algorithm '" + k + "' not accepted in the list";
    }
  }
  if (k != "none" && B === null) {
    throw "key shall be specified to verify.";
  }
  if (typeof B == "string" && B.indexOf("-----BEGIN ") != -1) {
    B = KEYUTIL.getKey(B);
  }
  if (z == "RS" || z == "PS") {
    if (!(B instanceof m)) {
      throw "key shall be a RSAKey obj for RS* and PS* algs";
    }
  }
  if (z == "ES") {
    if (!(B instanceof p)) {
      throw "key shall be a ECDSA obj for ES* algs";
    }
  }
  if (k == "none") {}
  var u = null;
  if (t.jwsalg2sigalg[l.alg] === undefined) {
    throw "unsupported alg name: " + k;
  } else {
    u = t.jwsalg2sigalg[k];
  }
  if (u == "none") {
    throw "not supported";
  } else {
    if (u.substr(0, 4) == "Hmac") {
      var o = null;
      if (B === undefined) {
        throw "hexadecimal key shall be specified for HMAC";
      }
      var j = new s({
        alg: u,
        pass: B
      });
      j.updateString(c);
      o = j.doFinal();
      return A == o;
    } else {
      if (u.indexOf("withECDSA") != -1) {
        var h = null;
        try {
          h = p.concatSigToASN1Sig(A);
        } catch (v) {
          return false;
        }
        var g = new d({
          alg: u
        });
        g.init(B);
        g.updateString(c);
        return g.verify(h);
      } else {
        var g = new d({
          alg: u
        });
        g.init(B);
        g.updateString(c);
        return g.verify(A);
      }
    }
  }
};
KJUR.jws.JWS.parse = function (g) {
  var c = g.split(".");
  var b = {};
  var f, e, d;
  if (c.length != 2 && c.length != 3) {
    throw "malformed sJWS: wrong number of '.' splitted elements";
  }
  f = c[0];
  e = c[1];
  if (c.length == 3) {
    d = c[2];
  }
  b.headerObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(f));
  b.payloadObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(e));
  b.headerPP = JSON.stringify(b.headerObj, null, "  ");
  if (b.payloadObj == null) {
    b.payloadPP = b64utoutf8(e);
  } else {
    b.payloadPP = JSON.stringify(b.payloadObj, null, "  ");
  }
  if (d !== undefined) {
    b.sigHex = b64utohex(d);
  }
  return b;
};
KJUR.jws.JWS.verifyJWT = function (e, l, r) {
  var d = KJUR,
    j = d.jws,
    o = j.JWS,
    n = o.readSafeJSONString,
    p = o.inArray,
    f = o.includedArray;
  if (!isBase64URLDot(e)) {
    return false;
  }
  var k = e.split(".");
  if (k.length != 3) {
    return false;
  }
  var c = k[0];
  var i = k[1];
  var q = c + "." + i;
  var m = b64utohex(k[2]);
  var h = n(b64utoutf8(c));
  var g = n(b64utoutf8(i));
  if (h.alg === undefined) {
    return false;
  }
  if (r.alg === undefined) {
    throw "acceptField.alg shall be specified";
  }
  if (!p(h.alg, r.alg)) {
    return false;
  }
  if (g.iss !== undefined && typeof r.iss === "object") {
    if (!p(g.iss, r.iss)) {
      return false;
    }
  }
  if (g.sub !== undefined && typeof r.sub === "object") {
    if (!p(g.sub, r.sub)) {
      return false;
    }
  }
  if (g.aud !== undefined && typeof r.aud === "object") {
    if (typeof g.aud == "string") {
      if (!p(g.aud, r.aud)) {
        return false;
      }
    } else {
      if (typeof g.aud == "object") {
        if (!f(g.aud, r.aud)) {
          return false;
        }
      }
    }
  }
  var b = j.IntDate.getNow();
  if (r.verifyAt !== undefined && typeof r.verifyAt === "number") {
    b = r.verifyAt;
  }
  if (r.gracePeriod === undefined || typeof r.gracePeriod !== "number") {
    r.gracePeriod = 0;
  }
  if (g.exp !== undefined && typeof g.exp == "number") {
    if (g.exp + r.gracePeriod < b) {
      return false;
    }
  }
  if (g.nbf !== undefined && typeof g.nbf == "number") {
    if (b < g.nbf - r.gracePeriod) {
      return false;
    }
  }
  if (g.iat !== undefined && typeof g.iat == "number") {
    if (b < g.iat - r.gracePeriod) {
      return false;
    }
  }
  if (g.jti !== undefined && r.jti !== undefined) {
    if (g.jti !== r.jti) {
      return false;
    }
  }
  if (!o.verify(e, l, r.alg)) {
    return false;
  }
  return true;
};
KJUR.jws.JWS.includedArray = function (b, a) {
  var c = KJUR.jws.JWS.inArray;
  if (b === null) {
    return false;
  }
  if (typeof b !== "object") {
    return false;
  }
  if (typeof b.length !== "number") {
    return false;
  }
  for (var d = 0; d < b.length; d++) {
    if (!c(b[d], a)) {
      return false;
    }
  }
  return true;
};
KJUR.jws.JWS.inArray = function (d, b) {
  if (b === null) {
    return false;
  }
  if (typeof b !== "object") {
    return false;
  }
  if (typeof b.length !== "number") {
    return false;
  }
  for (var c = 0; c < b.length; c++) {
    if (b[c] == d) {
      return true;
    }
  }
  return false;
};
KJUR.jws.JWS.jwsalg2sigalg = {
  HS256: "HmacSHA256",
  HS384: "HmacSHA384",
  HS512: "HmacSHA512",
  RS256: "SHA256withRSA",
  RS384: "SHA384withRSA",
  RS512: "SHA512withRSA",
  ES256: "SHA256withECDSA",
  ES384: "SHA384withECDSA",
  ES512: "SHA512withECDSA",
  PS256: "SHA256withRSAandMGF1",
  PS384: "SHA384withRSAandMGF1",
  PS512: "SHA512withRSAandMGF1",
  none: "none"
};
KJUR.jws.JWS.isSafeJSONString = function (c, b, d) {
  var e = null;
  try {
    e = jsonParse(c);
    if (typeof e != "object") {
      return 0;
    }
    if (e.constructor === Array) {
      return 0;
    }
    if (b) {
      b[d] = e;
    }
    return 1;
  } catch (a) {
    return 0;
  }
};
KJUR.jws.JWS.readSafeJSONString = function (b) {
  var c = null;
  try {
    c = jsonParse(b);
    if (typeof c != "object") {
      return null;
    }
    if (c.constructor === Array) {
      return null;
    }
    return c;
  } catch (a) {
    return null;
  }
};
KJUR.jws.JWS.getEncodedSignatureValueFromJWS = function (b) {
  var a = b.match(/^[^.]+\.[^.]+\.([^.]+)$/);
  if (a == null) {
    throw "JWS signature is not a form of 'Head.Payload.SigValue'.";
  }
  return a[1];
};
KJUR.jws.JWS.getJWKthumbprint = function (d) {
  if (d.kty !== "RSA" && d.kty !== "EC" && d.kty !== "oct") {
    throw "unsupported algorithm for JWK Thumprint";
  }
  var a = "{";
  if (d.kty === "RSA") {
    if (typeof d.n != "string" || typeof d.e != "string") {
      throw "wrong n and e value for RSA key";
    }
    a += '"e":"' + d.e + '",';
    a += '"kty":"' + d.kty + '",';
    a += '"n":"' + d.n + '"}';
  } else {
    if (d.kty === "EC") {
      if (typeof d.crv != "string" || typeof d.x != "string" || typeof d.y != "string") {
        throw "wrong crv, x and y value for EC key";
      }
      a += '"crv":"' + d.crv + '",';
      a += '"kty":"' + d.kty + '",';
      a += '"x":"' + d.x + '",';
      a += '"y":"' + d.y + '"}';
    } else {
      if (d.kty === "oct") {
        if (typeof d.k != "string") {
          throw "wrong k value for oct(symmetric) key";
        }
        a += '"kty":"' + d.kty + '",';
        a += '"k":"' + d.k + '"}';
      }
    }
  }
  var b = rstrtohex(a);
  var c = KJUR.crypto.Util.hashHex(b, "sha256");
  var e = hextob64u(c);
  return e;
};
KJUR.jws.IntDate = {};
KJUR.jws.IntDate.get = function (c) {
  var b = KJUR.jws.IntDate,
    d = b.getNow,
    a = b.getZulu;
  if (c == "now") {
    return d();
  } else {
    if (c == "now + 1hour") {
      return d() + 60 * 60;
    } else {
      if (c == "now + 1day") {
        return d() + 60 * 60 * 24;
      } else {
        if (c == "now + 1month") {
          return d() + 60 * 60 * 24 * 30;
        } else {
          if (c == "now + 1year") {
            return d() + 60 * 60 * 24 * 365;
          } else {
            if (c.match(/Z$/)) {
              return a(c);
            } else {
              if (c.match(/^[0-9]+$/)) {
                return parseInt(c);
              }
            }
          }
        }
      }
    }
  }
  throw "unsupported format: " + c;
};
KJUR.jws.IntDate.getZulu = function (a) {
  return zulutosec(a);
};
KJUR.jws.IntDate.getNow = function () {
  var a = ~~(new Date() / 1000);
  return a;
};
KJUR.jws.IntDate.intDate2UTCString = function (a) {
  var b = new Date(a * 1000);
  return b.toUTCString();
};
KJUR.jws.IntDate.intDate2Zulu = function (e) {
  var i = new Date(e * 1000),
    h = ("0000" + i.getUTCFullYear()).slice(-4),
    g = ("00" + (i.getUTCMonth() + 1)).slice(-2),
    b = ("00" + i.getUTCDate()).slice(-2),
    a = ("00" + i.getUTCHours()).slice(-2),
    c = ("00" + i.getUTCMinutes()).slice(-2),
    f = ("00" + i.getUTCSeconds()).slice(-2);
  return h + g + b + a + c + f + "Z";
};
if (typeof KJUR == "undefined" || !KJUR) {
  KJUR = {};
}
if (typeof KJUR.jws == "undefined" || !KJUR.jws) {
  KJUR.jws = {};
}
KJUR.jws.JWSJS = function () {
  var c = KJUR,
    b = c.jws,
    a = b.JWS,
    d = a.readSafeJSONString;
  this.aHeader = [];
  this.sPayload = "";
  this.aSignature = [];
  this.init = function () {
    this.aHeader = [];
    this.sPayload = undefined;
    this.aSignature = [];
  };
  this.initWithJWS = function (f) {
    this.init();
    var e = f.split(".");
    if (e.length != 3) {
      throw "malformed input JWS";
    }
    this.aHeader.push(e[0]);
    this.sPayload = e[1];
    this.aSignature.push(e[2]);
  };
  this.addSignature = function (e, h, m, k) {
    if (this.sPayload === undefined || this.sPayload === null) {
      throw "there's no JSON-JS signature to add.";
    }
    var l = this.aHeader.length;
    if (this.aHeader.length != this.aSignature.length) {
      throw "aHeader.length != aSignature.length";
    }
    try {
      var f = KJUR.jws.JWS.sign(e, h, this.sPayload, m, k);
      var j = f.split(".");
      var n = j[0];
      var g = j[2];
      this.aHeader.push(j[0]);
      this.aSignature.push(j[2]);
    } catch (i) {
      if (this.aHeader.length > l) {
        this.aHeader.pop();
      }
      if (this.aSignature.length > l) {
        this.aSignature.pop();
      }
      throw "addSignature failed: " + i;
    }
  };
  this.verifyAll = function (h) {
    if (this.aHeader.length !== h.length || this.aSignature.length !== h.length) {
      return false;
    }
    for (var g = 0; g < h.length; g++) {
      var f = h[g];
      if (f.length !== 2) {
        return false;
      }
      var e = this.verifyNth(g, f[0], f[1]);
      if (e === false) {
        return false;
      }
    }
    return true;
  };
  this.verifyNth = function (f, j, g) {
    if (this.aHeader.length <= f || this.aSignature.length <= f) {
      return false;
    }
    var h = this.aHeader[f];
    var k = this.aSignature[f];
    var l = h + "." + this.sPayload + "." + k;
    var e = false;
    try {
      e = a.verify(l, j, g);
    } catch (i) {
      return false;
    }
    return e;
  };
  this.readJWSJS = function (g) {
    if (typeof g === "string") {
      var f = d(g);
      if (f == null) {
        throw "argument is not safe JSON object string";
      }
      this.aHeader = f.headers;
      this.sPayload = f.payload;
      this.aSignature = f.signatures;
    } else {
      try {
        if (g.headers.length > 0) {
          this.aHeader = g.headers;
        } else {
          throw "malformed header";
        }
        if (typeof g.payload === "string") {
          this.sPayload = g.payload;
        } else {
          throw "malformed signatures";
        }
        if (g.signatures.length > 0) {
          this.aSignature = g.signatures;
        } else {
          throw "malformed signatures";
        }
      } catch (e) {
        throw "malformed JWS-JS JSON object: " + e;
      }
    }
  };
  this.getJSON = function () {
    return {
      headers: this.aHeader,
      payload: this.sPayload,
      signatures: this.aSignature
    };
  };
  this.isEmpty = function () {
    if (this.aHeader.length == 0) {
      return 1;
    }
    return 0;
  };
};
exports.SecureRandom = SecureRandom;
exports.rng_seed_time = rng_seed_time;
exports.BigInteger = BigInteger;
exports.RSAKey = RSAKey;
exports.ECDSA = KJUR.crypto.ECDSA;
exports.DSA = KJUR.crypto.DSA;
exports.Signature = KJUR.crypto.Signature;
exports.MessageDigest = KJUR.crypto.MessageDigest;
exports.Mac = KJUR.crypto.Mac;
//exports.Cipher = KJUR.crypto.Cipher;
exports.KEYUTIL = KEYUTIL;
exports.ASN1HEX = ASN1HEX;
exports.X509 = X509;
exports.X509CRL = X509CRL;
exports.CryptoJS = CryptoJS;

// ext/base64.js
exports.b64tohex = b64tohex;
exports.b64toBA = b64toBA;

// ext/ec*.js
exports.ECFieldElementFp = ECFieldElementFp;
exports.ECPointFp = ECPointFp;
exports.ECCurveFp = ECCurveFp;

// base64x.js
exports.stoBA = stoBA;
exports.BAtos = BAtos;
exports.BAtohex = BAtohex;
exports.stohex = stohex;
exports.stob64 = stob64;
exports.stob64u = stob64u;
exports.b64utos = b64utos;
exports.b64tob64u = b64tob64u;
exports.b64utob64 = b64utob64;
exports.hex2b64 = hex2b64;
exports.hextob64u = hextob64u;
exports.b64utohex = b64utohex;
exports.utf8tob64u = utf8tob64u;
exports.b64utoutf8 = b64utoutf8;
exports.utf8tob64 = utf8tob64;
exports.b64toutf8 = b64toutf8;
exports.utf8tohex = utf8tohex;
exports.hextoutf8 = hextoutf8;
exports.hextorstr = hextorstr;
exports.rstrtohex = rstrtohex;
exports.hextob64 = hextob64;
exports.hextob64nl = hextob64nl;
exports.b64nltohex = b64nltohex;
exports.hextopem = hextopem;
exports.pemtohex = pemtohex;
exports.hextoArrayBuffer = hextoArrayBuffer;
exports.ArrayBuffertohex = ArrayBuffertohex;
exports.zulutomsec = zulutomsec;
exports.msectozulu = msectozulu;
exports.zulutosec = zulutosec;
exports.zulutodate = zulutodate;
exports.datetozulu = datetozulu;
exports.uricmptohex = uricmptohex;
exports.hextouricmp = hextouricmp;
exports.ipv6tohex = ipv6tohex;
exports.hextoipv6 = hextoipv6;
exports.hextoip = hextoip;
exports.iptohex = iptohex;
exports.ucs2hextoutf8 = ucs2hextoutf8;
exports.encodeURIComponentAll = encodeURIComponentAll;
exports.newline_toUnix = newline_toUnix;
exports.newline_toDos = newline_toDos;
exports.hextoposhex = hextoposhex;
exports.intarystrtohex = intarystrtohex;
exports.strdiffidx = strdiffidx;
exports.oidtohex = oidtohex;
exports.hextooid = hextooid;
exports.strpad = strpad;
exports.bitstrtoint = bitstrtoint;
exports.inttobitstr = inttobitstr;
exports.bitstrtobinstr = bitstrtobinstr;
exports.binstrtobitstr = binstrtobitstr;
exports.isBase64URLDot = isBase64URLDot;
exports.namearraytobinstr = namearraytobinstr;
exports.extendClass = extendClass;
exports.foldnl = foldnl;
exports.b64topem = b64topem;
exports.pemtob64 = pemtob64;
exports.timeogen = timetogen;
exports.aryval = aryval;
exports.inttohex = inttohex;
exports.twoscompl = twoscompl;

// name spaces
exports.KJUR = KJUR;
exports.crypto = KJUR.crypto;
exports.asn1 = KJUR.asn1;
exports.jws = KJUR.jws;
exports.lang = KJUR.lang;
exports.VERSION = VERSION;
exports.VERSION_FULL = VERSION_FULL;

/***/ }),

/***/ 2836:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/BehaviorSubject.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   BehaviorSubject: () => (/* binding */ BehaviorSubject)
/* harmony export */ });
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subject */ 2714);

class BehaviorSubject extends _Subject__WEBPACK_IMPORTED_MODULE_0__.Subject {
  constructor(_value) {
    super();
    this._value = _value;
  }
  get value() {
    return this.getValue();
  }
  _subscribe(subscriber) {
    const subscription = super._subscribe(subscriber);
    !subscription.closed && subscriber.next(this._value);
    return subscription;
  }
  getValue() {
    const {
      hasError,
      thrownError,
      _value
    } = this;
    if (hasError) {
      throw thrownError;
    }
    this._throwIfClosed();
    return _value;
  }
  next(value) {
    super.next(this._value = value);
  }
}

/***/ }),

/***/ 893:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/NotificationFactories.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   COMPLETE_NOTIFICATION: () => (/* binding */ COMPLETE_NOTIFICATION),
/* harmony export */   createNotification: () => (/* binding */ createNotification),
/* harmony export */   errorNotification: () => (/* binding */ errorNotification),
/* harmony export */   nextNotification: () => (/* binding */ nextNotification)
/* harmony export */ });
const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined))();
function errorNotification(error) {
  return createNotification('E', undefined, error);
}
function nextNotification(value) {
  return createNotification('N', value, undefined);
}
function createNotification(kind, value, error) {
  return {
    kind,
    value,
    error
  };
}

/***/ }),

/***/ 2921:
/*!*****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/Observable.js ***!
  \*****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Observable: () => (/* binding */ Observable)
/* harmony export */ });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscriber */ 8926);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Subscription */ 2273);
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./symbol/observable */ 5678);
/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/pipe */ 5851);
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./config */ 6826);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./util/isFunction */ 1679);
/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/errorContext */ 8610);







let Observable = /*#__PURE__*/(() => {
  class Observable {
    constructor(subscribe) {
      if (subscribe) {
        this._subscribe = subscribe;
      }
    }
    lift(operator) {
      const observable = new Observable();
      observable.source = this;
      observable.operator = operator;
      return observable;
    }
    subscribe(observerOrNext, error, complete) {
      const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new _Subscriber__WEBPACK_IMPORTED_MODULE_0__.SafeSubscriber(observerOrNext, error, complete);
      (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_1__.errorContext)(() => {
        const {
          operator,
          source
        } = this;
        subscriber.add(operator ? operator.call(subscriber, source) : source ? this._subscribe(subscriber) : this._trySubscribe(subscriber));
      });
      return subscriber;
    }
    _trySubscribe(sink) {
      try {
        return this._subscribe(sink);
      } catch (err) {
        sink.error(err);
      }
    }
    forEach(next, promiseCtor) {
      promiseCtor = getPromiseCtor(promiseCtor);
      return new promiseCtor((resolve, reject) => {
        const subscriber = new _Subscriber__WEBPACK_IMPORTED_MODULE_0__.SafeSubscriber({
          next: value => {
            try {
              next(value);
            } catch (err) {
              reject(err);
              subscriber.unsubscribe();
            }
          },
          error: reject,
          complete: resolve
        });
        this.subscribe(subscriber);
      });
    }
    _subscribe(subscriber) {
      var _a;
      return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
    }
    [_symbol_observable__WEBPACK_IMPORTED_MODULE_2__.observable]() {
      return this;
    }
    pipe(...operations) {
      return (0,_util_pipe__WEBPACK_IMPORTED_MODULE_3__.pipeFromArray)(operations)(this);
    }
    toPromise(promiseCtor) {
      promiseCtor = getPromiseCtor(promiseCtor);
      return new promiseCtor((resolve, reject) => {
        let value;
        this.subscribe(x => value = x, err => reject(err), () => resolve(value));
      });
    }
  }
  Observable.create = subscribe => {
    return new Observable(subscribe);
  };
  return Observable;
})();
function getPromiseCtor(promiseCtor) {
  var _a;
  return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : _config__WEBPACK_IMPORTED_MODULE_4__.config.Promise) !== null && _a !== void 0 ? _a : Promise;
}
function isObserver(value) {
  return value && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.next) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.error) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.complete);
}
function isSubscriber(value) {
  return value && value instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__.Subscriber || isObserver(value) && (0,_Subscription__WEBPACK_IMPORTED_MODULE_6__.isSubscription)(value);
}

/***/ }),

/***/ 7255:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/Scheduler.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Scheduler: () => (/* binding */ Scheduler)
/* harmony export */ });
/* harmony import */ var _scheduler_dateTimestampProvider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scheduler/dateTimestampProvider */ 6345);

class Scheduler {
  constructor(schedulerActionCtor, now = Scheduler.now) {
    this.schedulerActionCtor = schedulerActionCtor;
    this.now = now;
  }
  schedule(work, delay = 0, state) {
    return new this.schedulerActionCtor(this, work).schedule(state, delay);
  }
}
Scheduler.now = _scheduler_dateTimestampProvider__WEBPACK_IMPORTED_MODULE_0__.dateTimestampProvider.now;

/***/ }),

/***/ 2714:
/*!**************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/Subject.js ***!
  \**************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AnonymousSubject: () => (/* binding */ AnonymousSubject),
/* harmony export */   Subject: () => (/* binding */ Subject)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Observable */ 2921);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Subscription */ 2273);
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/ObjectUnsubscribedError */ 6869);
/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./util/arrRemove */ 5868);
/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/errorContext */ 8610);





let Subject = /*#__PURE__*/(() => {
  class Subject extends _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable {
    constructor() {
      super();
      this.closed = false;
      this.currentObservers = null;
      this.observers = [];
      this.isStopped = false;
      this.hasError = false;
      this.thrownError = null;
    }
    lift(operator) {
      const subject = new AnonymousSubject(this, this);
      subject.operator = operator;
      return subject;
    }
    _throwIfClosed() {
      if (this.closed) {
        throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__.ObjectUnsubscribedError();
      }
    }
    next(value) {
      (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(() => {
        this._throwIfClosed();
        if (!this.isStopped) {
          if (!this.currentObservers) {
            this.currentObservers = Array.from(this.observers);
          }
          for (const observer of this.currentObservers) {
            observer.next(value);
          }
        }
      });
    }
    error(err) {
      (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(() => {
        this._throwIfClosed();
        if (!this.isStopped) {
          this.hasError = this.isStopped = true;
          this.thrownError = err;
          const {
            observers
          } = this;
          while (observers.length) {
            observers.shift().error(err);
          }
        }
      });
    }
    complete() {
      (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(() => {
        this._throwIfClosed();
        if (!this.isStopped) {
          this.isStopped = true;
          const {
            observers
          } = this;
          while (observers.length) {
            observers.shift().complete();
          }
        }
      });
    }
    unsubscribe() {
      this.isStopped = this.closed = true;
      this.observers = this.currentObservers = null;
    }
    get observed() {
      var _a;
      return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
    }
    _trySubscribe(subscriber) {
      this._throwIfClosed();
      return super._trySubscribe(subscriber);
    }
    _subscribe(subscriber) {
      this._throwIfClosed();
      this._checkFinalizedStatuses(subscriber);
      return this._innerSubscribe(subscriber);
    }
    _innerSubscribe(subscriber) {
      const {
        hasError,
        isStopped,
        observers
      } = this;
      if (hasError || isStopped) {
        return _Subscription__WEBPACK_IMPORTED_MODULE_3__.EMPTY_SUBSCRIPTION;
      }
      this.currentObservers = null;
      observers.push(subscriber);
      return new _Subscription__WEBPACK_IMPORTED_MODULE_3__.Subscription(() => {
        this.currentObservers = null;
        (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_4__.arrRemove)(observers, subscriber);
      });
    }
    _checkFinalizedStatuses(subscriber) {
      const {
        hasError,
        thrownError,
        isStopped
      } = this;
      if (hasError) {
        subscriber.error(thrownError);
      } else if (isStopped) {
        subscriber.complete();
      }
    }
    asObservable() {
      const observable = new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable();
      observable.source = this;
      return observable;
    }
  }
  Subject.create = (destination, source) => {
    return new AnonymousSubject(destination, source);
  };
  return Subject;
})();
class AnonymousSubject extends Subject {
  constructor(destination, source) {
    super();
    this.destination = destination;
    this.source = source;
  }
  next(value) {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
  }
  error(err) {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
  }
  complete() {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  _subscribe(subscriber) {
    var _a, _b;
    return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : _Subscription__WEBPACK_IMPORTED_MODULE_3__.EMPTY_SUBSCRIPTION;
  }
}

/***/ }),

/***/ 8926:
/*!*****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/Subscriber.js ***!
  \*****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EMPTY_OBSERVER: () => (/* binding */ EMPTY_OBSERVER),
/* harmony export */   SafeSubscriber: () => (/* binding */ SafeSubscriber),
/* harmony export */   Subscriber: () => (/* binding */ Subscriber)
/* harmony export */ });
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/isFunction */ 1679);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscription */ 2273);
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./config */ 6826);
/* harmony import */ var _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./util/reportUnhandledError */ 1438);
/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./util/noop */ 6599);
/* harmony import */ var _NotificationFactories__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NotificationFactories */ 893);
/* harmony import */ var _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./scheduler/timeoutProvider */ 2766);
/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./util/errorContext */ 8610);








class Subscriber extends _Subscription__WEBPACK_IMPORTED_MODULE_0__.Subscription {
  constructor(destination) {
    super();
    this.isStopped = false;
    if (destination) {
      this.destination = destination;
      if ((0,_Subscription__WEBPACK_IMPORTED_MODULE_0__.isSubscription)(destination)) {
        destination.add(this);
      }
    } else {
      this.destination = EMPTY_OBSERVER;
    }
  }
  static create(next, error, complete) {
    return new SafeSubscriber(next, error, complete);
  }
  next(value) {
    if (this.isStopped) {
      handleStoppedNotification((0,_NotificationFactories__WEBPACK_IMPORTED_MODULE_1__.nextNotification)(value), this);
    } else {
      this._next(value);
    }
  }
  error(err) {
    if (this.isStopped) {
      handleStoppedNotification((0,_NotificationFactories__WEBPACK_IMPORTED_MODULE_1__.errorNotification)(err), this);
    } else {
      this.isStopped = true;
      this._error(err);
    }
  }
  complete() {
    if (this.isStopped) {
      handleStoppedNotification(_NotificationFactories__WEBPACK_IMPORTED_MODULE_1__.COMPLETE_NOTIFICATION, this);
    } else {
      this.isStopped = true;
      this._complete();
    }
  }
  unsubscribe() {
    if (!this.closed) {
      this.isStopped = true;
      super.unsubscribe();
      this.destination = null;
    }
  }
  _next(value) {
    this.destination.next(value);
  }
  _error(err) {
    try {
      this.destination.error(err);
    } finally {
      this.unsubscribe();
    }
  }
  _complete() {
    try {
      this.destination.complete();
    } finally {
      this.unsubscribe();
    }
  }
}
const _bind = Function.prototype.bind;
function bind(fn, thisArg) {
  return _bind.call(fn, thisArg);
}
class ConsumerObserver {
  constructor(partialObserver) {
    this.partialObserver = partialObserver;
  }
  next(value) {
    const {
      partialObserver
    } = this;
    if (partialObserver.next) {
      try {
        partialObserver.next(value);
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  }
  error(err) {
    const {
      partialObserver
    } = this;
    if (partialObserver.error) {
      try {
        partialObserver.error(err);
      } catch (error) {
        handleUnhandledError(error);
      }
    } else {
      handleUnhandledError(err);
    }
  }
  complete() {
    const {
      partialObserver
    } = this;
    if (partialObserver.complete) {
      try {
        partialObserver.complete();
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  }
}
class SafeSubscriber extends Subscriber {
  constructor(observerOrNext, error, complete) {
    super();
    let partialObserver;
    if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_2__.isFunction)(observerOrNext) || !observerOrNext) {
      partialObserver = {
        next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
        error: error !== null && error !== void 0 ? error : undefined,
        complete: complete !== null && complete !== void 0 ? complete : undefined
      };
    } else {
      let context;
      if (this && _config__WEBPACK_IMPORTED_MODULE_3__.config.useDeprecatedNextContext) {
        context = Object.create(observerOrNext);
        context.unsubscribe = () => this.unsubscribe();
        partialObserver = {
          next: observerOrNext.next && bind(observerOrNext.next, context),
          error: observerOrNext.error && bind(observerOrNext.error, context),
          complete: observerOrNext.complete && bind(observerOrNext.complete, context)
        };
      } else {
        partialObserver = observerOrNext;
      }
    }
    this.destination = new ConsumerObserver(partialObserver);
  }
}
function handleUnhandledError(error) {
  if (_config__WEBPACK_IMPORTED_MODULE_3__.config.useDeprecatedSynchronousErrorHandling) {
    (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_4__.captureError)(error);
  } else {
    (0,_util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_5__.reportUnhandledError)(error);
  }
}
function defaultErrorHandler(err) {
  throw err;
}
function handleStoppedNotification(notification, subscriber) {
  const {
    onStoppedNotification
  } = _config__WEBPACK_IMPORTED_MODULE_3__.config;
  onStoppedNotification && _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_6__.timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));
}
const EMPTY_OBSERVER = {
  closed: true,
  next: _util_noop__WEBPACK_IMPORTED_MODULE_7__.noop,
  error: defaultErrorHandler,
  complete: _util_noop__WEBPACK_IMPORTED_MODULE_7__.noop
};

/***/ }),

/***/ 2273:
/*!*******************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/Subscription.js ***!
  \*******************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EMPTY_SUBSCRIPTION: () => (/* binding */ EMPTY_SUBSCRIPTION),
/* harmony export */   Subscription: () => (/* binding */ Subscription),
/* harmony export */   isSubscription: () => (/* binding */ isSubscription)
/* harmony export */ });
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/isFunction */ 1679);
/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/UnsubscriptionError */ 3687);
/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/arrRemove */ 5868);



class Subscription {
  constructor(initialTeardown) {
    this.initialTeardown = initialTeardown;
    this.closed = false;
    this._parentage = null;
    this._finalizers = null;
  }
  unsubscribe() {
    let errors;
    if (!this.closed) {
      this.closed = true;
      const {
        _parentage
      } = this;
      if (_parentage) {
        this._parentage = null;
        if (Array.isArray(_parentage)) {
          for (const parent of _parentage) {
            parent.remove(this);
          }
        } else {
          _parentage.remove(this);
        }
      }
      const {
        initialTeardown: initialFinalizer
      } = this;
      if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(initialFinalizer)) {
        try {
          initialFinalizer();
        } catch (e) {
          errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_1__.UnsubscriptionError ? e.errors : [e];
        }
      }
      const {
        _finalizers
      } = this;
      if (_finalizers) {
        this._finalizers = null;
        for (const finalizer of _finalizers) {
          try {
            execFinalizer(finalizer);
          } catch (err) {
            errors = errors !== null && errors !== void 0 ? errors : [];
            if (err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_1__.UnsubscriptionError) {
              errors = [...errors, ...err.errors];
            } else {
              errors.push(err);
            }
          }
        }
      }
      if (errors) {
        throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_1__.UnsubscriptionError(errors);
      }
    }
  }
  add(teardown) {
    var _a;
    if (teardown && teardown !== this) {
      if (this.closed) {
        execFinalizer(teardown);
      } else {
        if (teardown instanceof Subscription) {
          if (teardown.closed || teardown._hasParent(this)) {
            return;
          }
          teardown._addParent(this);
        }
        (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
      }
    }
  }
  _hasParent(parent) {
    const {
      _parentage
    } = this;
    return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
  }
  _addParent(parent) {
    const {
      _parentage
    } = this;
    this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
  }
  _removeParent(parent) {
    const {
      _parentage
    } = this;
    if (_parentage === parent) {
      this._parentage = null;
    } else if (Array.isArray(_parentage)) {
      (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_2__.arrRemove)(_parentage, parent);
    }
  }
  remove(teardown) {
    const {
      _finalizers
    } = this;
    _finalizers && (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_2__.arrRemove)(_finalizers, teardown);
    if (teardown instanceof Subscription) {
      teardown._removeParent(this);
    }
  }
}
Subscription.EMPTY = (() => {
  const empty = new Subscription();
  empty.closed = true;
  return empty;
})();
const EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
  return value instanceof Subscription || value && 'closed' in value && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value.remove) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value.add) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value.unsubscribe);
}
function execFinalizer(finalizer) {
  if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(finalizer)) {
    finalizer();
  } else {
    finalizer.unsubscribe();
  }
}

/***/ }),

/***/ 6826:
/*!*************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/config.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   config: () => (/* binding */ config)
/* harmony export */ });
const config = {
  onUnhandledError: null,
  onStoppedNotification: null,
  Promise: undefined,
  useDeprecatedSynchronousErrorHandling: false,
  useDeprecatedNextContext: false
};

/***/ }),

/***/ 4985:
/*!***************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/ConnectableObservable.js ***!
  \***************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ConnectableObservable: () => (/* binding */ ConnectableObservable)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscription */ 2273);
/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../operators/refCount */ 6018);
/* harmony import */ var _operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/OperatorSubscriber */ 5952);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);





class ConnectableObservable extends _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable {
  constructor(source, subjectFactory) {
    super();
    this.source = source;
    this.subjectFactory = subjectFactory;
    this._subject = null;
    this._refCount = 0;
    this._connection = null;
    if ((0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.hasLift)(source)) {
      this.lift = source.lift;
    }
  }
  _subscribe(subscriber) {
    return this.getSubject().subscribe(subscriber);
  }
  getSubject() {
    const subject = this._subject;
    if (!subject || subject.isStopped) {
      this._subject = this.subjectFactory();
    }
    return this._subject;
  }
  _teardown() {
    this._refCount = 0;
    const {
      _connection
    } = this;
    this._subject = this._connection = null;
    _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();
  }
  connect() {
    let connection = this._connection;
    if (!connection) {
      connection = this._connection = new _Subscription__WEBPACK_IMPORTED_MODULE_2__.Subscription();
      const subject = this.getSubject();
      connection.add(this.source.subscribe((0,_operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__.createOperatorSubscriber)(subject, undefined, () => {
        this._teardown();
        subject.complete();
      }, err => {
        this._teardown();
        subject.error(err);
      }, () => this._teardown())));
      if (connection.closed) {
        this._connection = null;
        connection = _Subscription__WEBPACK_IMPORTED_MODULE_2__.Subscription.EMPTY;
      }
    }
    return connection;
  }
  refCount() {
    return (0,_operators_refCount__WEBPACK_IMPORTED_MODULE_4__.refCount)()(this);
  }
}

/***/ }),

/***/ 1428:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/combineLatest.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   combineLatest: () => (/* binding */ combineLatest),
/* harmony export */   combineLatestInit: () => (/* binding */ combineLatestInit)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/argsArgArrayOrObject */ 3977);
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./from */ 580);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/identity */ 2525);
/* harmony import */ var _util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/mapOneOrManyArgs */ 5258);
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _util_createObject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/createObject */ 2536);
/* harmony import */ var _operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../operators/OperatorSubscriber */ 5952);
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);









function combineLatest(...args) {
  const scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args);
  const resultSelector = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popResultSelector)(args);
  const {
    args: observables,
    keys
  } = (0,_util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__.argsArgArrayOrObject)(args);
  if (observables.length === 0) {
    return (0,_from__WEBPACK_IMPORTED_MODULE_2__.from)([], scheduler);
  }
  const result = new _Observable__WEBPACK_IMPORTED_MODULE_3__.Observable(combineLatestInit(observables, scheduler, keys ? values => (0,_util_createObject__WEBPACK_IMPORTED_MODULE_4__.createObject)(keys, values) : _util_identity__WEBPACK_IMPORTED_MODULE_5__.identity));
  return resultSelector ? result.pipe((0,_util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__.mapOneOrManyArgs)(resultSelector)) : result;
}
function combineLatestInit(observables, scheduler, valueTransform = _util_identity__WEBPACK_IMPORTED_MODULE_5__.identity) {
  return subscriber => {
    maybeSchedule(scheduler, () => {
      const {
        length
      } = observables;
      const values = new Array(length);
      let active = length;
      let remainingFirstValues = length;
      for (let i = 0; i < length; i++) {
        maybeSchedule(scheduler, () => {
          const source = (0,_from__WEBPACK_IMPORTED_MODULE_2__.from)(observables[i], scheduler);
          let hasFirstValue = false;
          source.subscribe((0,_operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_7__.createOperatorSubscriber)(subscriber, value => {
            values[i] = value;
            if (!hasFirstValue) {
              hasFirstValue = true;
              remainingFirstValues--;
            }
            if (!remainingFirstValues) {
              subscriber.next(valueTransform(values.slice()));
            }
          }, () => {
            if (! --active) {
              subscriber.complete();
            }
          }));
        }, subscriber);
      }
    }, subscriber);
  };
}
function maybeSchedule(scheduler, execute, subscription) {
  if (scheduler) {
    (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_8__.executeSchedule)(subscription, scheduler, execute);
  } else {
    execute();
  }
}

/***/ }),

/***/ 8440:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/concat.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   concat: () => (/* binding */ concat)
/* harmony export */ });
/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../operators/concatAll */ 1571);
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ 580);



function concat(...args) {
  return (0,_operators_concatAll__WEBPACK_IMPORTED_MODULE_0__.concatAll)()((0,_from__WEBPACK_IMPORTED_MODULE_1__.from)(args, (0,_util_args__WEBPACK_IMPORTED_MODULE_2__.popScheduler)(args)));
}

/***/ }),

/***/ 3966:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/defer.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   defer: () => (/* binding */ defer)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./innerFrom */ 8422);


function defer(observableFactory) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    (0,_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(observableFactory()).subscribe(subscriber);
  });
}

/***/ }),

/***/ 3471:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/empty.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EMPTY: () => (/* binding */ EMPTY),
/* harmony export */   empty: () => (/* binding */ empty)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);

const EMPTY = new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => subscriber.complete());
function empty(scheduler) {
  return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => scheduler.schedule(() => subscriber.complete()));
}

/***/ }),

/***/ 3092:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/forkJoin.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   forkJoin: () => (/* binding */ forkJoin)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/argsArgArrayOrObject */ 3977);
/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./innerFrom */ 8422);
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../operators/OperatorSubscriber */ 5952);
/* harmony import */ var _util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/mapOneOrManyArgs */ 5258);
/* harmony import */ var _util_createObject__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/createObject */ 2536);







function forkJoin(...args) {
  const resultSelector = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popResultSelector)(args);
  const {
    args: sources,
    keys
  } = (0,_util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__.argsArgArrayOrObject)(args);
  const result = new _Observable__WEBPACK_IMPORTED_MODULE_2__.Observable(subscriber => {
    const {
      length
    } = sources;
    if (!length) {
      subscriber.complete();
      return;
    }
    const values = new Array(length);
    let remainingCompletions = length;
    let remainingEmissions = length;
    for (let sourceIndex = 0; sourceIndex < length; sourceIndex++) {
      let hasValue = false;
      (0,_innerFrom__WEBPACK_IMPORTED_MODULE_3__.innerFrom)(sources[sourceIndex]).subscribe((0,_operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_4__.createOperatorSubscriber)(subscriber, value => {
        if (!hasValue) {
          hasValue = true;
          remainingEmissions--;
        }
        values[sourceIndex] = value;
      }, () => remainingCompletions--, undefined, () => {
        if (!remainingCompletions || !hasValue) {
          if (!remainingEmissions) {
            subscriber.next(keys ? (0,_util_createObject__WEBPACK_IMPORTED_MODULE_5__.createObject)(keys, values) : values);
          }
          subscriber.complete();
        }
      }));
    }
  });
  return resultSelector ? result.pipe((0,_util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__.mapOneOrManyArgs)(resultSelector)) : result;
}

/***/ }),

/***/ 580:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/from.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   from: () => (/* binding */ from)
/* harmony export */ });
/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduled/scheduled */ 7689);
/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./innerFrom */ 8422);


function from(input, scheduler) {
  return scheduler ? (0,_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_0__.scheduled)(input, scheduler) : (0,_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(input);
}

/***/ }),

/***/ 8422:
/*!***************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/innerFrom.js ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   fromArrayLike: () => (/* binding */ fromArrayLike),
/* harmony export */   fromAsyncIterable: () => (/* binding */ fromAsyncIterable),
/* harmony export */   fromInteropObservable: () => (/* binding */ fromInteropObservable),
/* harmony export */   fromIterable: () => (/* binding */ fromIterable),
/* harmony export */   fromPromise: () => (/* binding */ fromPromise),
/* harmony export */   fromReadableStreamLike: () => (/* binding */ fromReadableStreamLike),
/* harmony export */   innerFrom: () => (/* binding */ innerFrom)
/* harmony export */ });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! tslib */ 3215);
/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isArrayLike */ 4329);
/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isPromise */ 7082);
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isInteropObservable */ 9287);
/* harmony import */ var _util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isAsyncIterable */ 7321);
/* harmony import */ var _util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/throwUnobservableError */ 471);
/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/isIterable */ 2797);
/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/isReadableStreamLike */ 7684);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/isFunction */ 1679);
/* harmony import */ var _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/reportUnhandledError */ 1438);
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../symbol/observable */ 5678);












function innerFrom(input) {
  if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable) {
    return input;
  }
  if (input != null) {
    if ((0,_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_1__.isInteropObservable)(input)) {
      return fromInteropObservable(input);
    }
    if ((0,_util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__.isArrayLike)(input)) {
      return fromArrayLike(input);
    }
    if ((0,_util_isPromise__WEBPACK_IMPORTED_MODULE_3__.isPromise)(input)) {
      return fromPromise(input);
    }
    if ((0,_util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_4__.isAsyncIterable)(input)) {
      return fromAsyncIterable(input);
    }
    if ((0,_util_isIterable__WEBPACK_IMPORTED_MODULE_5__.isIterable)(input)) {
      return fromIterable(input);
    }
    if ((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__.isReadableStreamLike)(input)) {
      return fromReadableStreamLike(input);
    }
  }
  throw (0,_util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_7__.createInvalidObservableTypeError)(input);
}
function fromInteropObservable(obj) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    const obs = obj[_symbol_observable__WEBPACK_IMPORTED_MODULE_8__.observable]();
    if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_9__.isFunction)(obs.subscribe)) {
      return obs.subscribe(subscriber);
    }
    throw new TypeError('Provided object does not correctly implement Symbol.observable');
  });
}
function fromArrayLike(array) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    for (let i = 0; i < array.length && !subscriber.closed; i++) {
      subscriber.next(array[i]);
    }
    subscriber.complete();
  });
}
function fromPromise(promise) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    promise.then(value => {
      if (!subscriber.closed) {
        subscriber.next(value);
        subscriber.complete();
      }
    }, err => subscriber.error(err)).then(null, _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_10__.reportUnhandledError);
  });
}
function fromIterable(iterable) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    for (const value of iterable) {
      subscriber.next(value);
      if (subscriber.closed) {
        return;
      }
    }
    subscriber.complete();
  });
}
function fromAsyncIterable(asyncIterable) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    process(asyncIterable, subscriber).catch(err => subscriber.error(err));
  });
}
function fromReadableStreamLike(readableStream) {
  return fromAsyncIterable((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__.readableStreamLikeToAsyncGenerator)(readableStream));
}
function process(asyncIterable, subscriber) {
  var asyncIterable_1, asyncIterable_1_1;
  var e_1, _a;
  return (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__awaiter)(this, void 0, void 0, function* () {
    try {
      for (asyncIterable_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__asyncValues)(asyncIterable); asyncIterable_1_1 = yield asyncIterable_1.next(), !asyncIterable_1_1.done;) {
        const value = asyncIterable_1_1.value;
        subscriber.next(value);
        if (subscriber.closed) {
          return;
        }
      }
    } catch (e_1_1) {
      e_1 = {
        error: e_1_1
      };
    } finally {
      try {
        if (asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return)) yield _a.call(asyncIterable_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    subscriber.complete();
  });
}

/***/ }),

/***/ 3250:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/merge.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   merge: () => (/* binding */ merge)
/* harmony export */ });
/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/mergeAll */ 4053);
/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./innerFrom */ 8422);
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./empty */ 3471);
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./from */ 580);





function merge(...args) {
  const scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args);
  const concurrent = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popNumber)(args, Infinity);
  const sources = args;
  return !sources.length ? _empty__WEBPACK_IMPORTED_MODULE_1__.EMPTY : sources.length === 1 ? (0,_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(sources[0]) : (0,_operators_mergeAll__WEBPACK_IMPORTED_MODULE_3__.mergeAll)(concurrent)((0,_from__WEBPACK_IMPORTED_MODULE_4__.from)(sources, scheduler));
}

/***/ }),

/***/ 2049:
/*!********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/of.js ***!
  \********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   of: () => (/* binding */ of)
/* harmony export */ });
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ 580);


function of(...args) {
  const scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args);
  return (0,_from__WEBPACK_IMPORTED_MODULE_1__.from)(args, scheduler);
}

/***/ }),

/***/ 3873:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/race.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   race: () => (/* binding */ race),
/* harmony export */   raceInit: () => (/* binding */ raceInit)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./innerFrom */ 8422);
/* harmony import */ var _util_argsOrArgArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/argsOrArgArray */ 366);
/* harmony import */ var _operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/OperatorSubscriber */ 5952);




function race(...sources) {
  sources = (0,_util_argsOrArgArray__WEBPACK_IMPORTED_MODULE_0__.argsOrArgArray)(sources);
  return sources.length === 1 ? (0,_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(sources[0]) : new _Observable__WEBPACK_IMPORTED_MODULE_2__.Observable(raceInit(sources));
}
function raceInit(sources) {
  return subscriber => {
    let subscriptions = [];
    for (let i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
      subscriptions.push((0,_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(sources[i]).subscribe((0,_operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__.createOperatorSubscriber)(subscriber, value => {
        if (subscriptions) {
          for (let s = 0; s < subscriptions.length; s++) {
            s !== i && subscriptions[s].unsubscribe();
          }
          subscriptions = null;
        }
        subscriber.next(value);
      })));
    }
  };
}

/***/ }),

/***/ 7954:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/throwError.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   throwError: () => (/* binding */ throwError)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ 1679);


function throwError(errorOrErrorFactory, scheduler) {
  const errorFactory = (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;
  const init = subscriber => subscriber.error(errorFactory());
  return new _Observable__WEBPACK_IMPORTED_MODULE_1__.Observable(scheduler ? subscriber => scheduler.schedule(init, 0, subscriber) : init);
}

/***/ }),

/***/ 823:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/observable/timer.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   timer: () => (/* binding */ timer)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ 4908);
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isScheduler */ 1478);
/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isDate */ 315);




function timer(dueTime = 0, intervalOrScheduler, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__.async) {
  let intervalDuration = -1;
  if (intervalOrScheduler != null) {
    if ((0,_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__.isScheduler)(intervalOrScheduler)) {
      scheduler = intervalOrScheduler;
    } else {
      intervalDuration = intervalOrScheduler;
    }
  }
  return new _Observable__WEBPACK_IMPORTED_MODULE_2__.Observable(subscriber => {
    let due = (0,_util_isDate__WEBPACK_IMPORTED_MODULE_3__.isValidDate)(dueTime) ? +dueTime - scheduler.now() : dueTime;
    if (due < 0) {
      due = 0;
    }
    let n = 0;
    return scheduler.schedule(function () {
      if (!subscriber.closed) {
        subscriber.next(n++);
        if (0 <= intervalDuration) {
          this.schedule(undefined, intervalDuration);
        } else {
          subscriber.complete();
        }
      }
    }, due);
  });
}

/***/ }),

/***/ 5952:
/*!***********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/OperatorSubscriber.js ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   OperatorSubscriber: () => (/* binding */ OperatorSubscriber),
/* harmony export */   createOperatorSubscriber: () => (/* binding */ createOperatorSubscriber)
/* harmony export */ });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscriber */ 8926);

function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
  return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
class OperatorSubscriber extends _Subscriber__WEBPACK_IMPORTED_MODULE_0__.Subscriber {
  constructor(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
    super(destination);
    this.onFinalize = onFinalize;
    this.shouldUnsubscribe = shouldUnsubscribe;
    this._next = onNext ? function (value) {
      try {
        onNext(value);
      } catch (err) {
        destination.error(err);
      }
    } : super._next;
    this._error = onError ? function (err) {
      try {
        onError(err);
      } catch (err) {
        destination.error(err);
      } finally {
        this.unsubscribe();
      }
    } : super._error;
    this._complete = onComplete ? function () {
      try {
        onComplete();
      } catch (err) {
        destination.error(err);
      } finally {
        this.unsubscribe();
      }
    } : super._complete;
  }
  unsubscribe() {
    var _a;
    if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
      const {
        closed
      } = this;
      super.unsubscribe();
      !closed && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
    }
  }
}

/***/ }),

/***/ 5685:
/*!***************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/catchError.js ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   catchError: () => (/* binding */ catchError)
/* harmony export */ });
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);



function catchError(selector) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let innerSub = null;
    let syncUnsub = false;
    let handledResult;
    innerSub = source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, undefined, undefined, err => {
      handledResult = (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(selector(err, catchError(selector)(source)));
      if (innerSub) {
        innerSub.unsubscribe();
        innerSub = null;
        handledResult.subscribe(subscriber);
      } else {
        syncUnsub = true;
      }
    }));
    if (syncUnsub) {
      innerSub.unsubscribe();
      innerSub = null;
      handledResult.subscribe(subscriber);
    }
  });
}

/***/ }),

/***/ 1571:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/concatAll.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   concatAll: () => (/* binding */ concatAll)
/* harmony export */ });
/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeAll */ 4053);

function concatAll() {
  return (0,_mergeAll__WEBPACK_IMPORTED_MODULE_0__.mergeAll)(1);
}

/***/ }),

/***/ 826:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/concatMap.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   concatMap: () => (/* binding */ concatMap)
/* harmony export */ });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mergeMap */ 1292);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ 1679);


function concatMap(project, resultSelector) {
  return (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(resultSelector) ? (0,_mergeMap__WEBPACK_IMPORTED_MODULE_1__.mergeMap)(project, resultSelector, 1) : (0,_mergeMap__WEBPACK_IMPORTED_MODULE_1__.mergeMap)(project, 1);
}

/***/ }),

/***/ 6128:
/*!*****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/debounceTime.js ***!
  \*****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   debounceTime: () => (/* binding */ debounceTime)
/* harmony export */ });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ 4908);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function debounceTime(dueTime, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__.asyncScheduler) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)((source, subscriber) => {
    let activeTask = null;
    let lastValue = null;
    let lastTime = null;
    const emit = () => {
      if (activeTask) {
        activeTask.unsubscribe();
        activeTask = null;
        const value = lastValue;
        lastValue = null;
        subscriber.next(value);
      }
    };
    function emitWhenIdle() {
      const targetTime = lastTime + dueTime;
      const now = scheduler.now();
      if (now < targetTime) {
        activeTask = this.schedule(undefined, targetTime - now);
        subscriber.add(activeTask);
        return;
      }
      emit();
    }
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__.createOperatorSubscriber)(subscriber, value => {
      lastValue = value;
      lastTime = scheduler.now();
      if (!activeTask) {
        activeTask = scheduler.schedule(emitWhenIdle, dueTime);
        subscriber.add(activeTask);
      }
    }, () => {
      emit();
      subscriber.complete();
    }, undefined, () => {
      lastValue = activeTask = null;
    }));
  });
}

/***/ }),

/***/ 997:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/defaultIfEmpty.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   defaultIfEmpty: () => (/* binding */ defaultIfEmpty)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);


function defaultIfEmpty(defaultValue) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let hasValue = false;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => {
      hasValue = true;
      subscriber.next(value);
    }, () => {
      if (!hasValue) {
        subscriber.next(defaultValue);
      }
      subscriber.complete();
    }));
  });
}

/***/ }),

/***/ 9207:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/delay.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   delay: () => (/* binding */ delay)
/* harmony export */ });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ 4908);
/* harmony import */ var _delayWhen__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./delayWhen */ 7863);
/* harmony import */ var _observable_timer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/timer */ 823);



function delay(due, scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__.asyncScheduler) {
  const duration = (0,_observable_timer__WEBPACK_IMPORTED_MODULE_1__.timer)(due, scheduler);
  return (0,_delayWhen__WEBPACK_IMPORTED_MODULE_2__.delayWhen)(() => duration);
}

/***/ }),

/***/ 7863:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/delayWhen.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   delayWhen: () => (/* binding */ delayWhen)
/* harmony export */ });
/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/concat */ 8440);
/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./take */ 1969);
/* harmony import */ var _ignoreElements__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ignoreElements */ 7229);
/* harmony import */ var _mapTo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./mapTo */ 5359);
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mergeMap */ 1292);
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);






function delayWhen(delayDurationSelector, subscriptionDelay) {
  if (subscriptionDelay) {
    return source => (0,_observable_concat__WEBPACK_IMPORTED_MODULE_0__.concat)(subscriptionDelay.pipe((0,_take__WEBPACK_IMPORTED_MODULE_1__.take)(1), (0,_ignoreElements__WEBPACK_IMPORTED_MODULE_2__.ignoreElements)()), source.pipe(delayWhen(delayDurationSelector)));
  }
  return (0,_mergeMap__WEBPACK_IMPORTED_MODULE_3__.mergeMap)((value, index) => (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_4__.innerFrom)(delayDurationSelector(value, index)).pipe((0,_take__WEBPACK_IMPORTED_MODULE_1__.take)(1), (0,_mapTo__WEBPACK_IMPORTED_MODULE_5__.mapTo)(value)));
}

/***/ }),

/***/ 9754:
/*!***************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/exhaustMap.js ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   exhaustMap: () => (/* binding */ exhaustMap)
/* harmony export */ });
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./map */ 6634);
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);




function exhaustMap(project, resultSelector) {
  if (resultSelector) {
    return source => source.pipe(exhaustMap((a, i) => (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(project(a, i)).pipe((0,_map__WEBPACK_IMPORTED_MODULE_1__.map)((b, ii) => resultSelector(a, b, i, ii)))));
  }
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_2__.operate)((source, subscriber) => {
    let index = 0;
    let innerSub = null;
    let isComplete = false;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__.createOperatorSubscriber)(subscriber, outerValue => {
      if (!innerSub) {
        innerSub = (0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_3__.createOperatorSubscriber)(subscriber, undefined, () => {
          innerSub = null;
          isComplete && subscriber.complete();
        });
        (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(project(outerValue, index++)).subscribe(innerSub);
      }
    }, () => {
      isComplete = true;
      !innerSub && subscriber.complete();
    }));
  });
}

/***/ }),

/***/ 4484:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/filter.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   filter: () => (/* binding */ filter)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);


function filter(predicate, thisArg) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let index = 0;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => predicate.call(thisArg, value, index++) && subscriber.next(value)));
  });
}

/***/ }),

/***/ 5996:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/finalize.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   finalize: () => (/* binding */ finalize)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);

function finalize(callback) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    try {
      source.subscribe(subscriber);
    } finally {
      subscriber.add(callback);
    }
  });
}

/***/ }),

/***/ 8898:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/first.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   first: () => (/* binding */ first)
/* harmony export */ });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/EmptyError */ 8638);
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./filter */ 4484);
/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./take */ 1969);
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./defaultIfEmpty */ 997);
/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./throwIfEmpty */ 5158);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ 2525);






function first(predicate, defaultValue) {
  const hasDefaultValue = arguments.length >= 2;
  return source => source.pipe(predicate ? (0,_filter__WEBPACK_IMPORTED_MODULE_0__.filter)((v, i) => predicate(v, i, source)) : _util_identity__WEBPACK_IMPORTED_MODULE_1__.identity, (0,_take__WEBPACK_IMPORTED_MODULE_2__.take)(1), hasDefaultValue ? (0,_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__.defaultIfEmpty)(defaultValue) : (0,_throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__.throwIfEmpty)(() => new _util_EmptyError__WEBPACK_IMPORTED_MODULE_5__.EmptyError()));
}

/***/ }),

/***/ 7229:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/ignoreElements.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ignoreElements: () => (/* binding */ ignoreElements)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);
/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/noop */ 6599);



function ignoreElements() {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, _util_noop__WEBPACK_IMPORTED_MODULE_2__.noop));
  });
}

/***/ }),

/***/ 6418:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/last.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   last: () => (/* binding */ last)
/* harmony export */ });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/EmptyError */ 8638);
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./filter */ 4484);
/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./takeLast */ 1437);
/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./throwIfEmpty */ 5158);
/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./defaultIfEmpty */ 997);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ 2525);






function last(predicate, defaultValue) {
  const hasDefaultValue = arguments.length >= 2;
  return source => source.pipe(predicate ? (0,_filter__WEBPACK_IMPORTED_MODULE_0__.filter)((v, i) => predicate(v, i, source)) : _util_identity__WEBPACK_IMPORTED_MODULE_1__.identity, (0,_takeLast__WEBPACK_IMPORTED_MODULE_2__.takeLast)(1), hasDefaultValue ? (0,_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__.defaultIfEmpty)(defaultValue) : (0,_throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__.throwIfEmpty)(() => new _util_EmptyError__WEBPACK_IMPORTED_MODULE_5__.EmptyError()));
}

/***/ }),

/***/ 6634:
/*!********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/map.js ***!
  \********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   map: () => (/* binding */ map)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);


function map(project, thisArg) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let index = 0;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => {
      subscriber.next(project.call(thisArg, value, index++));
    }));
  });
}

/***/ }),

/***/ 5359:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/mapTo.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   mapTo: () => (/* binding */ mapTo)
/* harmony export */ });
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./map */ 6634);

function mapTo(value) {
  return (0,_map__WEBPACK_IMPORTED_MODULE_0__.map)(() => value);
}

/***/ }),

/***/ 4053:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/mergeAll.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   mergeAll: () => (/* binding */ mergeAll)
/* harmony export */ });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeMap */ 1292);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ 2525);


function mergeAll(concurrent = Infinity) {
  return (0,_mergeMap__WEBPACK_IMPORTED_MODULE_0__.mergeMap)(_util_identity__WEBPACK_IMPORTED_MODULE_1__.identity, concurrent);
}

/***/ }),

/***/ 5180:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/mergeInternals.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   mergeInternals: () => (/* binding */ mergeInternals)
/* harmony export */ });
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
  const buffer = [];
  let active = 0;
  let index = 0;
  let isComplete = false;
  const checkComplete = () => {
    if (isComplete && !buffer.length && !active) {
      subscriber.complete();
    }
  };
  const outerNext = value => active < concurrent ? doInnerSub(value) : buffer.push(value);
  const doInnerSub = value => {
    expand && subscriber.next(value);
    active++;
    let innerComplete = false;
    (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(project(value, index++)).subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, innerValue => {
      onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
      if (expand) {
        outerNext(innerValue);
      } else {
        subscriber.next(innerValue);
      }
    }, () => {
      innerComplete = true;
    }, undefined, () => {
      if (innerComplete) {
        try {
          active--;
          while (buffer.length && active < concurrent) {
            const bufferedValue = buffer.shift();
            if (innerSubScheduler) {
              (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));
            } else {
              doInnerSub(bufferedValue);
            }
          }
          checkComplete();
        } catch (err) {
          subscriber.error(err);
        }
      }
    }));
  };
  source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, outerNext, () => {
    isComplete = true;
    checkComplete();
  }));
  return () => {
    additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
  };
}

/***/ }),

/***/ 1292:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/mergeMap.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   mergeMap: () => (/* binding */ mergeMap)
/* harmony export */ });
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./map */ 6634);
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _mergeInternals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./mergeInternals */ 5180);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ 1679);





function mergeMap(project, resultSelector, concurrent = Infinity) {
  if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(resultSelector)) {
    return mergeMap((a, i) => (0,_map__WEBPACK_IMPORTED_MODULE_1__.map)((b, ii) => resultSelector(a, b, i, ii))((0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(project(a, i))), concurrent);
  } else if (typeof resultSelector === 'number') {
    concurrent = resultSelector;
  }
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_3__.operate)((source, subscriber) => (0,_mergeInternals__WEBPACK_IMPORTED_MODULE_4__.mergeInternals)(source, subscriber, project, concurrent));
}

/***/ }),

/***/ 2549:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/observeOn.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   observeOn: () => (/* binding */ observeOn)
/* harmony export */ });
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function observeOn(scheduler, delay = 0) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, () => subscriber.next(value), delay), () => (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, () => subscriber.complete(), delay), err => (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, () => subscriber.error(err), delay)));
  });
}

/***/ }),

/***/ 6018:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/refCount.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   refCount: () => (/* binding */ refCount)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);


function refCount() {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let connection = null;
    source._refCount++;
    const refCounter = (0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, undefined, undefined, undefined, () => {
      if (!source || source._refCount <= 0 || 0 < --source._refCount) {
        connection = null;
        return;
      }
      const sharedConnection = source._connection;
      const conn = connection;
      connection = null;
      if (sharedConnection && (!conn || sharedConnection === conn)) {
        sharedConnection.unsubscribe();
      }
      subscriber.unsubscribe();
    });
    source.subscribe(refCounter);
    if (!refCounter.closed) {
      connection = source.connect();
    }
  });
}

/***/ }),

/***/ 8719:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/scan.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scan: () => (/* binding */ scan)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _scanInternals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scanInternals */ 7489);


function scan(accumulator, seed) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((0,_scanInternals__WEBPACK_IMPORTED_MODULE_1__.scanInternals)(accumulator, seed, arguments.length >= 2, true));
}

/***/ }),

/***/ 7489:
/*!******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/scanInternals.js ***!
  \******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scanInternals: () => (/* binding */ scanInternals)
/* harmony export */ });
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);

function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
  return (source, subscriber) => {
    let hasState = hasSeed;
    let state = seed;
    let index = 0;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_0__.createOperatorSubscriber)(subscriber, value => {
      const i = index++;
      state = hasState ? accumulator(state, value, i) : (hasState = true, value);
      emitOnNext && subscriber.next(state);
    }, emitBeforeComplete && (() => {
      hasState && subscriber.next(state);
      subscriber.complete();
    })));
  };
}

/***/ }),

/***/ 348:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/startWith.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   startWith: () => (/* binding */ startWith)
/* harmony export */ });
/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/concat */ 8440);
/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ 3286);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);



function startWith(...values) {
  const scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(values);
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)((source, subscriber) => {
    (scheduler ? (0,_observable_concat__WEBPACK_IMPORTED_MODULE_2__.concat)(values, source, scheduler) : (0,_observable_concat__WEBPACK_IMPORTED_MODULE_2__.concat)(values, source)).subscribe(subscriber);
  });
}

/***/ }),

/***/ 8129:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/subscribeOn.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   subscribeOn: () => (/* binding */ subscribeOn)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);

function subscribeOn(scheduler, delay = 0) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay));
  });
}

/***/ }),

/***/ 462:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/switchMap.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   switchMap: () => (/* binding */ switchMap)
/* harmony export */ });
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function switchMap(project, resultSelector) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let innerSubscriber = null;
    let index = 0;
    let isComplete = false;
    const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => {
      innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
      let innerIndex = 0;
      const outerIndex = index++;
      (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(project(value, outerIndex)).subscribe(innerSubscriber = (0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, innerValue => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue), () => {
        innerSubscriber = null;
        checkComplete();
      }));
    }, () => {
      isComplete = true;
      checkComplete();
    }));
  });
}

/***/ }),

/***/ 1969:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/take.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   take: () => (/* binding */ take)
/* harmony export */ });
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/empty */ 3471);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function take(count) {
  return count <= 0 ? () => _observable_empty__WEBPACK_IMPORTED_MODULE_0__.EMPTY : (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)((source, subscriber) => {
    let seen = 0;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__.createOperatorSubscriber)(subscriber, value => {
      if (++seen <= count) {
        subscriber.next(value);
        if (count <= seen) {
          subscriber.complete();
        }
      }
    }));
  });
}

/***/ }),

/***/ 1437:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/takeLast.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   takeLast: () => (/* binding */ takeLast)
/* harmony export */ });
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/empty */ 3471);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function takeLast(count) {
  return count <= 0 ? () => _observable_empty__WEBPACK_IMPORTED_MODULE_0__.EMPTY : (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)((source, subscriber) => {
    let buffer = [];
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__.createOperatorSubscriber)(subscriber, value => {
      buffer.push(value);
      count < buffer.length && buffer.shift();
    }, () => {
      for (const value of buffer) {
        subscriber.next(value);
      }
      subscriber.complete();
    }, undefined, () => {
      buffer = null;
    }));
  });
}

/***/ }),

/***/ 473:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/takeUntil.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   takeUntil: () => (/* binding */ takeUntil)
/* harmony export */ });
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/noop */ 6599);




function takeUntil(notifier) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(notifier).subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__.createOperatorSubscriber)(subscriber, () => subscriber.complete(), _util_noop__WEBPACK_IMPORTED_MODULE_3__.noop));
    !subscriber.closed && source.subscribe(subscriber);
  });
}

/***/ }),

/***/ 4997:
/*!********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/tap.js ***!
  \********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   tap: () => (/* binding */ tap)
/* harmony export */ });
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ 1679);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/identity */ 2525);




function tap(observerOrNext, error, complete) {
  const tapObserver = (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(observerOrNext) || error || complete ? {
    next: observerOrNext,
    error,
    complete
  } : observerOrNext;
  return tapObserver ? (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)((source, subscriber) => {
    var _a;
    (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
    let isUnsub = true;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_2__.createOperatorSubscriber)(subscriber, value => {
      var _a;
      (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
      subscriber.next(value);
    }, () => {
      var _a;
      isUnsub = false;
      (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
      subscriber.complete();
    }, err => {
      var _a;
      isUnsub = false;
      (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
      subscriber.error(err);
    }, () => {
      var _a, _b;
      if (isUnsub) {
        (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
      }
      (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
    }));
  }) : _util_identity__WEBPACK_IMPORTED_MODULE_3__.identity;
}

/***/ }),

/***/ 5158:
/*!*****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/throwIfEmpty.js ***!
  \*****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   throwIfEmpty: () => (/* binding */ throwIfEmpty)
/* harmony export */ });
/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/EmptyError */ 8638);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);



function throwIfEmpty(errorFactory = defaultErrorFactory) {
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)((source, subscriber) => {
    let hasValue = false;
    source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, value => {
      hasValue = true;
      subscriber.next(value);
    }, () => hasValue ? subscriber.complete() : subscriber.error(errorFactory())));
  });
}
function defaultErrorFactory() {
  return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__.EmptyError();
}

/***/ }),

/***/ 3439:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/operators/timeout.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   TimeoutError: () => (/* binding */ TimeoutError),
/* harmony export */   timeout: () => (/* binding */ timeout)
/* harmony export */ });
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scheduler/async */ 4908);
/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isDate */ 315);
/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/lift */ 2574);
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _util_createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/createErrorClass */ 6837);
/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./OperatorSubscriber */ 5952);
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);







const TimeoutError = (0,_util_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(_super => function TimeoutErrorImpl(info = null) {
  _super(this);
  this.message = 'Timeout has occurred';
  this.name = 'TimeoutError';
  this.info = info;
});
function timeout(config, schedulerArg) {
  const {
    first,
    each,
    with: _with = timeoutErrorFactory,
    scheduler = schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : _scheduler_async__WEBPACK_IMPORTED_MODULE_1__.asyncScheduler,
    meta = null
  } = (0,_util_isDate__WEBPACK_IMPORTED_MODULE_2__.isValidDate)(config) ? {
    first: config
  } : typeof config === 'number' ? {
    each: config
  } : config;
  if (first == null && each == null) {
    throw new TypeError('No timeout provided.');
  }
  return (0,_util_lift__WEBPACK_IMPORTED_MODULE_3__.operate)((source, subscriber) => {
    let originalSourceSubscription;
    let timerSubscription;
    let lastValue = null;
    let seen = 0;
    const startTimer = delay => {
      timerSubscription = (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_4__.executeSchedule)(subscriber, scheduler, () => {
        try {
          originalSourceSubscription.unsubscribe();
          (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_5__.innerFrom)(_with({
            meta,
            lastValue,
            seen
          })).subscribe(subscriber);
        } catch (err) {
          subscriber.error(err);
        }
      }, delay);
    };
    originalSourceSubscription = source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_6__.createOperatorSubscriber)(subscriber, value => {
      timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
      seen++;
      subscriber.next(lastValue = value);
      each > 0 && startTimer(each);
    }, undefined, undefined, () => {
      if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
        timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
      }
      lastValue = null;
    }));
    !seen && startTimer(first != null ? typeof first === 'number' ? first : +first - scheduler.now() : each);
  });
}
function timeoutErrorFactory(info) {
  throw new TimeoutError(info);
}

/***/ }),

/***/ 9900:
/*!******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduleArray.js ***!
  \******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduleArray: () => (/* binding */ scheduleArray)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);

function scheduleArray(input, scheduler) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    let i = 0;
    return scheduler.schedule(function () {
      if (i === input.length) {
        subscriber.complete();
      } else {
        subscriber.next(input[i++]);
        if (!subscriber.closed) {
          this.schedule();
        }
      }
    });
  });
}

/***/ }),

/***/ 5843:
/*!**************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduleAsyncIterable.js ***!
  \**************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduleAsyncIterable: () => (/* binding */ scheduleAsyncIterable)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);


function scheduleAsyncIterable(input, scheduler) {
  if (!input) {
    throw new Error('Iterable cannot be null');
  }
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, () => {
      const iterator = input[Symbol.asyncIterator]();
      (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, () => {
        iterator.next().then(result => {
          if (result.done) {
            subscriber.complete();
          } else {
            subscriber.next(result.value);
          }
        });
      }, 0, true);
    });
  });
}

/***/ }),

/***/ 3671:
/*!*********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduleIterable.js ***!
  \*********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduleIterable: () => (/* binding */ scheduleIterable)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../symbol/iterator */ 6065);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isFunction */ 1679);
/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/executeSchedule */ 5409);




function scheduleIterable(input, scheduler) {
  return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(subscriber => {
    let iterator;
    (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, () => {
      iterator = input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_2__.iterator]();
      (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, () => {
        let value;
        let done;
        try {
          ({
            value,
            done
          } = iterator.next());
        } catch (err) {
          subscriber.error(err);
          return;
        }
        if (done) {
          subscriber.complete();
        } else {
          subscriber.next(value);
        }
      }, 0, true);
    });
    return () => (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_3__.isFunction)(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return();
  });
}

/***/ }),

/***/ 4836:
/*!***********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduleObservable.js ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduleObservable: () => (/* binding */ scheduleObservable)
/* harmony export */ });
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/observeOn */ 2549);
/* harmony import */ var _operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/subscribeOn */ 8129);



function scheduleObservable(input, scheduler) {
  return (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(input).pipe((0,_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__.subscribeOn)(scheduler), (0,_operators_observeOn__WEBPACK_IMPORTED_MODULE_2__.observeOn)(scheduler));
}

/***/ }),

/***/ 620:
/*!********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/schedulePromise.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   schedulePromise: () => (/* binding */ schedulePromise)
/* harmony export */ });
/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ 8422);
/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/observeOn */ 2549);
/* harmony import */ var _operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/subscribeOn */ 8129);



function schedulePromise(input, scheduler) {
  return (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(input).pipe((0,_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__.subscribeOn)(scheduler), (0,_operators_observeOn__WEBPACK_IMPORTED_MODULE_2__.observeOn)(scheduler));
}

/***/ }),

/***/ 6954:
/*!*******************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduleReadableStreamLike.js ***!
  \*******************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduleReadableStreamLike: () => (/* binding */ scheduleReadableStreamLike)
/* harmony export */ });
/* harmony import */ var _scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scheduleAsyncIterable */ 5843);
/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isReadableStreamLike */ 7684);


function scheduleReadableStreamLike(input, scheduler) {
  return (0,_scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_0__.scheduleAsyncIterable)((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_1__.readableStreamLikeToAsyncGenerator)(input), scheduler);
}

/***/ }),

/***/ 7689:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduled/scheduled.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   scheduled: () => (/* binding */ scheduled)
/* harmony export */ });
/* harmony import */ var _scheduleObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scheduleObservable */ 4836);
/* harmony import */ var _schedulePromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./schedulePromise */ 620);
/* harmony import */ var _scheduleArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./scheduleArray */ 9900);
/* harmony import */ var _scheduleIterable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./scheduleIterable */ 3671);
/* harmony import */ var _scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./scheduleAsyncIterable */ 5843);
/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isInteropObservable */ 9287);
/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isPromise */ 7082);
/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isArrayLike */ 4329);
/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/isIterable */ 2797);
/* harmony import */ var _util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/isAsyncIterable */ 7321);
/* harmony import */ var _util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/throwUnobservableError */ 471);
/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/isReadableStreamLike */ 7684);
/* harmony import */ var _scheduleReadableStreamLike__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./scheduleReadableStreamLike */ 6954);













function scheduled(input, scheduler) {
  if (input != null) {
    if ((0,_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_0__.isInteropObservable)(input)) {
      return (0,_scheduleObservable__WEBPACK_IMPORTED_MODULE_1__.scheduleObservable)(input, scheduler);
    }
    if ((0,_util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__.isArrayLike)(input)) {
      return (0,_scheduleArray__WEBPACK_IMPORTED_MODULE_3__.scheduleArray)(input, scheduler);
    }
    if ((0,_util_isPromise__WEBPACK_IMPORTED_MODULE_4__.isPromise)(input)) {
      return (0,_schedulePromise__WEBPACK_IMPORTED_MODULE_5__.schedulePromise)(input, scheduler);
    }
    if ((0,_util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_6__.isAsyncIterable)(input)) {
      return (0,_scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_7__.scheduleAsyncIterable)(input, scheduler);
    }
    if ((0,_util_isIterable__WEBPACK_IMPORTED_MODULE_8__.isIterable)(input)) {
      return (0,_scheduleIterable__WEBPACK_IMPORTED_MODULE_9__.scheduleIterable)(input, scheduler);
    }
    if ((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_10__.isReadableStreamLike)(input)) {
      return (0,_scheduleReadableStreamLike__WEBPACK_IMPORTED_MODULE_11__.scheduleReadableStreamLike)(input, scheduler);
    }
  }
  throw (0,_util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_12__.createInvalidObservableTypeError)(input);
}

/***/ }),

/***/ 5252:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/Action.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Action: () => (/* binding */ Action)
/* harmony export */ });
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subscription */ 2273);

class Action extends _Subscription__WEBPACK_IMPORTED_MODULE_0__.Subscription {
  constructor(scheduler, work) {
    super();
  }
  schedule(state, delay = 0) {
    return this;
  }
}

/***/ }),

/***/ 1022:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/AsyncAction.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AsyncAction: () => (/* binding */ AsyncAction)
/* harmony export */ });
/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Action */ 5252);
/* harmony import */ var _intervalProvider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./intervalProvider */ 2046);
/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/arrRemove */ 5868);



class AsyncAction extends _Action__WEBPACK_IMPORTED_MODULE_0__.Action {
  constructor(scheduler, work) {
    super(scheduler, work);
    this.scheduler = scheduler;
    this.work = work;
    this.pending = false;
  }
  schedule(state, delay = 0) {
    var _a;
    if (this.closed) {
      return this;
    }
    this.state = state;
    const id = this.id;
    const scheduler = this.scheduler;
    if (id != null) {
      this.id = this.recycleAsyncId(scheduler, id, delay);
    }
    this.pending = true;
    this.delay = delay;
    this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay);
    return this;
  }
  requestAsyncId(scheduler, _id, delay = 0) {
    return _intervalProvider__WEBPACK_IMPORTED_MODULE_1__.intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
  }
  recycleAsyncId(_scheduler, id, delay = 0) {
    if (delay != null && this.delay === delay && this.pending === false) {
      return id;
    }
    if (id != null) {
      _intervalProvider__WEBPACK_IMPORTED_MODULE_1__.intervalProvider.clearInterval(id);
    }
    return undefined;
  }
  execute(state, delay) {
    if (this.closed) {
      return new Error('executing a cancelled action');
    }
    this.pending = false;
    const error = this._execute(state, delay);
    if (error) {
      return error;
    } else if (this.pending === false && this.id != null) {
      this.id = this.recycleAsyncId(this.scheduler, this.id, null);
    }
  }
  _execute(state, _delay) {
    let errored = false;
    let errorValue;
    try {
      this.work(state);
    } catch (e) {
      errored = true;
      errorValue = e ? e : new Error('Scheduled action threw falsy error');
    }
    if (errored) {
      this.unsubscribe();
      return errorValue;
    }
  }
  unsubscribe() {
    if (!this.closed) {
      const {
        id,
        scheduler
      } = this;
      const {
        actions
      } = scheduler;
      this.work = this.state = this.scheduler = null;
      this.pending = false;
      (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_2__.arrRemove)(actions, this);
      if (id != null) {
        this.id = this.recycleAsyncId(scheduler, id, null);
      }
      this.delay = null;
      super.unsubscribe();
    }
  }
}

/***/ }),

/***/ 5451:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/AsyncScheduler.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AsyncScheduler: () => (/* binding */ AsyncScheduler)
/* harmony export */ });
/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Scheduler */ 7255);

class AsyncScheduler extends _Scheduler__WEBPACK_IMPORTED_MODULE_0__.Scheduler {
  constructor(SchedulerAction, now = _Scheduler__WEBPACK_IMPORTED_MODULE_0__.Scheduler.now) {
    super(SchedulerAction, now);
    this.actions = [];
    this._active = false;
  }
  flush(action) {
    const {
      actions
    } = this;
    if (this._active) {
      actions.push(action);
      return;
    }
    let error;
    this._active = true;
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (action = actions.shift());
    this._active = false;
    if (error) {
      while (action = actions.shift()) {
        action.unsubscribe();
      }
      throw error;
    }
  }
}

/***/ }),

/***/ 4908:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/async.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   async: () => (/* binding */ async),
/* harmony export */   asyncScheduler: () => (/* binding */ asyncScheduler)
/* harmony export */ });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncAction */ 1022);
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncScheduler */ 5451);


const asyncScheduler = new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__.AsyncScheduler(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__.AsyncAction);
const async = asyncScheduler;

/***/ }),

/***/ 6345:
/*!**************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/dateTimestampProvider.js ***!
  \**************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   dateTimestampProvider: () => (/* binding */ dateTimestampProvider)
/* harmony export */ });
const dateTimestampProvider = {
  now() {
    return (dateTimestampProvider.delegate || Date).now();
  },
  delegate: undefined
};

/***/ }),

/***/ 2046:
/*!*********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/intervalProvider.js ***!
  \*********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   intervalProvider: () => (/* binding */ intervalProvider)
/* harmony export */ });
const intervalProvider = {
  setInterval(handler, timeout, ...args) {
    const {
      delegate
    } = intervalProvider;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
      return delegate.setInterval(handler, timeout, ...args);
    }
    return setInterval(handler, timeout, ...args);
  },
  clearInterval(handle) {
    const {
      delegate
    } = intervalProvider;
    return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
  },
  delegate: undefined
};

/***/ }),

/***/ 2766:
/*!********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/scheduler/timeoutProvider.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   timeoutProvider: () => (/* binding */ timeoutProvider)
/* harmony export */ });
const timeoutProvider = {
  setTimeout(handler, timeout, ...args) {
    const {
      delegate
    } = timeoutProvider;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
      return delegate.setTimeout(handler, timeout, ...args);
    }
    return setTimeout(handler, timeout, ...args);
  },
  clearTimeout(handle) {
    const {
      delegate
    } = timeoutProvider;
    return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
  },
  delegate: undefined
};

/***/ }),

/***/ 6065:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/symbol/iterator.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   getSymbolIterator: () => (/* binding */ getSymbolIterator),
/* harmony export */   iterator: () => (/* binding */ iterator)
/* harmony export */ });
function getSymbolIterator() {
  if (typeof Symbol !== 'function' || !Symbol.iterator) {
    return '@@iterator';
  }
  return Symbol.iterator;
}
const iterator = getSymbolIterator();

/***/ }),

/***/ 5678:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/symbol/observable.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   observable: () => (/* binding */ observable)
/* harmony export */ });
const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();

/***/ }),

/***/ 8638:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/EmptyError.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EmptyError: () => (/* binding */ EmptyError)
/* harmony export */ });
/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ 6837);

const EmptyError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(_super => function EmptyErrorImpl() {
  _super(this);
  this.name = 'EmptyError';
  this.message = 'no elements in sequence';
});

/***/ }),

/***/ 6869:
/*!***********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/ObjectUnsubscribedError.js ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ObjectUnsubscribedError: () => (/* binding */ ObjectUnsubscribedError)
/* harmony export */ });
/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ 6837);

const ObjectUnsubscribedError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(_super => function ObjectUnsubscribedErrorImpl() {
  _super(this);
  this.name = 'ObjectUnsubscribedError';
  this.message = 'object unsubscribed';
});

/***/ }),

/***/ 3687:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/UnsubscriptionError.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   UnsubscriptionError: () => (/* binding */ UnsubscriptionError)
/* harmony export */ });
/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ 6837);

const UnsubscriptionError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(_super => function UnsubscriptionErrorImpl(errors) {
  _super(this);
  this.message = errors ? `${errors.length} errors occurred during unsubscription:
${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\n  ')}` : '';
  this.name = 'UnsubscriptionError';
  this.errors = errors;
});

/***/ }),

/***/ 3286:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/args.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   popNumber: () => (/* binding */ popNumber),
/* harmony export */   popResultSelector: () => (/* binding */ popResultSelector),
/* harmony export */   popScheduler: () => (/* binding */ popScheduler)
/* harmony export */ });
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);
/* harmony import */ var _isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isScheduler */ 1478);


function last(arr) {
  return arr[arr.length - 1];
}
function popResultSelector(args) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(last(args)) ? args.pop() : undefined;
}
function popScheduler(args) {
  return (0,_isScheduler__WEBPACK_IMPORTED_MODULE_1__.isScheduler)(last(args)) ? args.pop() : undefined;
}
function popNumber(args, defaultValue) {
  return typeof last(args) === 'number' ? args.pop() : defaultValue;
}

/***/ }),

/***/ 3977:
/*!********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/argsArgArrayOrObject.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   argsArgArrayOrObject: () => (/* binding */ argsArgArrayOrObject)
/* harmony export */ });
const {
  isArray
} = Array;
const {
  getPrototypeOf,
  prototype: objectProto,
  keys: getKeys
} = Object;
function argsArgArrayOrObject(args) {
  if (args.length === 1) {
    const first = args[0];
    if (isArray(first)) {
      return {
        args: first,
        keys: null
      };
    }
    if (isPOJO(first)) {
      const keys = getKeys(first);
      return {
        args: keys.map(key => first[key]),
        keys
      };
    }
  }
  return {
    args: args,
    keys: null
  };
}
function isPOJO(obj) {
  return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;
}

/***/ }),

/***/ 366:
/*!**************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/argsOrArgArray.js ***!
  \**************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   argsOrArgArray: () => (/* binding */ argsOrArgArray)
/* harmony export */ });
const {
  isArray
} = Array;
function argsOrArgArray(args) {
  return args.length === 1 && isArray(args[0]) ? args[0] : args;
}

/***/ }),

/***/ 5868:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/arrRemove.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   arrRemove: () => (/* binding */ arrRemove)
/* harmony export */ });
function arrRemove(arr, item) {
  if (arr) {
    const index = arr.indexOf(item);
    0 <= index && arr.splice(index, 1);
  }
}

/***/ }),

/***/ 6837:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/createErrorClass.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createErrorClass: () => (/* binding */ createErrorClass)
/* harmony export */ });
function createErrorClass(createImpl) {
  const _super = instance => {
    Error.call(instance);
    instance.stack = new Error().stack;
  };
  const ctorFunc = createImpl(_super);
  ctorFunc.prototype = Object.create(Error.prototype);
  ctorFunc.prototype.constructor = ctorFunc;
  return ctorFunc;
}

/***/ }),

/***/ 2536:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/createObject.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createObject: () => (/* binding */ createObject)
/* harmony export */ });
function createObject(keys, values) {
  return keys.reduce((result, key, i) => (result[key] = values[i], result), {});
}

/***/ }),

/***/ 8610:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/errorContext.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   captureError: () => (/* binding */ captureError),
/* harmony export */   errorContext: () => (/* binding */ errorContext)
/* harmony export */ });
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config */ 6826);

let context = null;
function errorContext(cb) {
  if (_config__WEBPACK_IMPORTED_MODULE_0__.config.useDeprecatedSynchronousErrorHandling) {
    const isRoot = !context;
    if (isRoot) {
      context = {
        errorThrown: false,
        error: null
      };
    }
    cb();
    if (isRoot) {
      const {
        errorThrown,
        error
      } = context;
      context = null;
      if (errorThrown) {
        throw error;
      }
    }
  } else {
    cb();
  }
}
function captureError(err) {
  if (_config__WEBPACK_IMPORTED_MODULE_0__.config.useDeprecatedSynchronousErrorHandling && context) {
    context.errorThrown = true;
    context.error = err;
  }
}

/***/ }),

/***/ 5409:
/*!***************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/executeSchedule.js ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   executeSchedule: () => (/* binding */ executeSchedule)
/* harmony export */ });
function executeSchedule(parentSubscription, scheduler, work, delay = 0, repeat = false) {
  const scheduleSubscription = scheduler.schedule(function () {
    work();
    if (repeat) {
      parentSubscription.add(this.schedule(null, delay));
    } else {
      this.unsubscribe();
    }
  }, delay);
  parentSubscription.add(scheduleSubscription);
  if (!repeat) {
    return scheduleSubscription;
  }
}

/***/ }),

/***/ 2525:
/*!********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/identity.js ***!
  \********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   identity: () => (/* binding */ identity)
/* harmony export */ });
function identity(x) {
  return x;
}

/***/ }),

/***/ 4329:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isArrayLike.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isArrayLike: () => (/* binding */ isArrayLike)
/* harmony export */ });
const isArrayLike = x => x && typeof x.length === 'number' && typeof x !== 'function';

/***/ }),

/***/ 7321:
/*!***************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isAsyncIterable.js ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isAsyncIterable: () => (/* binding */ isAsyncIterable)
/* harmony export */ });
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);

function isAsyncIterable(obj) {
  return Symbol.asyncIterator && (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
}

/***/ }),

/***/ 315:
/*!******************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isDate.js ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isValidDate: () => (/* binding */ isValidDate)
/* harmony export */ });
function isValidDate(value) {
  return value instanceof Date && !isNaN(value);
}

/***/ }),

/***/ 1679:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isFunction.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isFunction: () => (/* binding */ isFunction)
/* harmony export */ });
function isFunction(value) {
  return typeof value === 'function';
}

/***/ }),

/***/ 9287:
/*!*******************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isInteropObservable.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isInteropObservable: () => (/* binding */ isInteropObservable)
/* harmony export */ });
/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../symbol/observable */ 5678);
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);


function isInteropObservable(input) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(input[_symbol_observable__WEBPACK_IMPORTED_MODULE_1__.observable]);
}

/***/ }),

/***/ 2797:
/*!**********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isIterable.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isIterable: () => (/* binding */ isIterable)
/* harmony export */ });
/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../symbol/iterator */ 6065);
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);


function isIterable(input) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(input === null || input === void 0 ? void 0 : input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_1__.iterator]);
}

/***/ }),

/***/ 9178:
/*!************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isObservable.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isObservable: () => (/* binding */ isObservable)
/* harmony export */ });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ 2921);
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isFunction */ 1679);


function isObservable(obj) {
  return !!obj && (obj instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable || (0,_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(obj.lift) && (0,_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(obj.subscribe));
}

/***/ }),

/***/ 7082:
/*!*********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isPromise.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isPromise: () => (/* binding */ isPromise)
/* harmony export */ });
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);

function isPromise(value) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value === null || value === void 0 ? void 0 : value.then);
}

/***/ }),

/***/ 7684:
/*!********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isReadableStreamLike.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isReadableStreamLike: () => (/* binding */ isReadableStreamLike),
/* harmony export */   readableStreamLikeToAsyncGenerator: () => (/* binding */ readableStreamLikeToAsyncGenerator)
/* harmony export */ });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ 3215);
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isFunction */ 1679);


function readableStreamLikeToAsyncGenerator(readableStream) {
  return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__asyncGenerator)(this, arguments, function* readableStreamLikeToAsyncGenerator_1() {
    const reader = readableStream.getReader();
    try {
      while (true) {
        const {
          value,
          done
        } = yield (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(reader.read());
        if (done) {
          return yield (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(void 0);
        }
        yield yield (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(value);
      }
    } finally {
      reader.releaseLock();
    }
  });
}
function isReadableStreamLike(obj) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(obj === null || obj === void 0 ? void 0 : obj.getReader);
}

/***/ }),

/***/ 1478:
/*!***********************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/isScheduler.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isScheduler: () => (/* binding */ isScheduler)
/* harmony export */ });
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);

function isScheduler(value) {
  return value && (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value.schedule);
}

/***/ }),

/***/ 2574:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/lift.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   hasLift: () => (/* binding */ hasLift),
/* harmony export */   operate: () => (/* binding */ operate)
/* harmony export */ });
/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ 1679);

function hasLift(source) {
  return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(source === null || source === void 0 ? void 0 : source.lift);
}
function operate(init) {
  return source => {
    if (hasLift(source)) {
      return source.lift(function (liftedSource) {
        try {
          return init(liftedSource, this);
        } catch (err) {
          this.error(err);
        }
      });
    }
    throw new TypeError('Unable to lift unknown Observable type');
  };
}

/***/ }),

/***/ 5258:
/*!****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/mapOneOrManyArgs.js ***!
  \****************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   mapOneOrManyArgs: () => (/* binding */ mapOneOrManyArgs)
/* harmony export */ });
/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../operators/map */ 6634);

const {
  isArray
} = Array;
function callOrApply(fn, args) {
  return isArray(args) ? fn(...args) : fn(args);
}
function mapOneOrManyArgs(fn) {
  return (0,_operators_map__WEBPACK_IMPORTED_MODULE_0__.map)(args => callOrApply(fn, args));
}

/***/ }),

/***/ 6599:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/noop.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   noop: () => (/* binding */ noop)
/* harmony export */ });
function noop() {}

/***/ }),

/***/ 5851:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/pipe.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   pipe: () => (/* binding */ pipe),
/* harmony export */   pipeFromArray: () => (/* binding */ pipeFromArray)
/* harmony export */ });
/* harmony import */ var _identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./identity */ 2525);

function pipe(...fns) {
  return pipeFromArray(fns);
}
function pipeFromArray(fns) {
  if (fns.length === 0) {
    return _identity__WEBPACK_IMPORTED_MODULE_0__.identity;
  }
  if (fns.length === 1) {
    return fns[0];
  }
  return function piped(input) {
    return fns.reduce((prev, fn) => fn(prev), input);
  };
}

/***/ }),

/***/ 1438:
/*!********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/reportUnhandledError.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   reportUnhandledError: () => (/* binding */ reportUnhandledError)
/* harmony export */ });
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ 6826);
/* harmony import */ var _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/timeoutProvider */ 2766);


function reportUnhandledError(err) {
  _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_0__.timeoutProvider.setTimeout(() => {
    const {
      onUnhandledError
    } = _config__WEBPACK_IMPORTED_MODULE_1__.config;
    if (onUnhandledError) {
      onUnhandledError(err);
    } else {
      throw err;
    }
  });
}

/***/ }),

/***/ 471:
/*!**********************************************************************************************************!*\
  !*** ./node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm/internal/util/throwUnobservableError.js ***!
  \**********************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createInvalidObservableTypeError: () => (/* binding */ createInvalidObservableTypeError)
/* harmony export */ });
function createInvalidObservableTypeError(input) {
  return new TypeError(`You provided ${input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`);
}

/***/ }),

/***/ 287:
/*!*************************************************************************************************!*\
  !*** ./node_modules/.pnpm/signature_pad@5.0.4/node_modules/signature_pad/dist/signature_pad.js ***!
  \*************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ SignaturePad)
/* harmony export */ });
/*!
 * Signature Pad v5.0.4 | https://github.com/szimek/signature_pad
 * (c) 2024 Szymon Nowak | Released under the MIT license
 */

class Point {
  constructor(x, y, pressure, time) {
    if (isNaN(x) || isNaN(y)) {
      throw new Error(`Point is invalid: (${x}, ${y})`);
    }
    this.x = +x;
    this.y = +y;
    this.pressure = pressure || 0;
    this.time = time || Date.now();
  }
  distanceTo(start) {
    return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
  }
  equals(other) {
    return this.x === other.x && this.y === other.y && this.pressure === other.pressure && this.time === other.time;
  }
  velocityFrom(start) {
    return this.time !== start.time ? this.distanceTo(start) / (this.time - start.time) : 0;
  }
}
class Bezier {
  static fromPoints(points, widths) {
    const c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;
    const c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;
    return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
  }
  static calculateControlPoints(s1, s2, s3) {
    const dx1 = s1.x - s2.x;
    const dy1 = s1.y - s2.y;
    const dx2 = s2.x - s3.x;
    const dy2 = s2.y - s3.y;
    const m1 = {
      x: (s1.x + s2.x) / 2.0,
      y: (s1.y + s2.y) / 2.0
    };
    const m2 = {
      x: (s2.x + s3.x) / 2.0,
      y: (s2.y + s3.y) / 2.0
    };
    const l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
    const l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
    const dxm = m1.x - m2.x;
    const dym = m1.y - m2.y;
    const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);
    const cm = {
      x: m2.x + dxm * k,
      y: m2.y + dym * k
    };
    const tx = s2.x - cm.x;
    const ty = s2.y - cm.y;
    return {
      c1: new Point(m1.x + tx, m1.y + ty),
      c2: new Point(m2.x + tx, m2.y + ty)
    };
  }
  constructor(startPoint, control2, control1, endPoint, startWidth, endWidth) {
    this.startPoint = startPoint;
    this.control2 = control2;
    this.control1 = control1;
    this.endPoint = endPoint;
    this.startWidth = startWidth;
    this.endWidth = endWidth;
  }
  length() {
    const steps = 10;
    let length = 0;
    let px;
    let py;
    for (let i = 0; i <= steps; i += 1) {
      const t = i / steps;
      const cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
      const cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
      if (i > 0) {
        const xdiff = cx - px;
        const ydiff = cy - py;
        length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
      }
      px = cx;
      py = cy;
    }
    return length;
  }
  point(t, start, c1, c2, end) {
    return start * (1.0 - t) * (1.0 - t) * (1.0 - t) + 3.0 * c1 * (1.0 - t) * (1.0 - t) * t + 3.0 * c2 * (1.0 - t) * t * t + end * t * t * t;
  }
}
class SignatureEventTarget {
  constructor() {
    try {
      this._et = new EventTarget();
    } catch (_a) {
      this._et = document;
    }
  }
  addEventListener(type, listener, options) {
    this._et.addEventListener(type, listener, options);
  }
  dispatchEvent(event) {
    return this._et.dispatchEvent(event);
  }
  removeEventListener(type, callback, options) {
    this._et.removeEventListener(type, callback, options);
  }
}
function throttle(fn, wait = 250) {
  let previous = 0;
  let timeout = null;
  let result;
  let storedContext;
  let storedArgs;
  const later = () => {
    previous = Date.now();
    timeout = null;
    result = fn.apply(storedContext, storedArgs);
    if (!timeout) {
      storedContext = null;
      storedArgs = [];
    }
  };
  return function wrapper(...args) {
    const now = Date.now();
    const remaining = wait - (now - previous);
    storedContext = this;
    storedArgs = args;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      result = fn.apply(storedContext, storedArgs);
      if (!timeout) {
        storedContext = null;
        storedArgs = [];
      }
    } else if (!timeout) {
      timeout = window.setTimeout(later, remaining);
    }
    return result;
  };
}
class SignaturePad extends SignatureEventTarget {
  constructor(canvas, options = {}) {
    var _a, _b, _c;
    super();
    this.canvas = canvas;
    this._drawingStroke = false;
    this._isEmpty = true;
    this._lastPoints = [];
    this._data = [];
    this._lastVelocity = 0;
    this._lastWidth = 0;
    this._handleMouseDown = event => {
      if (!this._isLeftButtonPressed(event, true) || this._drawingStroke) {
        return;
      }
      this._strokeBegin(this._pointerEventToSignatureEvent(event));
    };
    this._handleMouseMove = event => {
      if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {
        this._strokeEnd(this._pointerEventToSignatureEvent(event), false);
        return;
      }
      this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));
    };
    this._handleMouseUp = event => {
      if (this._isLeftButtonPressed(event)) {
        return;
      }
      this._strokeEnd(this._pointerEventToSignatureEvent(event));
    };
    this._handleTouchStart = event => {
      if (event.targetTouches.length !== 1 || this._drawingStroke) {
        return;
      }
      if (event.cancelable) {
        event.preventDefault();
      }
      this._strokeBegin(this._touchEventToSignatureEvent(event));
    };
    this._handleTouchMove = event => {
      if (event.targetTouches.length !== 1) {
        return;
      }
      if (event.cancelable) {
        event.preventDefault();
      }
      if (!this._drawingStroke) {
        this._strokeEnd(this._touchEventToSignatureEvent(event), false);
        return;
      }
      this._strokeMoveUpdate(this._touchEventToSignatureEvent(event));
    };
    this._handleTouchEnd = event => {
      if (event.targetTouches.length !== 0) {
        return;
      }
      if (event.cancelable) {
        event.preventDefault();
      }
      this.canvas.removeEventListener('touchmove', this._handleTouchMove);
      this._strokeEnd(this._touchEventToSignatureEvent(event));
    };
    this._handlePointerDown = event => {
      if (!event.isPrimary || !this._isLeftButtonPressed(event) || this._drawingStroke) {
        return;
      }
      event.preventDefault();
      this._strokeBegin(this._pointerEventToSignatureEvent(event));
    };
    this._handlePointerMove = event => {
      if (!event.isPrimary) {
        return;
      }
      if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {
        this._strokeEnd(this._pointerEventToSignatureEvent(event), false);
        return;
      }
      event.preventDefault();
      this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));
    };
    this._handlePointerUp = event => {
      if (!event.isPrimary || this._isLeftButtonPressed(event)) {
        return;
      }
      event.preventDefault();
      this._strokeEnd(this._pointerEventToSignatureEvent(event));
    };
    this.velocityFilterWeight = options.velocityFilterWeight || 0.7;
    this.minWidth = options.minWidth || 0.5;
    this.maxWidth = options.maxWidth || 2.5;
    this.throttle = (_a = options.throttle) !== null && _a !== void 0 ? _a : 16;
    this.minDistance = (_b = options.minDistance) !== null && _b !== void 0 ? _b : 5;
    this.dotSize = options.dotSize || 0;
    this.penColor = options.penColor || 'black';
    this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';
    this.compositeOperation = options.compositeOperation || 'source-over';
    this.canvasContextOptions = (_c = options.canvasContextOptions) !== null && _c !== void 0 ? _c : {};
    this._strokeMoveUpdate = this.throttle ? throttle(SignaturePad.prototype._strokeUpdate, this.throttle) : SignaturePad.prototype._strokeUpdate;
    this._ctx = canvas.getContext('2d', this.canvasContextOptions);
    this.clear();
    this.on();
  }
  clear() {
    const {
      _ctx: ctx,
      canvas
    } = this;
    ctx.fillStyle = this.backgroundColor;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    this._data = [];
    this._reset(this._getPointGroupOptions());
    this._isEmpty = true;
  }
  fromDataURL(dataUrl, options = {}) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      const ratio = options.ratio || window.devicePixelRatio || 1;
      const width = options.width || this.canvas.width / ratio;
      const height = options.height || this.canvas.height / ratio;
      const xOffset = options.xOffset || 0;
      const yOffset = options.yOffset || 0;
      this._reset(this._getPointGroupOptions());
      image.onload = () => {
        this._ctx.drawImage(image, xOffset, yOffset, width, height);
        resolve();
      };
      image.onerror = error => {
        reject(error);
      };
      image.crossOrigin = 'anonymous';
      image.src = dataUrl;
      this._isEmpty = false;
    });
  }
  toDataURL(type = 'image/png', encoderOptions) {
    switch (type) {
      case 'image/svg+xml':
        if (typeof encoderOptions !== 'object') {
          encoderOptions = undefined;
        }
        return `data:image/svg+xml;base64,${btoa(this.toSVG(encoderOptions))}`;
      default:
        if (typeof encoderOptions !== 'number') {
          encoderOptions = undefined;
        }
        return this.canvas.toDataURL(type, encoderOptions);
    }
  }
  on() {
    this.canvas.style.touchAction = 'none';
    this.canvas.style.msTouchAction = 'none';
    this.canvas.style.userSelect = 'none';
    const isIOS = /Macintosh/.test(navigator.userAgent) && 'ontouchstart' in document;
    if (window.PointerEvent && !isIOS) {
      this._handlePointerEvents();
    } else {
      this._handleMouseEvents();
      if ('ontouchstart' in window) {
        this._handleTouchEvents();
      }
    }
  }
  off() {
    this.canvas.style.touchAction = 'auto';
    this.canvas.style.msTouchAction = 'auto';
    this.canvas.style.userSelect = 'auto';
    this.canvas.removeEventListener('pointerdown', this._handlePointerDown);
    this.canvas.removeEventListener('mousedown', this._handleMouseDown);
    this.canvas.removeEventListener('touchstart', this._handleTouchStart);
    this._removeMoveUpEventListeners();
  }
  _getListenerFunctions() {
    var _a;
    const canvasWindow = window.document === this.canvas.ownerDocument ? window : (_a = this.canvas.ownerDocument.defaultView) !== null && _a !== void 0 ? _a : this.canvas.ownerDocument;
    return {
      addEventListener: canvasWindow.addEventListener.bind(canvasWindow),
      removeEventListener: canvasWindow.removeEventListener.bind(canvasWindow)
    };
  }
  _removeMoveUpEventListeners() {
    const {
      removeEventListener
    } = this._getListenerFunctions();
    removeEventListener('pointermove', this._handlePointerMove);
    removeEventListener('pointerup', this._handlePointerUp);
    removeEventListener('mousemove', this._handleMouseMove);
    removeEventListener('mouseup', this._handleMouseUp);
    removeEventListener('touchmove', this._handleTouchMove);
    removeEventListener('touchend', this._handleTouchEnd);
  }
  isEmpty() {
    return this._isEmpty;
  }
  fromData(pointGroups, {
    clear = true
  } = {}) {
    if (clear) {
      this.clear();
    }
    this._fromData(pointGroups, this._drawCurve.bind(this), this._drawDot.bind(this));
    this._data = this._data.concat(pointGroups);
  }
  toData() {
    return this._data;
  }
  _isLeftButtonPressed(event, only) {
    if (only) {
      return event.buttons === 1;
    }
    return (event.buttons & 1) === 1;
  }
  _pointerEventToSignatureEvent(event) {
    return {
      event: event,
      type: event.type,
      x: event.clientX,
      y: event.clientY,
      pressure: 'pressure' in event ? event.pressure : 0
    };
  }
  _touchEventToSignatureEvent(event) {
    const touch = event.changedTouches[0];
    return {
      event: event,
      type: event.type,
      x: touch.clientX,
      y: touch.clientY,
      pressure: touch.force
    };
  }
  _getPointGroupOptions(group) {
    return {
      penColor: group && 'penColor' in group ? group.penColor : this.penColor,
      dotSize: group && 'dotSize' in group ? group.dotSize : this.dotSize,
      minWidth: group && 'minWidth' in group ? group.minWidth : this.minWidth,
      maxWidth: group && 'maxWidth' in group ? group.maxWidth : this.maxWidth,
      velocityFilterWeight: group && 'velocityFilterWeight' in group ? group.velocityFilterWeight : this.velocityFilterWeight,
      compositeOperation: group && 'compositeOperation' in group ? group.compositeOperation : this.compositeOperation
    };
  }
  _strokeBegin(event) {
    const cancelled = !this.dispatchEvent(new CustomEvent('beginStroke', {
      detail: event,
      cancelable: true
    }));
    if (cancelled) {
      return;
    }
    const {
      addEventListener
    } = this._getListenerFunctions();
    switch (event.event.type) {
      case 'mousedown':
        addEventListener('mousemove', this._handleMouseMove);
        addEventListener('mouseup', this._handleMouseUp);
        break;
      case 'touchstart':
        addEventListener('touchmove', this._handleTouchMove);
        addEventListener('touchend', this._handleTouchEnd);
        break;
      case 'pointerdown':
        addEventListener('pointermove', this._handlePointerMove);
        addEventListener('pointerup', this._handlePointerUp);
        break;
    }
    this._drawingStroke = true;
    const pointGroupOptions = this._getPointGroupOptions();
    const newPointGroup = Object.assign(Object.assign({}, pointGroupOptions), {
      points: []
    });
    this._data.push(newPointGroup);
    this._reset(pointGroupOptions);
    this._strokeUpdate(event);
  }
  _strokeUpdate(event) {
    if (!this._drawingStroke) {
      return;
    }
    if (this._data.length === 0) {
      this._strokeBegin(event);
      return;
    }
    this.dispatchEvent(new CustomEvent('beforeUpdateStroke', {
      detail: event
    }));
    const point = this._createPoint(event.x, event.y, event.pressure);
    const lastPointGroup = this._data[this._data.length - 1];
    const lastPoints = lastPointGroup.points;
    const lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
    const isLastPointTooClose = lastPoint ? point.distanceTo(lastPoint) <= this.minDistance : false;
    const pointGroupOptions = this._getPointGroupOptions(lastPointGroup);
    if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
      const curve = this._addPoint(point, pointGroupOptions);
      if (!lastPoint) {
        this._drawDot(point, pointGroupOptions);
      } else if (curve) {
        this._drawCurve(curve, pointGroupOptions);
      }
      lastPoints.push({
        time: point.time,
        x: point.x,
        y: point.y,
        pressure: point.pressure
      });
    }
    this.dispatchEvent(new CustomEvent('afterUpdateStroke', {
      detail: event
    }));
  }
  _strokeEnd(event, shouldUpdate = true) {
    this._removeMoveUpEventListeners();
    if (!this._drawingStroke) {
      return;
    }
    if (shouldUpdate) {
      this._strokeUpdate(event);
    }
    this._drawingStroke = false;
    this.dispatchEvent(new CustomEvent('endStroke', {
      detail: event
    }));
  }
  _handlePointerEvents() {
    this._drawingStroke = false;
    this.canvas.addEventListener('pointerdown', this._handlePointerDown);
  }
  _handleMouseEvents() {
    this._drawingStroke = false;
    this.canvas.addEventListener('mousedown', this._handleMouseDown);
  }
  _handleTouchEvents() {
    this.canvas.addEventListener('touchstart', this._handleTouchStart);
  }
  _reset(options) {
    this._lastPoints = [];
    this._lastVelocity = 0;
    this._lastWidth = (options.minWidth + options.maxWidth) / 2;
    this._ctx.fillStyle = options.penColor;
    this._ctx.globalCompositeOperation = options.compositeOperation;
  }
  _createPoint(x, y, pressure) {
    const rect = this.canvas.getBoundingClientRect();
    return new Point(x - rect.left, y - rect.top, pressure, new Date().getTime());
  }
  _addPoint(point, options) {
    const {
      _lastPoints
    } = this;
    _lastPoints.push(point);
    if (_lastPoints.length > 2) {
      if (_lastPoints.length === 3) {
        _lastPoints.unshift(_lastPoints[0]);
      }
      const widths = this._calculateCurveWidths(_lastPoints[1], _lastPoints[2], options);
      const curve = Bezier.fromPoints(_lastPoints, widths);
      _lastPoints.shift();
      return curve;
    }
    return null;
  }
  _calculateCurveWidths(startPoint, endPoint, options) {
    const velocity = options.velocityFilterWeight * endPoint.velocityFrom(startPoint) + (1 - options.velocityFilterWeight) * this._lastVelocity;
    const newWidth = this._strokeWidth(velocity, options);
    const widths = {
      end: newWidth,
      start: this._lastWidth
    };
    this._lastVelocity = velocity;
    this._lastWidth = newWidth;
    return widths;
  }
  _strokeWidth(velocity, options) {
    return Math.max(options.maxWidth / (velocity + 1), options.minWidth);
  }
  _drawCurveSegment(x, y, width) {
    const ctx = this._ctx;
    ctx.moveTo(x, y);
    ctx.arc(x, y, width, 0, 2 * Math.PI, false);
    this._isEmpty = false;
  }
  _drawCurve(curve, options) {
    const ctx = this._ctx;
    const widthDelta = curve.endWidth - curve.startWidth;
    const drawSteps = Math.ceil(curve.length()) * 2;
    ctx.beginPath();
    ctx.fillStyle = options.penColor;
    for (let i = 0; i < drawSteps; i += 1) {
      const t = i / drawSteps;
      const tt = t * t;
      const ttt = tt * t;
      const u = 1 - t;
      const uu = u * u;
      const uuu = uu * u;
      let x = uuu * curve.startPoint.x;
      x += 3 * uu * t * curve.control1.x;
      x += 3 * u * tt * curve.control2.x;
      x += ttt * curve.endPoint.x;
      let y = uuu * curve.startPoint.y;
      y += 3 * uu * t * curve.control1.y;
      y += 3 * u * tt * curve.control2.y;
      y += ttt * curve.endPoint.y;
      const width = Math.min(curve.startWidth + ttt * widthDelta, options.maxWidth);
      this._drawCurveSegment(x, y, width);
    }
    ctx.closePath();
    ctx.fill();
  }
  _drawDot(point, options) {
    const ctx = this._ctx;
    const width = options.dotSize > 0 ? options.dotSize : (options.minWidth + options.maxWidth) / 2;
    ctx.beginPath();
    this._drawCurveSegment(point.x, point.y, width);
    ctx.closePath();
    ctx.fillStyle = options.penColor;
    ctx.fill();
  }
  _fromData(pointGroups, drawCurve, drawDot) {
    for (const group of pointGroups) {
      const {
        points
      } = group;
      const pointGroupOptions = this._getPointGroupOptions(group);
      if (points.length > 1) {
        for (let j = 0; j < points.length; j += 1) {
          const basicPoint = points[j];
          const point = new Point(basicPoint.x, basicPoint.y, basicPoint.pressure, basicPoint.time);
          if (j === 0) {
            this._reset(pointGroupOptions);
          }
          const curve = this._addPoint(point, pointGroupOptions);
          if (curve) {
            drawCurve(curve, pointGroupOptions);
          }
        }
      } else {
        this._reset(pointGroupOptions);
        drawDot(points[0], pointGroupOptions);
      }
    }
  }
  toSVG({
    includeBackgroundColor = false
  } = {}) {
    const pointGroups = this._data;
    const ratio = Math.max(window.devicePixelRatio || 1, 1);
    const minX = 0;
    const minY = 0;
    const maxX = this.canvas.width / ratio;
    const maxY = this.canvas.height / ratio;
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
    svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
    svg.setAttribute('viewBox', `${minX} ${minY} ${maxX} ${maxY}`);
    svg.setAttribute('width', maxX.toString());
    svg.setAttribute('height', maxY.toString());
    if (includeBackgroundColor && this.backgroundColor) {
      const rect = document.createElement('rect');
      rect.setAttribute('width', '100%');
      rect.setAttribute('height', '100%');
      rect.setAttribute('fill', this.backgroundColor);
      svg.appendChild(rect);
    }
    this._fromData(pointGroups, (curve, {
      penColor
    }) => {
      const path = document.createElement('path');
      if (!isNaN(curve.control1.x) && !isNaN(curve.control1.y) && !isNaN(curve.control2.x) && !isNaN(curve.control2.y)) {
        const attr = `M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(3)} ` + `C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ` + `${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ` + `${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;
        path.setAttribute('d', attr);
        path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));
        path.setAttribute('stroke', penColor);
        path.setAttribute('fill', 'none');
        path.setAttribute('stroke-linecap', 'round');
        svg.appendChild(path);
      }
    }, (point, {
      penColor,
      dotSize,
      minWidth,
      maxWidth
    }) => {
      const circle = document.createElement('circle');
      const size = dotSize > 0 ? dotSize : (minWidth + maxWidth) / 2;
      circle.setAttribute('r', size.toString());
      circle.setAttribute('cx', point.x.toString());
      circle.setAttribute('cy', point.y.toString());
      circle.setAttribute('fill', penColor);
      svg.appendChild(circle);
    });
    return svg.outerHTML;
  }
}


/***/ }),

/***/ 3936:
/*!************************!*\
  !*** crypto (ignored) ***!
  \************************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ 4232:
/*!****************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+animations@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0_/node_modules/@angular/animations/fesm2022/animations.mjs ***!
  \****************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AUTO_STYLE: () => (/* binding */ AUTO_STYLE),
/* harmony export */   AnimationBuilder: () => (/* binding */ AnimationBuilder),
/* harmony export */   AnimationFactory: () => (/* binding */ AnimationFactory),
/* harmony export */   AnimationMetadataType: () => (/* binding */ AnimationMetadataType),
/* harmony export */   NoopAnimationPlayer: () => (/* binding */ NoopAnimationPlayer),
/* harmony export */   animate: () => (/* binding */ animate),
/* harmony export */   animateChild: () => (/* binding */ animateChild),
/* harmony export */   animation: () => (/* binding */ animation),
/* harmony export */   group: () => (/* binding */ group),
/* harmony export */   keyframes: () => (/* binding */ keyframes),
/* harmony export */   query: () => (/* binding */ query),
/* harmony export */   sequence: () => (/* binding */ sequence),
/* harmony export */   stagger: () => (/* binding */ stagger),
/* harmony export */   state: () => (/* binding */ state),
/* harmony export */   style: () => (/* binding */ style),
/* harmony export */   transition: () => (/* binding */ transition),
/* harmony export */   trigger: () => (/* binding */ trigger),
/* harmony export */   useAnimation: () => (/* binding */ useAnimation),
/* harmony export */   "ɵAnimationGroupPlayer": () => (/* binding */ AnimationGroupPlayer),
/* harmony export */   "ɵBrowserAnimationBuilder": () => (/* binding */ BrowserAnimationBuilder),
/* harmony export */   "ɵPRE_STYLE": () => (/* binding */ ɵPRE_STYLE)
/* harmony export */ });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */





/**
 * @description Constants for the categories of parameters that can be defined for animations.
 *
 * A corresponding function defines a set of parameters for each category, and
 * collects them into a corresponding `AnimationMetadata` object.
 *
 * @publicApi
 */
var AnimationMetadataType = /*#__PURE__*/function (AnimationMetadataType) {
  /**
   * Associates a named animation state with a set of CSS styles.
   * See [`state()`](api/animations/state)
   */
  AnimationMetadataType[AnimationMetadataType["State"] = 0] = "State";
  /**
   * Data for a transition from one animation state to another.
   * See `transition()`
   */
  AnimationMetadataType[AnimationMetadataType["Transition"] = 1] = "Transition";
  /**
   * Contains a set of animation steps.
   * See `sequence()`
   */
  AnimationMetadataType[AnimationMetadataType["Sequence"] = 2] = "Sequence";
  /**
   * Contains a set of animation steps.
   * See `{@link animations/group group()}`
   */
  AnimationMetadataType[AnimationMetadataType["Group"] = 3] = "Group";
  /**
   * Contains an animation step.
   * See `animate()`
   */
  AnimationMetadataType[AnimationMetadataType["Animate"] = 4] = "Animate";
  /**
   * Contains a set of animation steps.
   * See `keyframes()`
   */
  AnimationMetadataType[AnimationMetadataType["Keyframes"] = 5] = "Keyframes";
  /**
   * Contains a set of CSS property-value pairs into a named style.
   * See `style()`
   */
  AnimationMetadataType[AnimationMetadataType["Style"] = 6] = "Style";
  /**
   * Associates an animation with an entry trigger that can be attached to an element.
   * See `trigger()`
   */
  AnimationMetadataType[AnimationMetadataType["Trigger"] = 7] = "Trigger";
  /**
   * Contains a re-usable animation.
   * See `animation()`
   */
  AnimationMetadataType[AnimationMetadataType["Reference"] = 8] = "Reference";
  /**
   * Contains data to use in executing child animations returned by a query.
   * See `animateChild()`
   */
  AnimationMetadataType[AnimationMetadataType["AnimateChild"] = 9] = "AnimateChild";
  /**
   * Contains animation parameters for a re-usable animation.
   * See `useAnimation()`
   */
  AnimationMetadataType[AnimationMetadataType["AnimateRef"] = 10] = "AnimateRef";
  /**
   * Contains child-animation query data.
   * See `query()`
   */
  AnimationMetadataType[AnimationMetadataType["Query"] = 11] = "Query";
  /**
   * Contains data for staggering an animation sequence.
   * See `stagger()`
   */
  AnimationMetadataType[AnimationMetadataType["Stagger"] = 12] = "Stagger";
  return AnimationMetadataType;
}(AnimationMetadataType || {});
/**
 * Specifies automatic styling.
 *
 * @publicApi
 */
const AUTO_STYLE = '*';
/**
 * Creates a named animation trigger, containing a  list of [`state()`](api/animations/state)
 * and `transition()` entries to be evaluated when the expression
 * bound to the trigger changes.
 *
 * @param name An identifying string.
 * @param definitions  An animation definition object, containing an array of
 * [`state()`](api/animations/state) and `transition()` declarations.
 *
 * @return An object that encapsulates the trigger data.
 *
 * @usageNotes
 * Define an animation trigger in the `animations` section of `@Component` metadata.
 * In the template, reference the trigger by name and bind it to a trigger expression that
 * evaluates to a defined animation state, using the following format:
 *
 * `[@triggerName]="expression"`
 *
 * Animation trigger bindings convert all values to strings, and then match the
 * previous and current values against any linked transitions.
 * Booleans can be specified as `1` or `true` and `0` or `false`.
 *
 * ### Usage Example
 *
 * The following example creates an animation trigger reference based on the provided
 * name value.
 * The provided animation value is expected to be an array consisting of state and
 * transition declarations.
 *
 * ```typescript
 * @Component({
 *   selector: "my-component",
 *   templateUrl: "my-component-tpl.html",
 *   animations: [
 *     trigger("myAnimationTrigger", [
 *       state(...),
 *       state(...),
 *       transition(...),
 *       transition(...)
 *     ])
 *   ]
 * })
 * class MyComponent {
 *   myStatusExp = "something";
 * }
 * ```
 *
 * The template associated with this component makes use of the defined trigger
 * by binding to an element within its template code.
 *
 * ```html
 * <!-- somewhere inside of my-component-tpl.html -->
 * <div [@myAnimationTrigger]="myStatusExp">...</div>
 * ```
 *
 * ### Using an inline function
 * The `transition` animation method also supports reading an inline function which can decide
 * if its associated animation should be run.
 *
 * ```typescript
 * // this method is run each time the `myAnimationTrigger` trigger value changes.
 * function myInlineMatcherFn(fromState: string, toState: string, element: any, params: {[key:
 string]: any}): boolean {
 *   // notice that `element` and `params` are also available here
 *   return toState == 'yes-please-animate';
 * }
 *
 * @Component({
 *   selector: 'my-component',
 *   templateUrl: 'my-component-tpl.html',
 *   animations: [
 *     trigger('myAnimationTrigger', [
 *       transition(myInlineMatcherFn, [
 *         // the animation sequence code
 *       ]),
 *     ])
 *   ]
 * })
 * class MyComponent {
 *   myStatusExp = "yes-please-animate";
 * }
 * ```
 *
 * ### Disabling Animations
 * When true, the special animation control binding `@.disabled` binding prevents
 * all animations from rendering.
 * Place the  `@.disabled` binding on an element to disable
 * animations on the element itself, as well as any inner animation triggers
 * within the element.
 *
 * The following example shows how to use this feature:
 *
 * ```typescript
 * @Component({
 *   selector: 'my-component',
 *   template: `
 *     <div [@.disabled]="isDisabled">
 *       <div [@childAnimation]="exp"></div>
 *     </div>
 *   `,
 *   animations: [
 *     trigger("childAnimation", [
 *       // ...
 *     ])
 *   ]
 * })
 * class MyComponent {
 *   isDisabled = true;
 *   exp = '...';
 * }
 * ```
 *
 * When `@.disabled` is true, it prevents the `@childAnimation` trigger from animating,
 * along with any inner animations.
 *
 * ### Disable animations application-wide
 * When an area of the template is set to have animations disabled,
 * **all** inner components have their animations disabled as well.
 * This means that you can disable all animations for an app
 * by placing a host binding set on `@.disabled` on the topmost Angular component.
 *
 * ```typescript
 * import {Component, HostBinding} from '@angular/core';
 *
 * @Component({
 *   selector: 'app-component',
 *   templateUrl: 'app.component.html',
 * })
 * class AppComponent {
 *   @HostBinding('@.disabled')
 *   public animationsDisabled = true;
 * }
 * ```
 *
 * ### Overriding disablement of inner animations
 * Despite inner animations being disabled, a parent animation can `query()`
 * for inner elements located in disabled areas of the template and still animate
 * them if needed. This is also the case for when a sub animation is
 * queried by a parent and then later animated using `animateChild()`.
 *
 * ### Detecting when an animation is disabled
 * If a region of the DOM (or the entire application) has its animations disabled, the animation
 * trigger callbacks still fire, but for zero seconds. When the callback fires, it provides
 * an instance of an `AnimationEvent`. If animations are disabled,
 * the `.disabled` flag on the event is true.
 *
 * @publicApi
 */
function trigger(name, definitions) {
  return {
    type: AnimationMetadataType.Trigger,
    name,
    definitions,
    options: {}
  };
}
/**
 * Defines an animation step that combines styling information with timing information.
 *
 * @param timings Sets `AnimateTimings` for the parent animation.
 * A string in the format "duration [delay] [easing]".
 *  - Duration and delay are expressed as a number and optional time unit,
 * such as "1s" or "10ms" for one second and 10 milliseconds, respectively.
 * The default unit is milliseconds.
 *  - The easing value controls how the animation accelerates and decelerates
 * during its runtime. Value is one of  `ease`, `ease-in`, `ease-out`,
 * `ease-in-out`, or a `cubic-bezier()` function call.
 * If not supplied, no easing is applied.
 *
 * For example, the string "1s 100ms ease-out" specifies a duration of
 * 1000 milliseconds, and delay of 100 ms, and the "ease-out" easing style,
 * which decelerates near the end of the duration.
 * @param styles Sets AnimationStyles for the parent animation.
 * A function call to either `style()` or `keyframes()`
 * that returns a collection of CSS style entries to be applied to the parent animation.
 * When null, uses the styles from the destination state.
 * This is useful when describing an animation step that will complete an animation;
 * see "Animating to the final state" in `transitions()`.
 * @returns An object that encapsulates the animation step.
 *
 * @usageNotes
 * Call within an animation `sequence()`, `{@link animations/group group()}`, or
 * `transition()` call to specify an animation step
 * that applies given style data to the parent animation for a given amount of time.
 *
 * ### Syntax Examples
 * **Timing examples**
 *
 * The following examples show various `timings` specifications.
 * - `animate(500)` : Duration is 500 milliseconds.
 * - `animate("1s")` : Duration is 1000 milliseconds.
 * - `animate("100ms 0.5s")` : Duration is 100 milliseconds, delay is 500 milliseconds.
 * - `animate("5s ease-in")` : Duration is 5000 milliseconds, easing in.
 * - `animate("5s 10ms cubic-bezier(.17,.67,.88,.1)")` : Duration is 5000 milliseconds, delay is 10
 * milliseconds, easing according to a bezier curve.
 *
 * **Style examples**
 *
 * The following example calls `style()` to set a single CSS style.
 * ```typescript
 * animate(500, style({ background: "red" }))
 * ```
 * The following example calls `keyframes()` to set a CSS style
 * to different values for successive keyframes.
 * ```typescript
 * animate(500, keyframes(
 *  [
 *   style({ background: "blue" }),
 *   style({ background: "red" })
 *  ])
 * ```
 *
 * @publicApi
 */
function animate(timings, styles = null) {
  return {
    type: AnimationMetadataType.Animate,
    styles,
    timings
  };
}
/**
 * @description Defines a list of animation steps to be run in parallel.
 *
 * @param steps An array of animation step objects.
 * - When steps are defined by `style()` or `animate()`
 * function calls, each call within the group is executed instantly.
 * - To specify offset styles to be applied at a later time, define steps with
 * `keyframes()`, or use `animate()` calls with a delay value.
 * For example:
 *
 * ```typescript
 * group([
 *   animate("1s", style({ background: "black" })),
 *   animate("2s", style({ color: "white" }))
 * ])
 * ```
 *
 * @param options An options object containing a delay and
 * developer-defined parameters that provide styling defaults and
 * can be overridden on invocation.
 *
 * @return An object that encapsulates the group data.
 *
 * @usageNotes
 * Grouped animations are useful when a series of styles must be
 * animated at different starting times and closed off at different ending times.
 *
 * When called within a `sequence()` or a
 * `transition()` call, does not continue to the next
 * instruction until all of the inner animation steps have completed.
 *
 * @publicApi
 */
function group(steps, options = null) {
  return {
    type: AnimationMetadataType.Group,
    steps,
    options
  };
}
/**
 * Defines a list of animation steps to be run sequentially, one by one.
 *
 * @param steps An array of animation step objects.
 * - Steps defined by `style()` calls apply the styling data immediately.
 * - Steps defined by `animate()` calls apply the styling data over time
 *   as specified by the timing data.
 *
 * ```typescript
 * sequence([
 *   style({ opacity: 0 }),
 *   animate("1s", style({ opacity: 1 }))
 * ])
 * ```
 *
 * @param options An options object containing a delay and
 * developer-defined parameters that provide styling defaults and
 * can be overridden on invocation.
 *
 * @return An object that encapsulates the sequence data.
 *
 * @usageNotes
 * When you pass an array of steps to a
 * `transition()` call, the steps run sequentially by default.
 * Compare this to the `{@link animations/group group()}` call, which runs animation steps in
 *parallel.
 *
 * When a sequence is used within a `{@link animations/group group()}` or a `transition()` call,
 * execution continues to the next instruction only after each of the inner animation
 * steps have completed.
 *
 * @publicApi
 **/
function sequence(steps, options = null) {
  return {
    type: AnimationMetadataType.Sequence,
    steps,
    options
  };
}
/**
 * Declares a key/value object containing CSS properties/styles that
 * can then be used for an animation [`state`](api/animations/state), within an animation
 *`sequence`, or as styling data for calls to `animate()` and `keyframes()`.
 *
 * @param tokens A set of CSS styles or HTML styles associated with an animation state.
 * The value can be any of the following:
 * - A key-value style pair associating a CSS property with a value.
 * - An array of key-value style pairs.
 * - An asterisk (*), to use auto-styling, where styles are derived from the element
 * being animated and applied to the animation when it starts.
 *
 * Auto-styling can be used to define a state that depends on layout or other
 * environmental factors.
 *
 * @return An object that encapsulates the style data.
 *
 * @usageNotes
 * The following examples create animation styles that collect a set of
 * CSS property values:
 *
 * ```typescript
 * // string values for CSS properties
 * style({ background: "red", color: "blue" })
 *
 * // numerical pixel values
 * style({ width: 100, height: 0 })
 * ```
 *
 * The following example uses auto-styling to allow an element to animate from
 * a height of 0 up to its full height:
 *
 * ```
 * style({ height: 0 }),
 * animate("1s", style({ height: "*" }))
 * ```
 *
 * @publicApi
 **/
function style(tokens) {
  return {
    type: AnimationMetadataType.Style,
    styles: tokens,
    offset: null
  };
}
/**
 * Declares an animation state within a trigger attached to an element.
 *
 * @param name One or more names for the defined state in a comma-separated string.
 * The following reserved state names can be supplied to define a style for specific use
 * cases:
 *
 * - `void` You can associate styles with this name to be used when
 * the element is detached from the application. For example, when an `ngIf` evaluates
 * to false, the state of the associated element is void.
 *  - `*` (asterisk) Indicates the default state. You can associate styles with this name
 * to be used as the fallback when the state that is being animated is not declared
 * within the trigger.
 *
 * @param styles A set of CSS styles associated with this state, created using the
 * `style()` function.
 * This set of styles persists on the element once the state has been reached.
 * @param options Parameters that can be passed to the state when it is invoked.
 * 0 or more key-value pairs.
 * @return An object that encapsulates the new state data.
 *
 * @usageNotes
 * Use the `trigger()` function to register states to an animation trigger.
 * Use the `transition()` function to animate between states.
 * When a state is active within a component, its associated styles persist on the element,
 * even when the animation ends.
 *
 * @publicApi
 **/
function state(name, styles, options) {
  return {
    type: AnimationMetadataType.State,
    name,
    styles,
    options
  };
}
/**
 * Defines a set of animation styles, associating each style with an optional `offset` value.
 *
 * @param steps A set of animation styles with optional offset data.
 * The optional `offset` value for a style specifies a percentage of the total animation
 * time at which that style is applied.
 * @returns An object that encapsulates the keyframes data.
 *
 * @usageNotes
 * Use with the `animate()` call. Instead of applying animations
 * from the current state
 * to the destination state, keyframes describe how each style entry is applied and at what point
 * within the animation arc.
 * Compare [CSS Keyframe Animations](https://www.w3schools.com/css/css3_animations.asp).
 *
 * ### Usage
 *
 * In the following example, the offset values describe
 * when each `backgroundColor` value is applied. The color is red at the start, and changes to
 * blue when 20% of the total time has elapsed.
 *
 * ```typescript
 * // the provided offset values
 * animate("5s", keyframes([
 *   style({ backgroundColor: "red", offset: 0 }),
 *   style({ backgroundColor: "blue", offset: 0.2 }),
 *   style({ backgroundColor: "orange", offset: 0.3 }),
 *   style({ backgroundColor: "black", offset: 1 })
 * ]))
 * ```
 *
 * If there are no `offset` values specified in the style entries, the offsets
 * are calculated automatically.
 *
 * ```typescript
 * animate("5s", keyframes([
 *   style({ backgroundColor: "red" }) // offset = 0
 *   style({ backgroundColor: "blue" }) // offset = 0.33
 *   style({ backgroundColor: "orange" }) // offset = 0.66
 *   style({ backgroundColor: "black" }) // offset = 1
 * ]))
 *```

 * @publicApi
 */
function keyframes(steps) {
  return {
    type: AnimationMetadataType.Keyframes,
    steps
  };
}
/**
 * Declares an animation transition which is played when a certain specified condition is met.
 *
 * @param stateChangeExpr A string with a specific format or a function that specifies when the
 * animation transition should occur (see [State Change Expression](#state-change-expression)).
 *
 * @param steps One or more animation objects that represent the animation's instructions.
 *
 * @param options An options object that can be used to specify a delay for the animation or provide
 * custom parameters for it.
 *
 * @returns An object that encapsulates the transition data.
 *
 * @usageNotes
 *
 * ### State Change Expression
 *
 * The State Change Expression instructs Angular when to run the transition's animations, it can
 *either be
 *  - a string with a specific syntax
 *  - or a function that compares the previous and current state (value of the expression bound to
 *    the element's trigger) and returns `true` if the transition should occur or `false` otherwise
 *
 * The string format can be:
 *  - `fromState => toState`, which indicates that the transition's animations should occur then the
 *    expression bound to the trigger's element goes from `fromState` to `toState`
 *
 *    _Example:_
 *      ```typescript
 *        transition('open => closed', animate('.5s ease-out', style({ height: 0 }) ))
 *      ```
 *
 *  - `fromState <=> toState`, which indicates that the transition's animations should occur then
 *    the expression bound to the trigger's element goes from `fromState` to `toState` or vice versa
 *
 *    _Example:_
 *      ```typescript
 *        transition('enabled <=> disabled', animate('1s cubic-bezier(0.8,0.3,0,1)'))
 *      ```
 *
 *  - `:enter`/`:leave`, which indicates that the transition's animations should occur when the
 *    element enters or exists the DOM
 *
 *    _Example:_
 *      ```typescript
 *        transition(':enter', [
 *          style({ opacity: 0 }),
 *          animate('500ms', style({ opacity: 1 }))
 *        ])
 *      ```
 *
 *  - `:increment`/`:decrement`, which indicates that the transition's animations should occur when
 *    the numerical expression bound to the trigger's element has increased in value or decreased
 *
 *    _Example:_
 *      ```typescript
 *        transition(':increment', query('@counter', animateChild()))
 *      ```
 *
 *  - a sequence of any of the above divided by commas, which indicates that transition's animations
 *    should occur whenever one of the state change expressions matches
 *
 *    _Example:_
 *      ```typescript
 *        transition(':increment, * => enabled, :enter', animate('1s ease', keyframes([
 *          style({ transform: 'scale(1)', offset: 0}),
 *          style({ transform: 'scale(1.1)', offset: 0.7}),
 *          style({ transform: 'scale(1)', offset: 1})
 *        ]))),
 *      ```
 *
 * Also note that in such context:
 *  - `void` can be used to indicate the absence of the element
 *  - asterisks can be used as wildcards that match any state
 *  - (as a consequence of the above, `void => *` is equivalent to `:enter` and `* => void` is
 *    equivalent to `:leave`)
 *  - `true` and `false` also match expression values of `1` and `0` respectively (but do not match
 *    _truthy_ and _falsy_ values)
 *
 * <div class="alert is-helpful">
 *
 *  Be careful about entering end leaving elements as their transitions present a common
 *  pitfall for developers.
 *
 *  Note that when an element with a trigger enters the DOM its `:enter` transition always
 *  gets executed, but its `:leave` transition will not be executed if the element is removed
 *  alongside its parent (as it will be removed "without warning" before its transition has
 *  a chance to be executed, the only way that such transition can occur is if the element
 *  is exiting the DOM on its own).
 *
 *
 * </div>
 *
 * ### Animating to a Final State
 *
 * If the final step in a transition is a call to `animate()` that uses a timing value
 * with no `style` data, that step is automatically considered the final animation arc,
 * for the element to reach the final state, in such case Angular automatically adds or removes
 * CSS styles to ensure that the element is in the correct final state.
 *
 *
 * ### Usage Examples
 *
 *  - Transition animations applied based on
 *    the trigger's expression value
 *
 *   ```html
 *   <div [@myAnimationTrigger]="myStatusExp">
 *    ...
 *   </div>
 *   ```
 *
 *   ```typescript
 *   trigger("myAnimationTrigger", [
 *     ..., // states
 *     transition("on => off, open => closed", animate(500)),
 *     transition("* <=> error", query('.indicator', animateChild()))
 *   ])
 *   ```
 *
 *  - Transition animations applied based on custom logic dependent
 *    on the trigger's expression value and provided parameters
 *
 *    ```html
 *    <div [@myAnimationTrigger]="{
 *     value: stepName,
 *     params: { target: currentTarget }
 *    }">
 *     ...
 *    </div>
 *    ```
 *
 *    ```typescript
 *    trigger("myAnimationTrigger", [
 *      ..., // states
 *      transition(
 *        (fromState, toState, _element, params) =>
 *          ['firststep', 'laststep'].includes(fromState.toLowerCase())
 *          && toState === params?.['target'],
 *        animate('1s')
 *      )
 *    ])
 *    ```
 *
 * @publicApi
 **/
function transition(stateChangeExpr, steps, options = null) {
  return {
    type: AnimationMetadataType.Transition,
    expr: stateChangeExpr,
    animation: steps,
    options
  };
}
/**
 * Produces a reusable animation that can be invoked in another animation or sequence,
 * by calling the `useAnimation()` function.
 *
 * @param steps One or more animation objects, as returned by the `animate()`
 * or `sequence()` function, that form a transformation from one state to another.
 * A sequence is used by default when you pass an array.
 * @param options An options object that can contain a delay value for the start of the
 * animation, and additional developer-defined parameters.
 * Provided values for additional parameters are used as defaults,
 * and override values can be passed to the caller on invocation.
 * @returns An object that encapsulates the animation data.
 *
 * @usageNotes
 * The following example defines a reusable animation, providing some default parameter
 * values.
 *
 * ```typescript
 * var fadeAnimation = animation([
 *   style({ opacity: '{{ start }}' }),
 *   animate('{{ time }}',
 *   style({ opacity: '{{ end }}'}))
 *   ],
 *   { params: { time: '1000ms', start: 0, end: 1 }});
 * ```
 *
 * The following invokes the defined animation with a call to `useAnimation()`,
 * passing in override parameter values.
 *
 * ```js
 * useAnimation(fadeAnimation, {
 *   params: {
 *     time: '2s',
 *     start: 1,
 *     end: 0
 *   }
 * })
 * ```
 *
 * If any of the passed-in parameter values are missing from this call,
 * the default values are used. If one or more parameter values are missing before a step is
 * animated, `useAnimation()` throws an error.
 *
 * @publicApi
 */
function animation(steps, options = null) {
  return {
    type: AnimationMetadataType.Reference,
    animation: steps,
    options
  };
}
/**
 * Executes a queried inner animation element within an animation sequence.
 *
 * @param options An options object that can contain a delay value for the start of the
 * animation, and additional override values for developer-defined parameters.
 * @return An object that encapsulates the child animation data.
 *
 * @usageNotes
 * Each time an animation is triggered in Angular, the parent animation
 * has priority and any child animations are blocked. In order
 * for a child animation to run, the parent animation must query each of the elements
 * containing child animations, and run them using this function.
 *
 * Note that this feature is designed to be used with `query()` and it will only work
 * with animations that are assigned using the Angular animation library. CSS keyframes
 * and transitions are not handled by this API.
 *
 * @publicApi
 */
function animateChild(options = null) {
  return {
    type: AnimationMetadataType.AnimateChild,
    options
  };
}
/**
 * Starts a reusable animation that is created using the `animation()` function.
 *
 * @param animation The reusable animation to start.
 * @param options An options object that can contain a delay value for the start of
 * the animation, and additional override values for developer-defined parameters.
 * @return An object that contains the animation parameters.
 *
 * @publicApi
 */
function useAnimation(animation, options = null) {
  return {
    type: AnimationMetadataType.AnimateRef,
    animation,
    options
  };
}
/**
 * Finds one or more inner elements within the current element that is
 * being animated within a sequence. Use with `animate()`.
 *
 * @param selector The element to query, or a set of elements that contain Angular-specific
 * characteristics, specified with one or more of the following tokens.
 *  - `query(":enter")` or `query(":leave")` : Query for newly inserted/removed elements (not
 *     all elements can be queried via these tokens, see
 *     [Entering and Leaving Elements](#entering-and-leaving-elements))
 *  - `query(":animating")` : Query all currently animating elements.
 *  - `query("@triggerName")` : Query elements that contain an animation trigger.
 *  - `query("@*")` : Query all elements that contain an animation triggers.
 *  - `query(":self")` : Include the current element into the animation sequence.
 *
 * @param animation One or more animation steps to apply to the queried element or elements.
 * An array is treated as an animation sequence.
 * @param options An options object. Use the 'limit' field to limit the total number of
 * items to collect.
 * @return An object that encapsulates the query data.
 *
 * @usageNotes
 *
 * ### Multiple Tokens
 *
 * Tokens can be merged into a combined query selector string. For example:
 *
 * ```typescript
 *  query(':self, .record:enter, .record:leave, @subTrigger', [...])
 * ```
 *
 * The `query()` function collects multiple elements and works internally by using
 * `element.querySelectorAll`. Use the `limit` field of an options object to limit
 * the total number of items to be collected. For example:
 *
 * ```js
 * query('div', [
 *   animate(...),
 *   animate(...)
 * ], { limit: 1 })
 * ```
 *
 * By default, throws an error when zero items are found. Set the
 * `optional` flag to ignore this error. For example:
 *
 * ```js
 * query('.some-element-that-may-not-be-there', [
 *   animate(...),
 *   animate(...)
 * ], { optional: true })
 * ```
 *
 * ### Entering and Leaving Elements
 *
 * Not all elements can be queried via the `:enter` and `:leave` tokens, the only ones
 * that can are those that Angular assumes can enter/leave based on their own logic
 * (if their insertion/removal is simply a consequence of that of their parent they
 * should be queried via a different token in their parent's `:enter`/`:leave` transitions).
 *
 * The only elements Angular assumes can enter/leave based on their own logic (thus the only
 * ones that can be queried via the `:enter` and `:leave` tokens) are:
 *  - Those inserted dynamically (via `ViewContainerRef`)
 *  - Those that have a structural directive (which, under the hood, are a subset of the above ones)
 *
 * <div class="alert is-helpful">
 *
 *  Note that elements will be successfully queried via `:enter`/`:leave` even if their
 *  insertion/removal is not done manually via `ViewContainerRef`or caused by their structural
 *  directive (e.g. they enter/exit alongside their parent).
 *
 * </div>
 *
 * <div class="alert is-important">
 *
 *  There is an exception to what previously mentioned, besides elements entering/leaving based on
 *  their own logic, elements with an animation trigger can always be queried via `:leave` when
 * their parent is also leaving.
 *
 * </div>
 *
 * ### Usage Example
 *
 * The following example queries for inner elements and animates them
 * individually using `animate()`.
 *
 * ```typescript
 * @Component({
 *   selector: 'inner',
 *   template: `
 *     <div [@queryAnimation]="exp">
 *       <h1>Title</h1>
 *       <div class="content">
 *         Blah blah blah
 *       </div>
 *     </div>
 *   `,
 *   animations: [
 *    trigger('queryAnimation', [
 *      transition('* => goAnimate', [
 *        // hide the inner elements
 *        query('h1', style({ opacity: 0 })),
 *        query('.content', style({ opacity: 0 })),
 *
 *        // animate the inner elements in, one by one
 *        query('h1', animate(1000, style({ opacity: 1 }))),
 *        query('.content', animate(1000, style({ opacity: 1 }))),
 *      ])
 *    ])
 *  ]
 * })
 * class Cmp {
 *   exp = '';
 *
 *   goAnimate() {
 *     this.exp = 'goAnimate';
 *   }
 * }
 * ```
 *
 * @publicApi
 */
function query(selector, animation, options = null) {
  return {
    type: AnimationMetadataType.Query,
    selector,
    animation,
    options
  };
}
/**
 * Use within an animation `query()` call to issue a timing gap after
 * each queried item is animated.
 *
 * @param timings A delay value.
 * @param animation One ore more animation steps.
 * @returns An object that encapsulates the stagger data.
 *
 * @usageNotes
 * In the following example, a container element wraps a list of items stamped out
 * by an `ngFor`. The container element contains an animation trigger that will later be set
 * to query for each of the inner items.
 *
 * Each time items are added, the opacity fade-in animation runs,
 * and each removed item is faded out.
 * When either of these animations occur, the stagger effect is
 * applied after each item's animation is started.
 *
 * ```html
 * <!-- list.component.html -->
 * <button (click)="toggle()">Show / Hide Items</button>
 * <hr />
 * <div [@listAnimation]="items.length">
 *   <div *ngFor="let item of items">
 *     {{ item }}
 *   </div>
 * </div>
 * ```
 *
 * Here is the component code:
 *
 * ```typescript
 * import {trigger, transition, style, animate, query, stagger} from '@angular/animations';
 * @Component({
 *   templateUrl: 'list.component.html',
 *   animations: [
 *     trigger('listAnimation', [
 *     ...
 *     ])
 *   ]
 * })
 * class ListComponent {
 *   items = [];
 *
 *   showItems() {
 *     this.items = [0,1,2,3,4];
 *   }
 *
 *   hideItems() {
 *     this.items = [];
 *   }
 *
 *   toggle() {
 *     this.items.length ? this.hideItems() : this.showItems();
 *    }
 *  }
 * ```
 *
 * Here is the animation trigger code:
 *
 * ```typescript
 * trigger('listAnimation', [
 *   transition('* => *', [ // each time the binding value changes
 *     query(':leave', [
 *       stagger(100, [
 *         animate('0.5s', style({ opacity: 0 }))
 *       ])
 *     ]),
 *     query(':enter', [
 *       style({ opacity: 0 }),
 *       stagger(100, [
 *         animate('0.5s', style({ opacity: 1 }))
 *       ])
 *     ])
 *   ])
 * ])
 * ```
 *
 * @publicApi
 */
function stagger(timings, animation) {
  return {
    type: AnimationMetadataType.Stagger,
    timings,
    animation
  };
}

/**
 * An injectable service that produces an animation sequence programmatically within an
 * Angular component or directive.
 * Provided by the `BrowserAnimationsModule` or `NoopAnimationsModule`.
 *
 * @usageNotes
 *
 * To use this service, add it to your component or directive as a dependency.
 * The service is instantiated along with your component.
 *
 * Apps do not typically need to create their own animation players, but if you
 * do need to, follow these steps:
 *
 * 1. Use the <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code> method
 * to create a programmatic animation. The method returns an `AnimationFactory` instance.
 *
 * 2. Use the factory object to create an `AnimationPlayer` and attach it to a DOM element.
 *
 * 3. Use the player object to control the animation programmatically.
 *
 * For example:
 *
 * ```ts
 * // import the service from BrowserAnimationsModule
 * import {AnimationBuilder} from '@angular/animations';
 * // require the service as a dependency
 * class MyCmp {
 *   constructor(private _builder: AnimationBuilder) {}
 *
 *   makeAnimation(element: any) {
 *     // first define a reusable animation
 *     const myAnimation = this._builder.build([
 *       style({ width: 0 }),
 *       animate(1000, style({ width: '100px' }))
 *     ]);
 *
 *     // use the returned factory object to create a player
 *     const player = myAnimation.create(element);
 *
 *     player.play();
 *   }
 * }
 * ```
 *
 * @publicApi
 */
let AnimationBuilder = /*#__PURE__*/(() => {
  class AnimationBuilder {
    static ɵfac = (() => function AnimationBuilder_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AnimationBuilder)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: AnimationBuilder,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.inject)(BrowserAnimationBuilder))(),
      providedIn: 'root'
    }))();
  }
  return AnimationBuilder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * A factory object returned from the
 * <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code>
 * method.
 *
 * @publicApi
 */
class AnimationFactory {}
let BrowserAnimationBuilder = /*#__PURE__*/(() => {
  class BrowserAnimationBuilder extends AnimationBuilder {
    animationModuleType = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_0__.ANIMATION_MODULE_TYPE, {
      optional: true
    }))();
    _nextAnimationId = 0;
    _renderer;
    constructor(rootRenderer, doc) {
      super();
      const typeData = {
        id: '0',
        encapsulation: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewEncapsulation.None,
        styles: [],
        data: {
          animation: []
        }
      };
      this._renderer = rootRenderer.createRenderer(doc.body, typeData);
      if (this.animationModuleType === null && !isAnimationRenderer(this._renderer)) {
        // We only support AnimationRenderer & DynamicDelegationRenderer for this AnimationBuilder
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3600 /* RuntimeErrorCode.BROWSER_ANIMATION_BUILDER_INJECTED_WITHOUT_ANIMATIONS */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Angular detected that the `AnimationBuilder` was injected, but animation support was not enabled. ' + 'Please make sure that you enable animations in your application by calling `provideAnimations()` or `provideAnimationsAsync()` function.');
      }
    }
    build(animation) {
      const id = this._nextAnimationId;
      this._nextAnimationId++;
      const entry = Array.isArray(animation) ? sequence(animation) : animation;
      issueAnimationCommand(this._renderer, null, id, 'register', [entry]);
      return new BrowserAnimationFactory(id, this._renderer);
    }
    static ɵfac = (() => function BrowserAnimationBuilder_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BrowserAnimationBuilder)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.RendererFactory2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_1__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: BrowserAnimationBuilder,
      factory: BrowserAnimationBuilder.ɵfac,
      providedIn: 'root'
    }))();
  }
  return BrowserAnimationBuilder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
class BrowserAnimationFactory extends AnimationFactory {
  _id;
  _renderer;
  constructor(_id, _renderer) {
    super();
    this._id = _id;
    this._renderer = _renderer;
  }
  create(element, options) {
    return new RendererAnimationPlayer(this._id, element, options || {}, this._renderer);
  }
}
class RendererAnimationPlayer {
  id;
  element;
  _renderer;
  parentPlayer = null;
  _started = false;
  constructor(id, element, options, _renderer) {
    this.id = id;
    this.element = element;
    this._renderer = _renderer;
    this._command('create', options);
  }
  _listen(eventName, callback) {
    return this._renderer.listen(this.element, `@@${this.id}:${eventName}`, callback);
  }
  _command(command, ...args) {
    issueAnimationCommand(this._renderer, this.element, this.id, command, args);
  }
  onDone(fn) {
    this._listen('done', fn);
  }
  onStart(fn) {
    this._listen('start', fn);
  }
  onDestroy(fn) {
    this._listen('destroy', fn);
  }
  init() {
    this._command('init');
  }
  hasStarted() {
    return this._started;
  }
  play() {
    this._command('play');
    this._started = true;
  }
  pause() {
    this._command('pause');
  }
  restart() {
    this._command('restart');
  }
  finish() {
    this._command('finish');
  }
  destroy() {
    this._command('destroy');
  }
  reset() {
    this._command('reset');
    this._started = false;
  }
  setPosition(p) {
    this._command('setPosition', p);
  }
  getPosition() {
    return unwrapAnimationRenderer(this._renderer)?.engine?.players[this.id]?.getPosition() ?? 0;
  }
  totalTime = 0;
}
function issueAnimationCommand(renderer, element, id, command, args) {
  renderer.setProperty(element, `@@${id}:${command}`, args);
}
/**
 * The following 2 methods cannot reference their correct types (AnimationRenderer &
 * DynamicDelegationRenderer) since this would introduce a import cycle.
 */
function unwrapAnimationRenderer(renderer) {
  const type = renderer.ɵtype;
  if (type === 0 /* AnimationRendererType.Regular */) {
    return renderer;
  } else if (type === 1 /* AnimationRendererType.Delegated */) {
    return renderer.animationRenderer;
  }
  return null;
}
function isAnimationRenderer(renderer) {
  const type = renderer.ɵtype;
  return type === 0 /* AnimationRendererType.Regular */ || type === 1 /* AnimationRendererType.Delegated */;
}

/**
 * An empty programmatic controller for reusable animations.
 * Used internally when animations are disabled, to avoid
 * checking for the null case when an animation player is expected.
 *
 * @see {@link animate}
 * @see {@link AnimationPlayer}
 *
 * @publicApi
 */
class NoopAnimationPlayer {
  _onDoneFns = [];
  _onStartFns = [];
  _onDestroyFns = [];
  _originalOnDoneFns = [];
  _originalOnStartFns = [];
  _started = false;
  _destroyed = false;
  _finished = false;
  _position = 0;
  parentPlayer = null;
  totalTime;
  constructor(duration = 0, delay = 0) {
    this.totalTime = duration + delay;
  }
  _onFinish() {
    if (!this._finished) {
      this._finished = true;
      this._onDoneFns.forEach(fn => fn());
      this._onDoneFns = [];
    }
  }
  onStart(fn) {
    this._originalOnStartFns.push(fn);
    this._onStartFns.push(fn);
  }
  onDone(fn) {
    this._originalOnDoneFns.push(fn);
    this._onDoneFns.push(fn);
  }
  onDestroy(fn) {
    this._onDestroyFns.push(fn);
  }
  hasStarted() {
    return this._started;
  }
  init() {}
  play() {
    if (!this.hasStarted()) {
      this._onStart();
      this.triggerMicrotask();
    }
    this._started = true;
  }
  /** @internal */
  triggerMicrotask() {
    queueMicrotask(() => this._onFinish());
  }
  _onStart() {
    this._onStartFns.forEach(fn => fn());
    this._onStartFns = [];
  }
  pause() {}
  restart() {}
  finish() {
    this._onFinish();
  }
  destroy() {
    if (!this._destroyed) {
      this._destroyed = true;
      if (!this.hasStarted()) {
        this._onStart();
      }
      this.finish();
      this._onDestroyFns.forEach(fn => fn());
      this._onDestroyFns = [];
    }
  }
  reset() {
    this._started = false;
    this._finished = false;
    this._onStartFns = this._originalOnStartFns;
    this._onDoneFns = this._originalOnDoneFns;
  }
  setPosition(position) {
    this._position = this.totalTime ? position * this.totalTime : 1;
  }
  getPosition() {
    return this.totalTime ? this._position / this.totalTime : 1;
  }
  /** @internal */
  triggerCallback(phaseName) {
    const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;
    methods.forEach(fn => fn());
    methods.length = 0;
  }
}

/**
 * A programmatic controller for a group of reusable animations.
 * Used internally to control animations.
 *
 * @see {@link AnimationPlayer}
 * @see {@link animations/group group}
 *
 */
class AnimationGroupPlayer {
  _onDoneFns = [];
  _onStartFns = [];
  _finished = false;
  _started = false;
  _destroyed = false;
  _onDestroyFns = [];
  parentPlayer = null;
  totalTime = 0;
  players;
  constructor(_players) {
    this.players = _players;
    let doneCount = 0;
    let destroyCount = 0;
    let startCount = 0;
    const total = this.players.length;
    if (total == 0) {
      queueMicrotask(() => this._onFinish());
    } else {
      this.players.forEach(player => {
        player.onDone(() => {
          if (++doneCount == total) {
            this._onFinish();
          }
        });
        player.onDestroy(() => {
          if (++destroyCount == total) {
            this._onDestroy();
          }
        });
        player.onStart(() => {
          if (++startCount == total) {
            this._onStart();
          }
        });
      });
    }
    this.totalTime = this.players.reduce((time, player) => Math.max(time, player.totalTime), 0);
  }
  _onFinish() {
    if (!this._finished) {
      this._finished = true;
      this._onDoneFns.forEach(fn => fn());
      this._onDoneFns = [];
    }
  }
  init() {
    this.players.forEach(player => player.init());
  }
  onStart(fn) {
    this._onStartFns.push(fn);
  }
  _onStart() {
    if (!this.hasStarted()) {
      this._started = true;
      this._onStartFns.forEach(fn => fn());
      this._onStartFns = [];
    }
  }
  onDone(fn) {
    this._onDoneFns.push(fn);
  }
  onDestroy(fn) {
    this._onDestroyFns.push(fn);
  }
  hasStarted() {
    return this._started;
  }
  play() {
    if (!this.parentPlayer) {
      this.init();
    }
    this._onStart();
    this.players.forEach(player => player.play());
  }
  pause() {
    this.players.forEach(player => player.pause());
  }
  restart() {
    this.players.forEach(player => player.restart());
  }
  finish() {
    this._onFinish();
    this.players.forEach(player => player.finish());
  }
  destroy() {
    this._onDestroy();
  }
  _onDestroy() {
    if (!this._destroyed) {
      this._destroyed = true;
      this._onFinish();
      this.players.forEach(player => player.destroy());
      this._onDestroyFns.forEach(fn => fn());
      this._onDestroyFns = [];
    }
  }
  reset() {
    this.players.forEach(player => player.reset());
    this._destroyed = false;
    this._finished = false;
    this._started = false;
  }
  setPosition(p) {
    const timeAtPosition = p * this.totalTime;
    this.players.forEach(player => {
      const position = player.totalTime ? Math.min(1, timeAtPosition / player.totalTime) : 1;
      player.setPosition(position);
    });
  }
  getPosition() {
    const longestPlayer = this.players.reduce((longestSoFar, player) => {
      const newPlayerIsLongest = longestSoFar === null || player.totalTime > longestSoFar.totalTime;
      return newPlayerIsLongest ? player : longestSoFar;
    }, null);
    return longestPlayer != null ? longestPlayer.getPosition() : 0;
  }
  beforeDestroy() {
    this.players.forEach(player => {
      if (player.beforeDestroy) {
        player.beforeDestroy();
      }
    });
  }
  /** @internal */
  triggerCallback(phaseName) {
    const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;
    methods.forEach(fn => fn());
    methods.length = 0;
  }
}
const ɵPRE_STYLE = '!';

/**
 * @module
 * @description
 * Entry point for all animation APIs of the animation package.
 */

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 8747:
/*!*************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+animations@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0_/node_modules/@angular/animations/fesm2022/browser.mjs ***!
  \*************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AnimationDriver: () => (/* binding */ AnimationDriver),
/* harmony export */   NoopAnimationDriver: () => (/* binding */ NoopAnimationDriver),
/* harmony export */   "ɵAnimation": () => (/* binding */ Animation),
/* harmony export */   "ɵAnimationEngine": () => (/* binding */ AnimationEngine),
/* harmony export */   "ɵAnimationRenderer": () => (/* binding */ AnimationRenderer),
/* harmony export */   "ɵAnimationRendererFactory": () => (/* binding */ AnimationRendererFactory),
/* harmony export */   "ɵAnimationStyleNormalizer": () => (/* binding */ AnimationStyleNormalizer),
/* harmony export */   "ɵBaseAnimationRenderer": () => (/* binding */ BaseAnimationRenderer),
/* harmony export */   "ɵNoopAnimationStyleNormalizer": () => (/* binding */ NoopAnimationStyleNormalizer),
/* harmony export */   "ɵWebAnimationsDriver": () => (/* binding */ WebAnimationsDriver),
/* harmony export */   "ɵWebAnimationsPlayer": () => (/* binding */ WebAnimationsPlayer),
/* harmony export */   "ɵWebAnimationsStyleNormalizer": () => (/* binding */ WebAnimationsStyleNormalizer),
/* harmony export */   "ɵallowPreviousPlayerStylesMerge": () => (/* binding */ allowPreviousPlayerStylesMerge),
/* harmony export */   "ɵcamelCaseToDashCase": () => (/* binding */ camelCaseToDashCase),
/* harmony export */   "ɵcontainsElement": () => (/* binding */ containsElement),
/* harmony export */   "ɵcreateEngine": () => (/* binding */ createEngine),
/* harmony export */   "ɵgetParentElement": () => (/* binding */ getParentElement),
/* harmony export */   "ɵinvokeQuery": () => (/* binding */ invokeQuery),
/* harmony export */   "ɵnormalizeKeyframes": () => (/* binding */ normalizeKeyframes),
/* harmony export */   "ɵvalidateStyleProperty": () => (/* binding */ validateStyleProperty),
/* harmony export */   "ɵvalidateWebAnimatableStyleProperty": () => (/* binding */ validateWebAnimatableStyleProperty)
/* harmony export */ });
/* harmony import */ var _angular_animations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/animations */ 4232);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */




const LINE_START = '\n - ';
function invalidTimingValue(exp) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value "${exp}" is invalid.`);
}
function negativeStepValue() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');
}
function negativeDelayValue() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');
}
function invalidStyleParams(varName) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode && `Unable to resolve the local animation param ${varName} in the given list of values`);
}
function invalidParamValue(varName) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);
}
function invalidNodeType(nodeType) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);
}
function invalidCssUnitValue(userProvidedProperty, value) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);
}
function invalidTrigger() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode && "animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))");
}
function invalidDefinition() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');
}
function invalidState(metadataName, missingSubs) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode && `state("${metadataName}", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);
}
function invalidStyleValue(value) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);
}
function invalidProperty(prop) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3009 /* RuntimeErrorCode.INVALID_PROPERTY */, ngDevMode && `The provided animation property "${prop}" is not a supported CSS property for animations`);
}
function invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode && `The CSS property "${prop}" that exists between the times of "${firstStart}ms" and "${firstEnd}ms" is also being animated in a parallel animation between the times of "${secondStart}ms" and "${secondEnd}ms"`);
}
function invalidKeyframes() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);
}
function invalidOffset() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);
}
function keyframeOffsetsOutOfOrder() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);
}
function keyframesMissingOffsets() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);
}
function invalidStagger() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);
}
function invalidQuery(selector) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode && `\`query("${selector}")\` returned zero elements. (Use \`query("${selector}", { optional: true })\` if you wish to allow this.)`);
}
function invalidExpression(expr) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression "${expr}" is not supported`);
}
function invalidTransitionAlias(alias) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value "${alias}" is not supported`);
}
function validationFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\n${errors.map(err => err.message).join('\n')}`);
}
function buildingFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\n${errors.map(err => err.message).join('\n')}`);
}
function triggerBuildFailed(name, errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode && `The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.map(err => err.message).join('\n - ')}`);
}
function animationFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode && `Unable to animate due to the following errors:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
}
function registerFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode && `Unable to build the animation due to the following errors: ${errors.map(err => err.message).join('\n')}`);
}
function missingOrDestroyedAnimation() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && "The requested animation doesn't exist or has already been destroyed");
}
function createAnimationFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode && `Unable to create the animation due to the following errors:${errors.map(err => err.message).join('\n')}`);
}
function missingPlayer(id) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);
}
function missingTrigger(phase, name) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode && `Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`);
}
function missingEvent(name) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode && `Unable to listen on the animation trigger "${name}" because the provided event is undefined!`);
}
function unsupportedTriggerEvent(phase, name) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode && `The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`);
}
function unregisteredTrigger(name) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger "${name}" has not been registered!`);
}
function triggerTransitionsFailed(errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode && `Unable to process animations due to the following failed trigger transitions\n ${errors.map(err => err.message).join('\n')}`);
}
function triggerParsingFailed(name, errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3403 /* RuntimeErrorCode.TRIGGER_PARSING_FAILED */, ngDevMode && `Animation parsing for the ${name} trigger have failed:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
}
function transitionFailed(name, errors) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\n ${errors.map(err => err.message).join('\n- ')}`);
}

/**
 * Set of all animatable CSS properties
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
 */
const ANIMATABLE_PROP_SET = /*#__PURE__*/new Set(['-moz-outline-radius', '-moz-outline-radius-bottomleft', '-moz-outline-radius-bottomright', '-moz-outline-radius-topleft', '-moz-outline-radius-topright', '-ms-grid-columns', '-ms-grid-rows', '-webkit-line-clamp', '-webkit-text-fill-color', '-webkit-text-stroke', '-webkit-text-stroke-color', 'accent-color', 'all', 'backdrop-filter', 'background', 'background-color', 'background-position', 'background-size', 'block-size', 'border', 'border-block-end', 'border-block-end-color', 'border-block-end-width', 'border-block-start', 'border-block-start-color', 'border-block-start-width', 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-bottom-width', 'border-color', 'border-end-end-radius', 'border-end-start-radius', 'border-image-outset', 'border-image-slice', 'border-image-width', 'border-inline-end', 'border-inline-end-color', 'border-inline-end-width', 'border-inline-start', 'border-inline-start-color', 'border-inline-start-width', 'border-left', 'border-left-color', 'border-left-width', 'border-radius', 'border-right', 'border-right-color', 'border-right-width', 'border-start-end-radius', 'border-start-start-radius', 'border-top', 'border-top-color', 'border-top-left-radius', 'border-top-right-radius', 'border-top-width', 'border-width', 'bottom', 'box-shadow', 'caret-color', 'clip', 'clip-path', 'color', 'column-count', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', 'column-width', 'columns', 'filter', 'flex', 'flex-basis', 'flex-grow', 'flex-shrink', 'font', 'font-size', 'font-size-adjust', 'font-stretch', 'font-variation-settings', 'font-weight', 'gap', 'grid-column-gap', 'grid-gap', 'grid-row-gap', 'grid-template-columns', 'grid-template-rows', 'height', 'inline-size', 'input-security', 'inset', 'inset-block', 'inset-block-end', 'inset-block-start', 'inset-inline', 'inset-inline-end', 'inset-inline-start', 'left', 'letter-spacing', 'line-clamp', 'line-height', 'margin', 'margin-block-end', 'margin-block-start', 'margin-bottom', 'margin-inline-end', 'margin-inline-start', 'margin-left', 'margin-right', 'margin-top', 'mask', 'mask-border', 'mask-position', 'mask-size', 'max-block-size', 'max-height', 'max-inline-size', 'max-lines', 'max-width', 'min-block-size', 'min-height', 'min-inline-size', 'min-width', 'object-position', 'offset', 'offset-anchor', 'offset-distance', 'offset-path', 'offset-position', 'offset-rotate', 'opacity', 'order', 'outline', 'outline-color', 'outline-offset', 'outline-width', 'padding', 'padding-block-end', 'padding-block-start', 'padding-bottom', 'padding-inline-end', 'padding-inline-start', 'padding-left', 'padding-right', 'padding-top', 'perspective', 'perspective-origin', 'right', 'rotate', 'row-gap', 'scale', 'scroll-margin', 'scroll-margin-block', 'scroll-margin-block-end', 'scroll-margin-block-start', 'scroll-margin-bottom', 'scroll-margin-inline', 'scroll-margin-inline-end', 'scroll-margin-inline-start', 'scroll-margin-left', 'scroll-margin-right', 'scroll-margin-top', 'scroll-padding', 'scroll-padding-block', 'scroll-padding-block-end', 'scroll-padding-block-start', 'scroll-padding-bottom', 'scroll-padding-inline', 'scroll-padding-inline-end', 'scroll-padding-inline-start', 'scroll-padding-left', 'scroll-padding-right', 'scroll-padding-top', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scrollbar-color', 'shape-image-threshold', 'shape-margin', 'shape-outside', 'tab-size', 'text-decoration', 'text-decoration-color', 'text-decoration-thickness', 'text-emphasis', 'text-emphasis-color', 'text-indent', 'text-shadow', 'text-underline-offset', 'top', 'transform', 'transform-origin', 'translate', 'vertical-align', 'visibility', 'width', 'word-spacing', 'z-index', 'zoom']);
function optimizeGroupPlayer(players) {
  switch (players.length) {
    case 0:
      return new _angular_animations__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationPlayer();
    case 1:
      return players[0];
    default:
      return new _angular_animations__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationGroupPlayer"](players);
  }
}
function normalizeKeyframes$1(normalizer, keyframes, preStyles = new Map(), postStyles = new Map()) {
  const errors = [];
  const normalizedKeyframes = [];
  let previousOffset = -1;
  let previousKeyframe = null;
  keyframes.forEach(kf => {
    const offset = kf.get('offset');
    const isSameOffset = offset == previousOffset;
    const normalizedKeyframe = isSameOffset && previousKeyframe || new Map();
    kf.forEach((val, prop) => {
      let normalizedProp = prop;
      let normalizedValue = val;
      if (prop !== 'offset') {
        normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
        switch (normalizedValue) {
          case _angular_animations__WEBPACK_IMPORTED_MODULE_1__["ɵPRE_STYLE"]:
            normalizedValue = preStyles.get(prop);
            break;
          case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE:
            normalizedValue = postStyles.get(prop);
            break;
          default:
            normalizedValue = normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);
            break;
        }
      }
      normalizedKeyframe.set(normalizedProp, normalizedValue);
    });
    if (!isSameOffset) {
      normalizedKeyframes.push(normalizedKeyframe);
    }
    previousKeyframe = normalizedKeyframe;
    previousOffset = offset;
  });
  if (errors.length) {
    throw animationFailed(errors);
  }
  return normalizedKeyframes;
}
function listenOnPlayer(player, eventName, event, callback) {
  switch (eventName) {
    case 'start':
      player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));
      break;
    case 'done':
      player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));
      break;
    case 'destroy':
      player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));
      break;
  }
}
function copyAnimationEvent(e, phaseName, player) {
  const totalTime = player.totalTime;
  const disabled = player.disabled ? true : false;
  const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);
  const data = e['_data'];
  if (data != null) {
    event['_data'] = data;
  }
  return event;
}
function makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {
  return {
    element,
    triggerName,
    fromState,
    toState,
    phaseName,
    totalTime,
    disabled: !!disabled
  };
}
function getOrSetDefaultValue(map, key, defaultValue) {
  let value = map.get(key);
  if (!value) {
    map.set(key, value = defaultValue);
  }
  return value;
}
function parseTimelineCommand(command) {
  const separatorPos = command.indexOf(':');
  const id = command.substring(1, separatorPos);
  const action = command.slice(separatorPos + 1);
  return [id, action];
}
const documentElement = /* @__PURE__ */(() => typeof document === 'undefined' ? null : document.documentElement)();
function getParentElement(element) {
  const parent = element.parentNode || element.host || null; // consider host to support shadow DOM
  if (parent === documentElement) {
    return null;
  }
  return parent;
}
function containsVendorPrefix(prop) {
  // Webkit is the only real popular vendor prefix nowadays
  // cc: http://shouldiprefix.com/
  return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit
}
let _CACHED_BODY = null;
let _IS_WEBKIT = false;
function validateStyleProperty(prop) {
  if (!_CACHED_BODY) {
    _CACHED_BODY = getBodyNode() || {};
    _IS_WEBKIT = _CACHED_BODY.style ? 'WebkitAppearance' in _CACHED_BODY.style : false;
  }
  let result = true;
  if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {
    result = prop in _CACHED_BODY.style;
    if (!result && _IS_WEBKIT) {
      const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);
      result = camelProp in _CACHED_BODY.style;
    }
  }
  return result;
}
function validateWebAnimatableStyleProperty(prop) {
  return ANIMATABLE_PROP_SET.has(prop);
}
function getBodyNode() {
  if (typeof document != 'undefined') {
    return document.body;
  }
  return null;
}
function containsElement(elm1, elm2) {
  while (elm2) {
    if (elm2 === elm1) {
      return true;
    }
    elm2 = getParentElement(elm2);
  }
  return false;
}
function invokeQuery(element, selector, multi) {
  if (multi) {
    return Array.from(element.querySelectorAll(selector));
  }
  const elem = element.querySelector(selector);
  return elem ? [elem] : [];
}
function hypenatePropsKeys(original) {
  const newMap = new Map();
  original.forEach((val, prop) => {
    const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
    newMap.set(newProp, val);
  });
  return newMap;
}

/**
 * @publicApi
 *
 * `AnimationDriver` implentation for Noop animations
 */
let NoopAnimationDriver = /*#__PURE__*/(() => {
  class NoopAnimationDriver {
    /**
     * @returns Whether `prop` is a valid CSS property
     */
    validateStyleProperty(prop) {
      return validateStyleProperty(prop);
    }
    /**
     *
     * @returns Whether elm1 contains elm2.
     */
    containsElement(elm1, elm2) {
      return containsElement(elm1, elm2);
    }
    /**
     * @returns Rhe parent of the given element or `null` if the element is the `document`
     */
    getParentElement(element) {
      return getParentElement(element);
    }
    /**
     * @returns The result of the query selector on the element. The array will contain up to 1 item
     *     if `multi` is  `false`.
     */
    query(element, selector, multi) {
      return invokeQuery(element, selector, multi);
    }
    /**
     * @returns The `defaultValue` or empty string
     */
    computeStyle(element, prop, defaultValue) {
      return defaultValue || '';
    }
    /**
     * @returns An `NoopAnimationPlayer`
     */
    animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
      return new _angular_animations__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationPlayer(duration, delay);
    }
    static ɵfac = (() => function NoopAnimationDriver_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NoopAnimationDriver)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: NoopAnimationDriver,
      factory: NoopAnimationDriver.ɵfac
    }))();
  }
  return NoopAnimationDriver;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @publicApi
 */
class AnimationDriver {
  /**
   * @deprecated Use the NoopAnimationDriver class.
   */
  static NOOP = /*#__PURE__*/(() => new NoopAnimationDriver())();
}
class AnimationStyleNormalizer {}
class NoopAnimationStyleNormalizer {
  normalizePropertyName(propertyName, errors) {
    return propertyName;
  }
  normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
    return value;
  }
}
const ONE_SECOND = 1000;
const SUBSTITUTION_EXPR_START = '{{';
const SUBSTITUTION_EXPR_END = '}}';
const ENTER_CLASSNAME = 'ng-enter';
const LEAVE_CLASSNAME = 'ng-leave';
const NG_TRIGGER_CLASSNAME = 'ng-trigger';
const NG_TRIGGER_SELECTOR = '.ng-trigger';
const NG_ANIMATING_CLASSNAME = 'ng-animating';
const NG_ANIMATING_SELECTOR = '.ng-animating';
function resolveTimingValue(value) {
  if (typeof value == 'number') return value;
  const matches = value.match(/^(-?[\.\d]+)(m?s)/);
  if (!matches || matches.length < 2) return 0;
  return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
}
function _convertTimeValueToMS(value, unit) {
  switch (unit) {
    case 's':
      return value * ONE_SECOND;
    default:
      // ms or something else
      return value;
  }
}
function resolveTiming(timings, errors, allowNegativeValues) {
  return timings.hasOwnProperty('duration') ? timings : parseTimeExpression(timings, errors, allowNegativeValues);
}
function parseTimeExpression(exp, errors, allowNegativeValues) {
  const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
  let duration;
  let delay = 0;
  let easing = '';
  if (typeof exp === 'string') {
    const matches = exp.match(regex);
    if (matches === null) {
      errors.push(invalidTimingValue(exp));
      return {
        duration: 0,
        delay: 0,
        easing: ''
      };
    }
    duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
    const delayMatch = matches[3];
    if (delayMatch != null) {
      delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
    }
    const easingVal = matches[5];
    if (easingVal) {
      easing = easingVal;
    }
  } else {
    duration = exp;
  }
  if (!allowNegativeValues) {
    let containsErrors = false;
    let startIndex = errors.length;
    if (duration < 0) {
      errors.push(negativeStepValue());
      containsErrors = true;
    }
    if (delay < 0) {
      errors.push(negativeDelayValue());
      containsErrors = true;
    }
    if (containsErrors) {
      errors.splice(startIndex, 0, invalidTimingValue(exp));
    }
  }
  return {
    duration,
    delay,
    easing
  };
}
function normalizeKeyframes(keyframes) {
  if (!keyframes.length) {
    return [];
  }
  if (keyframes[0] instanceof Map) {
    return keyframes;
  }
  return keyframes.map(kf => new Map(Object.entries(kf)));
}
function normalizeStyles(styles) {
  return Array.isArray(styles) ? new Map(...styles) : new Map(styles);
}
function setStyles(element, styles, formerStyles) {
  styles.forEach((val, prop) => {
    const camelProp = dashCaseToCamelCase(prop);
    if (formerStyles && !formerStyles.has(prop)) {
      formerStyles.set(prop, element.style[camelProp]);
    }
    element.style[camelProp] = val;
  });
}
function eraseStyles(element, styles) {
  styles.forEach((_, prop) => {
    const camelProp = dashCaseToCamelCase(prop);
    element.style[camelProp] = '';
  });
}
function normalizeAnimationEntry(steps) {
  if (Array.isArray(steps)) {
    if (steps.length == 1) return steps[0];
    return (0,_angular_animations__WEBPACK_IMPORTED_MODULE_1__.sequence)(steps);
  }
  return steps;
}
function validateStyleParams(value, options, errors) {
  const params = options.params || {};
  const matches = extractStyleParams(value);
  if (matches.length) {
    matches.forEach(varName => {
      if (!params.hasOwnProperty(varName)) {
        errors.push(invalidStyleParams(varName));
      }
    });
  }
}
const PARAM_REGEX = /*#__PURE__*/new RegExp(`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`, 'g');
function extractStyleParams(value) {
  let params = [];
  if (typeof value === 'string') {
    let match;
    while (match = PARAM_REGEX.exec(value)) {
      params.push(match[1]);
    }
    PARAM_REGEX.lastIndex = 0;
  }
  return params;
}
function interpolateParams(value, params, errors) {
  const original = `${value}`;
  const str = original.replace(PARAM_REGEX, (_, varName) => {
    let localVal = params[varName];
    // this means that the value was never overridden by the data passed in by the user
    if (localVal == null) {
      errors.push(invalidParamValue(varName));
      localVal = '';
    }
    return localVal.toString();
  });
  // we do this to assert that numeric values stay as they are
  return str == original ? value : str;
}
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
  return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
}
function camelCaseToDashCase(input) {
  return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
function allowPreviousPlayerStylesMerge(duration, delay) {
  return duration === 0 || delay === 0;
}
function balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {
  if (previousStyles.size && keyframes.length) {
    let startingKeyframe = keyframes[0];
    let missingStyleProps = [];
    previousStyles.forEach((val, prop) => {
      if (!startingKeyframe.has(prop)) {
        missingStyleProps.push(prop);
      }
      startingKeyframe.set(prop, val);
    });
    if (missingStyleProps.length) {
      for (let i = 1; i < keyframes.length; i++) {
        let kf = keyframes[i];
        missingStyleProps.forEach(prop => kf.set(prop, computeStyle(element, prop)));
      }
    }
  }
  return keyframes;
}
function visitDslNode(visitor, node, context) {
  switch (node.type) {
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Trigger:
      return visitor.visitTrigger(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.State:
      return visitor.visitState(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Transition:
      return visitor.visitTransition(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Sequence:
      return visitor.visitSequence(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Group:
      return visitor.visitGroup(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Animate:
      return visitor.visitAnimate(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Keyframes:
      return visitor.visitKeyframes(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Style:
      return visitor.visitStyle(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Reference:
      return visitor.visitReference(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.AnimateChild:
      return visitor.visitAnimateChild(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.AnimateRef:
      return visitor.visitAnimateRef(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Query:
      return visitor.visitQuery(node, context);
    case _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Stagger:
      return visitor.visitStagger(node, context);
    default:
      throw invalidNodeType(node.type);
  }
}
function computeStyle(element, prop) {
  return window.getComputedStyle(element)[prop];
}
const DIMENSIONAL_PROP_SET = /*#__PURE__*/new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'left', 'top', 'bottom', 'right', 'fontSize', 'outlineWidth', 'outlineOffset', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'marginTop', 'marginLeft', 'marginBottom', 'marginRight', 'borderRadius', 'borderWidth', 'borderTopWidth', 'borderLeftWidth', 'borderRightWidth', 'borderBottomWidth', 'textIndent', 'perspective']);
class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {
  normalizePropertyName(propertyName, errors) {
    return dashCaseToCamelCase(propertyName);
  }
  normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
    let unit = '';
    const strVal = value.toString().trim();
    if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {
      if (typeof value === 'number') {
        unit = 'px';
      } else {
        const valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/);
        if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
          errors.push(invalidCssUnitValue(userProvidedProperty, value));
        }
      }
    }
    return strVal + unit;
  }
}
function createListOfWarnings(warnings) {
  const LINE_START = '\n - ';
  return `${LINE_START}${warnings.filter(Boolean).map(warning => warning).join(LINE_START)}`;
}
function warnValidation(warnings) {
  (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
}
function warnTriggerBuild(name, warnings) {
  (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(warnings)}`);
}
function warnRegister(warnings) {
  (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
}
function triggerParsingWarnings(name, warnings) {
  (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(warnings)}`);
}
function pushUnrecognizedPropertiesWarning(warnings, props) {
  if (props.length) {
    warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);
  }
}
const ANY_STATE = '*';
function parseTransitionExpr(transitionValue, errors) {
  const expressions = [];
  if (typeof transitionValue == 'string') {
    transitionValue.split(/\s*,\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));
  } else {
    expressions.push(transitionValue);
  }
  return expressions;
}
function parseInnerTransitionStr(eventStr, expressions, errors) {
  if (eventStr[0] == ':') {
    const result = parseAnimationAlias(eventStr, errors);
    if (typeof result == 'function') {
      expressions.push(result);
      return;
    }
    eventStr = result;
  }
  const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
  if (match == null || match.length < 4) {
    errors.push(invalidExpression(eventStr));
    return expressions;
  }
  const fromState = match[1];
  const separator = match[2];
  const toState = match[3];
  expressions.push(makeLambdaFromStates(fromState, toState));
  const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
  if (separator[0] == '<' && !isFullAnyStateExpr) {
    expressions.push(makeLambdaFromStates(toState, fromState));
  }
  return;
}
function parseAnimationAlias(alias, errors) {
  switch (alias) {
    case ':enter':
      return 'void => *';
    case ':leave':
      return '* => void';
    case ':increment':
      return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);
    case ':decrement':
      return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);
    default:
      errors.push(invalidTransitionAlias(alias));
      return '* => *';
  }
}
// DO NOT REFACTOR ... keep the follow set instantiations
// with the values intact (closure compiler for some reason
// removes follow-up lines that add the values outside of
// the constructor...
const TRUE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['true', '1']);
const FALSE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['false', '0']);
function makeLambdaFromStates(lhs, rhs) {
  const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
  const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
  return (fromState, toState) => {
    let lhsMatch = lhs == ANY_STATE || lhs == fromState;
    let rhsMatch = rhs == ANY_STATE || rhs == toState;
    if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
      lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
    }
    if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
      rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
    }
    return lhsMatch && rhsMatch;
  };
}
const SELF_TOKEN = ':self';
const SELF_TOKEN_REGEX = /*#__PURE__*/new RegExp(`s*${SELF_TOKEN}s*,?`, 'g');
/*
 * [Validation]
 * The visitor code below will traverse the animation AST generated by the animation verb functions
 * (the output is a tree of objects) and attempt to perform a series of validations on the data. The
 * following corner-cases will be validated:
 *
 * 1. Overlap of animations
 * Given that a CSS property cannot be animated in more than one place at the same time, it's
 * important that this behavior is detected and validated. The way in which this occurs is that
 * each time a style property is examined, a string-map containing the property will be updated with
 * the start and end times for when the property is used within an animation step.
 *
 * If there are two or more parallel animations that are currently running (these are invoked by the
 * group()) on the same element then the validator will throw an error. Since the start/end timing
 * values are collected for each property then if the current animation step is animating the same
 * property and its timing values fall anywhere into the window of time that the property is
 * currently being animated within then this is what causes an error.
 *
 * 2. Timing values
 * The validator will validate to see if a timing value of `duration delay easing` or
 * `durationNumber` is valid or not.
 *
 * (note that upon validation the code below will replace the timing data with an object containing
 * {duration,delay,easing}.
 *
 * 3. Offset Validation
 * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().
 * Offsets within keyframes() are considered valid when:
 *
 *   - No offsets are used at all
 *   - Each style() entry contains an offset value
 *   - Each offset is between 0 and 1
 *   - Each offset is greater to or equal than the previous one
 *
 * Otherwise an error will be thrown.
 */
function buildAnimationAst(driver, metadata, errors, warnings) {
  return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);
}
const ROOT_SELECTOR = '';
class AnimationAstBuilderVisitor {
  _driver;
  constructor(_driver) {
    this._driver = _driver;
  }
  build(metadata, errors, warnings) {
    const context = new AnimationAstBuilderContext(errors);
    this._resetContextStyleTimingState(context);
    const ast = visitDslNode(this, normalizeAnimationEntry(metadata), context);
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      if (context.unsupportedCSSPropertiesFound.size) {
        pushUnrecognizedPropertiesWarning(warnings, [...context.unsupportedCSSPropertiesFound.keys()]);
      }
    }
    return ast;
  }
  _resetContextStyleTimingState(context) {
    context.currentQuerySelector = ROOT_SELECTOR;
    context.collectedStyles = new Map();
    context.collectedStyles.set(ROOT_SELECTOR, new Map());
    context.currentTime = 0;
  }
  visitTrigger(metadata, context) {
    let queryCount = context.queryCount = 0;
    let depCount = context.depCount = 0;
    const states = [];
    const transitions = [];
    if (metadata.name.charAt(0) == '@') {
      context.errors.push(invalidTrigger());
    }
    metadata.definitions.forEach(def => {
      this._resetContextStyleTimingState(context);
      if (def.type == _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.State) {
        const stateDef = def;
        const name = stateDef.name;
        name.toString().split(/\s*,\s*/).forEach(n => {
          stateDef.name = n;
          states.push(this.visitState(stateDef, context));
        });
        stateDef.name = name;
      } else if (def.type == _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Transition) {
        const transition = this.visitTransition(def, context);
        queryCount += transition.queryCount;
        depCount += transition.depCount;
        transitions.push(transition);
      } else {
        context.errors.push(invalidDefinition());
      }
    });
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Trigger,
      name: metadata.name,
      states,
      transitions,
      queryCount,
      depCount,
      options: null
    };
  }
  visitState(metadata, context) {
    const styleAst = this.visitStyle(metadata.styles, context);
    const astParams = metadata.options && metadata.options.params || null;
    if (styleAst.containsDynamicStyles) {
      const missingSubs = new Set();
      const params = astParams || {};
      styleAst.styles.forEach(style => {
        if (style instanceof Map) {
          style.forEach(value => {
            extractStyleParams(value).forEach(sub => {
              if (!params.hasOwnProperty(sub)) {
                missingSubs.add(sub);
              }
            });
          });
        }
      });
      if (missingSubs.size) {
        context.errors.push(invalidState(metadata.name, [...missingSubs.values()]));
      }
    }
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.State,
      name: metadata.name,
      style: styleAst,
      options: astParams ? {
        params: astParams
      } : null
    };
  }
  visitTransition(metadata, context) {
    context.queryCount = 0;
    context.depCount = 0;
    const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
    const matchers = parseTransitionExpr(metadata.expr, context.errors);
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Transition,
      matchers,
      animation,
      queryCount: context.queryCount,
      depCount: context.depCount,
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitSequence(metadata, context) {
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Sequence,
      steps: metadata.steps.map(s => visitDslNode(this, s, context)),
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitGroup(metadata, context) {
    const currentTime = context.currentTime;
    let furthestTime = 0;
    const steps = metadata.steps.map(step => {
      context.currentTime = currentTime;
      const innerAst = visitDslNode(this, step, context);
      furthestTime = Math.max(furthestTime, context.currentTime);
      return innerAst;
    });
    context.currentTime = furthestTime;
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Group,
      steps,
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitAnimate(metadata, context) {
    const timingAst = constructTimingAst(metadata.timings, context.errors);
    context.currentAnimateTimings = timingAst;
    let styleAst;
    let styleMetadata = metadata.styles ? metadata.styles : (0,_angular_animations__WEBPACK_IMPORTED_MODULE_1__.style)({});
    if (styleMetadata.type == _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Keyframes) {
      styleAst = this.visitKeyframes(styleMetadata, context);
    } else {
      let styleMetadata = metadata.styles;
      let isEmpty = false;
      if (!styleMetadata) {
        isEmpty = true;
        const newStyleData = {};
        if (timingAst.easing) {
          newStyleData['easing'] = timingAst.easing;
        }
        styleMetadata = (0,_angular_animations__WEBPACK_IMPORTED_MODULE_1__.style)(newStyleData);
      }
      context.currentTime += timingAst.duration + timingAst.delay;
      const _styleAst = this.visitStyle(styleMetadata, context);
      _styleAst.isEmptyStep = isEmpty;
      styleAst = _styleAst;
    }
    context.currentAnimateTimings = null;
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Animate,
      timings: timingAst,
      style: styleAst,
      options: null
    };
  }
  visitStyle(metadata, context) {
    const ast = this._makeStyleAst(metadata, context);
    this._validateStyleAst(ast, context);
    return ast;
  }
  _makeStyleAst(metadata, context) {
    const styles = [];
    const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];
    for (let styleTuple of metadataStyles) {
      if (typeof styleTuple === 'string') {
        if (styleTuple === _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE) {
          styles.push(styleTuple);
        } else {
          context.errors.push(invalidStyleValue(styleTuple));
        }
      } else {
        styles.push(new Map(Object.entries(styleTuple)));
      }
    }
    let containsDynamicStyles = false;
    let collectedEasing = null;
    styles.forEach(styleData => {
      if (styleData instanceof Map) {
        if (styleData.has('easing')) {
          collectedEasing = styleData.get('easing');
          styleData.delete('easing');
        }
        if (!containsDynamicStyles) {
          for (let value of styleData.values()) {
            if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {
              containsDynamicStyles = true;
              break;
            }
          }
        }
      }
    });
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Style,
      styles,
      easing: collectedEasing,
      offset: metadata.offset,
      containsDynamicStyles,
      options: null
    };
  }
  _validateStyleAst(ast, context) {
    const timings = context.currentAnimateTimings;
    let endTime = context.currentTime;
    let startTime = context.currentTime;
    if (timings && startTime > 0) {
      startTime -= timings.duration + timings.delay;
    }
    ast.styles.forEach(tuple => {
      if (typeof tuple === 'string') return;
      tuple.forEach((value, prop) => {
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          if (!this._driver.validateStyleProperty(prop)) {
            tuple.delete(prop);
            context.unsupportedCSSPropertiesFound.add(prop);
            return;
          }
        }
        // This is guaranteed to have a defined Map at this querySelector location making it
        // safe to add the assertion here. It is set as a default empty map in prior methods.
        const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);
        const collectedEntry = collectedStyles.get(prop);
        let updateCollectedStyle = true;
        if (collectedEntry) {
          if (startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime) {
            context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));
            updateCollectedStyle = false;
          }
          // we always choose the smaller start time value since we
          // want to have a record of the entire animation window where
          // the style property is being animated in between
          startTime = collectedEntry.startTime;
        }
        if (updateCollectedStyle) {
          collectedStyles.set(prop, {
            startTime,
            endTime
          });
        }
        if (context.options) {
          validateStyleParams(value, context.options, context.errors);
        }
      });
    });
  }
  visitKeyframes(metadata, context) {
    const ast = {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Keyframes,
      styles: [],
      options: null
    };
    if (!context.currentAnimateTimings) {
      context.errors.push(invalidKeyframes());
      return ast;
    }
    const MAX_KEYFRAME_OFFSET = 1;
    let totalKeyframesWithOffsets = 0;
    const offsets = [];
    let offsetsOutOfOrder = false;
    let keyframesOutOfRange = false;
    let previousOffset = 0;
    const keyframes = metadata.steps.map(styles => {
      const style = this._makeStyleAst(styles, context);
      let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);
      let offset = 0;
      if (offsetVal != null) {
        totalKeyframesWithOffsets++;
        offset = style.offset = offsetVal;
      }
      keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
      offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
      previousOffset = offset;
      offsets.push(offset);
      return style;
    });
    if (keyframesOutOfRange) {
      context.errors.push(invalidOffset());
    }
    if (offsetsOutOfOrder) {
      context.errors.push(keyframeOffsetsOutOfOrder());
    }
    const length = metadata.steps.length;
    let generatedOffset = 0;
    if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
      context.errors.push(keyframesMissingOffsets());
    } else if (totalKeyframesWithOffsets == 0) {
      generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);
    }
    const limit = length - 1;
    const currentTime = context.currentTime;
    const currentAnimateTimings = context.currentAnimateTimings;
    const animateDuration = currentAnimateTimings.duration;
    keyframes.forEach((kf, i) => {
      const offset = generatedOffset > 0 ? i == limit ? 1 : generatedOffset * i : offsets[i];
      const durationUpToThisFrame = offset * animateDuration;
      context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;
      currentAnimateTimings.duration = durationUpToThisFrame;
      this._validateStyleAst(kf, context);
      kf.offset = offset;
      ast.styles.push(kf);
    });
    return ast;
  }
  visitReference(metadata, context) {
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Reference,
      animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitAnimateChild(metadata, context) {
    context.depCount++;
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.AnimateChild,
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitAnimateRef(metadata, context) {
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.AnimateRef,
      animation: this.visitReference(metadata.animation, context),
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitQuery(metadata, context) {
    const parentSelector = context.currentQuerySelector;
    const options = metadata.options || {};
    context.queryCount++;
    context.currentQuery = metadata;
    const [selector, includeSelf] = normalizeSelector(metadata.selector);
    context.currentQuerySelector = parentSelector.length ? parentSelector + ' ' + selector : selector;
    getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());
    const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
    context.currentQuery = null;
    context.currentQuerySelector = parentSelector;
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Query,
      selector,
      limit: options.limit || 0,
      optional: !!options.optional,
      includeSelf,
      animation,
      originalSelector: metadata.selector,
      options: normalizeAnimationOptions(metadata.options)
    };
  }
  visitStagger(metadata, context) {
    if (!context.currentQuery) {
      context.errors.push(invalidStagger());
    }
    const timings = metadata.timings === 'full' ? {
      duration: 0,
      delay: 0,
      easing: 'full'
    } : resolveTiming(metadata.timings, context.errors, true);
    return {
      type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Stagger,
      animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
      timings,
      options: null
    };
  }
}
function normalizeSelector(selector) {
  const hasAmpersand = selector.split(/\s*,\s*/).find(token => token == SELF_TOKEN) ? true : false;
  if (hasAmpersand) {
    selector = selector.replace(SELF_TOKEN_REGEX, '');
  }
  // Note: the :enter and :leave aren't normalized here since those
  // selectors are filled in at runtime during timeline building
  selector = selector.replace(/@\*/g, NG_TRIGGER_SELECTOR).replace(/@\w+/g, match => NG_TRIGGER_SELECTOR + '-' + match.slice(1)).replace(/:animating/g, NG_ANIMATING_SELECTOR);
  return [selector, hasAmpersand];
}
function normalizeParams(obj) {
  return obj ? {
    ...obj
  } : null;
}
class AnimationAstBuilderContext {
  errors;
  queryCount = 0;
  depCount = 0;
  currentTransition = null;
  currentQuery = null;
  currentQuerySelector = null;
  currentAnimateTimings = null;
  currentTime = 0;
  collectedStyles = /*#__PURE__*/(() => new Map())();
  options = null;
  unsupportedCSSPropertiesFound = /*#__PURE__*/(() => new Set())();
  constructor(errors) {
    this.errors = errors;
  }
}
function consumeOffset(styles) {
  if (typeof styles == 'string') return null;
  let offset = null;
  if (Array.isArray(styles)) {
    styles.forEach(styleTuple => {
      if (styleTuple instanceof Map && styleTuple.has('offset')) {
        const obj = styleTuple;
        offset = parseFloat(obj.get('offset'));
        obj.delete('offset');
      }
    });
  } else if (styles instanceof Map && styles.has('offset')) {
    const obj = styles;
    offset = parseFloat(obj.get('offset'));
    obj.delete('offset');
  }
  return offset;
}
function constructTimingAst(value, errors) {
  if (value.hasOwnProperty('duration')) {
    return value;
  }
  if (typeof value == 'number') {
    const duration = resolveTiming(value, errors).duration;
    return makeTimingAst(duration, 0, '');
  }
  const strValue = value;
  const isDynamic = strValue.split(/\s+/).some(v => v.charAt(0) == '{' && v.charAt(1) == '{');
  if (isDynamic) {
    const ast = makeTimingAst(0, 0, '');
    ast.dynamic = true;
    ast.strValue = strValue;
    return ast;
  }
  const timings = resolveTiming(strValue, errors);
  return makeTimingAst(timings.duration, timings.delay, timings.easing);
}
function normalizeAnimationOptions(options) {
  if (options) {
    options = {
      ...options
    };
    if (options['params']) {
      options['params'] = normalizeParams(options['params']);
    }
  } else {
    options = {};
  }
  return options;
}
function makeTimingAst(duration, delay, easing) {
  return {
    duration,
    delay,
    easing
  };
}
function createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {
  return {
    type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,
    element,
    keyframes,
    preStyleProps,
    postStyleProps,
    duration,
    delay,
    totalTime: duration + delay,
    easing,
    subTimeline
  };
}
class ElementInstructionMap {
  _map = /*#__PURE__*/(() => new Map())();
  get(element) {
    return this._map.get(element) || [];
  }
  append(element, instructions) {
    let existingInstructions = this._map.get(element);
    if (!existingInstructions) {
      this._map.set(element, existingInstructions = []);
    }
    existingInstructions.push(...instructions);
  }
  has(element) {
    return this._map.has(element);
  }
  clear() {
    this._map.clear();
  }
}
const ONE_FRAME_IN_MILLISECONDS = 1;
const ENTER_TOKEN = ':enter';
const ENTER_TOKEN_REGEX = /*#__PURE__*/new RegExp(ENTER_TOKEN, 'g');
const LEAVE_TOKEN = ':leave';
const LEAVE_TOKEN_REGEX = /*#__PURE__*/new RegExp(LEAVE_TOKEN, 'g');
/*
 * The code within this file aims to generate web-animations-compatible keyframes from Angular's
 * animation DSL code.
 *
 * The code below will be converted from:
 *
 * ```
 * sequence([
 *   style({ opacity: 0 }),
 *   animate(1000, style({ opacity: 0 }))
 * ])
 * ```
 *
 * To:
 * ```
 * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]
 * duration = 1000
 * delay = 0
 * easing = ''
 * ```
 *
 * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a
 * combination of AST traversal and merge-sort-like algorithms are used.
 *
 * [AST Traversal]
 * Each of the animation verbs, when executed, will return an string-map object representing what
 * type of action it is (style, animate, group, etc...) and the data associated with it. This means
 * that when functional composition mix of these functions is evaluated (like in the example above)
 * then it will end up producing a tree of objects representing the animation itself.
 *
 * When this animation object tree is processed by the visitor code below it will visit each of the
 * verb statements within the visitor. And during each visit it will build the context of the
 * animation keyframes by interacting with the `TimelineBuilder`.
 *
 * [TimelineBuilder]
 * This class is responsible for tracking the styles and building a series of keyframe objects for a
 * timeline between a start and end time. The builder starts off with an initial timeline and each
 * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a
 * `sequence()` then it will generate a sub timeline for each step as well as a new one after
 * they are complete.
 *
 * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub
 * timeline was created (based on one of the cases above) then the parent timeline will attempt to
 * merge the styles used within the sub timelines into itself (only with group() this will happen).
 * This happens with a merge operation (much like how the merge works in mergeSort) and it will only
 * copy the most recently used styles from the sub timelines into the parent timeline. This ensures
 * that if the styles are used later on in another phase of the animation then they will be the most
 * up-to-date values.
 *
 * [How Missing Styles Are Updated]
 * Each timeline has a `backFill` property which is responsible for filling in new styles into
 * already processed keyframes if a new style shows up later within the animation sequence.
 *
 * ```
 * sequence([
 *   style({ width: 0 }),
 *   animate(1000, style({ width: 100 })),
 *   animate(1000, style({ width: 200 })),
 *   animate(1000, style({ width: 300 }))
 *   animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere
 * else
 * ])
 * ```
 *
 * What is happening here is that the `height` value is added later in the sequence, but is missing
 * from all previous animation steps. Therefore when a keyframe is created it would also be missing
 * from all previous keyframes up until where it is first used. For the timeline keyframe generation
 * to properly fill in the style it will place the previous value (the value from the parent
 * timeline) or a default value of `*` into the backFill map.
 *
 * When a sub-timeline is created it will have its own backFill property. This is done so that
 * styles present within the sub-timeline do not accidentally seep into the previous/future timeline
 * keyframes
 *
 * [Validation]
 * The code in this file is not responsible for validation. That functionality happens with within
 * the `AnimationValidatorVisitor` code.
 */
function buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {
  return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);
}
class AnimationTimelineBuilderVisitor {
  buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {
    subInstructions = subInstructions || new ElementInstructionMap();
    const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);
    context.options = options;
    const delay = options.delay ? resolveTimingValue(options.delay) : 0;
    context.currentTimeline.delayNextStep(delay);
    context.currentTimeline.setStyles([startingStyles], null, context.errors, options);
    visitDslNode(this, ast, context);
    // this checks to see if an actual animation happened
    const timelines = context.timelines.filter(timeline => timeline.containsAnimation());
    // note: we just want to apply the final styles for the rootElement, so we do not
    //       just apply the styles to the last timeline but the last timeline which
    //       element is the root one (basically `*`-styles are replaced with the actual
    //       state style values only for the root element)
    if (timelines.length && finalStyles.size) {
      let lastRootTimeline;
      for (let i = timelines.length - 1; i >= 0; i--) {
        const timeline = timelines[i];
        if (timeline.element === rootElement) {
          lastRootTimeline = timeline;
          break;
        }
      }
      if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {
        lastRootTimeline.setStyles([finalStyles], null, context.errors, options);
      }
    }
    return timelines.length ? timelines.map(timeline => timeline.buildKeyframes()) : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];
  }
  visitTrigger(ast, context) {
    // these values are not visited in this AST
  }
  visitState(ast, context) {
    // these values are not visited in this AST
  }
  visitTransition(ast, context) {
    // these values are not visited in this AST
  }
  visitAnimateChild(ast, context) {
    const elementInstructions = context.subInstructions.get(context.element);
    if (elementInstructions) {
      const innerContext = context.createSubContext(ast.options);
      const startTime = context.currentTimeline.currentTime;
      const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);
      if (startTime != endTime) {
        // we do this on the upper context because we created a sub context for
        // the sub child animations
        context.transformIntoNewTimeline(endTime);
      }
    }
    context.previousNode = ast;
  }
  visitAnimateRef(ast, context) {
    const innerContext = context.createSubContext(ast.options);
    innerContext.transformIntoNewTimeline();
    this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);
    this.visitReference(ast.animation, innerContext);
    context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);
    context.previousNode = ast;
  }
  _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {
    for (const animationRefOptions of animationsRefsOptions) {
      const animationDelay = animationRefOptions?.delay;
      if (animationDelay) {
        const animationDelayValue = typeof animationDelay === 'number' ? animationDelay : resolveTimingValue(interpolateParams(animationDelay, animationRefOptions?.params ?? {}, context.errors));
        innerContext.delayNextStep(animationDelayValue);
      }
    }
  }
  _visitSubInstructions(instructions, context, options) {
    const startTime = context.currentTimeline.currentTime;
    let furthestTime = startTime;
    // this is a special-case for when a user wants to skip a sub
    // animation from being fired entirely.
    const duration = options.duration != null ? resolveTimingValue(options.duration) : null;
    const delay = options.delay != null ? resolveTimingValue(options.delay) : null;
    if (duration !== 0) {
      instructions.forEach(instruction => {
        const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);
        furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);
      });
    }
    return furthestTime;
  }
  visitReference(ast, context) {
    context.updateOptions(ast.options, true);
    visitDslNode(this, ast.animation, context);
    context.previousNode = ast;
  }
  visitSequence(ast, context) {
    const subContextCount = context.subContextCount;
    let ctx = context;
    const options = ast.options;
    if (options && (options.params || options.delay)) {
      ctx = context.createSubContext(options);
      ctx.transformIntoNewTimeline();
      if (options.delay != null) {
        if (ctx.previousNode.type == _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Style) {
          ctx.currentTimeline.snapshotCurrentStyles();
          ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
        }
        const delay = resolveTimingValue(options.delay);
        ctx.delayNextStep(delay);
      }
    }
    if (ast.steps.length) {
      ast.steps.forEach(s => visitDslNode(this, s, ctx));
      // this is here just in case the inner steps only contain or end with a style() call
      ctx.currentTimeline.applyStylesToKeyframe();
      // this means that some animation function within the sequence
      // ended up creating a sub timeline (which means the current
      // timeline cannot overlap with the contents of the sequence)
      if (ctx.subContextCount > subContextCount) {
        ctx.transformIntoNewTimeline();
      }
    }
    context.previousNode = ast;
  }
  visitGroup(ast, context) {
    const innerTimelines = [];
    let furthestTime = context.currentTimeline.currentTime;
    const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;
    ast.steps.forEach(s => {
      const innerContext = context.createSubContext(ast.options);
      if (delay) {
        innerContext.delayNextStep(delay);
      }
      visitDslNode(this, s, innerContext);
      furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);
      innerTimelines.push(innerContext.currentTimeline);
    });
    // this operation is run after the AST loop because otherwise
    // if the parent timeline's collected styles were updated then
    // it would pass in invalid data into the new-to-be forked items
    innerTimelines.forEach(timeline => context.currentTimeline.mergeTimelineCollectedStyles(timeline));
    context.transformIntoNewTimeline(furthestTime);
    context.previousNode = ast;
  }
  _visitTiming(ast, context) {
    if (ast.dynamic) {
      const strValue = ast.strValue;
      const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue;
      return resolveTiming(timingValue, context.errors);
    } else {
      return {
        duration: ast.duration,
        delay: ast.delay,
        easing: ast.easing
      };
    }
  }
  visitAnimate(ast, context) {
    const timings = context.currentAnimateTimings = this._visitTiming(ast.timings, context);
    const timeline = context.currentTimeline;
    if (timings.delay) {
      context.incrementTime(timings.delay);
      timeline.snapshotCurrentStyles();
    }
    const style = ast.style;
    if (style.type == _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Keyframes) {
      this.visitKeyframes(style, context);
    } else {
      context.incrementTime(timings.duration);
      this.visitStyle(style, context);
      timeline.applyStylesToKeyframe();
    }
    context.currentAnimateTimings = null;
    context.previousNode = ast;
  }
  visitStyle(ast, context) {
    const timeline = context.currentTimeline;
    const timings = context.currentAnimateTimings;
    // this is a special case for when a style() call
    // directly follows  an animate() call (but not inside of an animate() call)
    if (!timings && timeline.hasCurrentStyleProperties()) {
      timeline.forwardFrame();
    }
    const easing = timings && timings.easing || ast.easing;
    if (ast.isEmptyStep) {
      timeline.applyEmptyStep(easing);
    } else {
      timeline.setStyles(ast.styles, easing, context.errors, context.options);
    }
    context.previousNode = ast;
  }
  visitKeyframes(ast, context) {
    const currentAnimateTimings = context.currentAnimateTimings;
    const startTime = context.currentTimeline.duration;
    const duration = currentAnimateTimings.duration;
    const innerContext = context.createSubContext();
    const innerTimeline = innerContext.currentTimeline;
    innerTimeline.easing = currentAnimateTimings.easing;
    ast.styles.forEach(step => {
      const offset = step.offset || 0;
      innerTimeline.forwardTime(offset * duration);
      innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);
      innerTimeline.applyStylesToKeyframe();
    });
    // this will ensure that the parent timeline gets all the styles from
    // the child even if the new timeline below is not used
    context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);
    // we do this because the window between this timeline and the sub timeline
    // should ensure that the styles within are exactly the same as they were before
    context.transformIntoNewTimeline(startTime + duration);
    context.previousNode = ast;
  }
  visitQuery(ast, context) {
    // in the event that the first step before this is a style step we need
    // to ensure the styles are applied before the children are animated
    const startTime = context.currentTimeline.currentTime;
    const options = ast.options || {};
    const delay = options.delay ? resolveTimingValue(options.delay) : 0;
    if (delay && (context.previousNode.type === _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Style || startTime == 0 && context.currentTimeline.hasCurrentStyleProperties())) {
      context.currentTimeline.snapshotCurrentStyles();
      context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
    }
    let furthestTime = startTime;
    const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);
    context.currentQueryTotal = elms.length;
    let sameElementTimeline = null;
    elms.forEach((element, i) => {
      context.currentQueryIndex = i;
      const innerContext = context.createSubContext(ast.options, element);
      if (delay) {
        innerContext.delayNextStep(delay);
      }
      if (element === context.element) {
        sameElementTimeline = innerContext.currentTimeline;
      }
      visitDslNode(this, ast.animation, innerContext);
      // this is here just incase the inner steps only contain or end
      // with a style() call (which is here to signal that this is a preparatory
      // call to style an element before it is animated again)
      innerContext.currentTimeline.applyStylesToKeyframe();
      const endTime = innerContext.currentTimeline.currentTime;
      furthestTime = Math.max(furthestTime, endTime);
    });
    context.currentQueryIndex = 0;
    context.currentQueryTotal = 0;
    context.transformIntoNewTimeline(furthestTime);
    if (sameElementTimeline) {
      context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);
      context.currentTimeline.snapshotCurrentStyles();
    }
    context.previousNode = ast;
  }
  visitStagger(ast, context) {
    const parentContext = context.parentContext;
    const tl = context.currentTimeline;
    const timings = ast.timings;
    const duration = Math.abs(timings.duration);
    const maxTime = duration * (context.currentQueryTotal - 1);
    let delay = duration * context.currentQueryIndex;
    let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;
    switch (staggerTransformer) {
      case 'reverse':
        delay = maxTime - delay;
        break;
      case 'full':
        delay = parentContext.currentStaggerTime;
        break;
    }
    const timeline = context.currentTimeline;
    if (delay) {
      timeline.delayNextStep(delay);
    }
    const startingTime = timeline.currentTime;
    visitDslNode(this, ast.animation, context);
    context.previousNode = ast;
    // time = duration + delay
    // the reason why this computation is so complex is because
    // the inner timeline may either have a delay value or a stretched
    // keyframe depending on if a subtimeline is not used or is used.
    parentContext.currentStaggerTime = tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime);
  }
}
const DEFAULT_NOOP_PREVIOUS_NODE = {};
class AnimationTimelineContext {
  _driver;
  element;
  subInstructions;
  _enterClassName;
  _leaveClassName;
  errors;
  timelines;
  parentContext = null;
  currentTimeline;
  currentAnimateTimings = null;
  previousNode = /*#__PURE__*/(() => DEFAULT_NOOP_PREVIOUS_NODE)();
  subContextCount = 0;
  options = {};
  currentQueryIndex = 0;
  currentQueryTotal = 0;
  currentStaggerTime = 0;
  constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {
    this._driver = _driver;
    this.element = element;
    this.subInstructions = subInstructions;
    this._enterClassName = _enterClassName;
    this._leaveClassName = _leaveClassName;
    this.errors = errors;
    this.timelines = timelines;
    this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);
    timelines.push(this.currentTimeline);
  }
  get params() {
    return this.options.params;
  }
  updateOptions(options, skipIfExists) {
    if (!options) return;
    const newOptions = options;
    let optionsToUpdate = this.options;
    // NOTE: this will get patched up when other animation methods support duration overrides
    if (newOptions.duration != null) {
      optionsToUpdate.duration = resolveTimingValue(newOptions.duration);
    }
    if (newOptions.delay != null) {
      optionsToUpdate.delay = resolveTimingValue(newOptions.delay);
    }
    const newParams = newOptions.params;
    if (newParams) {
      let paramsToUpdate = optionsToUpdate.params;
      if (!paramsToUpdate) {
        paramsToUpdate = this.options.params = {};
      }
      Object.keys(newParams).forEach(name => {
        if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {
          paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);
        }
      });
    }
  }
  _copyOptions() {
    const options = {};
    if (this.options) {
      const oldParams = this.options.params;
      if (oldParams) {
        const params = options['params'] = {};
        Object.keys(oldParams).forEach(name => {
          params[name] = oldParams[name];
        });
      }
    }
    return options;
  }
  createSubContext(options = null, element, newTime) {
    const target = element || this.element;
    const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));
    context.previousNode = this.previousNode;
    context.currentAnimateTimings = this.currentAnimateTimings;
    context.options = this._copyOptions();
    context.updateOptions(options);
    context.currentQueryIndex = this.currentQueryIndex;
    context.currentQueryTotal = this.currentQueryTotal;
    context.parentContext = this;
    this.subContextCount++;
    return context;
  }
  transformIntoNewTimeline(newTime) {
    this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
    this.currentTimeline = this.currentTimeline.fork(this.element, newTime);
    this.timelines.push(this.currentTimeline);
    return this.currentTimeline;
  }
  appendInstructionToTimeline(instruction, duration, delay) {
    const updatedTimings = {
      duration: duration != null ? duration : instruction.duration,
      delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,
      easing: ''
    };
    const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);
    this.timelines.push(builder);
    return updatedTimings;
  }
  incrementTime(time) {
    this.currentTimeline.forwardTime(this.currentTimeline.duration + time);
  }
  delayNextStep(delay) {
    // negative delays are not yet supported
    if (delay > 0) {
      this.currentTimeline.delayNextStep(delay);
    }
  }
  invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {
    let results = [];
    if (includeSelf) {
      results.push(this.element);
    }
    if (selector.length > 0) {
      // only if :self is used then the selector can be empty
      selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);
      selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);
      const multi = limit != 1;
      let elements = this._driver.query(this.element, selector, multi);
      if (limit !== 0) {
        elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) : elements.slice(0, limit);
      }
      results.push(...elements);
    }
    if (!optional && results.length == 0) {
      errors.push(invalidQuery(originalSelector));
    }
    return results;
  }
}
class TimelineBuilder {
  _driver;
  element;
  startTime;
  _elementTimelineStylesLookup;
  duration = 0;
  easing = null;
  _previousKeyframe = /*#__PURE__*/(() => new Map())();
  _currentKeyframe = /*#__PURE__*/(() => new Map())();
  _keyframes = /*#__PURE__*/(() => new Map())();
  _styleSummary = /*#__PURE__*/(() => new Map())();
  _localTimelineStyles = /*#__PURE__*/(() => new Map())();
  _globalTimelineStyles;
  _pendingStyles = /*#__PURE__*/(() => new Map())();
  _backFill = /*#__PURE__*/(() => new Map())();
  _currentEmptyStepKeyframe = null;
  constructor(_driver, element, startTime, _elementTimelineStylesLookup) {
    this._driver = _driver;
    this.element = element;
    this.startTime = startTime;
    this._elementTimelineStylesLookup = _elementTimelineStylesLookup;
    if (!this._elementTimelineStylesLookup) {
      this._elementTimelineStylesLookup = new Map();
    }
    this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);
    if (!this._globalTimelineStyles) {
      this._globalTimelineStyles = this._localTimelineStyles;
      this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);
    }
    this._loadKeyframe();
  }
  containsAnimation() {
    switch (this._keyframes.size) {
      case 0:
        return false;
      case 1:
        return this.hasCurrentStyleProperties();
      default:
        return true;
    }
  }
  hasCurrentStyleProperties() {
    return this._currentKeyframe.size > 0;
  }
  get currentTime() {
    return this.startTime + this.duration;
  }
  delayNextStep(delay) {
    // in the event that a style() step is placed right before a stagger()
    // and that style() step is the very first style() value in the animation
    // then we need to make a copy of the keyframe [0, copy, 1] so that the delay
    // properly applies the style() values to work with the stagger...
    const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;
    if (this.duration || hasPreStyleStep) {
      this.forwardTime(this.currentTime + delay);
      if (hasPreStyleStep) {
        this.snapshotCurrentStyles();
      }
    } else {
      this.startTime += delay;
    }
  }
  fork(element, currentTime) {
    this.applyStylesToKeyframe();
    return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);
  }
  _loadKeyframe() {
    if (this._currentKeyframe) {
      this._previousKeyframe = this._currentKeyframe;
    }
    this._currentKeyframe = this._keyframes.get(this.duration);
    if (!this._currentKeyframe) {
      this._currentKeyframe = new Map();
      this._keyframes.set(this.duration, this._currentKeyframe);
    }
  }
  forwardFrame() {
    this.duration += ONE_FRAME_IN_MILLISECONDS;
    this._loadKeyframe();
  }
  forwardTime(time) {
    this.applyStylesToKeyframe();
    this.duration = time;
    this._loadKeyframe();
  }
  _updateStyle(prop, value) {
    this._localTimelineStyles.set(prop, value);
    this._globalTimelineStyles.set(prop, value);
    this._styleSummary.set(prop, {
      time: this.currentTime,
      value
    });
  }
  allowOnlyTimelineStyles() {
    return this._currentEmptyStepKeyframe !== this._currentKeyframe;
  }
  applyEmptyStep(easing) {
    if (easing) {
      this._previousKeyframe.set('easing', easing);
    }
    // special case for animate(duration):
    // all missing styles are filled with a `*` value then
    // if any destination styles are filled in later on the same
    // keyframe then they will override the overridden styles
    // We use `_globalTimelineStyles` here because there may be
    // styles in previous keyframes that are not present in this timeline
    for (let [prop, value] of this._globalTimelineStyles) {
      this._backFill.set(prop, value || _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE);
      this._currentKeyframe.set(prop, _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE);
    }
    this._currentEmptyStepKeyframe = this._currentKeyframe;
  }
  setStyles(input, easing, errors, options) {
    if (easing) {
      this._previousKeyframe.set('easing', easing);
    }
    const params = options && options.params || {};
    const styles = flattenStyles(input, this._globalTimelineStyles);
    for (let [prop, value] of styles) {
      const val = interpolateParams(value, params, errors);
      this._pendingStyles.set(prop, val);
      if (!this._localTimelineStyles.has(prop)) {
        this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE);
      }
      this._updateStyle(prop, val);
    }
  }
  applyStylesToKeyframe() {
    if (this._pendingStyles.size == 0) return;
    this._pendingStyles.forEach((val, prop) => {
      this._currentKeyframe.set(prop, val);
    });
    this._pendingStyles.clear();
    this._localTimelineStyles.forEach((val, prop) => {
      if (!this._currentKeyframe.has(prop)) {
        this._currentKeyframe.set(prop, val);
      }
    });
  }
  snapshotCurrentStyles() {
    for (let [prop, val] of this._localTimelineStyles) {
      this._pendingStyles.set(prop, val);
      this._updateStyle(prop, val);
    }
  }
  getFinalKeyframe() {
    return this._keyframes.get(this.duration);
  }
  get properties() {
    const properties = [];
    for (let prop in this._currentKeyframe) {
      properties.push(prop);
    }
    return properties;
  }
  mergeTimelineCollectedStyles(timeline) {
    timeline._styleSummary.forEach((details1, prop) => {
      const details0 = this._styleSummary.get(prop);
      if (!details0 || details1.time > details0.time) {
        this._updateStyle(prop, details1.value);
      }
    });
  }
  buildKeyframes() {
    this.applyStylesToKeyframe();
    const preStyleProps = new Set();
    const postStyleProps = new Set();
    const isEmpty = this._keyframes.size === 1 && this.duration === 0;
    let finalKeyframes = [];
    this._keyframes.forEach((keyframe, time) => {
      const finalKeyframe = new Map([...this._backFill, ...keyframe]);
      finalKeyframe.forEach((value, prop) => {
        if (value === _angular_animations__WEBPACK_IMPORTED_MODULE_1__["ɵPRE_STYLE"]) {
          preStyleProps.add(prop);
        } else if (value === _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE) {
          postStyleProps.add(prop);
        }
      });
      if (!isEmpty) {
        finalKeyframe.set('offset', time / this.duration);
      }
      finalKeyframes.push(finalKeyframe);
    });
    const preProps = [...preStyleProps.values()];
    const postProps = [...postStyleProps.values()];
    // special case for a 0-second animation (which is designed just to place styles onscreen)
    if (isEmpty) {
      const kf0 = finalKeyframes[0];
      const kf1 = new Map(kf0);
      kf0.set('offset', 0);
      kf1.set('offset', 1);
      finalKeyframes = [kf0, kf1];
    }
    return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);
  }
}
class SubTimelineBuilder extends TimelineBuilder {
  keyframes;
  preStyleProps;
  postStyleProps;
  _stretchStartingKeyframe;
  timings;
  constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {
    super(driver, element, timings.delay);
    this.keyframes = keyframes;
    this.preStyleProps = preStyleProps;
    this.postStyleProps = postStyleProps;
    this._stretchStartingKeyframe = _stretchStartingKeyframe;
    this.timings = {
      duration: timings.duration,
      delay: timings.delay,
      easing: timings.easing
    };
  }
  containsAnimation() {
    return this.keyframes.length > 1;
  }
  buildKeyframes() {
    let keyframes = this.keyframes;
    let {
      delay,
      duration,
      easing
    } = this.timings;
    if (this._stretchStartingKeyframe && delay) {
      const newKeyframes = [];
      const totalTime = duration + delay;
      const startingGap = delay / totalTime;
      // the original starting keyframe now starts once the delay is done
      const newFirstKeyframe = new Map(keyframes[0]);
      newFirstKeyframe.set('offset', 0);
      newKeyframes.push(newFirstKeyframe);
      const oldFirstKeyframe = new Map(keyframes[0]);
      oldFirstKeyframe.set('offset', roundOffset(startingGap));
      newKeyframes.push(oldFirstKeyframe);
      /*
        When the keyframe is stretched then it means that the delay before the animation
        starts is gone. Instead the first keyframe is placed at the start of the animation
        and it is then copied to where it starts when the original delay is over. This basically
        means nothing animates during that delay, but the styles are still rendered. For this
        to work the original offset values that exist in the original keyframes must be "warped"
        so that they can take the new keyframe + delay into account.
               delay=1000, duration=1000, keyframes = 0 .5 1
               turns into
               delay=0, duration=2000, keyframes = 0 .33 .66 1
       */
      // offsets between 1 ... n -1 are all warped by the keyframe stretch
      const limit = keyframes.length - 1;
      for (let i = 1; i <= limit; i++) {
        let kf = new Map(keyframes[i]);
        const oldOffset = kf.get('offset');
        const timeAtKeyframe = delay + oldOffset * duration;
        kf.set('offset', roundOffset(timeAtKeyframe / totalTime));
        newKeyframes.push(kf);
      }
      // the new starting keyframe should be added at the start
      duration = totalTime;
      delay = 0;
      easing = '';
      keyframes = newKeyframes;
    }
    return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);
  }
}
function roundOffset(offset, decimalPoints = 3) {
  const mult = Math.pow(10, decimalPoints - 1);
  return Math.round(offset * mult) / mult;
}
function flattenStyles(input, allStyles) {
  const styles = new Map();
  let allProperties;
  input.forEach(token => {
    if (token === '*') {
      allProperties ??= allStyles.keys();
      for (let prop of allProperties) {
        styles.set(prop, _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE);
      }
    } else {
      for (let [prop, val] of token) {
        styles.set(prop, val);
      }
    }
  });
  return styles;
}
function createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {
  return {
    type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,
    element,
    triggerName,
    isRemovalTransition,
    fromState,
    fromStyles,
    toState,
    toStyles,
    timelines,
    queriedElements,
    preStyleProps,
    postStyleProps,
    totalTime,
    errors
  };
}
const EMPTY_OBJECT = {};
class AnimationTransitionFactory {
  _triggerName;
  ast;
  _stateStyles;
  constructor(_triggerName, ast, _stateStyles) {
    this._triggerName = _triggerName;
    this.ast = ast;
    this._stateStyles = _stateStyles;
  }
  match(currentState, nextState, element, params) {
    return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);
  }
  buildStyles(stateName, params, errors) {
    let styler = this._stateStyles.get('*');
    if (stateName !== undefined) {
      styler = this._stateStyles.get(stateName?.toString()) || styler;
    }
    return styler ? styler.buildStyles(params, errors) : new Map();
  }
  build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {
    const errors = [];
    const transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT;
    const currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT;
    const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);
    const nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT;
    const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);
    const queriedElements = new Set();
    const preStyleMap = new Map();
    const postStyleMap = new Map();
    const isRemoval = nextState === 'void';
    const animationOptions = {
      params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),
      delay: this.ast.options?.delay
    };
    const timelines = skipAstBuild ? [] : buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);
    let totalTime = 0;
    timelines.forEach(tl => {
      totalTime = Math.max(tl.duration + tl.delay, totalTime);
    });
    if (errors.length) {
      return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);
    }
    timelines.forEach(tl => {
      const elm = tl.element;
      const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());
      tl.preStyleProps.forEach(prop => preProps.add(prop));
      const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());
      tl.postStyleProps.forEach(prop => postProps.add(prop));
      if (elm !== element) {
        queriedElements.add(elm);
      }
    });
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      checkNonAnimatableInTimelines(timelines, this._triggerName, driver);
    }
    return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime);
  }
}
/**
 * Checks inside a set of timelines if they try to animate a css property which is not considered
 * animatable, in that case it prints a warning on the console.
 * Besides that the function doesn't have any other effect.
 *
 * Note: this check is done here after the timelines are built instead of doing on a lower level so
 * that we can make sure that the warning appears only once per instruction (we can aggregate here
 * all the issues instead of finding them separately).
 *
 * @param timelines The built timelines for the current instruction.
 * @param triggerName The name of the trigger for the current instruction.
 * @param driver Animation driver used to perform the check.
 *
 */
function checkNonAnimatableInTimelines(timelines, triggerName, driver) {
  if (!driver.validateAnimatableStyleProperty) {
    return;
  }
  const allowedNonAnimatableProps = new Set([
  // 'easing' is a utility/synthetic prop we use to represent
  // easing functions, it represents a property of the animation
  // which is not animatable but different values can be used
  // in different steps
  'easing']);
  const invalidNonAnimatableProps = new Set();
  timelines.forEach(({
    keyframes
  }) => {
    const nonAnimatablePropsInitialValues = new Map();
    keyframes.forEach(keyframe => {
      const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));
      for (const [prop, value] of entriesToCheck) {
        if (!driver.validateAnimatableStyleProperty(prop)) {
          if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {
            const propInitialValue = nonAnimatablePropsInitialValues.get(prop);
            if (propInitialValue !== value) {
              invalidNonAnimatableProps.add(prop);
            }
          } else {
            nonAnimatablePropsInitialValues.set(prop, value);
          }
        }
      }
    });
  });
  if (invalidNonAnimatableProps.size > 0) {
    console.warn(`Warning: The animation trigger "${triggerName}" is attempting to animate the following` + ' not animatable properties: ' + Array.from(invalidNonAnimatableProps).join(', ') + '\n' + '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');
  }
}
function oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {
  return matchFns.some(fn => fn(currentState, nextState, element, params));
}
function applyParamDefaults(userParams, defaults) {
  const result = {
    ...defaults
  };
  Object.entries(userParams).forEach(([key, value]) => {
    if (value != null) {
      result[key] = value;
    }
  });
  return result;
}
class AnimationStateStyles {
  styles;
  defaultParams;
  normalizer;
  constructor(styles, defaultParams, normalizer) {
    this.styles = styles;
    this.defaultParams = defaultParams;
    this.normalizer = normalizer;
  }
  buildStyles(params, errors) {
    const finalStyles = new Map();
    const combinedParams = applyParamDefaults(params, this.defaultParams);
    this.styles.styles.forEach(value => {
      if (typeof value !== 'string') {
        value.forEach((val, prop) => {
          if (val) {
            val = interpolateParams(val, combinedParams, errors);
          }
          const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);
          val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);
          finalStyles.set(prop, val);
        });
      }
    });
    return finalStyles;
  }
}
function buildTrigger(name, ast, normalizer) {
  return new AnimationTrigger(name, ast, normalizer);
}
class AnimationTrigger {
  name;
  ast;
  _normalizer;
  transitionFactories = [];
  fallbackTransition;
  states = /*#__PURE__*/(() => new Map())();
  constructor(name, ast, _normalizer) {
    this.name = name;
    this.ast = ast;
    this._normalizer = _normalizer;
    ast.states.forEach(ast => {
      const defaultParams = ast.options && ast.options.params || {};
      this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));
    });
    balanceProperties(this.states, 'true', '1');
    balanceProperties(this.states, 'false', '0');
    ast.transitions.forEach(ast => {
      this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));
    });
    this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer);
  }
  get containsQueries() {
    return this.ast.queryCount > 0;
  }
  matchTransition(currentState, nextState, element, params) {
    const entry = this.transitionFactories.find(f => f.match(currentState, nextState, element, params));
    return entry || null;
  }
  matchStyles(currentState, params, errors) {
    return this.fallbackTransition.buildStyles(currentState, params, errors);
  }
}
function createFallbackTransition(triggerName, states, normalizer) {
  const matchers = [(fromState, toState) => true];
  const animation = {
    type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Sequence,
    steps: [],
    options: null
  };
  const transition = {
    type: _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AnimationMetadataType.Transition,
    animation,
    matchers,
    options: null,
    queryCount: 0,
    depCount: 0
  };
  return new AnimationTransitionFactory(triggerName, transition, states);
}
function balanceProperties(stateMap, key1, key2) {
  if (stateMap.has(key1)) {
    if (!stateMap.has(key2)) {
      stateMap.set(key2, stateMap.get(key1));
    }
  } else if (stateMap.has(key2)) {
    stateMap.set(key1, stateMap.get(key2));
  }
}
const EMPTY_INSTRUCTION_MAP = /*#__PURE__*/new ElementInstructionMap();
class TimelineAnimationEngine {
  bodyNode;
  _driver;
  _normalizer;
  _animations = /*#__PURE__*/(() => new Map())();
  _playersById = /*#__PURE__*/(() => new Map())();
  players = [];
  constructor(bodyNode, _driver, _normalizer) {
    this.bodyNode = bodyNode;
    this._driver = _driver;
    this._normalizer = _normalizer;
  }
  register(id, metadata) {
    const errors = [];
    const warnings = [];
    const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
    if (errors.length) {
      throw registerFailed(errors);
    } else {
      if (warnings.length) {
        warnRegister(warnings);
      }
      this._animations.set(id, ast);
    }
  }
  _buildPlayer(i, preStyles, postStyles) {
    const element = i.element;
    const keyframes = normalizeKeyframes$1(this._normalizer, i.keyframes, preStyles, postStyles);
    return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);
  }
  create(id, element, options = {}) {
    const errors = [];
    const ast = this._animations.get(id);
    let instructions;
    const autoStylesMap = new Map();
    if (ast) {
      instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);
      instructions.forEach(inst => {
        const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());
        inst.postStyleProps.forEach(prop => styles.set(prop, null));
      });
    } else {
      errors.push(missingOrDestroyedAnimation());
      instructions = [];
    }
    if (errors.length) {
      throw createAnimationFailed(errors);
    }
    autoStylesMap.forEach((styles, element) => {
      styles.forEach((_, prop) => {
        styles.set(prop, this._driver.computeStyle(element, prop, _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE));
      });
    });
    const players = instructions.map(i => {
      const styles = autoStylesMap.get(i.element);
      return this._buildPlayer(i, new Map(), styles);
    });
    const player = optimizeGroupPlayer(players);
    this._playersById.set(id, player);
    player.onDestroy(() => this.destroy(id));
    this.players.push(player);
    return player;
  }
  destroy(id) {
    const player = this._getPlayer(id);
    player.destroy();
    this._playersById.delete(id);
    const index = this.players.indexOf(player);
    if (index >= 0) {
      this.players.splice(index, 1);
    }
  }
  _getPlayer(id) {
    const player = this._playersById.get(id);
    if (!player) {
      throw missingPlayer(id);
    }
    return player;
  }
  listen(id, element, eventName, callback) {
    // triggerName, fromState, toState are all ignored for timeline animations
    const baseEvent = makeAnimationEvent(element, '', '', '');
    listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);
    return () => {};
  }
  command(id, element, command, args) {
    if (command == 'register') {
      this.register(id, args[0]);
      return;
    }
    if (command == 'create') {
      const options = args[0] || {};
      this.create(id, element, options);
      return;
    }
    const player = this._getPlayer(id);
    switch (command) {
      case 'play':
        player.play();
        break;
      case 'pause':
        player.pause();
        break;
      case 'reset':
        player.reset();
        break;
      case 'restart':
        player.restart();
        break;
      case 'finish':
        player.finish();
        break;
      case 'init':
        player.init();
        break;
      case 'setPosition':
        player.setPosition(parseFloat(args[0]));
        break;
      case 'destroy':
        this.destroy(id);
        break;
    }
  }
}
const QUEUED_CLASSNAME = 'ng-animate-queued';
const QUEUED_SELECTOR = '.ng-animate-queued';
const DISABLED_CLASSNAME = 'ng-animate-disabled';
const DISABLED_SELECTOR = '.ng-animate-disabled';
const STAR_CLASSNAME = 'ng-star-inserted';
const STAR_SELECTOR = '.ng-star-inserted';
const EMPTY_PLAYER_ARRAY = [];
const NULL_REMOVAL_STATE = {
  namespaceId: '',
  setForRemoval: false,
  setForMove: false,
  hasAnimation: false,
  removedBeforeQueried: false
};
const NULL_REMOVED_QUERIED_STATE = {
  namespaceId: '',
  setForMove: false,
  setForRemoval: false,
  hasAnimation: false,
  removedBeforeQueried: true
};
const REMOVAL_FLAG = '__ng_removed';
class StateValue {
  namespaceId;
  value;
  options;
  get params() {
    return this.options.params;
  }
  constructor(input, namespaceId = '') {
    this.namespaceId = namespaceId;
    const isObj = input && input.hasOwnProperty('value');
    const value = isObj ? input['value'] : input;
    this.value = normalizeTriggerValue(value);
    if (isObj) {
      // we drop the value property from options.
      const {
        value,
        ...options
      } = input;
      this.options = options;
    } else {
      this.options = {};
    }
    if (!this.options.params) {
      this.options.params = {};
    }
  }
  absorbOptions(options) {
    const newParams = options.params;
    if (newParams) {
      const oldParams = this.options.params;
      Object.keys(newParams).forEach(prop => {
        if (oldParams[prop] == null) {
          oldParams[prop] = newParams[prop];
        }
      });
    }
  }
}
const VOID_VALUE = 'void';
const DEFAULT_STATE_VALUE = /*#__PURE__*/new StateValue(VOID_VALUE);
class AnimationTransitionNamespace {
  id;
  hostElement;
  _engine;
  players = [];
  _triggers = /*#__PURE__*/(() => new Map())();
  _queue = [];
  _elementListeners = /*#__PURE__*/(() => new Map())();
  _hostClassName;
  constructor(id, hostElement, _engine) {
    this.id = id;
    this.hostElement = hostElement;
    this._engine = _engine;
    this._hostClassName = 'ng-tns-' + id;
    addClass(hostElement, this._hostClassName);
  }
  listen(element, name, phase, callback) {
    if (!this._triggers.has(name)) {
      throw missingTrigger(phase, name);
    }
    if (phase == null || phase.length == 0) {
      throw missingEvent(name);
    }
    if (!isTriggerEventValid(phase)) {
      throw unsupportedTriggerEvent(phase, name);
    }
    const listeners = getOrSetDefaultValue(this._elementListeners, element, []);
    const data = {
      name,
      phase,
      callback
    };
    listeners.push(data);
    const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());
    if (!triggersWithStates.has(name)) {
      addClass(element, NG_TRIGGER_CLASSNAME);
      addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
      triggersWithStates.set(name, DEFAULT_STATE_VALUE);
    }
    return () => {
      // the event listener is removed AFTER the flush has occurred such
      // that leave animations callbacks can fire (otherwise if the node
      // is removed in between then the listeners would be deregistered)
      this._engine.afterFlush(() => {
        const index = listeners.indexOf(data);
        if (index >= 0) {
          listeners.splice(index, 1);
        }
        if (!this._triggers.has(name)) {
          triggersWithStates.delete(name);
        }
      });
    };
  }
  register(name, ast) {
    if (this._triggers.has(name)) {
      // throw
      return false;
    } else {
      this._triggers.set(name, ast);
      return true;
    }
  }
  _getTrigger(name) {
    const trigger = this._triggers.get(name);
    if (!trigger) {
      throw unregisteredTrigger(name);
    }
    return trigger;
  }
  trigger(element, triggerName, value, defaultToFallback = true) {
    const trigger = this._getTrigger(triggerName);
    const player = new TransitionAnimationPlayer(this.id, triggerName, element);
    let triggersWithStates = this._engine.statesByElement.get(element);
    if (!triggersWithStates) {
      addClass(element, NG_TRIGGER_CLASSNAME);
      addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
      this._engine.statesByElement.set(element, triggersWithStates = new Map());
    }
    let fromState = triggersWithStates.get(triggerName);
    const toState = new StateValue(value, this.id);
    const isObj = value && value.hasOwnProperty('value');
    if (!isObj && fromState) {
      toState.absorbOptions(fromState.options);
    }
    triggersWithStates.set(triggerName, toState);
    if (!fromState) {
      fromState = DEFAULT_STATE_VALUE;
    }
    const isRemoval = toState.value === VOID_VALUE;
    // normally this isn't reached by here, however, if an object expression
    // is passed in then it may be a new object each time. Comparing the value
    // is important since that will stay the same despite there being a new object.
    // The removal arc here is special cased because the same element is triggered
    // twice in the event that it contains animations on the outer/inner portions
    // of the host container
    if (!isRemoval && fromState.value === toState.value) {
      // this means that despite the value not changing, some inner params
      // have changed which means that the animation final styles need to be applied
      if (!objEquals(fromState.params, toState.params)) {
        const errors = [];
        const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
        const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
        if (errors.length) {
          this._engine.reportError(errors);
        } else {
          this._engine.afterFlush(() => {
            eraseStyles(element, fromStyles);
            setStyles(element, toStyles);
          });
        }
      }
      return;
    }
    const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);
    playersOnElement.forEach(player => {
      // only remove the player if it is queued on the EXACT same trigger/namespace
      // we only also deal with queued players here because if the animation has
      // started then we want to keep the player alive until the flush happens
      // (which is where the previousPlayers are passed into the new player)
      if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
        player.destroy();
      }
    });
    let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);
    let isFallbackTransition = false;
    if (!transition) {
      if (!defaultToFallback) return;
      transition = trigger.fallbackTransition;
      isFallbackTransition = true;
    }
    this._engine.totalQueuedPlayers++;
    this._queue.push({
      element,
      triggerName,
      transition,
      fromState,
      toState,
      player,
      isFallbackTransition
    });
    if (!isFallbackTransition) {
      addClass(element, QUEUED_CLASSNAME);
      player.onStart(() => {
        removeClass(element, QUEUED_CLASSNAME);
      });
    }
    player.onDone(() => {
      let index = this.players.indexOf(player);
      if (index >= 0) {
        this.players.splice(index, 1);
      }
      const players = this._engine.playersByElement.get(element);
      if (players) {
        let index = players.indexOf(player);
        if (index >= 0) {
          players.splice(index, 1);
        }
      }
    });
    this.players.push(player);
    playersOnElement.push(player);
    return player;
  }
  deregister(name) {
    this._triggers.delete(name);
    this._engine.statesByElement.forEach(stateMap => stateMap.delete(name));
    this._elementListeners.forEach((listeners, element) => {
      this._elementListeners.set(element, listeners.filter(entry => {
        return entry.name != name;
      }));
    });
  }
  clearElementCache(element) {
    this._engine.statesByElement.delete(element);
    this._elementListeners.delete(element);
    const elementPlayers = this._engine.playersByElement.get(element);
    if (elementPlayers) {
      elementPlayers.forEach(player => player.destroy());
      this._engine.playersByElement.delete(element);
    }
  }
  _signalRemovalForInnerTriggers(rootElement, context) {
    const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
    // emulate a leave animation for all inner nodes within this node.
    // If there are no animations found for any of the nodes then clear the cache
    // for the element.
    elements.forEach(elm => {
      // this means that an inner remove() operation has already kicked off
      // the animation on this element...
      if (elm[REMOVAL_FLAG]) return;
      const namespaces = this._engine.fetchNamespacesByElement(elm);
      if (namespaces.size) {
        namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));
      } else {
        this.clearElementCache(elm);
      }
    });
    // If the child elements were removed along with the parent, their animations might not
    // have completed. Clear all the elements from the cache so we don't end up with a memory leak.
    this._engine.afterFlushAnimationsDone(() => elements.forEach(elm => this.clearElementCache(elm)));
  }
  triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {
    const triggerStates = this._engine.statesByElement.get(element);
    const previousTriggersValues = new Map();
    if (triggerStates) {
      const players = [];
      triggerStates.forEach((state, triggerName) => {
        previousTriggersValues.set(triggerName, state.value);
        // this check is here in the event that an element is removed
        // twice (both on the host level and the component level)
        if (this._triggers.has(triggerName)) {
          const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
          if (player) {
            players.push(player);
          }
        }
      });
      if (players.length) {
        this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);
        if (destroyAfterComplete) {
          optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
        }
        return true;
      }
    }
    return false;
  }
  prepareLeaveAnimationListeners(element) {
    const listeners = this._elementListeners.get(element);
    const elementStates = this._engine.statesByElement.get(element);
    // if this statement fails then it means that the element was picked up
    // by an earlier flush (or there are no listeners at all to track the leave).
    if (listeners && elementStates) {
      const visitedTriggers = new Set();
      listeners.forEach(listener => {
        const triggerName = listener.name;
        if (visitedTriggers.has(triggerName)) return;
        visitedTriggers.add(triggerName);
        const trigger = this._triggers.get(triggerName);
        const transition = trigger.fallbackTransition;
        const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;
        const toState = new StateValue(VOID_VALUE);
        const player = new TransitionAnimationPlayer(this.id, triggerName, element);
        this._engine.totalQueuedPlayers++;
        this._queue.push({
          element,
          triggerName,
          transition,
          fromState,
          toState,
          player,
          isFallbackTransition: true
        });
      });
    }
  }
  removeNode(element, context) {
    const engine = this._engine;
    if (element.childElementCount) {
      this._signalRemovalForInnerTriggers(element, context);
    }
    // this means that a * => VOID animation was detected and kicked off
    if (this.triggerLeaveAnimation(element, context, true)) return;
    // find the player that is animating and make sure that the
    // removal is delayed until that player has completed
    let containsPotentialParentTransition = false;
    if (engine.totalAnimations) {
      const currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : [];
      // when this `if statement` does not continue forward it means that
      // a previous animation query has selected the current element and
      // is animating it. In this situation want to continue forwards and
      // allow the element to be queued up for animation later.
      if (currentPlayers && currentPlayers.length) {
        containsPotentialParentTransition = true;
      } else {
        let parent = element;
        while (parent = parent.parentNode) {
          const triggers = engine.statesByElement.get(parent);
          if (triggers) {
            containsPotentialParentTransition = true;
            break;
          }
        }
      }
    }
    // at this stage we know that the element will either get removed
    // during flush or will be picked up by a parent query. Either way
    // we need to fire the listeners for this element when it DOES get
    // removed (once the query parent animation is done or after flush)
    this.prepareLeaveAnimationListeners(element);
    // whether or not a parent has an animation we need to delay the deferral of the leave
    // operation until we have more information (which we do after flush() has been called)
    if (containsPotentialParentTransition) {
      engine.markElementAsRemoved(this.id, element, false, context);
    } else {
      const removalFlag = element[REMOVAL_FLAG];
      if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
        // we do this after the flush has occurred such
        // that the callbacks can be fired
        engine.afterFlush(() => this.clearElementCache(element));
        engine.destroyInnerAnimations(element);
        engine._onRemovalComplete(element, context);
      }
    }
  }
  insertNode(element, parent) {
    addClass(element, this._hostClassName);
  }
  drainQueuedTransitions(microtaskId) {
    const instructions = [];
    this._queue.forEach(entry => {
      const player = entry.player;
      if (player.destroyed) return;
      const element = entry.element;
      const listeners = this._elementListeners.get(element);
      if (listeners) {
        listeners.forEach(listener => {
          if (listener.name == entry.triggerName) {
            const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);
            baseEvent['_data'] = microtaskId;
            listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
          }
        });
      }
      if (player.markedForDestroy) {
        this._engine.afterFlush(() => {
          // now we can destroy the element properly since the event listeners have
          // been bound to the player
          player.destroy();
        });
      } else {
        instructions.push(entry);
      }
    });
    this._queue = [];
    return instructions.sort((a, b) => {
      // if depCount == 0 them move to front
      // otherwise if a contains b then move back
      const d0 = a.transition.ast.depCount;
      const d1 = b.transition.ast.depCount;
      if (d0 == 0 || d1 == 0) {
        return d0 - d1;
      }
      return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
    });
  }
  destroy(context) {
    this.players.forEach(p => p.destroy());
    this._signalRemovalForInnerTriggers(this.hostElement, context);
  }
}
class TransitionAnimationEngine {
  bodyNode;
  driver;
  _normalizer;
  players = [];
  newHostElements = /*#__PURE__*/(() => new Map())();
  playersByElement = /*#__PURE__*/(() => new Map())();
  playersByQueriedElement = /*#__PURE__*/(() => new Map())();
  statesByElement = /*#__PURE__*/(() => new Map())();
  disabledNodes = /*#__PURE__*/(() => new Set())();
  totalAnimations = 0;
  totalQueuedPlayers = 0;
  _namespaceLookup = {};
  _namespaceList = [];
  _flushFns = [];
  _whenQuietFns = [];
  namespacesByHostElement = /*#__PURE__*/(() => new Map())();
  collectedEnterElements = [];
  collectedLeaveElements = [];
  // this method is designed to be overridden by the code that uses this engine
  onRemovalComplete = (element, context) => {};
  /** @internal */
  _onRemovalComplete(element, context) {
    this.onRemovalComplete(element, context);
  }
  constructor(bodyNode, driver, _normalizer) {
    this.bodyNode = bodyNode;
    this.driver = driver;
    this._normalizer = _normalizer;
  }
  get queuedPlayers() {
    const players = [];
    this._namespaceList.forEach(ns => {
      ns.players.forEach(player => {
        if (player.queued) {
          players.push(player);
        }
      });
    });
    return players;
  }
  createNamespace(namespaceId, hostElement) {
    const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
    if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
      this._balanceNamespaceList(ns, hostElement);
    } else {
      // defer this later until flush during when the host element has
      // been inserted so that we know exactly where to place it in
      // the namespace list
      this.newHostElements.set(hostElement, ns);
      // given that this host element is a part of the animation code, it
      // may or may not be inserted by a parent node that is of an
      // animation renderer type. If this happens then we can still have
      // access to this item when we query for :enter nodes. If the parent
      // is a renderer then the set data-structure will normalize the entry
      this.collectEnterElement(hostElement);
    }
    return this._namespaceLookup[namespaceId] = ns;
  }
  _balanceNamespaceList(ns, hostElement) {
    const namespaceList = this._namespaceList;
    const namespacesByHostElement = this.namespacesByHostElement;
    const limit = namespaceList.length - 1;
    if (limit >= 0) {
      let found = false;
      // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,
      // establishing a top-down ordering of namespaces in `this._namespaceList`.
      let ancestor = this.driver.getParentElement(hostElement);
      while (ancestor) {
        const ancestorNs = namespacesByHostElement.get(ancestor);
        if (ancestorNs) {
          // An animation namespace has been registered for this ancestor, so we insert `ns`
          // right after it to establish top-down ordering of animation namespaces.
          const index = namespaceList.indexOf(ancestorNs);
          namespaceList.splice(index + 1, 0, ns);
          found = true;
          break;
        }
        ancestor = this.driver.getParentElement(ancestor);
      }
      if (!found) {
        // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to
        // ensure that any existing descendants are ordered after `ns`, retaining the desired
        // top-down ordering.
        namespaceList.unshift(ns);
      }
    } else {
      namespaceList.push(ns);
    }
    namespacesByHostElement.set(hostElement, ns);
    return ns;
  }
  register(namespaceId, hostElement) {
    let ns = this._namespaceLookup[namespaceId];
    if (!ns) {
      ns = this.createNamespace(namespaceId, hostElement);
    }
    return ns;
  }
  registerTrigger(namespaceId, name, trigger) {
    let ns = this._namespaceLookup[namespaceId];
    if (ns && ns.register(name, trigger)) {
      this.totalAnimations++;
    }
  }
  destroy(namespaceId, context) {
    if (!namespaceId) return;
    this.afterFlush(() => {});
    this.afterFlushAnimationsDone(() => {
      const ns = this._fetchNamespace(namespaceId);
      this.namespacesByHostElement.delete(ns.hostElement);
      const index = this._namespaceList.indexOf(ns);
      if (index >= 0) {
        this._namespaceList.splice(index, 1);
      }
      ns.destroy(context);
      delete this._namespaceLookup[namespaceId];
    });
  }
  _fetchNamespace(id) {
    return this._namespaceLookup[id];
  }
  fetchNamespacesByElement(element) {
    // normally there should only be one namespace per element, however
    // if @triggers are placed on both the component element and then
    // its host element (within the component code) then there will be
    // two namespaces returned. We use a set here to simply deduplicate
    // the namespaces in case (for the reason described above) there are multiple triggers
    const namespaces = new Set();
    const elementStates = this.statesByElement.get(element);
    if (elementStates) {
      for (let stateValue of elementStates.values()) {
        if (stateValue.namespaceId) {
          const ns = this._fetchNamespace(stateValue.namespaceId);
          if (ns) {
            namespaces.add(ns);
          }
        }
      }
    }
    return namespaces;
  }
  trigger(namespaceId, element, name, value) {
    if (isElementNode(element)) {
      const ns = this._fetchNamespace(namespaceId);
      if (ns) {
        ns.trigger(element, name, value);
        return true;
      }
    }
    return false;
  }
  insertNode(namespaceId, element, parent, insertBefore) {
    if (!isElementNode(element)) return;
    // special case for when an element is removed and reinserted (move operation)
    // when this occurs we do not want to use the element for deletion later
    const details = element[REMOVAL_FLAG];
    if (details && details.setForRemoval) {
      details.setForRemoval = false;
      details.setForMove = true;
      const index = this.collectedLeaveElements.indexOf(element);
      if (index >= 0) {
        this.collectedLeaveElements.splice(index, 1);
      }
    }
    // in the event that the namespaceId is blank then the caller
    // code does not contain any animation code in it, but it is
    // just being called so that the node is marked as being inserted
    if (namespaceId) {
      const ns = this._fetchNamespace(namespaceId);
      // This if-statement is a workaround for router issue #21947.
      // The router sometimes hits a race condition where while a route
      // is being instantiated a new navigation arrives, triggering leave
      // animation of DOM that has not been fully initialized, until this
      // is resolved, we need to handle the scenario when DOM is not in a
      // consistent state during the animation.
      if (ns) {
        ns.insertNode(element, parent);
      }
    }
    // only *directives and host elements are inserted before
    if (insertBefore) {
      this.collectEnterElement(element);
    }
  }
  collectEnterElement(element) {
    this.collectedEnterElements.push(element);
  }
  markElementAsDisabled(element, value) {
    if (value) {
      if (!this.disabledNodes.has(element)) {
        this.disabledNodes.add(element);
        addClass(element, DISABLED_CLASSNAME);
      }
    } else if (this.disabledNodes.has(element)) {
      this.disabledNodes.delete(element);
      removeClass(element, DISABLED_CLASSNAME);
    }
  }
  removeNode(namespaceId, element, context) {
    if (isElementNode(element)) {
      const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
      if (ns) {
        ns.removeNode(element, context);
      } else {
        this.markElementAsRemoved(namespaceId, element, false, context);
      }
      const hostNS = this.namespacesByHostElement.get(element);
      if (hostNS && hostNS.id !== namespaceId) {
        hostNS.removeNode(element, context);
      }
    } else {
      this._onRemovalComplete(element, context);
    }
  }
  markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {
    this.collectedLeaveElements.push(element);
    element[REMOVAL_FLAG] = {
      namespaceId,
      setForRemoval: context,
      hasAnimation,
      removedBeforeQueried: false,
      previousTriggersValues
    };
  }
  listen(namespaceId, element, name, phase, callback) {
    if (isElementNode(element)) {
      return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
    }
    return () => {};
  }
  _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {
    return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);
  }
  destroyInnerAnimations(containerElement) {
    let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
    elements.forEach(element => this.destroyActiveAnimationsForElement(element));
    if (this.playersByQueriedElement.size == 0) return;
    elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
    elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));
  }
  destroyActiveAnimationsForElement(element) {
    const players = this.playersByElement.get(element);
    if (players) {
      players.forEach(player => {
        // special case for when an element is set for destruction, but hasn't started.
        // in this situation we want to delay the destruction until the flush occurs
        // so that any event listeners attached to the player are triggered.
        if (player.queued) {
          player.markedForDestroy = true;
        } else {
          player.destroy();
        }
      });
    }
  }
  finishActiveQueriedAnimationOnElement(element) {
    const players = this.playersByQueriedElement.get(element);
    if (players) {
      players.forEach(player => player.finish());
    }
  }
  whenRenderingDone() {
    return new Promise(resolve => {
      if (this.players.length) {
        return optimizeGroupPlayer(this.players).onDone(() => resolve());
      } else {
        resolve();
      }
    });
  }
  processLeaveNode(element) {
    const details = element[REMOVAL_FLAG];
    if (details && details.setForRemoval) {
      // this will prevent it from removing it twice
      element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
      if (details.namespaceId) {
        this.destroyInnerAnimations(element);
        const ns = this._fetchNamespace(details.namespaceId);
        if (ns) {
          ns.clearElementCache(element);
        }
      }
      this._onRemovalComplete(element, details.setForRemoval);
    }
    if (element.classList?.contains(DISABLED_CLASSNAME)) {
      this.markElementAsDisabled(element, false);
    }
    this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {
      this.markElementAsDisabled(node, false);
    });
  }
  flush(microtaskId = -1) {
    let players = [];
    if (this.newHostElements.size) {
      this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
      this.newHostElements.clear();
    }
    if (this.totalAnimations && this.collectedEnterElements.length) {
      for (let i = 0; i < this.collectedEnterElements.length; i++) {
        const elm = this.collectedEnterElements[i];
        addClass(elm, STAR_CLASSNAME);
      }
    }
    if (this._namespaceList.length && (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
      const cleanupFns = [];
      try {
        players = this._flushAnimations(cleanupFns, microtaskId);
      } finally {
        for (let i = 0; i < cleanupFns.length; i++) {
          cleanupFns[i]();
        }
      }
    } else {
      for (let i = 0; i < this.collectedLeaveElements.length; i++) {
        const element = this.collectedLeaveElements[i];
        this.processLeaveNode(element);
      }
    }
    this.totalQueuedPlayers = 0;
    this.collectedEnterElements.length = 0;
    this.collectedLeaveElements.length = 0;
    this._flushFns.forEach(fn => fn());
    this._flushFns = [];
    if (this._whenQuietFns.length) {
      // we move these over to a variable so that
      // if any new callbacks are registered in another
      // flush they do not populate the existing set
      const quietFns = this._whenQuietFns;
      this._whenQuietFns = [];
      if (players.length) {
        optimizeGroupPlayer(players).onDone(() => {
          quietFns.forEach(fn => fn());
        });
      } else {
        quietFns.forEach(fn => fn());
      }
    }
  }
  reportError(errors) {
    throw triggerTransitionsFailed(errors);
  }
  _flushAnimations(cleanupFns, microtaskId) {
    const subTimelines = new ElementInstructionMap();
    const skippedPlayers = [];
    const skippedPlayersMap = new Map();
    const queuedInstructions = [];
    const queriedElements = new Map();
    const allPreStyleElements = new Map();
    const allPostStyleElements = new Map();
    const disabledElementsSet = new Set();
    this.disabledNodes.forEach(node => {
      disabledElementsSet.add(node);
      const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
      for (let i = 0; i < nodesThatAreDisabled.length; i++) {
        disabledElementsSet.add(nodesThatAreDisabled[i]);
      }
    });
    const bodyNode = this.bodyNode;
    const allTriggerElements = Array.from(this.statesByElement.keys());
    const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
    // this must occur before the instructions are built below such that
    // the :enter queries match the elements (since the timeline queries
    // are fired during instruction building).
    const enterNodeMapIds = new Map();
    let i = 0;
    enterNodeMap.forEach((nodes, root) => {
      const className = ENTER_CLASSNAME + i++;
      enterNodeMapIds.set(root, className);
      nodes.forEach(node => addClass(node, className));
    });
    const allLeaveNodes = [];
    const mergedLeaveNodes = new Set();
    const leaveNodesWithoutAnimations = new Set();
    for (let i = 0; i < this.collectedLeaveElements.length; i++) {
      const element = this.collectedLeaveElements[i];
      const details = element[REMOVAL_FLAG];
      if (details && details.setForRemoval) {
        allLeaveNodes.push(element);
        mergedLeaveNodes.add(element);
        if (details.hasAnimation) {
          this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));
        } else {
          leaveNodesWithoutAnimations.add(element);
        }
      }
    }
    const leaveNodeMapIds = new Map();
    const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
    leaveNodeMap.forEach((nodes, root) => {
      const className = LEAVE_CLASSNAME + i++;
      leaveNodeMapIds.set(root, className);
      nodes.forEach(node => addClass(node, className));
    });
    cleanupFns.push(() => {
      enterNodeMap.forEach((nodes, root) => {
        const className = enterNodeMapIds.get(root);
        nodes.forEach(node => removeClass(node, className));
      });
      leaveNodeMap.forEach((nodes, root) => {
        const className = leaveNodeMapIds.get(root);
        nodes.forEach(node => removeClass(node, className));
      });
      allLeaveNodes.forEach(element => {
        this.processLeaveNode(element);
      });
    });
    const allPlayers = [];
    const erroneousTransitions = [];
    for (let i = this._namespaceList.length - 1; i >= 0; i--) {
      const ns = this._namespaceList[i];
      ns.drainQueuedTransitions(microtaskId).forEach(entry => {
        const player = entry.player;
        const element = entry.element;
        allPlayers.push(player);
        if (this.collectedEnterElements.length) {
          const details = element[REMOVAL_FLAG];
          // animations for move operations (elements being removed and reinserted,
          // e.g. when the order of an *ngFor list changes) are currently not supported
          if (details && details.setForMove) {
            if (details.previousTriggersValues && details.previousTriggersValues.has(entry.triggerName)) {
              const previousValue = details.previousTriggersValues.get(entry.triggerName);
              // we need to restore the previous trigger value since the element has
              // only been moved and hasn't actually left the DOM
              const triggersWithStates = this.statesByElement.get(entry.element);
              if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {
                const state = triggersWithStates.get(entry.triggerName);
                state.value = previousValue;
                triggersWithStates.set(entry.triggerName, state);
              }
            }
            player.destroy();
            return;
          }
        }
        const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);
        const leaveClassName = leaveNodeMapIds.get(element);
        const enterClassName = enterNodeMapIds.get(element);
        const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);
        if (instruction.errors && instruction.errors.length) {
          erroneousTransitions.push(instruction);
          return;
        }
        // even though the element may not be in the DOM, it may still
        // be added at a later point (due to the mechanics of content
        // projection and/or dynamic component insertion) therefore it's
        // important to still style the element.
        if (nodeIsOrphaned) {
          player.onStart(() => eraseStyles(element, instruction.fromStyles));
          player.onDestroy(() => setStyles(element, instruction.toStyles));
          skippedPlayers.push(player);
          return;
        }
        // if an unmatched transition is queued and ready to go
        // then it SHOULD NOT render an animation and cancel the
        // previously running animations.
        if (entry.isFallbackTransition) {
          player.onStart(() => eraseStyles(element, instruction.fromStyles));
          player.onDestroy(() => setStyles(element, instruction.toStyles));
          skippedPlayers.push(player);
          return;
        }
        // this means that if a parent animation uses this animation as a sub-trigger
        // then it will instruct the timeline builder not to add a player delay, but
        // instead stretch the first keyframe gap until the animation starts. This is
        // important in order to prevent extra initialization styles from being
        // required by the user for the animation.
        const timelines = [];
        instruction.timelines.forEach(tl => {
          tl.stretchStartingKeyframe = true;
          if (!this.disabledNodes.has(tl.element)) {
            timelines.push(tl);
          }
        });
        instruction.timelines = timelines;
        subTimelines.append(element, instruction.timelines);
        const tuple = {
          instruction,
          player,
          element
        };
        queuedInstructions.push(tuple);
        instruction.queriedElements.forEach(element => getOrSetDefaultValue(queriedElements, element, []).push(player));
        instruction.preStyleProps.forEach((stringMap, element) => {
          if (stringMap.size) {
            let setVal = allPreStyleElements.get(element);
            if (!setVal) {
              allPreStyleElements.set(element, setVal = new Set());
            }
            stringMap.forEach((_, prop) => setVal.add(prop));
          }
        });
        instruction.postStyleProps.forEach((stringMap, element) => {
          let setVal = allPostStyleElements.get(element);
          if (!setVal) {
            allPostStyleElements.set(element, setVal = new Set());
          }
          stringMap.forEach((_, prop) => setVal.add(prop));
        });
      });
    }
    if (erroneousTransitions.length) {
      const errors = [];
      erroneousTransitions.forEach(instruction => {
        errors.push(transitionFailed(instruction.triggerName, instruction.errors));
      });
      allPlayers.forEach(player => player.destroy());
      this.reportError(errors);
    }
    const allPreviousPlayersMap = new Map();
    // this map tells us which element in the DOM tree is contained by
    // which animation. Further down this map will get populated once
    // the players are built and in doing so we can use it to efficiently
    // figure out if a sub player is skipped due to a parent player having priority.
    const animationElementMap = new Map();
    queuedInstructions.forEach(entry => {
      const element = entry.element;
      if (subTimelines.has(element)) {
        animationElementMap.set(element, element);
        this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);
      }
    });
    skippedPlayers.forEach(player => {
      const element = player.element;
      const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);
      previousPlayers.forEach(prevPlayer => {
        getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);
        prevPlayer.destroy();
      });
    });
    // this is a special case for nodes that will be removed either by
    // having their own leave animations or by being queried in a container
    // that will be removed once a parent animation is complete. The idea
    // here is that * styles must be identical to ! styles because of
    // backwards compatibility (* is also filled in by default in many places).
    // Otherwise * styles will return an empty value or "auto" since the element
    // passed to getComputedStyle will not be visible (since * === destination)
    const replaceNodes = allLeaveNodes.filter(node => {
      return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);
    });
    // POST STAGE: fill the * styles
    const postStylesMap = new Map();
    const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, _angular_animations__WEBPACK_IMPORTED_MODULE_1__.AUTO_STYLE);
    allLeaveQueriedNodes.forEach(node => {
      if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {
        replaceNodes.push(node);
      }
    });
    // PRE STAGE: fill the ! styles
    const preStylesMap = new Map();
    enterNodeMap.forEach((nodes, root) => {
      cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, _angular_animations__WEBPACK_IMPORTED_MODULE_1__["ɵPRE_STYLE"]);
    });
    replaceNodes.forEach(node => {
      const post = postStylesMap.get(node);
      const pre = preStylesMap.get(node);
      postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])]));
    });
    const rootPlayers = [];
    const subPlayers = [];
    const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};
    queuedInstructions.forEach(entry => {
      const {
        element,
        player,
        instruction
      } = entry;
      // this means that it was never consumed by a parent animation which
      // means that it is independent and therefore should be set for animation
      if (subTimelines.has(element)) {
        if (disabledElementsSet.has(element)) {
          player.onDestroy(() => setStyles(element, instruction.toStyles));
          player.disabled = true;
          player.overrideTotalTime(instruction.totalTime);
          skippedPlayers.push(player);
          return;
        }
        // this will flow up the DOM and query the map to figure out
        // if a parent animation has priority over it. In the situation
        // that a parent is detected then it will cancel the loop. If
        // nothing is detected, or it takes a few hops to find a parent,
        // then it will fill in the missing nodes and signal them as having
        // a detected parent (or a NO_PARENT value via a special constant).
        let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;
        if (animationElementMap.size > 1) {
          let elm = element;
          const parentsToAdd = [];
          while (elm = elm.parentNode) {
            const detectedParent = animationElementMap.get(elm);
            if (detectedParent) {
              parentWithAnimation = detectedParent;
              break;
            }
            parentsToAdd.push(elm);
          }
          parentsToAdd.forEach(parent => animationElementMap.set(parent, parentWithAnimation));
        }
        const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);
        player.setRealPlayer(innerPlayer);
        if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {
          rootPlayers.push(player);
        } else {
          const parentPlayers = this.playersByElement.get(parentWithAnimation);
          if (parentPlayers && parentPlayers.length) {
            player.parentPlayer = optimizeGroupPlayer(parentPlayers);
          }
          skippedPlayers.push(player);
        }
      } else {
        eraseStyles(element, instruction.fromStyles);
        player.onDestroy(() => setStyles(element, instruction.toStyles));
        // there still might be a ancestor player animating this
        // element therefore we will still add it as a sub player
        // even if its animation may be disabled
        subPlayers.push(player);
        if (disabledElementsSet.has(element)) {
          skippedPlayers.push(player);
        }
      }
    });
    // find all of the sub players' corresponding inner animation players
    subPlayers.forEach(player => {
      // even if no players are found for a sub animation it
      // will still complete itself after the next tick since it's Noop
      const playersForElement = skippedPlayersMap.get(player.element);
      if (playersForElement && playersForElement.length) {
        const innerPlayer = optimizeGroupPlayer(playersForElement);
        player.setRealPlayer(innerPlayer);
      }
    });
    // the reason why we don't actually play the animation is
    // because all that a skipped player is designed to do is to
    // fire the start/done transition callback events
    skippedPlayers.forEach(player => {
      if (player.parentPlayer) {
        player.syncPlayerEvents(player.parentPlayer);
      } else {
        player.destroy();
      }
    });
    // run through all of the queued removals and see if they
    // were picked up by a query. If not then perform the removal
    // operation right away unless a parent animation is ongoing.
    for (let i = 0; i < allLeaveNodes.length; i++) {
      const element = allLeaveNodes[i];
      const details = element[REMOVAL_FLAG];
      removeClass(element, LEAVE_CLASSNAME);
      // this means the element has a removal animation that is being
      // taken care of and therefore the inner elements will hang around
      // until that animation is over (or the parent queried animation)
      if (details && details.hasAnimation) continue;
      let players = [];
      // if this element is queried or if it contains queried children
      // then we want for the element not to be removed from the page
      // until the queried animations have finished
      if (queriedElements.size) {
        let queriedPlayerResults = queriedElements.get(element);
        if (queriedPlayerResults && queriedPlayerResults.length) {
          players.push(...queriedPlayerResults);
        }
        let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);
        for (let j = 0; j < queriedInnerElements.length; j++) {
          let queriedPlayers = queriedElements.get(queriedInnerElements[j]);
          if (queriedPlayers && queriedPlayers.length) {
            players.push(...queriedPlayers);
          }
        }
      }
      const activePlayers = players.filter(p => !p.destroyed);
      if (activePlayers.length) {
        removeNodesAfterAnimationDone(this, element, activePlayers);
      } else {
        this.processLeaveNode(element);
      }
    }
    // this is required so the cleanup method doesn't remove them
    allLeaveNodes.length = 0;
    rootPlayers.forEach(player => {
      this.players.push(player);
      player.onDone(() => {
        player.destroy();
        const index = this.players.indexOf(player);
        this.players.splice(index, 1);
      });
      player.play();
    });
    return rootPlayers;
  }
  afterFlush(callback) {
    this._flushFns.push(callback);
  }
  afterFlushAnimationsDone(callback) {
    this._whenQuietFns.push(callback);
  }
  _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {
    let players = [];
    if (isQueriedElement) {
      const queriedElementPlayers = this.playersByQueriedElement.get(element);
      if (queriedElementPlayers) {
        players = queriedElementPlayers;
      }
    } else {
      const elementPlayers = this.playersByElement.get(element);
      if (elementPlayers) {
        const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;
        elementPlayers.forEach(player => {
          if (player.queued) return;
          if (!isRemovalAnimation && player.triggerName != triggerName) return;
          players.push(player);
        });
      }
    }
    if (namespaceId || triggerName) {
      players = players.filter(player => {
        if (namespaceId && namespaceId != player.namespaceId) return false;
        if (triggerName && triggerName != player.triggerName) return false;
        return true;
      });
    }
    return players;
  }
  _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {
    const triggerName = instruction.triggerName;
    const rootElement = instruction.element;
    // when a removal animation occurs, ALL previous players are collected
    // and destroyed (even if they are outside of the current namespace)
    const targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId;
    const targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName;
    for (const timelineInstruction of instruction.timelines) {
      const element = timelineInstruction.element;
      const isQueriedElement = element !== rootElement;
      const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);
      const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);
      previousPlayers.forEach(player => {
        const realPlayer = player.getRealPlayer();
        if (realPlayer.beforeDestroy) {
          realPlayer.beforeDestroy();
        }
        player.destroy();
        players.push(player);
      });
    }
    // this needs to be done so that the PRE/POST styles can be
    // computed properly without interfering with the previous animation
    eraseStyles(rootElement, instruction.fromStyles);
  }
  _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {
    const triggerName = instruction.triggerName;
    const rootElement = instruction.element;
    // we first run this so that the previous animation player
    // data can be passed into the successive animation players
    const allQueriedPlayers = [];
    const allConsumedElements = new Set();
    const allSubElements = new Set();
    const allNewPlayers = instruction.timelines.map(timelineInstruction => {
      const element = timelineInstruction.element;
      allConsumedElements.add(element);
      // FIXME (matsko): make sure to-be-removed animations are removed properly
      const details = element[REMOVAL_FLAG];
      if (details && details.removedBeforeQueried) return new _angular_animations__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);
      const isQueriedElement = element !== rootElement;
      const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map(p => p.getRealPlayer())).filter(p => {
        // the `element` is not apart of the AnimationPlayer definition, but
        // Mock/WebAnimations
        // use the element within their implementation. This will be added in Angular5 to
        // AnimationPlayer
        const pp = p;
        return pp.element ? pp.element === element : false;
      });
      const preStyles = preStylesMap.get(element);
      const postStyles = postStylesMap.get(element);
      const keyframes = normalizeKeyframes$1(this._normalizer, timelineInstruction.keyframes, preStyles, postStyles);
      const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);
      // this means that this particular player belongs to a sub trigger. It is
      // important that we match this player up with the corresponding (@trigger.listener)
      if (timelineInstruction.subTimeline && skippedPlayersMap) {
        allSubElements.add(element);
      }
      if (isQueriedElement) {
        const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);
        wrappedPlayer.setRealPlayer(player);
        allQueriedPlayers.push(wrappedPlayer);
      }
      return player;
    });
    allQueriedPlayers.forEach(player => {
      getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);
      player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));
    });
    allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));
    const player = optimizeGroupPlayer(allNewPlayers);
    player.onDestroy(() => {
      allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));
      setStyles(rootElement, instruction.toStyles);
    });
    // this basically makes all of the callbacks for sub element animations
    // be dependent on the upper players for when they finish
    allSubElements.forEach(element => {
      getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);
    });
    return player;
  }
  _buildPlayer(instruction, keyframes, previousPlayers) {
    if (keyframes.length > 0) {
      return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);
    }
    // special case for when an empty transition|definition is provided
    // ... there is no point in rendering an empty animation
    return new _angular_animations__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationPlayer(instruction.duration, instruction.delay);
  }
}
class TransitionAnimationPlayer {
  namespaceId;
  triggerName;
  element;
  _player = /*#__PURE__*/(() => new _angular_animations__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationPlayer())();
  _containsRealPlayer = false;
  _queuedCallbacks = /*#__PURE__*/(() => new Map())();
  destroyed = false;
  parentPlayer = null;
  markedForDestroy = false;
  disabled = false;
  queued = true;
  totalTime = 0;
  constructor(namespaceId, triggerName, element) {
    this.namespaceId = namespaceId;
    this.triggerName = triggerName;
    this.element = element;
  }
  setRealPlayer(player) {
    if (this._containsRealPlayer) return;
    this._player = player;
    this._queuedCallbacks.forEach((callbacks, phase) => {
      callbacks.forEach(callback => listenOnPlayer(player, phase, undefined, callback));
    });
    this._queuedCallbacks.clear();
    this._containsRealPlayer = true;
    this.overrideTotalTime(player.totalTime);
    this.queued = false;
  }
  getRealPlayer() {
    return this._player;
  }
  overrideTotalTime(totalTime) {
    this.totalTime = totalTime;
  }
  syncPlayerEvents(player) {
    const p = this._player;
    if (p.triggerCallback) {
      player.onStart(() => p.triggerCallback('start'));
    }
    player.onDone(() => this.finish());
    player.onDestroy(() => this.destroy());
  }
  _queueEvent(name, callback) {
    getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);
  }
  onDone(fn) {
    if (this.queued) {
      this._queueEvent('done', fn);
    }
    this._player.onDone(fn);
  }
  onStart(fn) {
    if (this.queued) {
      this._queueEvent('start', fn);
    }
    this._player.onStart(fn);
  }
  onDestroy(fn) {
    if (this.queued) {
      this._queueEvent('destroy', fn);
    }
    this._player.onDestroy(fn);
  }
  init() {
    this._player.init();
  }
  hasStarted() {
    return this.queued ? false : this._player.hasStarted();
  }
  play() {
    !this.queued && this._player.play();
  }
  pause() {
    !this.queued && this._player.pause();
  }
  restart() {
    !this.queued && this._player.restart();
  }
  finish() {
    this._player.finish();
  }
  destroy() {
    this.destroyed = true;
    this._player.destroy();
  }
  reset() {
    !this.queued && this._player.reset();
  }
  setPosition(p) {
    if (!this.queued) {
      this._player.setPosition(p);
    }
  }
  getPosition() {
    return this.queued ? 0 : this._player.getPosition();
  }
  /** @internal */
  triggerCallback(phaseName) {
    const p = this._player;
    if (p.triggerCallback) {
      p.triggerCallback(phaseName);
    }
  }
}
function deleteOrUnsetInMap(map, key, value) {
  let currentValues = map.get(key);
  if (currentValues) {
    if (currentValues.length) {
      const index = currentValues.indexOf(value);
      currentValues.splice(index, 1);
    }
    if (currentValues.length == 0) {
      map.delete(key);
    }
  }
  return currentValues;
}
function normalizeTriggerValue(value) {
  // we use `!= null` here because it's the most simple
  // way to test against a "falsy" value without mixing
  // in empty strings or a zero value. DO NOT OPTIMIZE.
  return value != null ? value : null;
}
function isElementNode(node) {
  return node && node['nodeType'] === 1;
}
function isTriggerEventValid(eventName) {
  return eventName == 'start' || eventName == 'done';
}
function cloakElement(element, value) {
  const oldValue = element.style.display;
  element.style.display = value != null ? value : 'none';
  return oldValue;
}
function cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {
  const cloakVals = [];
  elements.forEach(element => cloakVals.push(cloakElement(element)));
  const failedElements = [];
  elementPropsMap.forEach((props, element) => {
    const styles = new Map();
    props.forEach(prop => {
      const value = driver.computeStyle(element, prop, defaultStyle);
      styles.set(prop, value);
      // there is no easy way to detect this because a sub element could be removed
      // by a parent animation element being detached.
      if (!value || value.length == 0) {
        element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;
        failedElements.push(element);
      }
    });
    valuesMap.set(element, styles);
  });
  // we use a index variable here since Set.forEach(a, i) does not return
  // an index value for the closure (but instead just the value)
  let i = 0;
  elements.forEach(element => cloakElement(element, cloakVals[i++]));
  return failedElements;
}
/*
Since the Angular renderer code will return a collection of inserted
nodes in all areas of a DOM tree, it's up to this algorithm to figure
out which nodes are roots for each animation @trigger.

By placing each inserted node into a Set and traversing upwards, it
is possible to find the @trigger elements and well any direct *star
insertion nodes, if a @trigger root is found then the enter element
is placed into the Map[@trigger] spot.
 */
function buildRootMap(roots, nodes) {
  const rootMap = new Map();
  roots.forEach(root => rootMap.set(root, []));
  if (nodes.length == 0) return rootMap;
  const NULL_NODE = 1;
  const nodeSet = new Set(nodes);
  const localRootMap = new Map();
  function getRoot(node) {
    if (!node) return NULL_NODE;
    let root = localRootMap.get(node);
    if (root) return root;
    const parent = node.parentNode;
    if (rootMap.has(parent)) {
      // ngIf inside @trigger
      root = parent;
    } else if (nodeSet.has(parent)) {
      // ngIf inside ngIf
      root = NULL_NODE;
    } else {
      // recurse upwards
      root = getRoot(parent);
    }
    localRootMap.set(node, root);
    return root;
  }
  nodes.forEach(node => {
    const root = getRoot(node);
    if (root !== NULL_NODE) {
      rootMap.get(root).push(node);
    }
  });
  return rootMap;
}
function addClass(element, className) {
  element.classList?.add(className);
}
function removeClass(element, className) {
  element.classList?.remove(className);
}
function removeNodesAfterAnimationDone(engine, element, players) {
  optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
}
function flattenGroupPlayers(players) {
  const finalPlayers = [];
  _flattenGroupPlayersRecur(players, finalPlayers);
  return finalPlayers;
}
function _flattenGroupPlayersRecur(players, finalPlayers) {
  for (let i = 0; i < players.length; i++) {
    const player = players[i];
    if (player instanceof _angular_animations__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationGroupPlayer"]) {
      _flattenGroupPlayersRecur(player.players, finalPlayers);
    } else {
      finalPlayers.push(player);
    }
  }
}
function objEquals(a, b) {
  const k1 = Object.keys(a);
  const k2 = Object.keys(b);
  if (k1.length != k2.length) return false;
  for (let i = 0; i < k1.length; i++) {
    const prop = k1[i];
    if (!b.hasOwnProperty(prop) || a[prop] !== b[prop]) return false;
  }
  return true;
}
function replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {
  const postEntry = allPostStyleElements.get(element);
  if (!postEntry) return false;
  let preEntry = allPreStyleElements.get(element);
  if (preEntry) {
    postEntry.forEach(data => preEntry.add(data));
  } else {
    allPreStyleElements.set(element, postEntry);
  }
  allPostStyleElements.delete(element);
  return true;
}
class AnimationEngine {
  _driver;
  _normalizer;
  _transitionEngine;
  _timelineEngine;
  _triggerCache = {};
  // this method is designed to be overridden by the code that uses this engine
  onRemovalComplete = (element, context) => {};
  constructor(doc, _driver, _normalizer) {
    this._driver = _driver;
    this._normalizer = _normalizer;
    this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer);
    this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);
    this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);
  }
  registerTrigger(componentId, namespaceId, hostElement, name, metadata) {
    const cacheKey = componentId + '-' + name;
    let trigger = this._triggerCache[cacheKey];
    if (!trigger) {
      const errors = [];
      const warnings = [];
      const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
      if (errors.length) {
        throw triggerBuildFailed(name, errors);
      }
      if (warnings.length) {
        warnTriggerBuild(name, warnings);
      }
      trigger = buildTrigger(name, ast, this._normalizer);
      this._triggerCache[cacheKey] = trigger;
    }
    this._transitionEngine.registerTrigger(namespaceId, name, trigger);
  }
  register(namespaceId, hostElement) {
    this._transitionEngine.register(namespaceId, hostElement);
  }
  destroy(namespaceId, context) {
    this._transitionEngine.destroy(namespaceId, context);
  }
  onInsert(namespaceId, element, parent, insertBefore) {
    this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
  }
  onRemove(namespaceId, element, context) {
    this._transitionEngine.removeNode(namespaceId, element, context);
  }
  disableAnimations(element, disable) {
    this._transitionEngine.markElementAsDisabled(element, disable);
  }
  process(namespaceId, element, property, value) {
    if (property.charAt(0) == '@') {
      const [id, action] = parseTimelineCommand(property);
      const args = value;
      this._timelineEngine.command(id, element, action, args);
    } else {
      this._transitionEngine.trigger(namespaceId, element, property, value);
    }
  }
  listen(namespaceId, element, eventName, eventPhase, callback) {
    // @@listen
    if (eventName.charAt(0) == '@') {
      const [id, action] = parseTimelineCommand(eventName);
      return this._timelineEngine.listen(id, element, action, callback);
    }
    return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
  }
  flush(microtaskId = -1) {
    this._transitionEngine.flush(microtaskId);
  }
  get players() {
    return [...this._transitionEngine.players, ...this._timelineEngine.players];
  }
  whenRenderingDone() {
    return this._transitionEngine.whenRenderingDone();
  }
  afterFlushAnimationsDone(cb) {
    this._transitionEngine.afterFlushAnimationsDone(cb);
  }
}

/**
 * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are
 * detected.
 *
 * In CSS there exist properties that cannot be animated within a keyframe animation
 * (whether it be via CSS keyframes or web-animations) and the animation implementation
 * will ignore them. This function is designed to detect those special cased styles and
 * return a container that will be executed at the start and end of the animation.
 *
 * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`
 */
function packageNonAnimatableStyles(element, styles) {
  let startStyles = null;
  let endStyles = null;
  if (Array.isArray(styles) && styles.length) {
    startStyles = filterNonAnimatableStyles(styles[0]);
    if (styles.length > 1) {
      endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);
    }
  } else if (styles instanceof Map) {
    startStyles = filterNonAnimatableStyles(styles);
  }
  return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;
}
/**
 * Designed to be executed during a keyframe-based animation to apply any special-cased styles.
 *
 * When started (when the `start()` method is run) then the provided `startStyles`
 * will be applied. When finished (when the `finish()` method is called) the
 * `endStyles` will be applied as well any any starting styles. Finally when
 * `destroy()` is called then all styles will be removed.
 */
let SpecialCasedStyles = /*#__PURE__*/(() => {
  class SpecialCasedStyles {
    _element;
    _startStyles;
    _endStyles;
    static initialStylesByElement = (() => /* @__PURE__ */new WeakMap())();
    _state = 0 /* SpecialCasedStylesState.Pending */;
    _initialStyles;
    constructor(_element, _startStyles, _endStyles) {
      this._element = _element;
      this._startStyles = _startStyles;
      this._endStyles = _endStyles;
      let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);
      if (!initialStyles) {
        SpecialCasedStyles.initialStylesByElement.set(_element, initialStyles = new Map());
      }
      this._initialStyles = initialStyles;
    }
    start() {
      if (this._state < 1 /* SpecialCasedStylesState.Started */) {
        if (this._startStyles) {
          setStyles(this._element, this._startStyles, this._initialStyles);
        }
        this._state = 1 /* SpecialCasedStylesState.Started */;
      }
    }
    finish() {
      this.start();
      if (this._state < 2 /* SpecialCasedStylesState.Finished */) {
        setStyles(this._element, this._initialStyles);
        if (this._endStyles) {
          setStyles(this._element, this._endStyles);
          this._endStyles = null;
        }
        this._state = 1 /* SpecialCasedStylesState.Started */;
      }
    }
    destroy() {
      this.finish();
      if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {
        SpecialCasedStyles.initialStylesByElement.delete(this._element);
        if (this._startStyles) {
          eraseStyles(this._element, this._startStyles);
          this._endStyles = null;
        }
        if (this._endStyles) {
          eraseStyles(this._element, this._endStyles);
          this._endStyles = null;
        }
        setStyles(this._element, this._initialStyles);
        this._state = 3 /* SpecialCasedStylesState.Destroyed */;
      }
    }
  }
  return SpecialCasedStyles;
})();
function filterNonAnimatableStyles(styles) {
  let result = null;
  styles.forEach((val, prop) => {
    if (isNonAnimatableStyle(prop)) {
      result = result || new Map();
      result.set(prop, val);
    }
  });
  return result;
}
function isNonAnimatableStyle(prop) {
  return prop === 'display' || prop === 'position';
}
class WebAnimationsPlayer {
  element;
  keyframes;
  options;
  _specialStyles;
  _onDoneFns = [];
  _onStartFns = [];
  _onDestroyFns = [];
  _duration;
  _delay;
  _initialized = false;
  _finished = false;
  _started = false;
  _destroyed = false;
  _finalKeyframe;
  // the following original fns are persistent copies of the _onStartFns and _onDoneFns
  // and are used to reset the fns to their original values upon reset()
  // (since the _onStartFns and _onDoneFns get deleted after they are called)
  _originalOnDoneFns = [];
  _originalOnStartFns = [];
  // using non-null assertion because it's re(set) by init();
  domPlayer;
  time = 0;
  parentPlayer = null;
  currentSnapshot = /*#__PURE__*/(() => new Map())();
  constructor(element, keyframes, options, _specialStyles) {
    this.element = element;
    this.keyframes = keyframes;
    this.options = options;
    this._specialStyles = _specialStyles;
    this._duration = options['duration'];
    this._delay = options['delay'] || 0;
    this.time = this._duration + this._delay;
  }
  _onFinish() {
    if (!this._finished) {
      this._finished = true;
      this._onDoneFns.forEach(fn => fn());
      this._onDoneFns = [];
    }
  }
  init() {
    this._buildPlayer();
    this._preparePlayerBeforeStart();
  }
  _buildPlayer() {
    if (this._initialized) return;
    this._initialized = true;
    const keyframes = this.keyframes;
    // @ts-expect-error overwriting a readonly property
    this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);
    this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();
    const onFinish = () => this._onFinish();
    this.domPlayer.addEventListener('finish', onFinish);
    this.onDestroy(() => {
      // We must remove the `finish` event listener once an animation has completed all its
      // iterations. This action is necessary to prevent a memory leak since the listener captures
      // `this`, creating a closure that prevents `this` from being garbage collected.
      this.domPlayer.removeEventListener('finish', onFinish);
    });
  }
  _preparePlayerBeforeStart() {
    // this is required so that the player doesn't start to animate right away
    if (this._delay) {
      this._resetDomPlayerState();
    } else {
      this.domPlayer.pause();
    }
  }
  _convertKeyframesToObject(keyframes) {
    const kfs = [];
    keyframes.forEach(frame => {
      kfs.push(Object.fromEntries(frame));
    });
    return kfs;
  }
  /** @internal */
  _triggerWebAnimation(element, keyframes, options) {
    return element.animate(this._convertKeyframesToObject(keyframes), options);
  }
  onStart(fn) {
    this._originalOnStartFns.push(fn);
    this._onStartFns.push(fn);
  }
  onDone(fn) {
    this._originalOnDoneFns.push(fn);
    this._onDoneFns.push(fn);
  }
  onDestroy(fn) {
    this._onDestroyFns.push(fn);
  }
  play() {
    this._buildPlayer();
    if (!this.hasStarted()) {
      this._onStartFns.forEach(fn => fn());
      this._onStartFns = [];
      this._started = true;
      if (this._specialStyles) {
        this._specialStyles.start();
      }
    }
    this.domPlayer.play();
  }
  pause() {
    this.init();
    this.domPlayer.pause();
  }
  finish() {
    this.init();
    if (this._specialStyles) {
      this._specialStyles.finish();
    }
    this._onFinish();
    this.domPlayer.finish();
  }
  reset() {
    this._resetDomPlayerState();
    this._destroyed = false;
    this._finished = false;
    this._started = false;
    this._onStartFns = this._originalOnStartFns;
    this._onDoneFns = this._originalOnDoneFns;
  }
  _resetDomPlayerState() {
    if (this.domPlayer) {
      this.domPlayer.cancel();
    }
  }
  restart() {
    this.reset();
    this.play();
  }
  hasStarted() {
    return this._started;
  }
  destroy() {
    if (!this._destroyed) {
      this._destroyed = true;
      this._resetDomPlayerState();
      this._onFinish();
      if (this._specialStyles) {
        this._specialStyles.destroy();
      }
      this._onDestroyFns.forEach(fn => fn());
      this._onDestroyFns = [];
    }
  }
  setPosition(p) {
    if (this.domPlayer === undefined) {
      this.init();
    }
    this.domPlayer.currentTime = p * this.time;
  }
  getPosition() {
    // tsc is complaining with TS2362 without the conversion to number
    return +(this.domPlayer.currentTime ?? 0) / this.time;
  }
  get totalTime() {
    return this._delay + this._duration;
  }
  beforeDestroy() {
    const styles = new Map();
    if (this.hasStarted()) {
      // note: this code is invoked only when the `play` function was called prior to this
      // (thus `hasStarted` returns true), this implies that the code that initializes
      // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here
      const finalKeyframe = this._finalKeyframe;
      finalKeyframe.forEach((val, prop) => {
        if (prop !== 'offset') {
          styles.set(prop, this._finished ? val : computeStyle(this.element, prop));
        }
      });
    }
    this.currentSnapshot = styles;
  }
  /** @internal */
  triggerCallback(phaseName) {
    const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;
    methods.forEach(fn => fn());
    methods.length = 0;
  }
}
class WebAnimationsDriver {
  validateStyleProperty(prop) {
    // Perform actual validation in dev mode only, in prod mode this check is a noop.
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      return validateStyleProperty(prop);
    }
    return true;
  }
  validateAnimatableStyleProperty(prop) {
    // Perform actual validation in dev mode only, in prod mode this check is a noop.
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      const cssProp = camelCaseToDashCase(prop);
      return validateWebAnimatableStyleProperty(cssProp);
    }
    return true;
  }
  containsElement(elm1, elm2) {
    return containsElement(elm1, elm2);
  }
  getParentElement(element) {
    return getParentElement(element);
  }
  query(element, selector, multi) {
    return invokeQuery(element, selector, multi);
  }
  computeStyle(element, prop, defaultValue) {
    return computeStyle(element, prop);
  }
  animate(element, keyframes, duration, delay, easing, previousPlayers = []) {
    const fill = delay == 0 ? 'both' : 'forwards';
    const playerOptions = {
      duration,
      delay,
      fill
    };
    // we check for this to avoid having a null|undefined value be present
    // for the easing (which results in an error for certain browsers #9752)
    if (easing) {
      playerOptions['easing'] = easing;
    }
    const previousStyles = new Map();
    const previousWebAnimationPlayers = previousPlayers.filter(player => player instanceof WebAnimationsPlayer);
    if (allowPreviousPlayerStylesMerge(duration, delay)) {
      previousWebAnimationPlayers.forEach(player => {
        player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));
      });
    }
    let _keyframes = normalizeKeyframes(keyframes).map(styles => new Map(styles));
    _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);
    const specialStyles = packageNonAnimatableStyles(element, _keyframes);
    return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);
  }
}
function createEngine(type, doc) {
  // TODO: find a way to make this tree shakable.
  if (type === 'noop') {
    return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer());
  }
  return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer());
}
class Animation {
  _driver;
  _animationAst;
  constructor(_driver, input) {
    this._driver = _driver;
    const errors = [];
    const warnings = [];
    const ast = buildAnimationAst(_driver, input, errors, warnings);
    if (errors.length) {
      throw validationFailed(errors);
    }
    if (warnings.length) {
      warnValidation(warnings);
    }
    this._animationAst = ast;
  }
  buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {
    const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : startingStyles;
    const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : destinationStyles;
    const errors = [];
    subInstructions = subInstructions || new ElementInstructionMap();
    const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);
    if (errors.length) {
      throw buildingFailed(errors);
    }
    return result;
  }
}
const ANIMATION_PREFIX = '@';
const DISABLE_ANIMATIONS_FLAG = '@.disabled';
class BaseAnimationRenderer {
  namespaceId;
  delegate;
  engine;
  _onDestroy;
  // We need to explicitly type this property because of an api-extractor bug
  // See https://github.com/microsoft/rushstack/issues/4390
  ɵtype = 0 /* AnimationRendererType.Regular */;
  constructor(namespaceId, delegate, engine, _onDestroy) {
    this.namespaceId = namespaceId;
    this.delegate = delegate;
    this.engine = engine;
    this._onDestroy = _onDestroy;
  }
  get data() {
    return this.delegate.data;
  }
  destroyNode(node) {
    this.delegate.destroyNode?.(node);
  }
  destroy() {
    this.engine.destroy(this.namespaceId, this.delegate);
    this.engine.afterFlushAnimationsDone(() => {
      // Call the renderer destroy method after the animations has finished as otherwise
      // styles will be removed too early which will cause an unstyled animation.
      queueMicrotask(() => {
        this.delegate.destroy();
      });
    });
    this._onDestroy?.();
  }
  createElement(name, namespace) {
    return this.delegate.createElement(name, namespace);
  }
  createComment(value) {
    return this.delegate.createComment(value);
  }
  createText(value) {
    return this.delegate.createText(value);
  }
  appendChild(parent, newChild) {
    this.delegate.appendChild(parent, newChild);
    this.engine.onInsert(this.namespaceId, newChild, parent, false);
  }
  insertBefore(parent, newChild, refChild, isMove = true) {
    this.delegate.insertBefore(parent, newChild, refChild);
    // If `isMove` true than we should animate this insert.
    this.engine.onInsert(this.namespaceId, newChild, parent, isMove);
  }
  removeChild(parent, oldChild, isHostElement) {
    // Prior to the changes in #57203, this method wasn't being called at all by `core` if the child
    // doesn't have a parent. There appears to be some animation-specific downstream logic that
    // depends on the null check happening before the animation engine. This check keeps the old
    // behavior while allowing `core` to not have to check for the parent element anymore.
    if (this.parentNode(oldChild)) {
      this.engine.onRemove(this.namespaceId, oldChild, this.delegate);
    }
  }
  selectRootElement(selectorOrNode, preserveContent) {
    return this.delegate.selectRootElement(selectorOrNode, preserveContent);
  }
  parentNode(node) {
    return this.delegate.parentNode(node);
  }
  nextSibling(node) {
    return this.delegate.nextSibling(node);
  }
  setAttribute(el, name, value, namespace) {
    this.delegate.setAttribute(el, name, value, namespace);
  }
  removeAttribute(el, name, namespace) {
    this.delegate.removeAttribute(el, name, namespace);
  }
  addClass(el, name) {
    this.delegate.addClass(el, name);
  }
  removeClass(el, name) {
    this.delegate.removeClass(el, name);
  }
  setStyle(el, style, value, flags) {
    this.delegate.setStyle(el, style, value, flags);
  }
  removeStyle(el, style, flags) {
    this.delegate.removeStyle(el, style, flags);
  }
  setProperty(el, name, value) {
    if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) {
      this.disableAnimations(el, !!value);
    } else {
      this.delegate.setProperty(el, name, value);
    }
  }
  setValue(node, value) {
    this.delegate.setValue(node, value);
  }
  listen(target, eventName, callback) {
    return this.delegate.listen(target, eventName, callback);
  }
  disableAnimations(element, value) {
    this.engine.disableAnimations(element, value);
  }
}
class AnimationRenderer extends BaseAnimationRenderer {
  factory;
  constructor(factory, namespaceId, delegate, engine, onDestroy) {
    super(namespaceId, delegate, engine, onDestroy);
    this.factory = factory;
    this.namespaceId = namespaceId;
  }
  setProperty(el, name, value) {
    if (name.charAt(0) == ANIMATION_PREFIX) {
      if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) {
        value = value === undefined ? true : !!value;
        this.disableAnimations(el, value);
      } else {
        this.engine.process(this.namespaceId, el, name.slice(1), value);
      }
    } else {
      this.delegate.setProperty(el, name, value);
    }
  }
  listen(target, eventName, callback) {
    if (eventName.charAt(0) == ANIMATION_PREFIX) {
      const element = resolveElementFromTarget(target);
      let name = eventName.slice(1);
      let phase = '';
      // @listener.phase is for trigger animation callbacks
      // @@listener is for animation builder callbacks
      if (name.charAt(0) != ANIMATION_PREFIX) {
        [name, phase] = parseTriggerCallbackName(name);
      }
      return this.engine.listen(this.namespaceId, element, name, phase, event => {
        const countId = event['_data'] || -1;
        this.factory.scheduleListenerCallback(countId, callback, event);
      });
    }
    return this.delegate.listen(target, eventName, callback);
  }
}
function resolveElementFromTarget(target) {
  switch (target) {
    case 'body':
      return document.body;
    case 'document':
      return document;
    case 'window':
      return window;
    default:
      return target;
  }
}
function parseTriggerCallbackName(triggerName) {
  const dotIndex = triggerName.indexOf('.');
  const trigger = triggerName.substring(0, dotIndex);
  const phase = triggerName.slice(dotIndex + 1);
  return [trigger, phase];
}
class AnimationRendererFactory {
  delegate;
  engine;
  _zone;
  _currentId = 0;
  _microtaskId = 1;
  _animationCallbacksBuffer = [];
  _rendererCache = /*#__PURE__*/(() => new Map())();
  _cdRecurDepth = 0;
  constructor(delegate, engine, _zone) {
    this.delegate = delegate;
    this.engine = engine;
    this._zone = _zone;
    engine.onRemovalComplete = (element, delegate) => {
      delegate?.removeChild(null, element);
    };
  }
  createRenderer(hostElement, type) {
    const EMPTY_NAMESPACE_ID = '';
    // cache the delegates to find out which cached delegate can
    // be used by which cached renderer
    const delegate = this.delegate.createRenderer(hostElement, type);
    if (!hostElement || !type?.data?.['animation']) {
      const cache = this._rendererCache;
      let renderer = cache.get(delegate);
      if (!renderer) {
        // Ensure that the renderer is removed from the cache on destroy
        // since it may contain references to detached DOM nodes.
        const onRendererDestroy = () => cache.delete(delegate);
        renderer = new BaseAnimationRenderer(EMPTY_NAMESPACE_ID, delegate, this.engine, onRendererDestroy);
        // only cache this result when the base renderer is used
        cache.set(delegate, renderer);
      }
      return renderer;
    }
    const componentId = type.id;
    const namespaceId = type.id + '-' + this._currentId;
    this._currentId++;
    this.engine.register(namespaceId, hostElement);
    const registerTrigger = trigger => {
      if (Array.isArray(trigger)) {
        trigger.forEach(registerTrigger);
      } else {
        this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);
      }
    };
    const animationTriggers = type.data['animation'];
    animationTriggers.forEach(registerTrigger);
    return new AnimationRenderer(this, namespaceId, delegate, this.engine);
  }
  begin() {
    this._cdRecurDepth++;
    if (this.delegate.begin) {
      this.delegate.begin();
    }
  }
  _scheduleCountTask() {
    queueMicrotask(() => {
      this._microtaskId++;
    });
  }
  /** @internal */
  scheduleListenerCallback(count, fn, data) {
    if (count >= 0 && count < this._microtaskId) {
      this._zone.run(() => fn(data));
      return;
    }
    const animationCallbacksBuffer = this._animationCallbacksBuffer;
    if (animationCallbacksBuffer.length == 0) {
      queueMicrotask(() => {
        this._zone.run(() => {
          animationCallbacksBuffer.forEach(tuple => {
            const [fn, data] = tuple;
            fn(data);
          });
          this._animationCallbacksBuffer = [];
        });
      });
    }
    animationCallbacksBuffer.push([fn, data]);
  }
  end() {
    this._cdRecurDepth--;
    // this is to prevent animations from running twice when an inner
    // component does CD when a parent component instead has inserted it
    if (this._cdRecurDepth == 0) {
      this._zone.runOutsideAngular(() => {
        this._scheduleCountTask();
        this.engine.flush(this._microtaskId);
      });
    }
    if (this.delegate.end) {
      this.delegate.end();
    }
  }
  whenRenderingDone() {
    return this.engine.whenRenderingDone();
  }
}

/**
 * @module
 * @description
 * Entry point for all animation APIs of the animation browser package.
 */

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 6216:
/*!***************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+common@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0__rxjs@7.8.1/node_modules/@angular/common/fesm2022/common.mjs ***!
  \***************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   APP_BASE_HREF: () => (/* binding */ APP_BASE_HREF),
/* harmony export */   AsyncPipe: () => (/* binding */ AsyncPipe),
/* harmony export */   BrowserPlatformLocation: () => (/* binding */ BrowserPlatformLocation),
/* harmony export */   CommonModule: () => (/* binding */ CommonModule),
/* harmony export */   CurrencyPipe: () => (/* binding */ CurrencyPipe),
/* harmony export */   DATE_PIPE_DEFAULT_OPTIONS: () => (/* binding */ DATE_PIPE_DEFAULT_OPTIONS),
/* harmony export */   DATE_PIPE_DEFAULT_TIMEZONE: () => (/* binding */ DATE_PIPE_DEFAULT_TIMEZONE),
/* harmony export */   DOCUMENT: () => (/* binding */ DOCUMENT),
/* harmony export */   DatePipe: () => (/* binding */ DatePipe),
/* harmony export */   DecimalPipe: () => (/* binding */ DecimalPipe),
/* harmony export */   FormStyle: () => (/* binding */ FormStyle),
/* harmony export */   FormatWidth: () => (/* binding */ FormatWidth),
/* harmony export */   HashLocationStrategy: () => (/* binding */ HashLocationStrategy),
/* harmony export */   I18nPluralPipe: () => (/* binding */ I18nPluralPipe),
/* harmony export */   I18nSelectPipe: () => (/* binding */ I18nSelectPipe),
/* harmony export */   IMAGE_CONFIG: () => (/* reexport safe */ _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵIMAGE_CONFIG"]),
/* harmony export */   IMAGE_LOADER: () => (/* binding */ IMAGE_LOADER),
/* harmony export */   JsonPipe: () => (/* binding */ JsonPipe),
/* harmony export */   KeyValuePipe: () => (/* binding */ KeyValuePipe),
/* harmony export */   LOCATION_INITIALIZED: () => (/* binding */ LOCATION_INITIALIZED),
/* harmony export */   Location: () => (/* binding */ Location),
/* harmony export */   LocationStrategy: () => (/* binding */ LocationStrategy),
/* harmony export */   LowerCasePipe: () => (/* binding */ LowerCasePipe),
/* harmony export */   NgClass: () => (/* binding */ NgClass),
/* harmony export */   NgComponentOutlet: () => (/* binding */ NgComponentOutlet),
/* harmony export */   NgFor: () => (/* binding */ NgForOf),
/* harmony export */   NgForOf: () => (/* binding */ NgForOf),
/* harmony export */   NgForOfContext: () => (/* binding */ NgForOfContext),
/* harmony export */   NgIf: () => (/* binding */ NgIf),
/* harmony export */   NgIfContext: () => (/* binding */ NgIfContext),
/* harmony export */   NgLocaleLocalization: () => (/* binding */ NgLocaleLocalization),
/* harmony export */   NgLocalization: () => (/* binding */ NgLocalization),
/* harmony export */   NgOptimizedImage: () => (/* binding */ NgOptimizedImage),
/* harmony export */   NgPlural: () => (/* binding */ NgPlural),
/* harmony export */   NgPluralCase: () => (/* binding */ NgPluralCase),
/* harmony export */   NgStyle: () => (/* binding */ NgStyle),
/* harmony export */   NgSwitch: () => (/* binding */ NgSwitch),
/* harmony export */   NgSwitchCase: () => (/* binding */ NgSwitchCase),
/* harmony export */   NgSwitchDefault: () => (/* binding */ NgSwitchDefault),
/* harmony export */   NgTemplateOutlet: () => (/* binding */ NgTemplateOutlet),
/* harmony export */   NumberFormatStyle: () => (/* binding */ NumberFormatStyle),
/* harmony export */   NumberSymbol: () => (/* binding */ NumberSymbol),
/* harmony export */   PRECONNECT_CHECK_BLOCKLIST: () => (/* binding */ PRECONNECT_CHECK_BLOCKLIST),
/* harmony export */   PathLocationStrategy: () => (/* binding */ PathLocationStrategy),
/* harmony export */   PercentPipe: () => (/* binding */ PercentPipe),
/* harmony export */   PlatformLocation: () => (/* binding */ PlatformLocation),
/* harmony export */   Plural: () => (/* binding */ Plural),
/* harmony export */   SlicePipe: () => (/* binding */ SlicePipe),
/* harmony export */   TitleCasePipe: () => (/* binding */ TitleCasePipe),
/* harmony export */   TranslationWidth: () => (/* binding */ TranslationWidth),
/* harmony export */   UpperCasePipe: () => (/* binding */ UpperCasePipe),
/* harmony export */   VERSION: () => (/* binding */ VERSION),
/* harmony export */   ViewportScroller: () => (/* binding */ ViewportScroller),
/* harmony export */   WeekDay: () => (/* binding */ WeekDay),
/* harmony export */   XhrFactory: () => (/* binding */ XhrFactory),
/* harmony export */   formatCurrency: () => (/* binding */ formatCurrency),
/* harmony export */   formatDate: () => (/* binding */ formatDate),
/* harmony export */   formatNumber: () => (/* binding */ formatNumber),
/* harmony export */   formatPercent: () => (/* binding */ formatPercent),
/* harmony export */   getCurrencySymbol: () => (/* binding */ getCurrencySymbol),
/* harmony export */   getLocaleCurrencyCode: () => (/* binding */ getLocaleCurrencyCode),
/* harmony export */   getLocaleCurrencyName: () => (/* binding */ getLocaleCurrencyName),
/* harmony export */   getLocaleCurrencySymbol: () => (/* binding */ getLocaleCurrencySymbol),
/* harmony export */   getLocaleDateFormat: () => (/* binding */ getLocaleDateFormat),
/* harmony export */   getLocaleDateTimeFormat: () => (/* binding */ getLocaleDateTimeFormat),
/* harmony export */   getLocaleDayNames: () => (/* binding */ getLocaleDayNames),
/* harmony export */   getLocaleDayPeriods: () => (/* binding */ getLocaleDayPeriods),
/* harmony export */   getLocaleDirection: () => (/* binding */ getLocaleDirection),
/* harmony export */   getLocaleEraNames: () => (/* binding */ getLocaleEraNames),
/* harmony export */   getLocaleExtraDayPeriodRules: () => (/* binding */ getLocaleExtraDayPeriodRules),
/* harmony export */   getLocaleExtraDayPeriods: () => (/* binding */ getLocaleExtraDayPeriods),
/* harmony export */   getLocaleFirstDayOfWeek: () => (/* binding */ getLocaleFirstDayOfWeek),
/* harmony export */   getLocaleId: () => (/* binding */ getLocaleId),
/* harmony export */   getLocaleMonthNames: () => (/* binding */ getLocaleMonthNames),
/* harmony export */   getLocaleNumberFormat: () => (/* binding */ getLocaleNumberFormat),
/* harmony export */   getLocaleNumberSymbol: () => (/* binding */ getLocaleNumberSymbol),
/* harmony export */   getLocalePluralCase: () => (/* binding */ getLocalePluralCase),
/* harmony export */   getLocaleTimeFormat: () => (/* binding */ getLocaleTimeFormat),
/* harmony export */   getLocaleWeekEndRange: () => (/* binding */ getLocaleWeekEndRange),
/* harmony export */   getNumberOfCurrencyDigits: () => (/* binding */ getNumberOfCurrencyDigits),
/* harmony export */   isPlatformBrowser: () => (/* binding */ isPlatformBrowser),
/* harmony export */   isPlatformServer: () => (/* binding */ isPlatformServer),
/* harmony export */   provideCloudflareLoader: () => (/* binding */ provideCloudflareLoader),
/* harmony export */   provideCloudinaryLoader: () => (/* binding */ provideCloudinaryLoader),
/* harmony export */   provideImageKitLoader: () => (/* binding */ provideImageKitLoader),
/* harmony export */   provideImgixLoader: () => (/* binding */ provideImgixLoader),
/* harmony export */   provideNetlifyLoader: () => (/* binding */ provideNetlifyLoader),
/* harmony export */   registerLocaleData: () => (/* binding */ registerLocaleData),
/* harmony export */   "ɵDomAdapter": () => (/* binding */ DomAdapter),
/* harmony export */   "ɵNullViewportScroller": () => (/* binding */ NullViewportScroller),
/* harmony export */   "ɵPLATFORM_BROWSER_ID": () => (/* binding */ PLATFORM_BROWSER_ID),
/* harmony export */   "ɵPLATFORM_SERVER_ID": () => (/* binding */ PLATFORM_SERVER_ID),
/* harmony export */   "ɵPlatformNavigation": () => (/* binding */ PlatformNavigation),
/* harmony export */   "ɵgetDOM": () => (/* binding */ getDOM),
/* harmony export */   "ɵnormalizeQueryParams": () => (/* binding */ normalizeQueryParams),
/* harmony export */   "ɵparseCookieValue": () => (/* binding */ parseCookieValue),
/* harmony export */   "ɵsetRootDomAdapter": () => (/* binding */ setRootDomAdapter)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2714);

/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */





let _DOM = null;
function getDOM() {
  return _DOM;
}
function setRootDomAdapter(adapter) {
  _DOM ??= adapter;
}
/* tslint:disable:requireParameterType */
/**
 * Provides DOM operations in an environment-agnostic way.
 *
 * @security Tread carefully! Interacting with the DOM directly is dangerous and
 * can introduce XSS risks.
 */
class DomAdapter {}

/**
 * This class wraps the platform Navigation API which allows server-specific and test
 * implementations.
 */
let PlatformNavigation = /*#__PURE__*/(() => {
  class PlatformNavigation {
    static ɵfac = (() => function PlatformNavigation_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PlatformNavigation)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PlatformNavigation,
      factory: () => (() => window.navigation)(),
      providedIn: 'platform'
    }))();
  }
  return PlatformNavigation;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * A DI Token representing the main rendering context.
 * In a browser and SSR this is the DOM Document.
 * When using SSR, that document is created by [Domino](https://github.com/angular/domino).
 *
 * @publicApi
 */
const DOCUMENT = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'DocumentToken' : '');

/**
 * This class should not be used directly by an application developer. Instead, use
 * {@link Location}.
 *
 * `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be
 * platform-agnostic.
 * This means that we can have different implementation of `PlatformLocation` for the different
 * platforms that Angular supports. For example, `@angular/platform-browser` provides an
 * implementation specific to the browser environment, while `@angular/platform-server` provides
 * one suitable for use with server-side rendering.
 *
 * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy}
 * when they need to interact with the DOM APIs like pushState, popState, etc.
 *
 * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly
 * by the {@link Router} in order to navigate between routes. Since all interactions between {@link
 * Router} /
 * {@link Location} / {@link LocationStrategy} and DOM APIs flow through the `PlatformLocation`
 * class, they are all platform-agnostic.
 *
 * @publicApi
 */
let PlatformLocation = /*#__PURE__*/(() => {
  class PlatformLocation {
    historyGo(relativePosition) {
      throw new Error(ngDevMode ? 'Not implemented' : '');
    }
    static ɵfac = (() => function PlatformLocation_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PlatformLocation)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PlatformLocation,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(BrowserPlatformLocation))(),
      providedIn: 'platform'
    }))();
  }
  return PlatformLocation;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Indicates when a location is initialized.
 *
 * @publicApi
 */
const LOCATION_INITIALIZED = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'Location Initialized' : '');
/**
 * `PlatformLocation` encapsulates all of the direct calls to platform APIs.
 * This class should not be used directly by an application developer. Instead, use
 * {@link Location}.
 *
 * @publicApi
 */
let BrowserPlatformLocation = /*#__PURE__*/(() => {
  class BrowserPlatformLocation extends PlatformLocation {
    _location;
    _history;
    _doc = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT))();
    constructor() {
      super();
      this._location = window.location;
      this._history = window.history;
    }
    getBaseHrefFromDOM() {
      return getDOM().getBaseHref(this._doc);
    }
    onPopState(fn) {
      const window = getDOM().getGlobalEventTarget(this._doc, 'window');
      window.addEventListener('popstate', fn, false);
      return () => window.removeEventListener('popstate', fn);
    }
    onHashChange(fn) {
      const window = getDOM().getGlobalEventTarget(this._doc, 'window');
      window.addEventListener('hashchange', fn, false);
      return () => window.removeEventListener('hashchange', fn);
    }
    get href() {
      return this._location.href;
    }
    get protocol() {
      return this._location.protocol;
    }
    get hostname() {
      return this._location.hostname;
    }
    get port() {
      return this._location.port;
    }
    get pathname() {
      return this._location.pathname;
    }
    get search() {
      return this._location.search;
    }
    get hash() {
      return this._location.hash;
    }
    set pathname(newPath) {
      this._location.pathname = newPath;
    }
    pushState(state, title, url) {
      this._history.pushState(state, title, url);
    }
    replaceState(state, title, url) {
      this._history.replaceState(state, title, url);
    }
    forward() {
      this._history.forward();
    }
    back() {
      this._history.back();
    }
    historyGo(relativePosition = 0) {
      this._history.go(relativePosition);
    }
    getState() {
      return this._history.state;
    }
    static ɵfac = (() => function BrowserPlatformLocation_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BrowserPlatformLocation)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: BrowserPlatformLocation,
      factory: () => (() => new BrowserPlatformLocation())(),
      providedIn: 'platform'
    }))();
  }
  return BrowserPlatformLocation;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Joins two parts of a URL with a slash if needed.
 *
 * @param start  URL string
 * @param end    URL string
 *
 *
 * @returns The joined URL string.
 */
function joinWithSlash(start, end) {
  if (start.length == 0) {
    return end;
  }
  if (end.length == 0) {
    return start;
  }
  let slashes = 0;
  if (start.endsWith('/')) {
    slashes++;
  }
  if (end.startsWith('/')) {
    slashes++;
  }
  if (slashes == 2) {
    return start + end.substring(1);
  }
  if (slashes == 1) {
    return start + end;
  }
  return start + '/' + end;
}
/**
 * Removes a trailing slash from a URL string if needed.
 * Looks for the first occurrence of either `#`, `?`, or the end of the
 * line as `/` characters and removes the trailing slash if one exists.
 *
 * @param url URL string.
 *
 * @returns The URL string, modified if needed.
 */
function stripTrailingSlash(url) {
  const match = url.match(/#|\?|$/);
  const pathEndIdx = match && match.index || url.length;
  const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
  return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx);
}
/**
 * Normalizes URL parameters by prepending with `?` if needed.
 *
 * @param  params String of URL parameters.
 *
 * @returns The normalized URL parameters string.
 */
function normalizeQueryParams(params) {
  return params && params[0] !== '?' ? '?' + params : params;
}

/**
 * Enables the `Location` service to read route state from the browser's URL.
 * Angular provides two strategies:
 * `HashLocationStrategy` and `PathLocationStrategy`.
 *
 * Applications should use the `Router` or `Location` services to
 * interact with application route state.
 *
 * For instance, `HashLocationStrategy` produces URLs like
 * <code class="no-auto-link">http://example.com/#/foo</code>,
 * and `PathLocationStrategy` produces
 * <code class="no-auto-link">http://example.com/foo</code> as an equivalent URL.
 *
 * See these two classes for more.
 *
 * @publicApi
 */
let LocationStrategy = /*#__PURE__*/(() => {
  class LocationStrategy {
    historyGo(relativePosition) {
      throw new Error(ngDevMode ? 'Not implemented' : '');
    }
    static ɵfac = (() => function LocationStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || LocationStrategy)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: LocationStrategy,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(PathLocationStrategy))(),
      providedIn: 'root'
    }))();
  }
  return LocationStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * A predefined DI token for the base href
 * to be used with the `PathLocationStrategy`.
 * The base href is the URL prefix that should be preserved when generating
 * and recognizing URLs.
 *
 * @usageNotes
 *
 * The following example shows how to use this token to configure the root app injector
 * with a base href value, so that the DI framework can supply the dependency anywhere in the app.
 *
 * ```typescript
 * import {NgModule} from '@angular/core';
 * import {APP_BASE_HREF} from '@angular/common';
 *
 * @NgModule({
 *   providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
 * })
 * class AppModule {}
 * ```
 *
 * @publicApi
 */
const APP_BASE_HREF = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'appBaseHref' : '');
/**
 * @description
 * A {@link LocationStrategy} used to configure the {@link Location} service to
 * represent its state in the
 * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
 * browser's URL.
 *
 * If you're using `PathLocationStrategy`, you may provide a {@link APP_BASE_HREF}
 * or add a `<base href>` element to the document to override the default.
 *
 * For instance, if you provide an `APP_BASE_HREF` of `'/my/app/'` and call
 * `location.go('/foo')`, the browser's URL will become
 * `example.com/my/app/foo`. To ensure all relative URIs resolve correctly,
 * the `<base href>` and/or `APP_BASE_HREF` should end with a `/`.
 *
 * Similarly, if you add `<base href='/my/app/'/>` to the document and call
 * `location.go('/foo')`, the browser's URL will become
 * `example.com/my/app/foo`.
 *
 * Note that when using `PathLocationStrategy`, neither the query nor
 * the fragment in the `<base href>` will be preserved, as outlined
 * by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2).
 *
 * @usageNotes
 *
 * ### Example
 *
 * {@example common/location/ts/path_location_component.ts region='LocationComponent'}
 *
 * @publicApi
 */
let PathLocationStrategy = /*#__PURE__*/(() => {
  class PathLocationStrategy extends LocationStrategy {
    _platformLocation;
    _baseHref;
    _removeListenerFns = [];
    constructor(_platformLocation, href) {
      super();
      this._platformLocation = _platformLocation;
      this._baseHref = href ?? this._platformLocation.getBaseHrefFromDOM() ?? (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT).location?.origin ?? '';
    }
    /** @nodoc */
    ngOnDestroy() {
      while (this._removeListenerFns.length) {
        this._removeListenerFns.pop()();
      }
    }
    onPopState(fn) {
      this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn));
    }
    getBaseHref() {
      return this._baseHref;
    }
    prepareExternalUrl(internal) {
      return joinWithSlash(this._baseHref, internal);
    }
    path(includeHash = false) {
      const pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search);
      const hash = this._platformLocation.hash;
      return hash && includeHash ? `${pathname}${hash}` : pathname;
    }
    pushState(state, title, url, queryParams) {
      const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
      this._platformLocation.pushState(state, title, externalUrl);
    }
    replaceState(state, title, url, queryParams) {
      const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
      this._platformLocation.replaceState(state, title, externalUrl);
    }
    forward() {
      this._platformLocation.forward();
    }
    back() {
      this._platformLocation.back();
    }
    getState() {
      return this._platformLocation.getState();
    }
    historyGo(relativePosition = 0) {
      this._platformLocation.historyGo?.(relativePosition);
    }
    static ɵfac = (() => function PathLocationStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PathLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](APP_BASE_HREF, 8));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PathLocationStrategy,
      factory: PathLocationStrategy.ɵfac,
      providedIn: 'root'
    }))();
  }
  return PathLocationStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @description
 * A {@link LocationStrategy} used to configure the {@link Location} service to
 * represent its state in the
 * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
 * of the browser's URL.
 *
 * For instance, if you call `location.go('/foo')`, the browser's URL will become
 * `example.com#/foo`.
 *
 * @usageNotes
 *
 * ### Example
 *
 * {@example common/location/ts/hash_location_component.ts region='LocationComponent'}
 *
 * @publicApi
 */
let HashLocationStrategy = /*#__PURE__*/(() => {
  class HashLocationStrategy extends LocationStrategy {
    _platformLocation;
    _baseHref = '';
    _removeListenerFns = [];
    constructor(_platformLocation, _baseHref) {
      super();
      this._platformLocation = _platformLocation;
      if (_baseHref != null) {
        this._baseHref = _baseHref;
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      while (this._removeListenerFns.length) {
        this._removeListenerFns.pop()();
      }
    }
    onPopState(fn) {
      this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn));
    }
    getBaseHref() {
      return this._baseHref;
    }
    path(includeHash = false) {
      // the hash value is always prefixed with a `#`
      // and if it is empty then it will stay empty
      const path = this._platformLocation.hash ?? '#';
      return path.length > 0 ? path.substring(1) : path;
    }
    prepareExternalUrl(internal) {
      const url = joinWithSlash(this._baseHref, internal);
      return url.length > 0 ? '#' + url : url;
    }
    pushState(state, title, path, queryParams) {
      let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
      if (url.length == 0) {
        url = this._platformLocation.pathname;
      }
      this._platformLocation.pushState(state, title, url);
    }
    replaceState(state, title, path, queryParams) {
      let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams));
      if (url.length == 0) {
        url = this._platformLocation.pathname;
      }
      this._platformLocation.replaceState(state, title, url);
    }
    forward() {
      this._platformLocation.forward();
    }
    back() {
      this._platformLocation.back();
    }
    getState() {
      return this._platformLocation.getState();
    }
    historyGo(relativePosition = 0) {
      this._platformLocation.historyGo?.(relativePosition);
    }
    static ɵfac = (() => function HashLocationStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HashLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](APP_BASE_HREF, 8));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: HashLocationStrategy,
      factory: HashLocationStrategy.ɵfac
    }))();
  }
  return HashLocationStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @description
 *
 * A service that applications can use to interact with a browser's URL.
 *
 * Depending on the `LocationStrategy` used, `Location` persists
 * to the URL's path or the URL's hash segment.
 *
 * @usageNotes
 *
 * It's better to use the `Router.navigate()` service to trigger route changes. Use
 * `Location` only if you need to interact with or create normalized URLs outside of
 * routing.
 *
 * `Location` is responsible for normalizing the URL against the application's base href.
 * A normalized URL is absolute from the URL host, includes the application's base href, and has no
 * trailing slash:
 * - `/my/app/user/123` is normalized
 * - `my/app/user/123` **is not** normalized
 * - `/my/app/user/123/` **is not** normalized
 *
 * ### Example
 *
 * <code-example path='common/location/ts/path_location_component.ts'
 * region='LocationComponent'></code-example>
 *
 * @publicApi
 */
let Location = /*#__PURE__*/(() => {
  class Location {
    /** @internal */
    _subject = (() => new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject())();
    /** @internal */
    _basePath;
    /** @internal */
    _locationStrategy;
    /** @internal */
    _urlChangeListeners = [];
    /** @internal */
    _urlChangeSubscription = null;
    constructor(locationStrategy) {
      this._locationStrategy = locationStrategy;
      const baseHref = this._locationStrategy.getBaseHref();
      // Note: This class's interaction with base HREF does not fully follow the rules
      // outlined in the spec https://www.freesoft.org/CIE/RFC/1808/18.htm.
      // Instead of trying to fix individual bugs with more and more code, we should
      // investigate using the URL constructor and providing the base as a second
      // argument.
      // https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#parameters
      this._basePath = _stripOrigin(stripTrailingSlash(_stripIndexHtml(baseHref)));
      this._locationStrategy.onPopState(ev => {
        this._subject.next({
          'url': this.path(true),
          'pop': true,
          'state': ev.state,
          'type': ev.type
        });
      });
    }
    /** @nodoc */
    ngOnDestroy() {
      this._urlChangeSubscription?.unsubscribe();
      this._urlChangeListeners = [];
    }
    /**
     * Normalizes the URL path for this location.
     *
     * @param includeHash True to include an anchor fragment in the path.
     *
     * @returns The normalized URL path.
     */
    // TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is
    // removed.
    path(includeHash = false) {
      return this.normalize(this._locationStrategy.path(includeHash));
    }
    /**
     * Reports the current state of the location history.
     * @returns The current value of the `history.state` object.
     */
    getState() {
      return this._locationStrategy.getState();
    }
    /**
     * Normalizes the given path and compares to the current normalized path.
     *
     * @param path The given URL path.
     * @param query Query parameters.
     *
     * @returns True if the given URL path is equal to the current normalized path, false
     * otherwise.
     */
    isCurrentPathEqualTo(path, query = '') {
      return this.path() == this.normalize(path + normalizeQueryParams(query));
    }
    /**
     * Normalizes a URL path by stripping any trailing slashes.
     *
     * @param url String representing a URL.
     *
     * @returns The normalized URL string.
     */
    normalize(url) {
      return Location.stripTrailingSlash(_stripBasePath(this._basePath, _stripIndexHtml(url)));
    }
    /**
     * Normalizes an external URL path.
     * If the given URL doesn't begin with a leading slash (`'/'`), adds one
     * before normalizing. Adds a hash if `HashLocationStrategy` is
     * in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
     *
     * @param url String representing a URL.
     *
     * @returns  A normalized platform-specific URL.
     */
    prepareExternalUrl(url) {
      if (url && url[0] !== '/') {
        url = '/' + url;
      }
      return this._locationStrategy.prepareExternalUrl(url);
    }
    // TODO: rename this method to pushState
    /**
     * Changes the browser's URL to a normalized version of a given URL, and pushes a
     * new item onto the platform's history.
     *
     * @param path  URL path to normalize.
     * @param query Query parameters.
     * @param state Location history state.
     *
     */
    go(path, query = '', state = null) {
      this._locationStrategy.pushState(state, '', path, query);
      this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
    }
    /**
     * Changes the browser's URL to a normalized version of the given URL, and replaces
     * the top item on the platform's history stack.
     *
     * @param path  URL path to normalize.
     * @param query Query parameters.
     * @param state Location history state.
     */
    replaceState(path, query = '', state = null) {
      this._locationStrategy.replaceState(state, '', path, query);
      this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state);
    }
    /**
     * Navigates forward in the platform's history.
     */
    forward() {
      this._locationStrategy.forward();
    }
    /**
     * Navigates back in the platform's history.
     */
    back() {
      this._locationStrategy.back();
    }
    /**
     * Navigate to a specific page from session history, identified by its relative position to the
     * current page.
     *
     * @param relativePosition  Position of the target page in the history relative to the current
     *     page.
     * A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)`
     * moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go
     * beyond what's stored in the history session, we stay in the current page. Same behaviour occurs
     * when `relativePosition` equals 0.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history
     */
    historyGo(relativePosition = 0) {
      this._locationStrategy.historyGo?.(relativePosition);
    }
    /**
     * Registers a URL change listener. Use to catch updates performed by the Angular
     * framework that are not detectible through "popstate" or "hashchange" events.
     *
     * @param fn The change handler function, which take a URL and a location history state.
     * @returns A function that, when executed, unregisters a URL change listener.
     */
    onUrlChange(fn) {
      this._urlChangeListeners.push(fn);
      this._urlChangeSubscription ??= this.subscribe(v => {
        this._notifyUrlChangeListeners(v.url, v.state);
      });
      return () => {
        const fnIndex = this._urlChangeListeners.indexOf(fn);
        this._urlChangeListeners.splice(fnIndex, 1);
        if (this._urlChangeListeners.length === 0) {
          this._urlChangeSubscription?.unsubscribe();
          this._urlChangeSubscription = null;
        }
      };
    }
    /** @internal */
    _notifyUrlChangeListeners(url = '', state) {
      this._urlChangeListeners.forEach(fn => fn(url, state));
    }
    /**
     * Subscribes to the platform's `popState` events.
     *
     * Note: `Location.go()` does not trigger the `popState` event in the browser. Use
     * `Location.onUrlChange()` to subscribe to URL changes instead.
     *
     * @param value Event that is triggered when the state history changes.
     * @param exception The exception to throw.
     *
     * @see [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate)
     *
     * @returns Subscribed events.
     */
    subscribe(onNext, onThrow, onReturn) {
      return this._subject.subscribe({
        next: onNext,
        error: onThrow ?? undefined,
        complete: onReturn ?? undefined
      });
    }
    /**
     * Normalizes URL parameters by prepending with `?` if needed.
     *
     * @param  params String of URL parameters.
     *
     * @returns The normalized URL parameters string.
     */
    static normalizeQueryParams = (() => normalizeQueryParams)();
    /**
     * Joins two parts of a URL with a slash if needed.
     *
     * @param start  URL string
     * @param end    URL string
     *
     *
     * @returns The joined URL string.
     */
    static joinWithSlash = (() => joinWithSlash)();
    /**
     * Removes a trailing slash from a URL string if needed.
     * Looks for the first occurrence of either `#`, `?`, or the end of the
     * line as `/` characters and removes the trailing slash if one exists.
     *
     * @param url URL string.
     *
     * @returns The URL string, modified if needed.
     */
    static stripTrailingSlash = (() => stripTrailingSlash)();
    static ɵfac = (() => function Location_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Location)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](LocationStrategy));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: Location,
      factory: () => createLocation(),
      providedIn: 'root'
    }))();
  }
  return Location;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function createLocation() {
  return new Location((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"])(LocationStrategy));
}
function _stripBasePath(basePath, url) {
  if (!basePath || !url.startsWith(basePath)) {
    return url;
  }
  const strippedUrl = url.substring(basePath.length);
  if (strippedUrl === '' || ['/', ';', '?', '#'].includes(strippedUrl[0])) {
    return strippedUrl;
  }
  return url;
}
function _stripIndexHtml(url) {
  return url.replace(/\/index.html$/, '');
}
function _stripOrigin(baseHref) {
  // DO NOT REFACTOR! Previously, this check looked like this:
  // `/^(https?:)?\/\//.test(baseHref)`, but that resulted in
  // syntactically incorrect code after Closure Compiler minification.
  // This was likely caused by a bug in Closure Compiler, but
  // for now, the check is rewritten to use `new RegExp` instead.
  const isAbsoluteUrl = new RegExp('^(https?:)?//').test(baseHref);
  if (isAbsoluteUrl) {
    const [, pathname] = baseHref.split(/\/\/[^\/]+/);
    return pathname;
  }
  return baseHref;
}

/** @internal */
const CURRENCIES_EN = {
  "ADP": [undefined, undefined, 0],
  "AFN": [undefined, "؋", 0],
  "ALL": [undefined, undefined, 0],
  "AMD": [undefined, "֏", 2],
  "AOA": [undefined, "Kz"],
  "ARS": [undefined, "$"],
  "AUD": ["A$", "$"],
  "AZN": [undefined, "₼"],
  "BAM": [undefined, "KM"],
  "BBD": [undefined, "$"],
  "BDT": [undefined, "৳"],
  "BHD": [undefined, undefined, 3],
  "BIF": [undefined, undefined, 0],
  "BMD": [undefined, "$"],
  "BND": [undefined, "$"],
  "BOB": [undefined, "Bs"],
  "BRL": ["R$"],
  "BSD": [undefined, "$"],
  "BWP": [undefined, "P"],
  "BYN": [undefined, undefined, 2],
  "BYR": [undefined, undefined, 0],
  "BZD": [undefined, "$"],
  "CAD": ["CA$", "$", 2],
  "CHF": [undefined, undefined, 2],
  "CLF": [undefined, undefined, 4],
  "CLP": [undefined, "$", 0],
  "CNY": ["CN¥", "¥"],
  "COP": [undefined, "$", 2],
  "CRC": [undefined, "₡", 2],
  "CUC": [undefined, "$"],
  "CUP": [undefined, "$"],
  "CZK": [undefined, "Kč", 2],
  "DJF": [undefined, undefined, 0],
  "DKK": [undefined, "kr", 2],
  "DOP": [undefined, "$"],
  "EGP": [undefined, "E£"],
  "ESP": [undefined, "₧", 0],
  "EUR": ["€"],
  "FJD": [undefined, "$"],
  "FKP": [undefined, "£"],
  "GBP": ["£"],
  "GEL": [undefined, "₾"],
  "GHS": [undefined, "GH₵"],
  "GIP": [undefined, "£"],
  "GNF": [undefined, "FG", 0],
  "GTQ": [undefined, "Q"],
  "GYD": [undefined, "$", 2],
  "HKD": ["HK$", "$"],
  "HNL": [undefined, "L"],
  "HRK": [undefined, "kn"],
  "HUF": [undefined, "Ft", 2],
  "IDR": [undefined, "Rp", 2],
  "ILS": ["₪"],
  "INR": ["₹"],
  "IQD": [undefined, undefined, 0],
  "IRR": [undefined, undefined, 0],
  "ISK": [undefined, "kr", 0],
  "ITL": [undefined, undefined, 0],
  "JMD": [undefined, "$"],
  "JOD": [undefined, undefined, 3],
  "JPY": ["¥", undefined, 0],
  "KHR": [undefined, "៛"],
  "KMF": [undefined, "CF", 0],
  "KPW": [undefined, "₩", 0],
  "KRW": ["₩", undefined, 0],
  "KWD": [undefined, undefined, 3],
  "KYD": [undefined, "$"],
  "KZT": [undefined, "₸"],
  "LAK": [undefined, "₭", 0],
  "LBP": [undefined, "L£", 0],
  "LKR": [undefined, "Rs"],
  "LRD": [undefined, "$"],
  "LTL": [undefined, "Lt"],
  "LUF": [undefined, undefined, 0],
  "LVL": [undefined, "Ls"],
  "LYD": [undefined, undefined, 3],
  "MGA": [undefined, "Ar", 0],
  "MGF": [undefined, undefined, 0],
  "MMK": [undefined, "K", 0],
  "MNT": [undefined, "₮", 2],
  "MRO": [undefined, undefined, 0],
  "MUR": [undefined, "Rs", 2],
  "MXN": ["MX$", "$"],
  "MYR": [undefined, "RM"],
  "NAD": [undefined, "$"],
  "NGN": [undefined, "₦"],
  "NIO": [undefined, "C$"],
  "NOK": [undefined, "kr", 2],
  "NPR": [undefined, "Rs"],
  "NZD": ["NZ$", "$"],
  "OMR": [undefined, undefined, 3],
  "PHP": ["₱"],
  "PKR": [undefined, "Rs", 2],
  "PLN": [undefined, "zł"],
  "PYG": [undefined, "₲", 0],
  "RON": [undefined, "lei"],
  "RSD": [undefined, undefined, 0],
  "RUB": [undefined, "₽"],
  "RWF": [undefined, "RF", 0],
  "SBD": [undefined, "$"],
  "SEK": [undefined, "kr", 2],
  "SGD": [undefined, "$"],
  "SHP": [undefined, "£"],
  "SLE": [undefined, undefined, 2],
  "SLL": [undefined, undefined, 0],
  "SOS": [undefined, undefined, 0],
  "SRD": [undefined, "$"],
  "SSP": [undefined, "£"],
  "STD": [undefined, undefined, 0],
  "STN": [undefined, "Db"],
  "SYP": [undefined, "£", 0],
  "THB": [undefined, "฿"],
  "TMM": [undefined, undefined, 0],
  "TND": [undefined, undefined, 3],
  "TOP": [undefined, "T$"],
  "TRL": [undefined, undefined, 0],
  "TRY": [undefined, "₺"],
  "TTD": [undefined, "$"],
  "TWD": ["NT$", "$", 2],
  "TZS": [undefined, undefined, 2],
  "UAH": [undefined, "₴"],
  "UGX": [undefined, undefined, 0],
  "USD": ["$"],
  "UYI": [undefined, undefined, 0],
  "UYU": [undefined, "$"],
  "UYW": [undefined, undefined, 4],
  "UZS": [undefined, undefined, 2],
  "VEF": [undefined, "Bs", 2],
  "VND": ["₫", undefined, 0],
  "VUV": [undefined, undefined, 0],
  "XAF": ["FCFA", undefined, 0],
  "XCD": ["EC$", "$"],
  "XOF": ["F CFA", undefined, 0],
  "XPF": ["CFPF", undefined, 0],
  "XXX": ["¤"],
  "YER": [undefined, undefined, 0],
  "ZAR": [undefined, "R"],
  "ZMK": [undefined, undefined, 0],
  "ZMW": [undefined, "ZK"],
  "ZWD": [undefined, undefined, 0]
};

/**
 * Format styles that can be used to represent numbers.
 * @see {@link getLocaleNumberFormat}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated `getLocaleNumberFormat` is deprecated
 */
var NumberFormatStyle = /*#__PURE__*/function (NumberFormatStyle) {
  NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal";
  NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent";
  NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency";
  NumberFormatStyle[NumberFormatStyle["Scientific"] = 3] = "Scientific";
  return NumberFormatStyle;
}(NumberFormatStyle || {});
/**
 * Plurality cases used for translating plurals to different languages.
 *
 * @see {@link NgPlural}
 * @see {@link NgPluralCase}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated `getLocalePluralCase` is deprecated
 */
var Plural = /*#__PURE__*/function (Plural) {
  Plural[Plural["Zero"] = 0] = "Zero";
  Plural[Plural["One"] = 1] = "One";
  Plural[Plural["Two"] = 2] = "Two";
  Plural[Plural["Few"] = 3] = "Few";
  Plural[Plural["Many"] = 4] = "Many";
  Plural[Plural["Other"] = 5] = "Other";
  return Plural;
}(Plural || {});
/**
 * Context-dependant translation forms for strings.
 * Typically the standalone version is for the nominative form of the word,
 * and the format version is used for the genitive case.
 * @see [CLDR website](http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles)
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated locale data getters are deprecated
 */
var FormStyle = /*#__PURE__*/function (FormStyle) {
  FormStyle[FormStyle["Format"] = 0] = "Format";
  FormStyle[FormStyle["Standalone"] = 1] = "Standalone";
  return FormStyle;
}(FormStyle || {});
/**
 * String widths available for translations.
 * The specific character widths are locale-specific.
 * Examples are given for the word "Sunday" in English.
 *
 * @publicApi
 *
 * @deprecated locale data getters are deprecated
 */
var TranslationWidth = /*#__PURE__*/function (TranslationWidth) {
  /** 1 character for `en-US`. For example: 'S' */
  TranslationWidth[TranslationWidth["Narrow"] = 0] = "Narrow";
  /** 3 characters for `en-US`. For example: 'Sun' */
  TranslationWidth[TranslationWidth["Abbreviated"] = 1] = "Abbreviated";
  /** Full length for `en-US`. For example: "Sunday" */
  TranslationWidth[TranslationWidth["Wide"] = 2] = "Wide";
  /** 2 characters for `en-US`, For example: "Su" */
  TranslationWidth[TranslationWidth["Short"] = 3] = "Short";
  return TranslationWidth;
}(TranslationWidth || {});
/**
 * String widths available for date-time formats.
 * The specific character widths are locale-specific.
 * Examples are given for `en-US`.
 *
 * @see {@link getLocaleDateFormat}
 * @see {@link getLocaleTimeFormat}
 * @see {@link getLocaleDateTimeFormat}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 * @publicApi
 *
 * @deprecated Date locale data getters are deprecated
 */
var FormatWidth = /*#__PURE__*/function (FormatWidth) {
  /**
   * For `en-US`, `'M/d/yy, h:mm a'`
   * (Example: `6/15/15, 9:03 AM`)
   */
  FormatWidth[FormatWidth["Short"] = 0] = "Short";
  /**
   * For `en-US`, `'MMM d, y, h:mm:ss a'`
   * (Example: `Jun 15, 2015, 9:03:01 AM`)
   */
  FormatWidth[FormatWidth["Medium"] = 1] = "Medium";
  /**
   * For `en-US`, `'MMMM d, y, h:mm:ss a z'`
   * (Example: `June 15, 2015 at 9:03:01 AM GMT+1`)
   */
  FormatWidth[FormatWidth["Long"] = 2] = "Long";
  /**
   * For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'`
   * (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`)
   */
  FormatWidth[FormatWidth["Full"] = 3] = "Full";
  return FormatWidth;
}(FormatWidth || {});
// This needs to be an object literal, rather than an enum, because TypeScript 5.4+
// doesn't allow numeric keys and we have `Infinity` and `NaN`.
/**
 * Symbols that can be used to replace placeholders in number patterns.
 * Examples are based on `en-US` values.
 *
 * @see {@link getLocaleNumberSymbol}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated `getLocaleNumberSymbol` is deprecated
 *
 * @object-literal-as-enum
 */
const NumberSymbol = {
  /**
   * Decimal separator.
   * For `en-US`, the dot character.
   * Example: 2,345`.`67
   */
  Decimal: 0,
  /**
   * Grouping separator, typically for thousands.
   * For `en-US`, the comma character.
   * Example: 2`,`345.67
   */
  Group: 1,
  /**
   * List-item separator.
   * Example: "one, two, and three"
   */
  List: 2,
  /**
   * Sign for percentage (out of 100).
   * Example: 23.4%
   */
  PercentSign: 3,
  /**
   * Sign for positive numbers.
   * Example: +23
   */
  PlusSign: 4,
  /**
   * Sign for negative numbers.
   * Example: -23
   */
  MinusSign: 5,
  /**
   * Computer notation for exponential value (n times a power of 10).
   * Example: 1.2E3
   */
  Exponential: 6,
  /**
   * Human-readable format of exponential.
   * Example: 1.2x103
   */
  SuperscriptingExponent: 7,
  /**
   * Sign for permille (out of 1000).
   * Example: 23.4‰
   */
  PerMille: 8,
  /**
   * Infinity, can be used with plus and minus.
   * Example: ∞, +∞, -∞
   */
  Infinity: 9,
  /**
   * Not a number.
   * Example: NaN
   */
  NaN: 10,
  /**
   * Symbol used between time units.
   * Example: 10:52
   */
  TimeSeparator: 11,
  /**
   * Decimal separator for currency values (fallback to `Decimal`).
   * Example: $2,345.67
   */
  CurrencyDecimal: 12,
  /**
   * Group separator for currency values (fallback to `Group`).
   * Example: $2,345.67
   */
  CurrencyGroup: 13
};
/**
 * The value for each day of the week, based on the `en-US` locale
 *
 * @publicApi
 *
 * @deprecated Week locale getters are deprecated
 */
var WeekDay = /*#__PURE__*/function (WeekDay) {
  WeekDay[WeekDay["Sunday"] = 0] = "Sunday";
  WeekDay[WeekDay["Monday"] = 1] = "Monday";
  WeekDay[WeekDay["Tuesday"] = 2] = "Tuesday";
  WeekDay[WeekDay["Wednesday"] = 3] = "Wednesday";
  WeekDay[WeekDay["Thursday"] = 4] = "Thursday";
  WeekDay[WeekDay["Friday"] = 5] = "Friday";
  WeekDay[WeekDay["Saturday"] = 6] = "Saturday";
  return WeekDay;
}(WeekDay || {});
/**
 * Retrieves the locale ID from the currently loaded locale.
 * The loaded locale could be, for example, a global one rather than a regional one.
 * @param locale A locale code, such as `fr-FR`.
 * @returns The locale code. For example, `fr`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * This function serves no purpose when relying on the `Intl` API.
 */
function getLocaleId(locale) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale)[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].LocaleId];
}
/**
 * Retrieves day period strings for the given locale.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param formStyle The required grammatical form.
 * @param width The required character width.
 * @returns An array of localized period strings. For example, `[AM, PM]` for `en-US`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleDayPeriods(locale, formStyle, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const amPmData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DayPeriodsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DayPeriodsStandalone]];
  const amPm = getLastDefinedValue(amPmData, formStyle);
  return getLastDefinedValue(amPm, width);
}
/**
 * Retrieves days of the week for the given locale, using the Gregorian calendar.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param formStyle The required grammatical form.
 * @param width The required character width.
 * @returns An array of localized name strings.
 * For example,`[Sunday, Monday, ... Saturday]` for `en-US`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleDayNames(locale, formStyle, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const daysData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DaysFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DaysStandalone]];
  const days = getLastDefinedValue(daysData, formStyle);
  return getLastDefinedValue(days, width);
}
/**
 * Retrieves months of the year for the given locale, using the Gregorian calendar.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param formStyle The required grammatical form.
 * @param width The required character width.
 * @returns An array of localized name strings.
 * For example,  `[January, February, ...]` for `en-US`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleMonthNames(locale, formStyle, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const monthsData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].MonthsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].MonthsStandalone]];
  const months = getLastDefinedValue(monthsData, formStyle);
  return getLastDefinedValue(months, width);
}
/**
 * Retrieves Gregorian-calendar eras for the given locale.
 * @param locale A locale code for the locale format rules to use.
 * @param width The required character width.

 * @returns An array of localized era strings.
 * For example, `[AD, BC]` for `en-US`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleEraNames(locale, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const erasData = data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].Eras];
  return getLastDefinedValue(erasData, width);
}
/**
 * Retrieves the first day of the week for the given locale.
 *
 * @param locale A locale code for the locale format rules to use.
 * @returns A day index number, using the 0-based week-day index for `en-US`
 * (Sunday = 0, Monday = 1, ...).
 * For example, for `fr-FR`, returns 1 to indicate that the first day is Monday.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Intl's [`getWeekInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo) has partial support (Chromium M99 & Safari 17).
 * You may want to rely on the following alternatives:
 * - Libraries like [`Luxon`](https://moment.github.io/luxon/#/) rely on `Intl` but fallback on the ISO 8601 definition (monday) if `getWeekInfo` is not supported.
 * - Other librairies like [`date-fns`](https://date-fns.org/), [`day.js`](https://day.js.org/en/) or [`weekstart`](https://www.npmjs.com/package/weekstart) library provide their own locale based data for the first day of the week.
 */
function getLocaleFirstDayOfWeek(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].FirstDayOfWeek];
}
/**
 * Range of week days that are considered the week-end for the given locale.
 *
 * @param locale A locale code for the locale format rules to use.
 * @returns The range of day values, `[startDay, endDay]`.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Intl's [`getWeekInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo) has partial support (Chromium M99 & Safari 17).
 * Libraries like [`Luxon`](https://moment.github.io/luxon/#/) rely on `Intl` but fallback on the ISO 8601 definition (Saturday+Sunday) if `getWeekInfo` is not supported .
 */
function getLocaleWeekEndRange(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].WeekendRange];
}
/**
 * Retrieves a localized date-value formatting string.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param width The format type.
 * @returns The localized formatting string.
 * @see {@link FormatWidth}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleDateFormat(locale, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DateFormat], width);
}
/**
 * Retrieves a localized time-value formatting string.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param width The format type.
 * @returns The localized formatting string.
 * @see {@link FormatWidth}
 * @see [Internationalization (i18n) Guide](guide/i18n)

 * @publicApi
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleTimeFormat(locale, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].TimeFormat], width);
}
/**
 * Retrieves a localized date-time formatting string.
 *
 * @param locale A locale code for the locale format rules to use.
 * @param width The format type.
 * @returns The localized formatting string.
 * @see {@link FormatWidth}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.DateTimeFormat` for date formating instead.
 */
function getLocaleDateTimeFormat(locale, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const dateTimeFormatData = data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].DateTimeFormat];
  return getLastDefinedValue(dateTimeFormatData, width);
}
/**
 * Retrieves a localized number symbol that can be used to replace placeholders in number formats.
 * @param locale The locale code.
 * @param symbol The symbol to localize. Must be one of `NumberSymbol`.
 * @returns The character for the localized symbol.
 * @see {@link NumberSymbol}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.NumberFormat` to format numbers instead.
 */
function getLocaleNumberSymbol(locale, symbol) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  const res = data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].NumberSymbols][symbol];
  if (typeof res === 'undefined') {
    if (symbol === NumberSymbol.CurrencyDecimal) {
      return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Decimal];
    } else if (symbol === NumberSymbol.CurrencyGroup) {
      return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Group];
    }
  }
  return res;
}
/**
 * Retrieves a number format for a given locale.
 *
 * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00`
 * when used to format the number 12345.678 could result in "12'345,678". That would happen if the
 * grouping separator for your language is an apostrophe, and the decimal separator is a comma.
 *
 * <b>Important:</b> The characters `.` `,` `0` `#` (and others below) are special placeholders
 * that stand for the decimal separator, and so on, and are NOT real characters.
 * You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in
 * your language the decimal point is written with a comma. The symbols should be replaced by the
 * local equivalents, using the appropriate `NumberSymbol` for your language.
 *
 * Here are the special characters used in number patterns:
 *
 * | Symbol | Meaning |
 * |--------|---------|
 * | . | Replaced automatically by the character used for the decimal point. |
 * | , | Replaced by the "grouping" (thousands) separator. |
 * | 0 | Replaced by a digit (or zero if there aren't enough digits). |
 * | # | Replaced by a digit (or nothing if there aren't enough). |
 * | ¤ | Replaced by a currency symbol, such as $ or USD. |
 * | % | Marks a percent format. The % symbol may change position, but must be retained. |
 * | E | Marks a scientific format. The E symbol may change position, but must be retained. |
 * | ' | Special characters used as literal characters are quoted with ASCII single quotes. |
 *
 * @param locale A locale code for the locale format rules to use.
 * @param type The type of numeric value to be formatted (such as `Decimal` or `Currency`.)
 * @returns The localized format string.
 * @see {@link NumberFormatStyle}
 * @see [CLDR website](http://cldr.unicode.org/translation/number-patterns)
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Let `Intl.NumberFormat` determine the number format instead
 */
function getLocaleNumberFormat(locale, type) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].NumberFormats][type];
}
/**
 * Retrieves the symbol used to represent the currency for the main country
 * corresponding to a given locale. For example, '$' for `en-US`.
 *
 * @param locale A locale code for the locale format rules to use.
 * @returns The localized symbol character,
 * or `null` if the main country cannot be determined.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Use the `Intl` API to format a currency with from currency code
 */
function getLocaleCurrencySymbol(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].CurrencySymbol] || null;
}
/**
 * Retrieves the name of the currency for the main country corresponding
 * to a given locale. For example, 'US Dollar' for `en-US`.
 * @param locale A locale code for the locale format rules to use.
 * @returns The currency name,
 * or `null` if the main country cannot be determined.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Use the `Intl` API to format a currency with from currency code
 */
function getLocaleCurrencyName(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].CurrencyName] || null;
}
/**
 * Retrieves the default currency code for the given locale.
 *
 * The default is defined as the first currency which is still in use.
 *
 * @param locale The code of the locale whose currency code we want.
 * @returns The code of the default currency for the given locale.
 *
 * @publicApi
 *
 * @deprecated We recommend you create a map of locale to ISO 4217 currency codes.
 * Time relative currency data is provided by the CLDR project. See https://www.unicode.org/cldr/charts/44/supplemental/detailed_territory_currency_information.html
 */
function getLocaleCurrencyCode(locale) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵgetLocaleCurrencyCode"])(locale);
}
/**
 * Retrieves the currency values for a given locale.
 * @param locale A locale code for the locale format rules to use.
 * @returns The currency values.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 */
function getLocaleCurrencies(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].Currencies];
}
/**
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Use `Intl.PluralRules` instead
 */
const getLocalePluralCase = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵgetLocalePluralCase"];
function checkFullData(data) {
  if (!data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].ExtraData]) {
    throw new Error(`Missing extra locale data for the locale "${data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`);
  }
}
/**
 * Retrieves locale-specific rules used to determine which day period to use
 * when more than one period is defined for a locale.
 *
 * There is a rule for each defined day period. The
 * first rule is applied to the first day period and so on.
 * Fall back to AM/PM when no rules are available.
 *
 * A rule can specify a period as time range, or as a single time value.
 *
 * This functionality is only available when you have loaded the full locale data.
 * See the ["I18n guide"](guide/i18n/format-data-locale).
 *
 * @param locale A locale code for the locale format rules to use.
 * @returns The rules for the locale, a single time value or array of *from-time, to-time*,
 * or null if no periods are available.
 *
 * @see {@link getLocaleExtraDayPeriods}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * Let `Intl.DateTimeFormat` determine the day period instead.
 */
function getLocaleExtraDayPeriodRules(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  checkFullData(data);
  const rules = data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].ExtraData][2 /* ɵExtraLocaleDataIndex.ExtraDayPeriodsRules */] || [];
  return rules.map(rule => {
    if (typeof rule === 'string') {
      return extractTime(rule);
    }
    return [extractTime(rule[0]), extractTime(rule[1])];
  });
}
/**
 * Retrieves locale-specific day periods, which indicate roughly how a day is broken up
 * in different languages.
 * For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight.
 *
 * This functionality is only available when you have loaded the full locale data.
 * See the ["I18n guide"](guide/i18n/format-data-locale).
 *
 * @param locale A locale code for the locale format rules to use.
 * @param formStyle The required grammatical form.
 * @param width The required character width.
 * @returns The translated day-period strings.
 * @see {@link getLocaleExtraDayPeriodRules}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * To extract a day period use `Intl.DateTimeFormat` with the `dayPeriod` option instead.
 */
function getLocaleExtraDayPeriods(locale, formStyle, width) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  checkFullData(data);
  const dayPeriodsData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].ExtraData][0 /* ɵExtraLocaleDataIndex.ExtraDayPeriodFormats */], data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].ExtraData][1 /* ɵExtraLocaleDataIndex.ExtraDayPeriodStandalone */]];
  const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || [];
  return getLastDefinedValue(dayPeriods, width) || [];
}
/**
 * Retrieves the writing direction of a specified locale
 * @param locale A locale code for the locale format rules to use.
 * @publicApi
 * @returns 'rtl' or 'ltr'
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * For dates and numbers, let `Intl.DateTimeFormat()` and `Intl.NumberFormat()` determine the writing direction.
 * The `Intl` alternative [`getTextInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo).
 * has only partial support (Chromium M99 & Safari 17).
 * 3rd party alternatives like [`rtl-detect`](https://www.npmjs.com/package/rtl-detect) can work around this issue.
 */
function getLocaleDirection(locale) {
  const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵfindLocaleData"])(locale);
  return data[_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵLocaleDataIndex"].Directionality];
}
/**
 * Retrieves the first value that is defined in an array, going backwards from an index position.
 *
 * To avoid repeating the same data (as when the "format" and "standalone" forms are the same)
 * add the first value to the locale data arrays, and add other values only if they are different.
 *
 * @param data The data array to retrieve from.
 * @param index A 0-based index into the array to start from.
 * @returns The value immediately before the given index position.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 */
function getLastDefinedValue(data, index) {
  for (let i = index; i > -1; i--) {
    if (typeof data[i] !== 'undefined') {
      return data[i];
    }
  }
  throw new Error('Locale data API: locale data undefined');
}
/**
 * Extracts the hours and minutes from a string like "15:45"
 */
function extractTime(time) {
  const [h, m] = time.split(':');
  return {
    hours: +h,
    minutes: +m
  };
}
/**
 * Retrieves the currency symbol for a given currency code.
 *
 * For example, for the default `en-US` locale, the code `USD` can
 * be represented by the narrow symbol `$` or the wide symbol `US$`.
 *
 * @param code The currency code.
 * @param format The format, `wide` or `narrow`.
 * @param locale A locale code for the locale format rules to use.
 *
 * @returns The symbol, or the currency code if no symbol is available.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * You can use `Intl.NumberFormat().formatToParts()` to extract the currency symbol.
 * For example: `Intl.NumberFormat('en', {style:'currency', currency: 'USD'}).formatToParts().find(part => part.type === 'currency').value`
 * returns `$` for USD currency code in the `en` locale.
 * Note: `US$` is a currency symbol for the `en-ca` locale but not the `en-us` locale.
 */
function getCurrencySymbol(code, format, locale = 'en') {
  const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || [];
  const symbolNarrow = currency[1 /* ɵCurrencyIndex.SymbolNarrow */];
  if (format === 'narrow' && typeof symbolNarrow === 'string') {
    return symbolNarrow;
  }
  return currency[0 /* ɵCurrencyIndex.Symbol */] || code;
}
// Most currencies have cents, that's why the default is 2
const DEFAULT_NB_OF_CURRENCY_DIGITS = 2;
/**
 * Reports the number of decimal digits for a given currency.
 * The value depends upon the presence of cents in that particular currency.
 *
 * @param code The currency code.
 * @returns The number of decimal digits, typically 0 or 2.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 *
 * @deprecated Angular recommends relying on the `Intl` API for i18n.
 * This function should not be used anymore. Let `Intl.NumberFormat` determine the number of digits to display for the currency
 */
function getNumberOfCurrencyDigits(code) {
  let digits;
  const currency = CURRENCIES_EN[code];
  if (currency) {
    digits = currency[2 /* ɵCurrencyIndex.NbOfDigits */];
  }
  return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS;
}
const ISO8601_DATE_REGEX = /^(\d{4,})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
//    1        2       3         4          5          6          7          8  9     10      11
const NAMED_FORMATS = {};
const DATE_FORMATS_SPLIT = /((?:[^BEGHLMOSWYZabcdhmswyz']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|Y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|c{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/;
var ZoneWidth = /*#__PURE__*/function (ZoneWidth) {
  ZoneWidth[ZoneWidth["Short"] = 0] = "Short";
  ZoneWidth[ZoneWidth["ShortGMT"] = 1] = "ShortGMT";
  ZoneWidth[ZoneWidth["Long"] = 2] = "Long";
  ZoneWidth[ZoneWidth["Extended"] = 3] = "Extended";
  return ZoneWidth;
}(ZoneWidth || {});
var DateType = /*#__PURE__*/function (DateType) {
  DateType[DateType["FullYear"] = 0] = "FullYear";
  DateType[DateType["Month"] = 1] = "Month";
  DateType[DateType["Date"] = 2] = "Date";
  DateType[DateType["Hours"] = 3] = "Hours";
  DateType[DateType["Minutes"] = 4] = "Minutes";
  DateType[DateType["Seconds"] = 5] = "Seconds";
  DateType[DateType["FractionalSeconds"] = 6] = "FractionalSeconds";
  DateType[DateType["Day"] = 7] = "Day";
  return DateType;
}(DateType || {});
var TranslationType = /*#__PURE__*/function (TranslationType) {
  TranslationType[TranslationType["DayPeriods"] = 0] = "DayPeriods";
  TranslationType[TranslationType["Days"] = 1] = "Days";
  TranslationType[TranslationType["Months"] = 2] = "Months";
  TranslationType[TranslationType["Eras"] = 3] = "Eras";
  return TranslationType;
}(TranslationType || {});
/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a date according to locale rules.
 *
 * @param value The date to format, as a Date, or a number (milliseconds since UTC epoch)
 * or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime).
 * @param format The date-time components to include. See `DatePipe` for details.
 * @param locale A locale code for the locale format rules to use.
 * @param timezone The time zone. A time zone offset from GMT (such as `'+0430'`).
 * If not specified, uses host system settings.
 *
 * @returns The formatted date string.
 *
 * @see {@link DatePipe}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 */
function formatDate(value, format, locale, timezone) {
  let date = toDate(value);
  const namedFormat = getNamedFormat(locale, format);
  format = namedFormat || format;
  let parts = [];
  let match;
  while (format) {
    match = DATE_FORMATS_SPLIT.exec(format);
    if (match) {
      parts = parts.concat(match.slice(1));
      const part = parts.pop();
      if (!part) {
        break;
      }
      format = part;
    } else {
      parts.push(format);
      break;
    }
  }
  let dateTimezoneOffset = date.getTimezoneOffset();
  if (timezone) {
    dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
    date = convertTimezoneToLocal(date, timezone, true);
  }
  let text = '';
  parts.forEach(value => {
    const dateFormatter = getDateFormatter(value);
    text += dateFormatter ? dateFormatter(date, locale, dateTimezoneOffset) : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  });
  return text;
}
/**
 * Create a new Date object with the given date value, and the time set to midnight.
 *
 * We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999.
 * See: https://github.com/angular/angular/issues/40377
 *
 * Note that this function returns a Date object whose time is midnight in the current locale's
 * timezone. In the future we might want to change this to be midnight in UTC, but this would be a
 * considerable breaking change.
 */
function createDate(year, month, date) {
  // The `newDate` is set to midnight (UTC) on January 1st 1970.
  // - In PST this will be December 31st 1969 at 4pm.
  // - In GMT this will be January 1st 1970 at 1am.
  // Note that they even have different years, dates and months!
  const newDate = new Date(0);
  // `setFullYear()` allows years like 0001 to be set correctly. This function does not
  // change the internal time of the date.
  // Consider calling `setFullYear(2019, 8, 20)` (September 20, 2019).
  // - In PST this will now be September 20, 2019 at 4pm
  // - In GMT this will now be September 20, 2019 at 1am
  newDate.setFullYear(year, month, date);
  // We want the final date to be at local midnight, so we reset the time.
  // - In PST this will now be September 20, 2019 at 12am
  // - In GMT this will now be September 20, 2019 at 12am
  newDate.setHours(0, 0, 0);
  return newDate;
}
function getNamedFormat(locale, format) {
  const localeId = getLocaleId(locale);
  NAMED_FORMATS[localeId] ??= {};
  if (NAMED_FORMATS[localeId][format]) {
    return NAMED_FORMATS[localeId][format];
  }
  let formatValue = '';
  switch (format) {
    case 'shortDate':
      formatValue = getLocaleDateFormat(locale, FormatWidth.Short);
      break;
    case 'mediumDate':
      formatValue = getLocaleDateFormat(locale, FormatWidth.Medium);
      break;
    case 'longDate':
      formatValue = getLocaleDateFormat(locale, FormatWidth.Long);
      break;
    case 'fullDate':
      formatValue = getLocaleDateFormat(locale, FormatWidth.Full);
      break;
    case 'shortTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Short);
      break;
    case 'mediumTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium);
      break;
    case 'longTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Long);
      break;
    case 'fullTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Full);
      break;
    case 'short':
      const shortTime = getNamedFormat(locale, 'shortTime');
      const shortDate = getNamedFormat(locale, 'shortDate');
      formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [shortTime, shortDate]);
      break;
    case 'medium':
      const mediumTime = getNamedFormat(locale, 'mediumTime');
      const mediumDate = getNamedFormat(locale, 'mediumDate');
      formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [mediumTime, mediumDate]);
      break;
    case 'long':
      const longTime = getNamedFormat(locale, 'longTime');
      const longDate = getNamedFormat(locale, 'longDate');
      formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [longTime, longDate]);
      break;
    case 'full':
      const fullTime = getNamedFormat(locale, 'fullTime');
      const fullDate = getNamedFormat(locale, 'fullDate');
      formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [fullTime, fullDate]);
      break;
  }
  if (formatValue) {
    NAMED_FORMATS[localeId][format] = formatValue;
  }
  return formatValue;
}
function formatDateTime(str, opt_values) {
  if (opt_values) {
    str = str.replace(/\{([^}]+)}/g, function (match, key) {
      return opt_values != null && key in opt_values ? opt_values[key] : match;
    });
  }
  return str;
}
function padNumber(num, digits, minusSign = '-', trim, negWrap) {
  let neg = '';
  if (num < 0 || negWrap && num <= 0) {
    if (negWrap) {
      num = -num + 1;
    } else {
      num = -num;
      neg = minusSign;
    }
  }
  let strNum = String(num);
  while (strNum.length < digits) {
    strNum = '0' + strNum;
  }
  if (trim) {
    strNum = strNum.slice(strNum.length - digits);
  }
  return neg + strNum;
}
function formatFractionalSeconds(milliseconds, digits) {
  const strMs = padNumber(milliseconds, 3);
  return strMs.substring(0, digits);
}
/**
 * Returns a date formatter that transforms a date into its locale digit representation
 */
function dateGetter(name, size, offset = 0, trim = false, negWrap = false) {
  return function (date, locale) {
    let part = getDatePart(name, date);
    if (offset > 0 || part > -offset) {
      part += offset;
    }
    if (name === DateType.Hours) {
      if (part === 0 && offset === -12) {
        part = 12;
      }
    } else if (name === DateType.FractionalSeconds) {
      return formatFractionalSeconds(part, size);
    }
    const localeMinus = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
    return padNumber(part, size, localeMinus, trim, negWrap);
  };
}
function getDatePart(part, date) {
  switch (part) {
    case DateType.FullYear:
      return date.getFullYear();
    case DateType.Month:
      return date.getMonth();
    case DateType.Date:
      return date.getDate();
    case DateType.Hours:
      return date.getHours();
    case DateType.Minutes:
      return date.getMinutes();
    case DateType.Seconds:
      return date.getSeconds();
    case DateType.FractionalSeconds:
      return date.getMilliseconds();
    case DateType.Day:
      return date.getDay();
    default:
      throw new Error(`Unknown DateType value "${part}".`);
  }
}
/**
 * Returns a date formatter that transforms a date into its locale string representation
 */
function dateStrGetter(name, width, form = FormStyle.Format, extended = false) {
  return function (date, locale) {
    return getDateTranslation(date, locale, name, width, form, extended);
  };
}
/**
 * Returns the locale translation of a date for a given form, type and width
 */
function getDateTranslation(date, locale, name, width, form, extended) {
  switch (name) {
    case TranslationType.Months:
      return getLocaleMonthNames(locale, form, width)[date.getMonth()];
    case TranslationType.Days:
      return getLocaleDayNames(locale, form, width)[date.getDay()];
    case TranslationType.DayPeriods:
      const currentHours = date.getHours();
      const currentMinutes = date.getMinutes();
      if (extended) {
        const rules = getLocaleExtraDayPeriodRules(locale);
        const dayPeriods = getLocaleExtraDayPeriods(locale, form, width);
        const index = rules.findIndex(rule => {
          if (Array.isArray(rule)) {
            // morning, afternoon, evening, night
            const [from, to] = rule;
            const afterFrom = currentHours >= from.hours && currentMinutes >= from.minutes;
            const beforeTo = currentHours < to.hours || currentHours === to.hours && currentMinutes < to.minutes;
            // We must account for normal rules that span a period during the day (e.g. 6am-9am)
            // where `from` is less (earlier) than `to`. But also rules that span midnight (e.g.
            // 10pm - 5am) where `from` is greater (later!) than `to`.
            //
            // In the first case the current time must be BOTH after `from` AND before `to`
            // (e.g. 8am is after 6am AND before 10am).
            //
            // In the second case the current time must be EITHER after `from` OR before `to`
            // (e.g. 4am is before 5am but not after 10pm; and 11pm is not before 5am but it is
            // after 10pm).
            if (from.hours < to.hours) {
              if (afterFrom && beforeTo) {
                return true;
              }
            } else if (afterFrom || beforeTo) {
              return true;
            }
          } else {
            // noon or midnight
            if (rule.hours === currentHours && rule.minutes === currentMinutes) {
              return true;
            }
          }
          return false;
        });
        if (index !== -1) {
          return dayPeriods[index];
        }
      }
      // if no rules for the day periods, we use am/pm by default
      return getLocaleDayPeriods(locale, form, width)[currentHours < 12 ? 0 : 1];
    case TranslationType.Eras:
      return getLocaleEraNames(locale, width)[date.getFullYear() <= 0 ? 0 : 1];
    default:
      // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
      // However Closure Compiler does not understand that and reports an error in typed mode.
      // The `throw new Error` below works around the problem, and the unexpected: never variable
      // makes sure tsc still checks this code is unreachable.
      const unexpected = name;
      throw new Error(`unexpected translation type ${unexpected}`);
  }
}
/**
 * Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or
 * GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30,
 * extended = +04:30)
 */
function timeZoneGetter(width) {
  return function (date, locale, offset) {
    const zone = -1 * offset;
    const minusSign = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign);
    const hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60);
    switch (width) {
      case ZoneWidth.Short:
        return (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + padNumber(Math.abs(zone % 60), 2, minusSign);
      case ZoneWidth.ShortGMT:
        return 'GMT' + (zone >= 0 ? '+' : '') + padNumber(hours, 1, minusSign);
      case ZoneWidth.Long:
        return 'GMT' + (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign);
      case ZoneWidth.Extended:
        if (offset === 0) {
          return 'Z';
        } else {
          return (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign);
        }
      default:
        throw new Error(`Unknown zone width "${width}"`);
    }
  };
}
const JANUARY = 0;
const THURSDAY = 4;
function getFirstThursdayOfYear(year) {
  const firstDayOfYear = createDate(year, JANUARY, 1).getDay();
  return createDate(year, 0, 1 + (firstDayOfYear <= THURSDAY ? THURSDAY : THURSDAY + 7) - firstDayOfYear);
}
/**
 *  ISO Week starts on day 1 (Monday) and ends with day 0 (Sunday)
 */
function getThursdayThisIsoWeek(datetime) {
  // getDay returns 0-6 range with sunday as 0.
  const currentDay = datetime.getDay();
  // On a Sunday, read the previous Thursday since ISO weeks start on Monday.
  const deltaToThursday = currentDay === 0 ? -3 : THURSDAY - currentDay;
  return createDate(datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + deltaToThursday);
}
function weekGetter(size, monthBased = false) {
  return function (date, locale) {
    let result;
    if (monthBased) {
      const nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1;
      const today = date.getDate();
      result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7);
    } else {
      const thisThurs = getThursdayThisIsoWeek(date);
      // Some days of a year are part of next year according to ISO 8601.
      // Compute the firstThurs from the year of this week's Thursday
      const firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear());
      const diff = thisThurs.getTime() - firstThurs.getTime();
      result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
    }
    return padNumber(result, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  };
}
/**
 * Returns a date formatter that provides the week-numbering year for the input date.
 */
function weekNumberingYearGetter(size, trim = false) {
  return function (date, locale) {
    const thisThurs = getThursdayThisIsoWeek(date);
    const weekNumberingYear = thisThurs.getFullYear();
    return padNumber(weekNumberingYear, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim);
  };
}
const DATE_FORMATS = {};
// Based on CLDR formats:
// See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
// See also explanations: http://cldr.unicode.org/translation/date-time
// TODO(ocombe): support all missing cldr formats: U, Q, D, F, e, j, J, C, A, v, V, X, x
function getDateFormatter(format) {
  if (DATE_FORMATS[format]) {
    return DATE_FORMATS[format];
  }
  let formatter;
  switch (format) {
    // Era name (AD/BC)
    case 'G':
    case 'GG':
    case 'GGG':
      formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Abbreviated);
      break;
    case 'GGGG':
      formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Wide);
      break;
    case 'GGGGG':
      formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Narrow);
      break;
    // 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199)
    case 'y':
      formatter = dateGetter(DateType.FullYear, 1, 0, false, true);
      break;
    // 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
    case 'yy':
      formatter = dateGetter(DateType.FullYear, 2, 0, true, true);
      break;
    // 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10)
    case 'yyy':
      formatter = dateGetter(DateType.FullYear, 3, 0, false, true);
      break;
    // 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010)
    case 'yyyy':
      formatter = dateGetter(DateType.FullYear, 4, 0, false, true);
      break;
    // 1 digit representation of the week-numbering year, e.g. (AD 1 => 1, AD 199 => 199)
    case 'Y':
      formatter = weekNumberingYearGetter(1);
      break;
    // 2 digit representation of the week-numbering year, padded (00-99). (e.g. AD 2001 => 01, AD
    // 2010 => 10)
    case 'YY':
      formatter = weekNumberingYearGetter(2, true);
      break;
    // 3 digit representation of the week-numbering year, padded (000-999). (e.g. AD 1 => 001, AD
    // 2010 => 2010)
    case 'YYY':
      formatter = weekNumberingYearGetter(3);
      break;
    // 4 digit representation of the week-numbering year (e.g. AD 1 => 0001, AD 2010 => 2010)
    case 'YYYY':
      formatter = weekNumberingYearGetter(4);
      break;
    // Month of the year (1-12), numeric
    case 'M':
    case 'L':
      formatter = dateGetter(DateType.Month, 1, 1);
      break;
    case 'MM':
    case 'LL':
      formatter = dateGetter(DateType.Month, 2, 1);
      break;
    // Month of the year (January, ...), string, format
    case 'MMM':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated);
      break;
    case 'MMMM':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide);
      break;
    case 'MMMMM':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow);
      break;
    // Month of the year (January, ...), string, standalone
    case 'LLL':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated, FormStyle.Standalone);
      break;
    case 'LLLL':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide, FormStyle.Standalone);
      break;
    case 'LLLLL':
      formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow, FormStyle.Standalone);
      break;
    // Week of the year (1, ... 52)
    case 'w':
      formatter = weekGetter(1);
      break;
    case 'ww':
      formatter = weekGetter(2);
      break;
    // Week of the month (1, ...)
    case 'W':
      formatter = weekGetter(1, true);
      break;
    // Day of the month (1-31)
    case 'd':
      formatter = dateGetter(DateType.Date, 1);
      break;
    case 'dd':
      formatter = dateGetter(DateType.Date, 2);
      break;
    // Day of the Week StandAlone (1, 1, Mon, Monday, M, Mo)
    case 'c':
    case 'cc':
      formatter = dateGetter(DateType.Day, 1);
      break;
    case 'ccc':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated, FormStyle.Standalone);
      break;
    case 'cccc':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide, FormStyle.Standalone);
      break;
    case 'ccccc':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow, FormStyle.Standalone);
      break;
    case 'cccccc':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short, FormStyle.Standalone);
      break;
    // Day of the Week
    case 'E':
    case 'EE':
    case 'EEE':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated);
      break;
    case 'EEEE':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide);
      break;
    case 'EEEEE':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow);
      break;
    case 'EEEEEE':
      formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short);
      break;
    // Generic period of the day (am-pm)
    case 'a':
    case 'aa':
    case 'aaa':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated);
      break;
    case 'aaaa':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide);
      break;
    case 'aaaaa':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow);
      break;
    // Extended period of the day (midnight, at night, ...), standalone
    case 'b':
    case 'bb':
    case 'bbb':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Standalone, true);
      break;
    case 'bbbb':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Standalone, true);
      break;
    case 'bbbbb':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Standalone, true);
      break;
    // Extended period of the day (midnight, night, ...), standalone
    case 'B':
    case 'BB':
    case 'BBB':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Format, true);
      break;
    case 'BBBB':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Format, true);
      break;
    case 'BBBBB':
      formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Format, true);
      break;
    // Hour in AM/PM, (1-12)
    case 'h':
      formatter = dateGetter(DateType.Hours, 1, -12);
      break;
    case 'hh':
      formatter = dateGetter(DateType.Hours, 2, -12);
      break;
    // Hour of the day (0-23)
    case 'H':
      formatter = dateGetter(DateType.Hours, 1);
      break;
    // Hour in day, padded (00-23)
    case 'HH':
      formatter = dateGetter(DateType.Hours, 2);
      break;
    // Minute of the hour (0-59)
    case 'm':
      formatter = dateGetter(DateType.Minutes, 1);
      break;
    case 'mm':
      formatter = dateGetter(DateType.Minutes, 2);
      break;
    // Second of the minute (0-59)
    case 's':
      formatter = dateGetter(DateType.Seconds, 1);
      break;
    case 'ss':
      formatter = dateGetter(DateType.Seconds, 2);
      break;
    // Fractional second
    case 'S':
      formatter = dateGetter(DateType.FractionalSeconds, 1);
      break;
    case 'SS':
      formatter = dateGetter(DateType.FractionalSeconds, 2);
      break;
    case 'SSS':
      formatter = dateGetter(DateType.FractionalSeconds, 3);
      break;
    // Timezone ISO8601 short format (-0430)
    case 'Z':
    case 'ZZ':
    case 'ZZZ':
      formatter = timeZoneGetter(ZoneWidth.Short);
      break;
    // Timezone ISO8601 extended format (-04:30)
    case 'ZZZZZ':
      formatter = timeZoneGetter(ZoneWidth.Extended);
      break;
    // Timezone GMT short format (GMT+4)
    case 'O':
    case 'OO':
    case 'OOO':
    // Should be location, but fallback to format O instead because we don't have the data yet
    case 'z':
    case 'zz':
    case 'zzz':
      formatter = timeZoneGetter(ZoneWidth.ShortGMT);
      break;
    // Timezone GMT long format (GMT+0430)
    case 'OOOO':
    case 'ZZZZ':
    // Should be location, but fallback to format O instead because we don't have the data yet
    case 'zzzz':
      formatter = timeZoneGetter(ZoneWidth.Long);
      break;
    default:
      return null;
  }
  DATE_FORMATS[format] = formatter;
  return formatter;
}
function timezoneToOffset(timezone, fallback) {
  // Support: IE 11 only, Edge 13-15+
  // IE/Edge do not "understand" colon (`:`) in timezone
  timezone = timezone.replace(/:/g, '');
  const requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
  date = new Date(date.getTime());
  date.setMinutes(date.getMinutes() + minutes);
  return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
  const reverseValue = reverse ? -1 : 1;
  const dateTimezoneOffset = date.getTimezoneOffset();
  const timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset));
}
/**
 * Converts a value to date.
 *
 * Supported input formats:
 * - `Date`
 * - number: timestamp
 * - string: numeric (e.g. "1234"), ISO and date strings in a format supported by
 *   [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse).
 *   Note: ISO strings without time return a date without timeoffset.
 *
 * Throws if unable to convert to a date.
 */
function toDate(value) {
  if (isDate(value)) {
    return value;
  }
  if (typeof value === 'number' && !isNaN(value)) {
    return new Date(value);
  }
  if (typeof value === 'string') {
    value = value.trim();
    if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) {
      /* For ISO Strings without time the day, month and year must be extracted from the ISO String
      before Date creation to avoid time offset and errors in the new Date.
      If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new
      date, some browsers (e.g. IE 9) will throw an invalid Date error.
      If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset
      is applied.
      Note: ISO months are 0 for January, 1 for February, ... */
      const [y, m = 1, d = 1] = value.split('-').map(val => +val);
      return createDate(y, m - 1, d);
    }
    const parsedNb = parseFloat(value);
    // any string that only contains numbers, like "1234" but not like "1234hello"
    if (!isNaN(value - parsedNb)) {
      return new Date(parsedNb);
    }
    let match;
    if (match = value.match(ISO8601_DATE_REGEX)) {
      return isoStringToDate(match);
    }
  }
  const date = new Date(value);
  if (!isDate(date)) {
    throw new Error(`Unable to convert "${value}" into a date`);
  }
  return date;
}
/**
 * Converts a date in ISO8601 to a Date.
 * Used instead of `Date.parse` because of browser discrepancies.
 */
function isoStringToDate(match) {
  const date = new Date(0);
  let tzHour = 0;
  let tzMin = 0;
  // match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100"
  const dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear;
  const timeSetter = match[8] ? date.setUTCHours : date.setHours;
  // if there is a timezone defined like "+01:00" or "+0100"
  if (match[9]) {
    tzHour = Number(match[9] + match[10]);
    tzMin = Number(match[9] + match[11]);
  }
  dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3]));
  const h = Number(match[4] || 0) - tzHour;
  const m = Number(match[5] || 0) - tzMin;
  const s = Number(match[6] || 0);
  // The ECMAScript specification (https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.11)
  // defines that `DateTime` milliseconds should always be rounded down, so that `999.9ms`
  // becomes `999ms`.
  const ms = Math.floor(parseFloat('0.' + (match[7] || 0)) * 1000);
  timeSetter.call(date, h, m, s, ms);
  return date;
}
function isDate(value) {
  return value instanceof Date && !isNaN(value.valueOf());
}
const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
const MAX_DIGITS = 22;
const DECIMAL_SEP = '.';
const ZERO_CHAR = '0';
const PATTERN_SEP = ';';
const GROUP_SEP = ',';
const DIGIT_CHAR = '#';
const CURRENCY_CHAR = '¤';
const PERCENT_CHAR = '%';
/**
 * Transforms a number to a locale string based on a style and a format.
 */
function formatNumberToLocaleString(value, pattern, locale, groupSymbol, decimalSymbol, digitsInfo, isPercent = false) {
  let formattedText = '';
  let isZero = false;
  if (!isFinite(value)) {
    formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity);
  } else {
    let parsedNumber = parseNumber(value);
    if (isPercent) {
      parsedNumber = toPercent(parsedNumber);
    }
    let minInt = pattern.minInt;
    let minFraction = pattern.minFrac;
    let maxFraction = pattern.maxFrac;
    if (digitsInfo) {
      const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP);
      if (parts === null) {
        throw new Error(`${digitsInfo} is not a valid digit info`);
      }
      const minIntPart = parts[1];
      const minFractionPart = parts[3];
      const maxFractionPart = parts[5];
      if (minIntPart != null) {
        minInt = parseIntAutoRadix(minIntPart);
      }
      if (minFractionPart != null) {
        minFraction = parseIntAutoRadix(minFractionPart);
      }
      if (maxFractionPart != null) {
        maxFraction = parseIntAutoRadix(maxFractionPart);
      } else if (minFractionPart != null && minFraction > maxFraction) {
        maxFraction = minFraction;
      }
    }
    roundNumber(parsedNumber, minFraction, maxFraction);
    let digits = parsedNumber.digits;
    let integerLen = parsedNumber.integerLen;
    const exponent = parsedNumber.exponent;
    let decimals = [];
    isZero = digits.every(d => !d);
    // pad zeros for small numbers
    for (; integerLen < minInt; integerLen++) {
      digits.unshift(0);
    }
    // pad zeros for small numbers
    for (; integerLen < 0; integerLen++) {
      digits.unshift(0);
    }
    // extract decimals digits
    if (integerLen > 0) {
      decimals = digits.splice(integerLen, digits.length);
    } else {
      decimals = digits;
      digits = [0];
    }
    // format the integer digits with grouping separators
    const groups = [];
    if (digits.length >= pattern.lgSize) {
      groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
    }
    while (digits.length > pattern.gSize) {
      groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
    }
    if (digits.length) {
      groups.unshift(digits.join(''));
    }
    formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol));
    // append the decimal digits
    if (decimals.length) {
      formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join('');
    }
    if (exponent) {
      formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent;
    }
  }
  if (value < 0 && !isZero) {
    formattedText = pattern.negPre + formattedText + pattern.negSuf;
  } else {
    formattedText = pattern.posPre + formattedText + pattern.posSuf;
  }
  return formattedText;
}
/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as currency using locale rules.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param currency A string containing the currency symbol or its name,
 * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation
 * of the function.
 * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)
 * currency code, such as `USD` for the US dollar and `EUR` for the euro.
 * Used to determine the number of digits in the decimal part.
 * @param digitsInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted currency value.
 *
 * @see {@link formatNumber}
 * @see {@link DecimalPipe}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 */
function formatCurrency(value, locale, currency, currencyCode, digitsInfo) {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  pattern.minFrac = getNumberOfCurrencyDigits(currencyCode);
  pattern.maxFrac = pattern.minFrac;
  const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo);
  return res.replace(CURRENCY_CHAR, currency)
  // if we have 2 time the currency character, the second one is ignored
  .replace(CURRENCY_CHAR, '')
  // If there is a spacing between currency character and the value and
  // the currency character is suppressed by passing an empty string, the
  // spacing character would remain as part of the string. Then we
  // should remove it.
  .trim();
}
/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as a percentage according to locale rules.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param digitsInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted percentage value.
 *
 * @see {@link formatNumber}
 * @see {@link DecimalPipe}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 * @publicApi
 *
 */
function formatPercent(value, locale, digitsInfo) {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true);
  return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign));
}
/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as text, with group sizing, separator, and other
 * parameters based on the locale.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param digitsInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted text string.
 * @see [Internationalization (i18n) Guide](guide/i18n)
 *
 * @publicApi
 */
function formatNumber(value, locale, digitsInfo) {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  return formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo);
}
function parseNumberFormat(format, minusSign = '-') {
  const p = {
    minInt: 1,
    minFrac: 0,
    maxFrac: 0,
    posPre: '',
    posSuf: '',
    negPre: '',
    negSuf: '',
    gSize: 0,
    lgSize: 0
  };
  const patternParts = format.split(PATTERN_SEP);
  const positive = patternParts[0];
  const negative = patternParts[1];
  const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ? positive.split(DECIMAL_SEP) : [positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1), positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1)],
    integer = positiveParts[0],
    fraction = positiveParts[1] || '';
  p.posPre = integer.substring(0, integer.indexOf(DIGIT_CHAR));
  for (let i = 0; i < fraction.length; i++) {
    const ch = fraction.charAt(i);
    if (ch === ZERO_CHAR) {
      p.minFrac = p.maxFrac = i + 1;
    } else if (ch === DIGIT_CHAR) {
      p.maxFrac = i + 1;
    } else {
      p.posSuf += ch;
    }
  }
  const groups = integer.split(GROUP_SEP);
  p.gSize = groups[1] ? groups[1].length : 0;
  p.lgSize = groups[2] || groups[1] ? (groups[2] || groups[1]).length : 0;
  if (negative) {
    const trunkLen = positive.length - p.posPre.length - p.posSuf.length,
      pos = negative.indexOf(DIGIT_CHAR);
    p.negPre = negative.substring(0, pos).replace(/'/g, '');
    p.negSuf = negative.slice(pos + trunkLen).replace(/'/g, '');
  } else {
    p.negPre = minusSign + p.posPre;
    p.negSuf = p.posSuf;
  }
  return p;
}
// Transforms a parsed number into a percentage by multiplying it by 100
function toPercent(parsedNumber) {
  // if the number is 0, don't do anything
  if (parsedNumber.digits[0] === 0) {
    return parsedNumber;
  }
  // Getting the current number of decimals
  const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen;
  if (parsedNumber.exponent) {
    parsedNumber.exponent += 2;
  } else {
    if (fractionLen === 0) {
      parsedNumber.digits.push(0, 0);
    } else if (fractionLen === 1) {
      parsedNumber.digits.push(0);
    }
    parsedNumber.integerLen += 2;
  }
  return parsedNumber;
}
/**
 * Parses a number.
 * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/
 */
function parseNumber(num) {
  let numStr = Math.abs(num) + '';
  let exponent = 0,
    digits,
    integerLen;
  let i, j, zeros;
  // Decimal point?
  if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) {
    numStr = numStr.replace(DECIMAL_SEP, '');
  }
  // Exponential form?
  if ((i = numStr.search(/e/i)) > 0) {
    // Work out the exponent.
    if (integerLen < 0) integerLen = i;
    integerLen += +numStr.slice(i + 1);
    numStr = numStr.substring(0, i);
  } else if (integerLen < 0) {
    // There was no decimal point or exponent so it is an integer.
    integerLen = numStr.length;
  }
  // Count the number of leading zeros.
  for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) {
    /* empty */
  }
  if (i === (zeros = numStr.length)) {
    // The digits are all zero.
    digits = [0];
    integerLen = 1;
  } else {
    // Count the number of trailing zeros
    zeros--;
    while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
    // Trailing zeros are insignificant so ignore them
    integerLen -= i;
    digits = [];
    // Convert string to array of digits without leading/trailing zeros.
    for (j = 0; i <= zeros; i++, j++) {
      digits[j] = Number(numStr.charAt(i));
    }
  }
  // If the number overflows the maximum allowed digits then use an exponent.
  if (integerLen > MAX_DIGITS) {
    digits = digits.splice(0, MAX_DIGITS - 1);
    exponent = integerLen - 1;
    integerLen = 1;
  }
  return {
    digits,
    exponent,
    integerLen
  };
}
/**
 * Round the parsed number to the specified number of decimal places
 * This function changes the parsedNumber in-place
 */
function roundNumber(parsedNumber, minFrac, maxFrac) {
  if (minFrac > maxFrac) {
    throw new Error(`The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`);
  }
  let digits = parsedNumber.digits;
  let fractionLen = digits.length - parsedNumber.integerLen;
  const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac);
  // The index of the digit to where rounding is to occur
  let roundAt = fractionSize + parsedNumber.integerLen;
  let digit = digits[roundAt];
  if (roundAt > 0) {
    // Drop fractional digits beyond `roundAt`
    digits.splice(Math.max(parsedNumber.integerLen, roundAt));
    // Set non-fractional digits beyond `roundAt` to 0
    for (let j = roundAt; j < digits.length; j++) {
      digits[j] = 0;
    }
  } else {
    // We rounded to zero so reset the parsedNumber
    fractionLen = Math.max(0, fractionLen);
    parsedNumber.integerLen = 1;
    digits.length = Math.max(1, roundAt = fractionSize + 1);
    digits[0] = 0;
    for (let i = 1; i < roundAt; i++) digits[i] = 0;
  }
  if (digit >= 5) {
    if (roundAt - 1 < 0) {
      for (let k = 0; k > roundAt; k--) {
        digits.unshift(0);
        parsedNumber.integerLen++;
      }
      digits.unshift(1);
      parsedNumber.integerLen++;
    } else {
      digits[roundAt - 1]++;
    }
  }
  // Pad out with zeros to get the required fraction length
  for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  let dropTrailingZeros = fractionSize !== 0;
  // Minimal length = nb of decimals required + current nb of integers
  // Any number besides that is optional and can be removed if it's a trailing 0
  const minLen = minFrac + parsedNumber.integerLen;
  // Do any carrying, e.g. a digit was rounded up to 10
  const carry = digits.reduceRight(function (carry, d, i, digits) {
    d = d + carry;
    digits[i] = d < 10 ? d : d - 10; // d % 10
    if (dropTrailingZeros) {
      // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52)
      if (digits[i] === 0 && i >= minLen) {
        digits.pop();
      } else {
        dropTrailingZeros = false;
      }
    }
    return d >= 10 ? 1 : 0; // Math.floor(d / 10);
  }, 0);
  if (carry) {
    digits.unshift(carry);
    parsedNumber.integerLen++;
  }
}
function parseIntAutoRadix(text) {
  const result = parseInt(text);
  if (isNaN(result)) {
    throw new Error('Invalid integer literal when parsing ' + text);
  }
  return result;
}

/**
 * @publicApi
 */
let NgLocalization = /*#__PURE__*/(() => {
  class NgLocalization {
    static ɵfac = (() => function NgLocalization_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgLocalization)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: NgLocalization,
      factory: function NgLocalization_Factory(__ngFactoryType__) {
        let __ngConditionalFactory__ = null;
        if (__ngFactoryType__) {
          __ngConditionalFactory__ = new __ngFactoryType__();
        } else {
          __ngConditionalFactory__ = (locale => new NgLocaleLocalization(locale))(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID));
        }
        return __ngConditionalFactory__;
      },
      providedIn: 'root'
    }))();
  }
  return NgLocalization;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Returns the plural category for a given value.
 * - "=value" when the case exists,
 * - the plural category otherwise
 */
function getPluralCategory(value, cases, ngLocalization, locale) {
  let key = `=${value}`;
  if (cases.indexOf(key) > -1) {
    return key;
  }
  key = ngLocalization.getPluralCategory(value, locale);
  if (cases.indexOf(key) > -1) {
    return key;
  }
  if (cases.indexOf('other') > -1) {
    return 'other';
  }
  throw new Error(`No plural message found for value "${value}"`);
}
/**
 * Returns the plural case based on the locale
 *
 * @publicApi
 */
let NgLocaleLocalization = /*#__PURE__*/(() => {
  class NgLocaleLocalization extends NgLocalization {
    locale;
    constructor(locale) {
      super();
      this.locale = locale;
    }
    getPluralCategory(value, locale) {
      const plural = getLocalePluralCase(locale || this.locale)(value);
      switch (plural) {
        case Plural.Zero:
          return 'zero';
        case Plural.One:
          return 'one';
        case Plural.Two:
          return 'two';
        case Plural.Few:
          return 'few';
        case Plural.Many:
          return 'many';
        default:
          return 'other';
      }
    }
    static ɵfac = (() => function NgLocaleLocalization_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgLocaleLocalization)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: NgLocaleLocalization,
      factory: NgLocaleLocalization.ɵfac
    }))();
  }
  return NgLocaleLocalization;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Register global data to be used internally by Angular. See the
 * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
 * data.
 *
 * The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
 *
 * @publicApi
 */
function registerLocaleData(data, localeId, extraData) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵregisterLocaleData"])(data, localeId, extraData);
}
function parseCookieValue(cookieStr, name) {
  name = encodeURIComponent(name);
  for (const cookie of cookieStr.split(';')) {
    const eqIndex = cookie.indexOf('=');
    const [cookieName, cookieValue] = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)];
    if (cookieName.trim() === name) {
      return decodeURIComponent(cookieValue);
    }
  }
  return null;
}
const WS_REGEXP = /\s+/;
const EMPTY_ARRAY = [];
/**
 * @ngModule CommonModule
 *
 * @usageNotes
 * ```
 *     <some-element [ngClass]="'first second'">...</some-element>
 *
 *     <some-element [ngClass]="['first', 'second']">...</some-element>
 *
 *     <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
 *
 *     <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
 *
 *     <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
 * ```
 *
 * @description
 *
 * Adds and removes CSS classes on an HTML element.
 *
 * The CSS classes are updated as follows, depending on the type of the expression evaluation:
 * - `string` - the CSS classes listed in the string (space delimited) are added,
 * - `Array` - the CSS classes declared as Array elements are added,
 * - `Object` - keys are CSS classes that get added when the expression given in the value
 *              evaluates to a truthy value, otherwise they are removed.
 *
 * @publicApi
 */
let NgClass = /*#__PURE__*/(() => {
  class NgClass {
    _ngEl;
    _renderer;
    initialClasses = (() => EMPTY_ARRAY)();
    rawClass;
    stateMap = (() => new Map())();
    constructor(_ngEl, _renderer) {
      this._ngEl = _ngEl;
      this._renderer = _renderer;
    }
    set klass(value) {
      this.initialClasses = value != null ? value.trim().split(WS_REGEXP) : EMPTY_ARRAY;
    }
    set ngClass(value) {
      this.rawClass = typeof value === 'string' ? value.trim().split(WS_REGEXP) : value;
    }
    /*
    The NgClass directive uses the custom change detection algorithm for its inputs. The custom
    algorithm is necessary since inputs are represented as complex object or arrays that need to be
    deeply-compared.
       This algorithm is perf-sensitive since NgClass is used very frequently and its poor performance
    might negatively impact runtime performance of the entire change detection cycle. The design of
    this algorithm is making sure that:
    - there is no unnecessary DOM manipulation (CSS classes are added / removed from the DOM only when
    needed), even if references to bound objects change;
    - there is no memory allocation if nothing changes (even relatively modest memory allocation
    during the change detection cycle can result in GC pauses for some of the CD cycles).
       The algorithm works by iterating over the set of bound classes, staring with [class] binding and
    then going over [ngClass] binding. For each CSS class name:
    - check if it was seen before (this information is tracked in the state map) and if its value
    changed;
    - mark it as "touched" - names that are not marked are not present in the latest set of binding
    and we can remove such class name from the internal data structures;
       After iteration over all the CSS class names we've got data structure with all the information
    necessary to synchronize changes to the DOM - it is enough to iterate over the state map, flush
    changes to the DOM and reset internal data structures so those are ready for the next change
    detection cycle.
     */
    ngDoCheck() {
      // classes from the [class] binding
      for (const klass of this.initialClasses) {
        this._updateState(klass, true);
      }
      // classes from the [ngClass] binding
      const rawClass = this.rawClass;
      if (Array.isArray(rawClass) || rawClass instanceof Set) {
        for (const klass of rawClass) {
          this._updateState(klass, true);
        }
      } else if (rawClass != null) {
        for (const klass of Object.keys(rawClass)) {
          this._updateState(klass, Boolean(rawClass[klass]));
        }
      }
      this._applyStateDiff();
    }
    _updateState(klass, nextEnabled) {
      const state = this.stateMap.get(klass);
      if (state !== undefined) {
        if (state.enabled !== nextEnabled) {
          state.changed = true;
          state.enabled = nextEnabled;
        }
        state.touched = true;
      } else {
        this.stateMap.set(klass, {
          enabled: nextEnabled,
          changed: true,
          touched: true
        });
      }
    }
    _applyStateDiff() {
      for (const stateEntry of this.stateMap) {
        const klass = stateEntry[0];
        const state = stateEntry[1];
        if (state.changed) {
          this._toggleClass(klass, state.enabled);
          state.changed = false;
        } else if (!state.touched) {
          // A class that was previously active got removed from the new collection of classes -
          // remove from the DOM as well.
          if (state.enabled) {
            this._toggleClass(klass, false);
          }
          this.stateMap.delete(klass);
        }
        state.touched = false;
      }
    }
    _toggleClass(klass, enabled) {
      if (ngDevMode) {
        if (typeof klass !== 'string') {
          throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵstringify"])(klass)}`);
        }
      }
      klass = klass.trim();
      if (klass.length > 0) {
        klass.split(WS_REGEXP).forEach(klass => {
          if (enabled) {
            this._renderer.addClass(this._ngEl.nativeElement, klass);
          } else {
            this._renderer.removeClass(this._ngEl.nativeElement, klass);
          }
        });
      }
    }
    static ɵfac = (() => function NgClass_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgClass)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.Renderer2));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgClass,
      selectors: [["", "ngClass", ""]],
      inputs: {
        klass: [0, "class", "klass"],
        ngClass: "ngClass"
      }
    }))();
  }
  return NgClass;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Instantiates a {@link Component} type and inserts its Host View into the current View.
 * `NgComponentOutlet` provides a declarative approach for dynamic component creation.
 *
 * `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and
 * any existing component will be destroyed.
 *
 * @usageNotes
 *
 * ### Fine tune control
 *
 * You can control the component creation process by using the following optional attributes:
 *
 * * `ngComponentOutletInputs`: Optional component inputs object, which will be bind to the
 * component.
 *
 * * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for
 * the Component. Defaults to the injector of the current view container.
 *
 * * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content
 * section of the component, if it exists.
 *
 * * `ngComponentOutletNgModule`: Optional NgModule class reference to allow loading another
 * module dynamically, then loading a component from that module.
 *
 * * `ngComponentOutletNgModuleFactory`: Deprecated config option that allows providing optional
 * NgModule factory to allow loading another module dynamically, then loading a component from that
 * module. Use `ngComponentOutletNgModule` instead.
 *
 * ### Syntax
 *
 * Simple
 * ```
 * <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
 * ```
 *
 * With inputs
 * ```
 * <ng-container *ngComponentOutlet="componentTypeExpression;
 *                                   inputs: inputsExpression;">
 * </ng-container>
 * ```
 *
 * Customized injector/content
 * ```
 * <ng-container *ngComponentOutlet="componentTypeExpression;
 *                                   injector: injectorExpression;
 *                                   content: contentNodesExpression;">
 * </ng-container>
 * ```
 *
 * Customized NgModule reference
 * ```
 * <ng-container *ngComponentOutlet="componentTypeExpression;
 *                                   ngModule: ngModuleClass;">
 * </ng-container>
 * ```
 *
 * ### A simple example
 *
 * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'}
 *
 * A more complete example with additional options:
 *
 * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'}
 *
 * @publicApi
 * @ngModule CommonModule
 */
let NgComponentOutlet = /*#__PURE__*/(() => {
  class NgComponentOutlet {
    _viewContainerRef;
    ngComponentOutlet = null;
    ngComponentOutletInputs;
    ngComponentOutletInjector;
    ngComponentOutletContent;
    ngComponentOutletNgModule;
    /**
     * @deprecated This input is deprecated, use `ngComponentOutletNgModule` instead.
     */
    ngComponentOutletNgModuleFactory;
    _componentRef;
    _moduleRef;
    /**
     * A helper data structure that allows us to track inputs that were part of the
     * ngComponentOutletInputs expression. Tracking inputs is necessary for proper removal of ones
     * that are no longer referenced.
     */
    _inputsUsed = (() => new Map())();
    constructor(_viewContainerRef) {
      this._viewContainerRef = _viewContainerRef;
    }
    _needToReCreateNgModuleInstance(changes) {
      // Note: square brackets property accessor is safe for Closure compiler optimizations (the
      // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
      // were changed).
      return changes['ngComponentOutletNgModule'] !== undefined || changes['ngComponentOutletNgModuleFactory'] !== undefined;
    }
    _needToReCreateComponentInstance(changes) {
      // Note: square brackets property accessor is safe for Closure compiler optimizations (the
      // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
      // were changed).
      return changes['ngComponentOutlet'] !== undefined || changes['ngComponentOutletContent'] !== undefined || changes['ngComponentOutletInjector'] !== undefined || this._needToReCreateNgModuleInstance(changes);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      if (this._needToReCreateComponentInstance(changes)) {
        this._viewContainerRef.clear();
        this._inputsUsed.clear();
        this._componentRef = undefined;
        if (this.ngComponentOutlet) {
          const injector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;
          if (this._needToReCreateNgModuleInstance(changes)) {
            this._moduleRef?.destroy();
            if (this.ngComponentOutletNgModule) {
              this._moduleRef = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.createNgModule)(this.ngComponentOutletNgModule, getParentInjector(injector));
            } else if (this.ngComponentOutletNgModuleFactory) {
              this._moduleRef = this.ngComponentOutletNgModuleFactory.create(getParentInjector(injector));
            } else {
              this._moduleRef = undefined;
            }
          }
          this._componentRef = this._viewContainerRef.createComponent(this.ngComponentOutlet, {
            injector,
            ngModuleRef: this._moduleRef,
            projectableNodes: this.ngComponentOutletContent
          });
        }
      }
    }
    /** @nodoc */
    ngDoCheck() {
      if (this._componentRef) {
        if (this.ngComponentOutletInputs) {
          for (const inputName of Object.keys(this.ngComponentOutletInputs)) {
            this._inputsUsed.set(inputName, true);
          }
        }
        this._applyInputStateDiff(this._componentRef);
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      this._moduleRef?.destroy();
    }
    _applyInputStateDiff(componentRef) {
      for (const [inputName, touched] of this._inputsUsed) {
        if (!touched) {
          // The input that was previously active no longer exists and needs to be set to undefined.
          componentRef.setInput(inputName, undefined);
          this._inputsUsed.delete(inputName);
        } else {
          // Since touched is true, it can be asserted that the inputs object is not empty.
          componentRef.setInput(inputName, this.ngComponentOutletInputs[inputName]);
          this._inputsUsed.set(inputName, false);
        }
      }
    }
    static ɵfac = (() => function NgComponentOutlet_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgComponentOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgComponentOutlet,
      selectors: [["", "ngComponentOutlet", ""]],
      inputs: {
        ngComponentOutlet: "ngComponentOutlet",
        ngComponentOutletInputs: "ngComponentOutletInputs",
        ngComponentOutletInjector: "ngComponentOutletInjector",
        ngComponentOutletContent: "ngComponentOutletContent",
        ngComponentOutletNgModule: "ngComponentOutletNgModule",
        ngComponentOutletNgModuleFactory: "ngComponentOutletNgModuleFactory"
      },
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return NgComponentOutlet;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
// Helper function that returns an Injector instance of a parent NgModule.
function getParentInjector(injector) {
  const parentNgModule = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgModuleRef);
  return parentNgModule.injector;
}

/**
 * @publicApi
 */
class NgForOfContext {
  $implicit;
  ngForOf;
  index;
  count;
  constructor(/** Reference to the current item from the collection. */
  $implicit,
  /**
   * The value of the iterable expression. Useful when the expression is
   * more complex then a property access, for example when using the async pipe
   * (`userStreams | async`).
   */
  ngForOf, /** Returns an index of the current item in the collection. */
  index, /** Returns total amount of items in the collection. */
  count) {
    this.$implicit = $implicit;
    this.ngForOf = ngForOf;
    this.index = index;
    this.count = count;
  }
  // Indicates whether this is the first item in the collection.
  get first() {
    return this.index === 0;
  }
  // Indicates whether this is the last item in the collection.
  get last() {
    return this.index === this.count - 1;
  }
  // Indicates whether an index of this item in the collection is even.
  get even() {
    return this.index % 2 === 0;
  }
  // Indicates whether an index of this item in the collection is odd.
  get odd() {
    return !this.even;
  }
}
/**
 * A [structural directive](guide/directives/structural-directives) that renders
 * a template for each item in a collection.
 * The directive is placed on an element, which becomes the parent
 * of the cloned templates.
 *
 * The `ngForOf` directive is generally used in the
 * [shorthand form](guide/directives/structural-directives#asterisk) `*ngFor`.
 * In this form, the template to be rendered for each iteration is the content
 * of an anchor element containing the directive.
 *
 * The following example shows the shorthand syntax with some options,
 * contained in an `<li>` element.
 *
 * ```
 * <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
 * ```
 *
 * The shorthand form expands into a long form that uses the `ngForOf` selector
 * on an `<ng-template>` element.
 * The content of the `<ng-template>` element is the `<li>` element that held the
 * short-form directive.
 *
 * Here is the expanded version of the short-form example.
 *
 * ```
 * <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
 *   <li>...</li>
 * </ng-template>
 * ```
 *
 * Angular automatically expands the shorthand syntax as it compiles the template.
 * The context for each embedded view is logically merged to the current component
 * context according to its lexical position.
 *
 * When using the shorthand syntax, Angular allows only [one structural directive
 * on an element](guide/directives/structural-directives#one-per-element).
 * If you want to iterate conditionally, for example,
 * put the `*ngIf` on a container element that wraps the `*ngFor` element.
 * For further discussion, see
 * [Structural Directives](guide/directives/structural-directives#one-per-element).
 *
 * @usageNotes
 *
 * ### Local variables
 *
 * `NgForOf` provides exported values that can be aliased to local variables.
 * For example:
 *
 *  ```
 * <li *ngFor="let user of users; index as i; first as isFirst">
 *    {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
 * </li>
 * ```
 *
 * The following exported values can be aliased to local variables:
 *
 * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`).
 * - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is
 * more complex then a property access, for example when using the async pipe (`userStreams |
 * async`).
 * - `index: number`: The index of the current item in the iterable.
 * - `count: number`: The length of the iterable.
 * - `first: boolean`: True when the item is the first item in the iterable.
 * - `last: boolean`: True when the item is the last item in the iterable.
 * - `even: boolean`: True when the item has an even index in the iterable.
 * - `odd: boolean`: True when the item has an odd index in the iterable.
 *
 * ### Change propagation
 *
 * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM:
 *
 * * When an item is added, a new instance of the template is added to the DOM.
 * * When an item is removed, its template instance is removed from the DOM.
 * * When items are reordered, their respective templates are reordered in the DOM.
 *
 * Angular uses object identity to track insertions and deletions within the iterator and reproduce
 * those changes in the DOM. This has important implications for animations and any stateful
 * controls that are present, such as `<input>` elements that accept user input. Inserted rows can
 * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state
 * such as user input.
 * For more on animations, see [Transitions and Triggers](guide/animations/transition-and-triggers).
 *
 * The identities of elements in the iterator can change while the data does not.
 * This can happen, for example, if the iterator is produced from an RPC to the server, and that
 * RPC is re-run. Even if the data hasn't changed, the second response produces objects with
 * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old
 * elements were deleted and all new elements inserted).
 *
 * To avoid this expensive operation, you can customize the default tracking algorithm.
 * by supplying the `trackBy` option to `NgForOf`.
 * `trackBy` takes a function that has two arguments: `index` and `item`.
 * If `trackBy` is given, Angular tracks changes by the return value of the function.
 *
 * @see [Structural Directives](guide/directives/structural-directives)
 * @ngModule CommonModule
 * @publicApi
 */
let NgForOf = /*#__PURE__*/(() => {
  class NgForOf {
    _viewContainer;
    _template;
    _differs;
    /**
     * The value of the iterable expression, which can be used as a
     * [template input variable](guide/directives/structural-directives#shorthand).
     */
    set ngForOf(ngForOf) {
      this._ngForOf = ngForOf;
      this._ngForOfDirty = true;
    }
    /**
     * Specifies a custom `TrackByFunction` to compute the identity of items in an iterable.
     *
     * If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object
     * identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
     * as the key.
     *
     * `NgForOf` uses the computed key to associate items in an iterable with DOM elements
     * it produces for these items.
     *
     * A custom `TrackByFunction` is useful to provide good user experience in cases when items in an
     * iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a
     * primary key), and this iterable could be updated with new object instances that still
     * represent the same underlying entity (for example, when data is re-fetched from the server,
     * and the iterable is recreated and re-rendered, but most of the data is still the same).
     *
     * @see {@link TrackByFunction}
     */
    set ngForTrackBy(fn) {
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
        console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}. ` + `See https://angular.io/api/common/NgForOf#change-propagation for more information.`);
      }
      this._trackByFn = fn;
    }
    get ngForTrackBy() {
      return this._trackByFn;
    }
    _ngForOf = null;
    _ngForOfDirty = true;
    _differ = null;
    // TODO(issue/24571): remove '!'
    // waiting for microsoft/typescript#43662 to allow the return type `TrackByFunction|undefined` for
    // the getter
    _trackByFn;
    constructor(_viewContainer, _template, _differs) {
      this._viewContainer = _viewContainer;
      this._template = _template;
      this._differs = _differs;
    }
    /**
     * A reference to the template that is stamped out for each item in the iterable.
     * @see [template reference variable](guide/templates/variables#template-reference-variables)
     */
    set ngForTemplate(value) {
      // TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1
      // The current type is too restrictive; a template that just uses index, for example,
      // should be acceptable.
      if (value) {
        this._template = value;
      }
    }
    /**
     * Applies the changes when needed.
     * @nodoc
     */
    ngDoCheck() {
      if (this._ngForOfDirty) {
        this._ngForOfDirty = false;
        // React on ngForOf changes only once all inputs have been initialized
        const value = this._ngForOf;
        if (!this._differ && value) {
          if (typeof ngDevMode === 'undefined' || ngDevMode) {
            try {
              // CAUTION: this logic is duplicated for production mode below, as the try-catch
              // is only present in development builds.
              this._differ = this._differs.find(value).create(this.ngForTrackBy);
            } catch {
              let errorMessage = `Cannot find a differ supporting object '${value}' of type '` + `${getTypeName(value)}'. NgFor only supports binding to Iterables, such as Arrays.`;
              if (typeof value === 'object') {
                errorMessage += ' Did you mean to use the keyvalue pipe?';
              }
              throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](-2200 /* RuntimeErrorCode.NG_FOR_MISSING_DIFFER */, errorMessage);
            }
          } else {
            // CAUTION: this logic is duplicated for development mode above, as the try-catch
            // is only present in development builds.
            this._differ = this._differs.find(value).create(this.ngForTrackBy);
          }
        }
      }
      if (this._differ) {
        const changes = this._differ.diff(this._ngForOf);
        if (changes) this._applyChanges(changes);
      }
    }
    _applyChanges(changes) {
      const viewContainer = this._viewContainer;
      changes.forEachOperation((item, adjustedPreviousIndex, currentIndex) => {
        if (item.previousIndex == null) {
          // NgForOf is never "null" or "undefined" here because the differ detected
          // that a new item needs to be inserted from the iterable. This implies that
          // there is an iterable value for "_ngForOf".
          viewContainer.createEmbeddedView(this._template, new NgForOfContext(item.item, this._ngForOf, -1, -1), currentIndex === null ? undefined : currentIndex);
        } else if (currentIndex == null) {
          viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex);
        } else if (adjustedPreviousIndex !== null) {
          const view = viewContainer.get(adjustedPreviousIndex);
          viewContainer.move(view, currentIndex);
          applyViewChange(view, item);
        }
      });
      for (let i = 0, ilen = viewContainer.length; i < ilen; i++) {
        const viewRef = viewContainer.get(i);
        const context = viewRef.context;
        context.index = i;
        context.count = ilen;
        context.ngForOf = this._ngForOf;
      }
      changes.forEachIdentityChange(record => {
        const viewRef = viewContainer.get(record.currentIndex);
        applyViewChange(viewRef, record);
      });
    }
    /**
     * Asserts the correct type of the context for the template that `NgForOf` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgForOf` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard(dir, ctx) {
      return true;
    }
    static ɵfac = (() => function NgForOf_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgForOf)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.IterableDiffers));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgForOf,
      selectors: [["", "ngFor", "", "ngForOf", ""]],
      inputs: {
        ngForOf: "ngForOf",
        ngForTrackBy: "ngForTrackBy",
        ngForTemplate: "ngForTemplate"
      }
    }))();
  }
  return NgForOf;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function applyViewChange(view, record) {
  view.context.$implicit = record.item;
}
function getTypeName(type) {
  return type['name'] || typeof type;
}

/**
 * A structural directive that conditionally includes a template based on the value of
 * an expression coerced to Boolean.
 * When the expression evaluates to true, Angular renders the template
 * provided in a `then` clause, and when  false or null,
 * Angular renders the template provided in an optional `else` clause. The default
 * template for the `else` clause is blank.
 *
 * A [shorthand form](guide/directives/structural-directives#asterisk) of the directive,
 * `*ngIf="condition"`, is generally used, provided
 * as an attribute of the anchor element for the inserted template.
 * Angular expands this into a more explicit version, in which the anchor element
 * is contained in an `<ng-template>` element.
 *
 * Simple form with shorthand syntax:
 *
 * ```
 * <div *ngIf="condition">Content to render when condition is true.</div>
 * ```
 *
 * Simple form with expanded syntax:
 *
 * ```
 * <ng-template [ngIf]="condition"><div>Content to render when condition is
 * true.</div></ng-template>
 * ```
 *
 * Form with an "else" block:
 *
 * ```
 * <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
 * <ng-template #elseBlock>Content to render when condition is false.</ng-template>
 * ```
 *
 * Shorthand form with "then" and "else" blocks:
 *
 * ```
 * <div *ngIf="condition; then thenBlock else elseBlock"></div>
 * <ng-template #thenBlock>Content to render when condition is true.</ng-template>
 * <ng-template #elseBlock>Content to render when condition is false.</ng-template>
 * ```
 *
 * Form with storing the value locally:
 *
 * ```
 * <div *ngIf="condition as value; else elseBlock">{{value}}</div>
 * <ng-template #elseBlock>Content to render when value is null.</ng-template>
 * ```
 *
 * @usageNotes
 *
 * The `*ngIf` directive is most commonly used to conditionally show an inline template,
 * as seen in the following  example.
 * The default `else` template is blank.
 *
 * {@example common/ngIf/ts/module.ts region='NgIfSimple'}
 *
 * ### Showing an alternative template using `else`
 *
 * To display a template when `expression` evaluates to false, use an `else` template
 * binding as shown in the following example.
 * The `else` binding points to an `<ng-template>`  element labeled `#elseBlock`.
 * The template can be defined anywhere in the component view, but is typically placed right after
 * `ngIf` for readability.
 *
 * {@example common/ngIf/ts/module.ts region='NgIfElse'}
 *
 * ### Using an external `then` template
 *
 * In the previous example, the then-clause template is specified inline, as the content of the
 * tag that contains the `ngIf` directive. You can also specify a template that is defined
 * externally, by referencing a labeled `<ng-template>` element. When you do this, you can
 * change which template to use at runtime, as shown in the following example.
 *
 * {@example common/ngIf/ts/module.ts region='NgIfThenElse'}
 *
 * ### Storing a conditional result in a variable
 *
 * You might want to show a set of properties from the same object. If you are waiting
 * for asynchronous data, the object can be undefined.
 * In this case, you can use `ngIf` and store the result of the condition in a local
 * variable as shown in the following example.
 *
 * {@example common/ngIf/ts/module.ts region='NgIfAs'}
 *
 * This code uses only one `AsyncPipe`, so only one subscription is created.
 * The conditional statement stores the result of `userStream|async` in the local variable `user`.
 * You can then bind the local `user` repeatedly.
 *
 * The conditional displays the data only if `userStream` returns a value,
 * so you don't need to use the
 * safe-navigation-operator (`?.`)
 * to guard against null values when accessing properties.
 * You can display an alternative template while waiting for the data.
 *
 * ### Shorthand syntax
 *
 * The shorthand syntax `*ngIf` expands into two separate template specifications
 * for the "then" and "else" clauses. For example, consider the following shorthand statement,
 * that is meant to show a loading page while waiting for data to be loaded.
 *
 * ```
 * <div class="hero-list" *ngIf="heroes else loading">
 *  ...
 * </div>
 *
 * <ng-template #loading>
 *  <div>Loading...</div>
 * </ng-template>
 * ```
 *
 * You can see that the "else" clause references the `<ng-template>`
 * with the `#loading` label, and the template for the "then" clause
 * is provided as the content of the anchor element.
 *
 * However, when Angular expands the shorthand syntax, it creates
 * another `<ng-template>` tag, with `ngIf` and `ngIfElse` directives.
 * The anchor element containing the template for the "then" clause becomes
 * the content of this unlabeled `<ng-template>` tag.
 *
 * ```
 * <ng-template [ngIf]="heroes" [ngIfElse]="loading">
 *  <div class="hero-list">
 *   ...
 *  </div>
 * </ng-template>
 *
 * <ng-template #loading>
 *  <div>Loading...</div>
 * </ng-template>
 * ```
 *
 * The presence of the implicit template object has implications for the nesting of
 * structural directives. For more on this subject, see
 * [Structural Directives](guide/directives/structural-directives#one-per-element).
 *
 * @ngModule CommonModule
 * @publicApi
 */
let NgIf = /*#__PURE__*/(() => {
  class NgIf {
    _viewContainer;
    _context = (() => new NgIfContext())();
    _thenTemplateRef = null;
    _elseTemplateRef = null;
    _thenViewRef = null;
    _elseViewRef = null;
    constructor(_viewContainer, templateRef) {
      this._viewContainer = _viewContainer;
      this._thenTemplateRef = templateRef;
    }
    /**
     * The Boolean expression to evaluate as the condition for showing a template.
     */
    set ngIf(condition) {
      this._context.$implicit = this._context.ngIf = condition;
      this._updateView();
    }
    /**
     * A template to show if the condition expression evaluates to true.
     */
    set ngIfThen(templateRef) {
      assertTemplate('ngIfThen', templateRef);
      this._thenTemplateRef = templateRef;
      this._thenViewRef = null; // clear previous view if any.
      this._updateView();
    }
    /**
     * A template to show if the condition expression evaluates to false.
     */
    set ngIfElse(templateRef) {
      assertTemplate('ngIfElse', templateRef);
      this._elseTemplateRef = templateRef;
      this._elseViewRef = null; // clear previous view if any.
      this._updateView();
    }
    _updateView() {
      if (this._context.$implicit) {
        if (!this._thenViewRef) {
          this._viewContainer.clear();
          this._elseViewRef = null;
          if (this._thenTemplateRef) {
            this._thenViewRef = this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
          }
        }
      } else {
        if (!this._elseViewRef) {
          this._viewContainer.clear();
          this._thenViewRef = null;
          if (this._elseTemplateRef) {
            this._elseViewRef = this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
          }
        }
      }
    }
    /** @internal */
    static ngIfUseIfTypeGuard;
    /**
     * Assert the correct type of the expression bound to the `ngIf` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgIf` structural directive renders its template, the type of the expression bound
     * to `ngIf` should be narrowed in some way. For `NgIf`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgIf`.
     */
    static ngTemplateGuard_ngIf;
    /**
     * Asserts the correct type of the context for the template that `NgIf` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgIf` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard(dir, ctx) {
      return true;
    }
    static ɵfac = (() => function NgIf_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgIf)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.TemplateRef));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgIf,
      selectors: [["", "ngIf", ""]],
      inputs: {
        ngIf: "ngIf",
        ngIfThen: "ngIfThen",
        ngIfElse: "ngIfElse"
      }
    }))();
  }
  return NgIf;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @publicApi
 */
class NgIfContext {
  $implicit = null;
  ngIf = null;
}
function assertTemplate(property, templateRef) {
  const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView);
  if (!isTemplateRefOrNull) {
    throw new Error(`${property} must be a TemplateRef, but received '${(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵstringify"])(templateRef)}'.`);
  }
}
class SwitchView {
  _viewContainerRef;
  _templateRef;
  _created = false;
  constructor(_viewContainerRef, _templateRef) {
    this._viewContainerRef = _viewContainerRef;
    this._templateRef = _templateRef;
  }
  create() {
    this._created = true;
    this._viewContainerRef.createEmbeddedView(this._templateRef);
  }
  destroy() {
    this._created = false;
    this._viewContainerRef.clear();
  }
  enforceState(created) {
    if (created && !this._created) {
      this.create();
    } else if (!created && this._created) {
      this.destroy();
    }
  }
}
/**
 * @ngModule CommonModule
 *
 * @description
 * The `[ngSwitch]` directive on a container specifies an expression to match against.
 * The expressions to match are provided by `ngSwitchCase` directives on views within the container.
 * - Every view that matches is rendered.
 * - If there are no matches, a view with the `ngSwitchDefault` directive is rendered.
 * - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase`
 * or `ngSwitchDefault` directive are preserved at the location.
 *
 * @usageNotes
 * Define a container element for the directive, and specify the switch expression
 * to match against as an attribute:
 *
 * ```
 * <container-element [ngSwitch]="switch_expression">
 * ```
 *
 * Within the container, `*ngSwitchCase` statements specify the match expressions
 * as attributes. Include `*ngSwitchDefault` as the final case.
 *
 * ```
 * <container-element [ngSwitch]="switch_expression">
 *    <some-element *ngSwitchCase="match_expression_1">...</some-element>
 * ...
 *    <some-element *ngSwitchDefault>...</some-element>
 * </container-element>
 * ```
 *
 * ### Usage Examples
 *
 * The following example shows how to use more than one case to display the same view:
 *
 * ```
 * <container-element [ngSwitch]="switch_expression">
 *   <!-- the same view can be shown in more than one case -->
 *   <some-element *ngSwitchCase="match_expression_1">...</some-element>
 *   <some-element *ngSwitchCase="match_expression_2">...</some-element>
 *   <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
 *   <!--default case when there are no matches -->
 *   <some-element *ngSwitchDefault>...</some-element>
 * </container-element>
 * ```
 *
 * The following example shows how cases can be nested:
 * ```
 * <container-element [ngSwitch]="switch_expression">
 *       <some-element *ngSwitchCase="match_expression_1">...</some-element>
 *       <some-element *ngSwitchCase="match_expression_2">...</some-element>
 *       <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
 *       <ng-container *ngSwitchCase="match_expression_3">
 *         <!-- use a ng-container to group multiple root nodes -->
 *         <inner-element></inner-element>
 *         <inner-other-element></inner-other-element>
 *       </ng-container>
 *       <some-element *ngSwitchDefault>...</some-element>
 *     </container-element>
 * ```
 *
 * @publicApi
 * @see {@link NgSwitchCase}
 * @see {@link NgSwitchDefault}
 * @see [Structural Directives](guide/directives/structural-directives)
 *
 */
let NgSwitch = /*#__PURE__*/(() => {
  class NgSwitch {
    _defaultViews = [];
    _defaultUsed = false;
    _caseCount = 0;
    _lastCaseCheckIndex = 0;
    _lastCasesMatched = false;
    _ngSwitch;
    set ngSwitch(newValue) {
      this._ngSwitch = newValue;
      if (this._caseCount === 0) {
        this._updateDefaultCases(true);
      }
    }
    /** @internal */
    _addCase() {
      return this._caseCount++;
    }
    /** @internal */
    _addDefault(view) {
      this._defaultViews.push(view);
    }
    /** @internal */
    _matchCase(value) {
      const matched = value === this._ngSwitch;
      this._lastCasesMatched ||= matched;
      this._lastCaseCheckIndex++;
      if (this._lastCaseCheckIndex === this._caseCount) {
        this._updateDefaultCases(!this._lastCasesMatched);
        this._lastCaseCheckIndex = 0;
        this._lastCasesMatched = false;
      }
      return matched;
    }
    _updateDefaultCases(useDefault) {
      if (this._defaultViews.length > 0 && useDefault !== this._defaultUsed) {
        this._defaultUsed = useDefault;
        for (const defaultView of this._defaultViews) {
          defaultView.enforceState(useDefault);
        }
      }
    }
    static ɵfac = (() => function NgSwitch_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgSwitch)();
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgSwitch,
      selectors: [["", "ngSwitch", ""]],
      inputs: {
        ngSwitch: "ngSwitch"
      }
    }))();
  }
  return NgSwitch;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @ngModule CommonModule
 *
 * @description
 * Provides a switch case expression to match against an enclosing `ngSwitch` expression.
 * When the expressions match, the given `NgSwitchCase` template is rendered.
 * If multiple match expressions match the switch expression value, all of them are displayed.
 *
 * @usageNotes
 *
 * Within a switch container, `*ngSwitchCase` statements specify the match expressions
 * as attributes. Include `*ngSwitchDefault` as the final case.
 *
 * ```
 * <container-element [ngSwitch]="switch_expression">
 *   <some-element *ngSwitchCase="match_expression_1">...</some-element>
 *   ...
 *   <some-element *ngSwitchDefault>...</some-element>
 * </container-element>
 * ```
 *
 * Each switch-case statement contains an in-line HTML template or template reference
 * that defines the subtree to be selected if the value of the match expression
 * matches the value of the switch expression.
 *
 * As of Angular v17 the NgSwitch directive uses strict equality comparison (`===`) instead of
 * loose equality (`==`) to match different cases.
 *
 * @publicApi
 * @see {@link NgSwitch}
 * @see {@link NgSwitchDefault}
 *
 */
let NgSwitchCase = /*#__PURE__*/(() => {
  class NgSwitchCase {
    ngSwitch;
    _view;
    /**
     * Stores the HTML template to be selected on match.
     */
    ngSwitchCase;
    constructor(viewContainer, templateRef, ngSwitch) {
      this.ngSwitch = ngSwitch;
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
        throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase');
      }
      ngSwitch._addCase();
      this._view = new SwitchView(viewContainer, templateRef);
    }
    /**
     * Performs case matching. For internal use only.
     * @nodoc
     */
    ngDoCheck() {
      this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase));
    }
    static ɵfac = (() => function NgSwitchCase_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgSwitchCase)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](NgSwitch, 9));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgSwitchCase,
      selectors: [["", "ngSwitchCase", ""]],
      inputs: {
        ngSwitchCase: "ngSwitchCase"
      }
    }))();
  }
  return NgSwitchCase;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @ngModule CommonModule
 *
 * @description
 *
 * Creates a view that is rendered when no `NgSwitchCase` expressions
 * match the `NgSwitch` expression.
 * This statement should be the final case in an `NgSwitch`.
 *
 * @publicApi
 * @see {@link NgSwitch}
 * @see {@link NgSwitchCase}
 *
 */
let NgSwitchDefault = /*#__PURE__*/(() => {
  class NgSwitchDefault {
    constructor(viewContainer, templateRef, ngSwitch) {
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
        throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault');
      }
      ngSwitch._addDefault(new SwitchView(viewContainer, templateRef));
    }
    static ɵfac = (() => function NgSwitchDefault_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgSwitchDefault)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](NgSwitch, 9));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgSwitchDefault,
      selectors: [["", "ngSwitchDefault", ""]]
    }))();
  }
  return NgSwitchDefault;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function throwNgSwitchProviderNotFoundError(attrName, directiveName) {
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2000 /* RuntimeErrorCode.PARENT_NG_SWITCH_NOT_FOUND */, `An element with the "${attrName}" attribute ` + `(matching the "${directiveName}" directive) must be located inside an element with the "ngSwitch" attribute ` + `(matching "NgSwitch" directive)`);
}
function stringifyValue(value) {
  return typeof value === 'string' ? `'${value}'` : String(value);
}

/**
 * @ngModule CommonModule
 *
 * @usageNotes
 * ```
 * <some-element [ngPlural]="value">
 *   <ng-template ngPluralCase="=0">there is nothing</ng-template>
 *   <ng-template ngPluralCase="=1">there is one</ng-template>
 *   <ng-template ngPluralCase="few">there are a few</ng-template>
 * </some-element>
 * ```
 *
 * @description
 *
 * Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization.
 *
 * Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees
 * that match the switch expression's pluralization category.
 *
 * To use this directive you must provide a container element that sets the `[ngPlural]` attribute
 * to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their
 * expression:
 * - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value
 *   matches the switch expression exactly,
 * - otherwise, the view will be treated as a "category match", and will only display if exact
 *   value matches aren't found and the value maps to its category for the defined locale.
 *
 * See http://cldr.unicode.org/index/cldr-spec/plural-rules
 *
 * @publicApi
 */
let NgPlural = /*#__PURE__*/(() => {
  class NgPlural {
    _localization;
    _activeView;
    _caseViews = {};
    constructor(_localization) {
      this._localization = _localization;
    }
    set ngPlural(value) {
      this._updateView(value);
    }
    addCase(value, switchView) {
      this._caseViews[value] = switchView;
    }
    _updateView(switchValue) {
      this._clearViews();
      const cases = Object.keys(this._caseViews);
      const key = getPluralCategory(switchValue, cases, this._localization);
      this._activateView(this._caseViews[key]);
    }
    _clearViews() {
      if (this._activeView) this._activeView.destroy();
    }
    _activateView(view) {
      if (view) {
        this._activeView = view;
        this._activeView.create();
      }
    }
    static ɵfac = (() => function NgPlural_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgPlural)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](NgLocalization));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgPlural,
      selectors: [["", "ngPlural", ""]],
      inputs: {
        ngPlural: "ngPlural"
      }
    }))();
  }
  return NgPlural;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @ngModule CommonModule
 *
 * @description
 *
 * Creates a view that will be added/removed from the parent {@link NgPlural} when the
 * given expression matches the plural expression according to CLDR rules.
 *
 * @usageNotes
 * ```
 * <some-element [ngPlural]="value">
 *   <ng-template ngPluralCase="=0">...</ng-template>
 *   <ng-template ngPluralCase="other">...</ng-template>
 * </some-element>
 *```
 *
 * See {@link NgPlural} for more details and example.
 *
 * @publicApi
 */
let NgPluralCase = /*#__PURE__*/(() => {
  class NgPluralCase {
    value;
    constructor(value, template, viewContainer, ngPlural) {
      this.value = value;
      const isANumber = !isNaN(Number(value));
      ngPlural.addCase(isANumber ? `=${value}` : value, new SwitchView(viewContainer, template));
    }
    static ɵfac = (() => function NgPluralCase_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgPluralCase)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinjectAttribute"]('ngPluralCase'), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](NgPlural, 1));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgPluralCase,
      selectors: [["", "ngPluralCase", ""]]
    }))();
  }
  return NgPluralCase;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @ngModule CommonModule
 *
 * @usageNotes
 *
 * Set the font of the containing element to the result of an expression.
 *
 * ```
 * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
 * ```
 *
 * Set the width of the containing element to a pixel value returned by an expression.
 *
 * ```
 * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
 * ```
 *
 * Set a collection of style values using an expression that returns key-value pairs.
 *
 * ```
 * <some-element [ngStyle]="objExp">...</some-element>
 * ```
 *
 * @description
 *
 * An attribute directive that updates styles for the containing HTML element.
 * Sets one or more style properties, specified as colon-separated key-value pairs.
 * The key is a style name, with an optional `.<unit>` suffix
 * (such as 'top.px', 'font-style.em').
 * The value is an expression to be evaluated.
 * The resulting non-null value, expressed in the given unit,
 * is assigned to the given style property.
 * If the result of evaluation is null, the corresponding style is removed.
 *
 * @publicApi
 */
let NgStyle = /*#__PURE__*/(() => {
  class NgStyle {
    _ngEl;
    _differs;
    _renderer;
    _ngStyle = null;
    _differ = null;
    constructor(_ngEl, _differs, _renderer) {
      this._ngEl = _ngEl;
      this._differs = _differs;
      this._renderer = _renderer;
    }
    set ngStyle(values) {
      this._ngStyle = values;
      if (!this._differ && values) {
        this._differ = this._differs.find(values).create();
      }
    }
    ngDoCheck() {
      if (this._differ) {
        const changes = this._differ.diff(this._ngStyle);
        if (changes) {
          this._applyChanges(changes);
        }
      }
    }
    _setStyle(nameAndUnit, value) {
      const [name, unit] = nameAndUnit.split('.');
      const flags = name.indexOf('-') === -1 ? undefined : _angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererStyleFlags2.DashCase;
      if (value != null) {
        this._renderer.setStyle(this._ngEl.nativeElement, name, unit ? `${value}${unit}` : value, flags);
      } else {
        this._renderer.removeStyle(this._ngEl.nativeElement, name, flags);
      }
    }
    _applyChanges(changes) {
      changes.forEachRemovedItem(record => this._setStyle(record.key, null));
      changes.forEachAddedItem(record => this._setStyle(record.key, record.currentValue));
      changes.forEachChangedItem(record => this._setStyle(record.key, record.currentValue));
    }
    static ɵfac = (() => function NgStyle_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgStyle)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.KeyValueDiffers), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.Renderer2));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgStyle,
      selectors: [["", "ngStyle", ""]],
      inputs: {
        ngStyle: "ngStyle"
      }
    }))();
  }
  return NgStyle;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @ngModule CommonModule
 *
 * @description
 *
 * Inserts an embedded view from a prepared `TemplateRef`.
 *
 * You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`.
 * `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding
 * by the local template `let` declarations.
 *
 * @usageNotes
 * ```
 * <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>
 * ```
 *
 * Using the key `$implicit` in the context object will set its value as default.
 *
 * ### Example
 *
 * {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'}
 *
 * @publicApi
 */
let NgTemplateOutlet = /*#__PURE__*/(() => {
  class NgTemplateOutlet {
    _viewContainerRef;
    _viewRef = null;
    /**
     * A context object to attach to the {@link EmbeddedViewRef}. This should be an
     * object, the object's keys will be available for binding by the local template `let`
     * declarations.
     * Using the key `$implicit` in the context object will set its value as default.
     */
    ngTemplateOutletContext = null;
    /**
     * A string defining the template reference and optionally the context object for the template.
     */
    ngTemplateOutlet = null;
    /** Injector to be used within the embedded view. */
    ngTemplateOutletInjector = null;
    constructor(_viewContainerRef) {
      this._viewContainerRef = _viewContainerRef;
    }
    ngOnChanges(changes) {
      if (this._shouldRecreateView(changes)) {
        const viewContainerRef = this._viewContainerRef;
        if (this._viewRef) {
          viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef));
        }
        // If there is no outlet, clear the destroyed view ref.
        if (!this.ngTemplateOutlet) {
          this._viewRef = null;
          return;
        }
        // Create a context forward `Proxy` that will always bind to the user-specified context,
        // without having to destroy and re-create views whenever the context changes.
        const viewContext = this._createContextForwardProxy();
        this._viewRef = viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, viewContext, {
          injector: this.ngTemplateOutletInjector ?? undefined
        });
      }
    }
    /**
     * We need to re-create existing embedded view if either is true:
     * - the outlet changed.
     * - the injector changed.
     */
    _shouldRecreateView(changes) {
      return !!changes['ngTemplateOutlet'] || !!changes['ngTemplateOutletInjector'];
    }
    /**
     * For a given outlet instance, we create a proxy object that delegates
     * to the user-specified context. This allows changing, or swapping out
     * the context object completely without having to destroy/re-create the view.
     */
    _createContextForwardProxy() {
      return new Proxy({}, {
        set: (_target, prop, newValue) => {
          if (!this.ngTemplateOutletContext) {
            return false;
          }
          return Reflect.set(this.ngTemplateOutletContext, prop, newValue);
        },
        get: (_target, prop, receiver) => {
          if (!this.ngTemplateOutletContext) {
            return undefined;
          }
          return Reflect.get(this.ngTemplateOutletContext, prop, receiver);
        }
      });
    }
    static ɵfac = (() => function NgTemplateOutlet_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgTemplateOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgTemplateOutlet,
      selectors: [["", "ngTemplateOutlet", ""]],
      inputs: {
        ngTemplateOutletContext: "ngTemplateOutletContext",
        ngTemplateOutlet: "ngTemplateOutlet",
        ngTemplateOutletInjector: "ngTemplateOutletInjector"
      },
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return NgTemplateOutlet;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * A collection of Angular directives that are likely to be used in each and every Angular
 * application.
 */
const COMMON_DIRECTIVES = [NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase];
function invalidPipeArgumentError(type, value) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2100 /* RuntimeErrorCode.INVALID_PIPE_ARGUMENT */, ngDevMode && `InvalidPipeArgument: '${value}' for pipe '${(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵstringify"])(type)}'`);
}
class SubscribableStrategy {
  createSubscription(async, updateLatestValue) {
    // Subscription can be side-effectful, and we don't want any signal reads which happen in the
    // side effect of the subscription to be tracked by a component's template when that
    // subscription is triggered via the async pipe. So we wrap the subscription in `untracked` to
    // decouple from the current reactive context.
    //
    // `untracked` also prevents signal _writes_ which happen in the subscription side effect from
    // being treated as signal writes during the template evaluation (which throws errors).
    return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.untracked)(() => async.subscribe({
      next: updateLatestValue,
      error: e => {
        throw e;
      }
    }));
  }
  dispose(subscription) {
    // See the comment in `createSubscription` above on the use of `untracked`.
    (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.untracked)(() => subscription.unsubscribe());
  }
}
class PromiseStrategy {
  createSubscription(async, updateLatestValue) {
    return async.then(updateLatestValue, e => {
      throw e;
    });
  }
  dispose(subscription) {}
}
const _promiseStrategy = /*#__PURE__*/new PromiseStrategy();
const _subscribableStrategy = /*#__PURE__*/new SubscribableStrategy();
/**
 * @ngModule CommonModule
 * @description
 *
 * Unwraps a value from an asynchronous primitive.
 *
 * The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
 * emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
 * changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
 * potential memory leaks. When the reference of the expression changes, the `async` pipe
 * automatically unsubscribes from the old `Observable` or `Promise` and subscribes to the new one.
 *
 * @usageNotes
 *
 * ### Examples
 *
 * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
 * promise.
 *
 * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
 *
 * It's also possible to use `async` with Observables. The example below binds the `time` Observable
 * to the view. The Observable continuously updates the view with the current time.
 *
 * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
 *
 * @publicApi
 */
let AsyncPipe = /*#__PURE__*/(() => {
  class AsyncPipe {
    _ref;
    _latestValue = null;
    markForCheckOnValueUpdate = true;
    _subscription = null;
    _obj = null;
    _strategy = null;
    constructor(ref) {
      // Assign `ref` into `this._ref` manually instead of declaring `_ref` in the constructor
      // parameter list, as the type of `this._ref` includes `null` unlike the type of `ref`.
      this._ref = ref;
    }
    ngOnDestroy() {
      if (this._subscription) {
        this._dispose();
      }
      // Clear the `ChangeDetectorRef` and its association with the view data, to mitigate
      // potential memory leaks in Observables that could otherwise cause the view data to
      // be retained.
      // https://github.com/angular/angular/issues/17624
      this._ref = null;
    }
    transform(obj) {
      if (!this._obj) {
        if (obj) {
          try {
            // Only call `markForCheck` if the value is updated asynchronously.
            // Synchronous updates _during_ subscription should not wastefully mark for check -
            // this value is already going to be returned from the transform function.
            this.markForCheckOnValueUpdate = false;
            this._subscribe(obj);
          } finally {
            this.markForCheckOnValueUpdate = true;
          }
        }
        return this._latestValue;
      }
      if (obj !== this._obj) {
        this._dispose();
        return this.transform(obj);
      }
      return this._latestValue;
    }
    _subscribe(obj) {
      this._obj = obj;
      this._strategy = this._selectStrategy(obj);
      this._subscription = this._strategy.createSubscription(obj, value => this._updateLatestValue(obj, value));
    }
    _selectStrategy(obj) {
      if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisPromise"])(obj)) {
        return _promiseStrategy;
      }
      if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisSubscribable"])(obj)) {
        return _subscribableStrategy;
      }
      throw invalidPipeArgumentError(AsyncPipe, obj);
    }
    _dispose() {
      // Note: `dispose` is only called if a subscription has been initialized before, indicating
      // that `this._strategy` is also available.
      this._strategy.dispose(this._subscription);
      this._latestValue = null;
      this._subscription = null;
      this._obj = null;
    }
    _updateLatestValue(async, value) {
      if (async === this._obj) {
        this._latestValue = value;
        if (this.markForCheckOnValueUpdate) {
          this._ref?.markForCheck();
        }
      }
    }
    static ɵfac = (() => function AsyncPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AsyncPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ChangeDetectorRef, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "async",
      type: AsyncPipe,
      pure: false
    }))();
  }
  return AsyncPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Transforms text to all lower case.
 *
 * @see {@link UpperCasePipe}
 * @see {@link TitleCasePipe}
 * @usageNotes
 *
 * The following example defines a view that allows the user to enter
 * text, and then uses the pipe to convert the input text to all lower case.
 *
 * <code-example path="common/pipes/ts/lowerupper_pipe.ts" region='LowerUpperPipe'></code-example>
 *
 * @ngModule CommonModule
 * @publicApi
 */
let LowerCasePipe = /*#__PURE__*/(() => {
  class LowerCasePipe {
    transform(value) {
      if (value == null) return null;
      if (typeof value !== 'string') {
        throw invalidPipeArgumentError(LowerCasePipe, value);
      }
      return value.toLowerCase();
    }
    static ɵfac = (() => function LowerCasePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || LowerCasePipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "lowercase",
      type: LowerCasePipe,
      pure: true
    }))();
  }
  return LowerCasePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
//
// Regex below matches any Unicode word and number compatible with ES5. In ES2018 the same result
// can be achieved by using /[0-9\p{L}]\S*/gu and also known as Unicode Property Escapes
// (https://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no
// transpilation of this functionality down to ES5 without external tool, the only solution is
// to use already transpiled form. Example can be found here -
// https://mothereff.in/regexpu#input=var+regex+%3D+%2F%5B0-9%5Cp%7BL%7D%5D%5CS*%2Fgu%3B%0A%0A&unicodePropertyEscape=1
//
const unicodeWordMatch = /(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])\S*/g;
/**
 * Transforms text to title case.
 * Capitalizes the first letter of each word and transforms the
 * rest of the word to lower case.
 * Words are delimited by any whitespace character, such as a space, tab, or line-feed character.
 *
 * @see {@link LowerCasePipe}
 * @see {@link UpperCasePipe}
 *
 * @usageNotes
 * The following example shows the result of transforming various strings into title case.
 *
 * <code-example path="common/pipes/ts/titlecase_pipe.ts" region='TitleCasePipe'></code-example>
 *
 * @ngModule CommonModule
 * @publicApi
 */
let TitleCasePipe = /*#__PURE__*/(() => {
  class TitleCasePipe {
    transform(value) {
      if (value == null) return null;
      if (typeof value !== 'string') {
        throw invalidPipeArgumentError(TitleCasePipe, value);
      }
      return value.replace(unicodeWordMatch, txt => txt[0].toUpperCase() + txt.slice(1).toLowerCase());
    }
    static ɵfac = (() => function TitleCasePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || TitleCasePipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "titlecase",
      type: TitleCasePipe,
      pure: true
    }))();
  }
  return TitleCasePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Transforms text to all upper case.
 * @see {@link LowerCasePipe}
 * @see {@link TitleCasePipe}
 *
 * @ngModule CommonModule
 * @publicApi
 */
let UpperCasePipe = /*#__PURE__*/(() => {
  class UpperCasePipe {
    transform(value) {
      if (value == null) return null;
      if (typeof value !== 'string') {
        throw invalidPipeArgumentError(UpperCasePipe, value);
      }
      return value.toUpperCase();
    }
    static ɵfac = (() => function UpperCasePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UpperCasePipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "uppercase",
      type: UpperCasePipe,
      pure: true
    }))();
  }
  return UpperCasePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * The default date format of Angular date pipe, which corresponds to the following format:
 * `'MMM d,y'` (e.g. `Jun 15, 2015`)
 */
const DEFAULT_DATE_FORMAT = 'mediumDate';

/**
 * Optionally-provided default timezone to use for all instances of `DatePipe` (such as `'+0430'`).
 * If the value isn't provided, the `DatePipe` will use the end-user's local system timezone.
 *
 * @deprecated use DATE_PIPE_DEFAULT_OPTIONS token to configure DatePipe
 */
const DATE_PIPE_DEFAULT_TIMEZONE = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'DATE_PIPE_DEFAULT_TIMEZONE' : '');
/**
 * DI token that allows to provide default configuration for the `DatePipe` instances in an
 * application. The value is an object which can include the following fields:
 * - `dateFormat`: configures the default date format. If not provided, the `DatePipe`
 * will use the 'mediumDate' as a value.
 * - `timezone`: configures the default timezone. If not provided, the `DatePipe` will
 * use the end-user's local system timezone.
 *
 * @see {@link DatePipeConfig}
 *
 * @usageNotes
 *
 * Various date pipe default values can be overwritten by providing this token with
 * the value that has this interface.
 *
 * For example:
 *
 * Override the default date format by providing a value using the token:
 * ```typescript
 * providers: [
 *   {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}}
 * ]
 * ```
 *
 * Override the default timezone by providing a value using the token:
 * ```typescript
 * providers: [
 *   {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}}
 * ]
 * ```
 */
const DATE_PIPE_DEFAULT_OPTIONS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'DATE_PIPE_DEFAULT_OPTIONS' : '');
/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a date value according to locale rules.
 *
 * `DatePipe` is executed only when it detects a pure change to the input value.
 * A pure change is either a change to a primitive input value
 * (such as `String`, `Number`, `Boolean`, or `Symbol`),
 * or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`).
 *
 * Note that mutating a `Date` object does not cause the pipe to be rendered again.
 * To ensure that the pipe is executed, you must create a new `Date` object.
 *
 * Only the `en-US` locale data comes with Angular. To localize dates
 * in another language, you must import the corresponding locale data.
 * See the [I18n guide](guide/i18n/format-data-locale) for more information.
 *
 * The time zone of the formatted value can be specified either by passing it in as the second
 * parameter of the pipe, or by setting the default through the `DATE_PIPE_DEFAULT_OPTIONS`
 * injection token. The value that is passed in as the second parameter takes precedence over
 * the one defined using the injection token.
 *
 * @see {@link formatDate}
 *
 *
 * @usageNotes
 *
 * The result of this pipe is not reevaluated when the input is mutated. To avoid the need to
 * reformat the date on every change-detection cycle, treat the date as an immutable object
 * and change the reference when the pipe needs to run again.
 *
 * ### Pre-defined format options
 *
 * | Option        | Equivalent to                       | Examples (given in `en-US` locale)              |
 * |---------------|-------------------------------------|-------------------------------------------------|
 * | `'short'`     | `'M/d/yy, h:mm a'`                  | `6/15/15, 9:03 AM`                              |
 * | `'medium'`    | `'MMM d, y, h:mm:ss a'`             | `Jun 15, 2015, 9:03:01 AM`                      |
 * | `'long'`      | `'MMMM d, y, h:mm:ss a z'`          | `June 15, 2015 at 9:03:01 AM GMT+1`             |
 * | `'full'`      | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` |
 * | `'shortDate'` | `'M/d/yy'`                          | `6/15/15`                                       |
 * | `'mediumDate'`| `'MMM d, y'`                        | `Jun 15, 2015`                                  |
 * | `'longDate'`  | `'MMMM d, y'`                       | `June 15, 2015`                                 |
 * | `'fullDate'`  | `'EEEE, MMMM d, y'`                 | `Monday, June 15, 2015`                         |
 * | `'shortTime'` | `'h:mm a'`                          | `9:03 AM`                                       |
 * | `'mediumTime'`| `'h:mm:ss a'`                       | `9:03:01 AM`                                    |
 * | `'longTime'`  | `'h:mm:ss a z'`                     | `9:03:01 AM GMT+1`                              |
 * | `'fullTime'`  | `'h:mm:ss a zzzz'`                  | `9:03:01 AM GMT+01:00`                          |
 *
 * ### Custom format options
 *
 * You can construct a format string using symbols to specify the components
 * of a date-time value, as described in the following table.
 * Format details depend on the locale.
 * Fields marked with (*) are only available in the extra data set for the given locale.
 *
 *  | Field type              | Format      | Description                                                   | Example Value                                              |
 *  |-------------------------|-------------|---------------------------------------------------------------|------------------------------------------------------------|
 *  | Era                     | G, GG & GGG | Abbreviated                                                   | AD                                                         |
 *  |                         | GGGG        | Wide                                                          | Anno Domini                                                |
 *  |                         | GGGGG       | Narrow                                                        | A                                                          |
 *  | Year                    | y           | Numeric: minimum digits                                       | 2, 20, 201, 2017, 20173                                    |
 *  |                         | yy          | Numeric: 2 digits + zero padded                               | 02, 20, 01, 17, 73                                         |
 *  |                         | yyy         | Numeric: 3 digits + zero padded                               | 002, 020, 201, 2017, 20173                                 |
 *  |                         | yyyy        | Numeric: 4 digits or more + zero padded                       | 0002, 0020, 0201, 2017, 20173                              |
 *  | ISO Week-numbering year | Y           | Numeric: minimum digits                                       | 2, 20, 201, 2017, 20173                                    |
 *  |                         | YY          | Numeric: 2 digits + zero padded                               | 02, 20, 01, 17, 73                                         |
 *  |                         | YYY         | Numeric: 3 digits + zero padded                               | 002, 020, 201, 2017, 20173                                 |
 *  |                         | YYYY        | Numeric: 4 digits or more + zero padded                       | 0002, 0020, 0201, 2017, 20173                              |
 *  | Month                   | M           | Numeric: 1 digit                                              | 9, 12                                                      |
 *  |                         | MM          | Numeric: 2 digits + zero padded                               | 09, 12                                                     |
 *  |                         | MMM         | Abbreviated                                                   | Sep                                                        |
 *  |                         | MMMM        | Wide                                                          | September                                                  |
 *  |                         | MMMMM       | Narrow                                                        | S                                                          |
 *  | Month standalone        | L           | Numeric: 1 digit                                              | 9, 12                                                      |
 *  |                         | LL          | Numeric: 2 digits + zero padded                               | 09, 12                                                     |
 *  |                         | LLL         | Abbreviated                                                   | Sep                                                        |
 *  |                         | LLLL        | Wide                                                          | September                                                  |
 *  |                         | LLLLL       | Narrow                                                        | S                                                          |
 *  | ISO Week of year        | w           | Numeric: minimum digits                                       | 1... 53                                                    |
 *  |                         | ww          | Numeric: 2 digits + zero padded                               | 01... 53                                                   |
 *  | Week of month           | W           | Numeric: 1 digit                                              | 1... 5                                                     |
 *  | Day of month            | d           | Numeric: minimum digits                                       | 1                                                          |
 *  |                         | dd          | Numeric: 2 digits + zero padded                               | 01                                                         |
 *  | Week day                | E, EE & EEE | Abbreviated                                                   | Tue                                                        |
 *  |                         | EEEE        | Wide                                                          | Tuesday                                                    |
 *  |                         | EEEEE       | Narrow                                                        | T                                                          |
 *  |                         | EEEEEE      | Short                                                         | Tu                                                         |
 *  | Week day standalone     | c, cc       | Numeric: 1 digit                                              | 2                                                          |
 *  |                         | ccc         | Abbreviated                                                   | Tue                                                        |
 *  |                         | cccc        | Wide                                                          | Tuesday                                                    |
 *  |                         | ccccc       | Narrow                                                        | T                                                          |
 *  |                         | cccccc      | Short                                                         | Tu                                                         |
 *  | Period                  | a, aa & aaa | Abbreviated                                                   | am/pm or AM/PM                                             |
 *  |                         | aaaa        | Wide (fallback to `a` when missing)                           | ante meridiem/post meridiem                                |
 *  |                         | aaaaa       | Narrow                                                        | a/p                                                        |
 *  | Period*                 | B, BB & BBB | Abbreviated                                                   | mid.                                                       |
 *  |                         | BBBB        | Wide                                                          | am, pm, midnight, noon, morning, afternoon, evening, night |
 *  |                         | BBBBB       | Narrow                                                        | md                                                         |
 *  | Period standalone*      | b, bb & bbb | Abbreviated                                                   | mid.                                                       |
 *  |                         | bbbb        | Wide                                                          | am, pm, midnight, noon, morning, afternoon, evening, night |
 *  |                         | bbbbb       | Narrow                                                        | md                                                         |
 *  | Hour 1-12               | h           | Numeric: minimum digits                                       | 1, 12                                                      |
 *  |                         | hh          | Numeric: 2 digits + zero padded                               | 01, 12                                                     |
 *  | Hour 0-23               | H           | Numeric: minimum digits                                       | 0, 23                                                      |
 *  |                         | HH          | Numeric: 2 digits + zero padded                               | 00, 23                                                     |
 *  | Minute                  | m           | Numeric: minimum digits                                       | 8, 59                                                      |
 *  |                         | mm          | Numeric: 2 digits + zero padded                               | 08, 59                                                     |
 *  | Second                  | s           | Numeric: minimum digits                                       | 0... 59                                                    |
 *  |                         | ss          | Numeric: 2 digits + zero padded                               | 00... 59                                                   |
 *  | Fractional seconds      | S           | Numeric: 1 digit                                              | 0... 9                                                     |
 *  |                         | SS          | Numeric: 2 digits + zero padded                               | 00... 99                                                   |
 *  |                         | SSS         | Numeric: 3 digits + zero padded (= milliseconds)              | 000... 999                                                 |
 *  | Zone                    | z, zz & zzz | Short specific non location format (fallback to O)            | GMT-8                                                      |
 *  |                         | zzzz        | Long specific non location format (fallback to OOOO)          | GMT-08:00                                                  |
 *  |                         | Z, ZZ & ZZZ | ISO8601 basic format                                          | -0800                                                      |
 *  |                         | ZZZZ        | Long localized GMT format                                     | GMT-8:00                                                   |
 *  |                         | ZZZZZ       | ISO8601 extended format + Z indicator for offset 0 (= XXXXX)  | -08:00                                                     |
 *  |                         | O, OO & OOO | Short localized GMT format                                    | GMT-8                                                      |
 *  |                         | OOOO        | Long localized GMT format                                     | GMT-08:00                                                  |
 *
 *
 * ### Format examples
 *
 * These examples transform a date into various formats,
 * assuming that `dateObj` is a JavaScript `Date` object for
 * year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11,
 * given in the local time for the `en-US` locale.
 *
 * ```
 * {{ dateObj | date }}               // output is 'Jun 15, 2015'
 * {{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
 * {{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
 * {{ dateObj | date:'mm:ss' }}       // output is '43:11'
 * {{ dateObj | date:"MMM dd, yyyy 'at' hh:mm a" }}  // output is 'Jun 15, 2015 at 09:43 PM'
 * ```
 *
 * ### Usage example
 *
 * The following component uses a date pipe to display the current date in different formats.
 *
 * ```
 * @Component({
 *  selector: 'date-pipe',
 *  template: `<div>
 *    <p>Today is {{today | date}}</p>
 *    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
 *    <p>The time is {{today | date:'h:mm a z'}}</p>
 *  </div>`
 * })
 * // Get the current date and time as a date-time value.
 * export class DatePipeComponent {
 *   today: number = Date.now();
 * }
 * ```
 *
 * @publicApi
 */
let DatePipe = /*#__PURE__*/(() => {
  class DatePipe {
    locale;
    defaultTimezone;
    defaultOptions;
    constructor(locale, defaultTimezone, defaultOptions) {
      this.locale = locale;
      this.defaultTimezone = defaultTimezone;
      this.defaultOptions = defaultOptions;
    }
    transform(value, format, timezone, locale) {
      if (value == null || value === '' || value !== value) return null;
      try {
        const _format = format ?? this.defaultOptions?.dateFormat ?? DEFAULT_DATE_FORMAT;
        const _timezone = timezone ?? this.defaultOptions?.timezone ?? this.defaultTimezone ?? undefined;
        return formatDate(value, _format, locale || this.locale, _timezone);
      } catch (error) {
        throw invalidPipeArgumentError(DatePipe, error.message);
      }
    }
    static ɵfac = (() => function DatePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DatePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID, 16), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](DATE_PIPE_DEFAULT_TIMEZONE, 24), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](DATE_PIPE_DEFAULT_OPTIONS, 24));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "date",
      type: DatePipe,
      pure: true
    }))();
  }
  return DatePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const _INTERPOLATION_REGEXP = /#/g;
/**
 * @ngModule CommonModule
 * @description
 *
 * Maps a value to a string that pluralizes the value according to locale rules.
 *
 * @usageNotes
 *
 * ### Example
 *
 * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
 *
 * @publicApi
 */
let I18nPluralPipe = /*#__PURE__*/(() => {
  class I18nPluralPipe {
    _localization;
    constructor(_localization) {
      this._localization = _localization;
    }
    /**
     * @param value the number to be formatted
     * @param pluralMap an object that mimics the ICU format, see
     * https://unicode-org.github.io/icu/userguide/format_parse/messages/.
     * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
     * default).
     */
    transform(value, pluralMap, locale) {
      if (value == null) return '';
      if (typeof pluralMap !== 'object' || pluralMap === null) {
        throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
      }
      const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale);
      return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
    }
    static ɵfac = (() => function I18nPluralPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || I18nPluralPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](NgLocalization, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "i18nPlural",
      type: I18nPluralPipe,
      pure: true
    }))();
  }
  return I18nPluralPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @ngModule CommonModule
 * @description
 *
 * Generic selector that displays the string that matches the current value.
 *
 * If none of the keys of the `mapping` match the `value`, then the content
 * of the `other` key is returned when present, otherwise an empty string is returned.
 *
 * @usageNotes
 *
 * ### Example
 *
 * {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
 *
 * @publicApi
 */
let I18nSelectPipe = /*#__PURE__*/(() => {
  class I18nSelectPipe {
    /**
     * @param value a string to be internationalized.
     * @param mapping an object that indicates the text that should be displayed
     * for different values of the provided `value`.
     */
    transform(value, mapping) {
      if (value == null) return '';
      if (typeof mapping !== 'object' || typeof value !== 'string') {
        throw invalidPipeArgumentError(I18nSelectPipe, mapping);
      }
      if (mapping.hasOwnProperty(value)) {
        return mapping[value];
      }
      if (mapping.hasOwnProperty('other')) {
        return mapping['other'];
      }
      return '';
    }
    static ɵfac = (() => function I18nSelectPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || I18nSelectPipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "i18nSelect",
      type: I18nSelectPipe,
      pure: true
    }))();
  }
  return I18nSelectPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @ngModule CommonModule
 * @description
 *
 * Converts a value into its JSON-format representation.  Useful for debugging.
 *
 * @usageNotes
 *
 * The following component uses a JSON pipe to convert an object
 * to JSON format, and displays the string in both formats for comparison.
 *
 * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'}
 *
 * @publicApi
 */
let JsonPipe = /*#__PURE__*/(() => {
  class JsonPipe {
    /**
     * @param value A value of any type to convert into a JSON-format string.
     */
    transform(value) {
      return JSON.stringify(value, null, 2);
    }
    static ɵfac = (() => function JsonPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || JsonPipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "json",
      type: JsonPipe,
      pure: false
    }))();
  }
  return JsonPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function makeKeyValuePair(key, value) {
  return {
    key: key,
    value: value
  };
}
/**
 * @ngModule CommonModule
 * @description
 *
 * Transforms Object or Map into an array of key value pairs.
 *
 * The output array will be ordered by keys.
 * By default the comparator will be by Unicode point value.
 * You can optionally pass a compareFn if your keys are complex types.
 * Passing `null` as the compareFn will use natural ordering of the input.
 *
 * @usageNotes
 * ### Examples
 *
 * This examples show how an Object or a Map can be iterated by ngFor with the use of this
 * keyvalue pipe.
 *
 * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'}
 *
 * @publicApi
 */
let KeyValuePipe = /*#__PURE__*/(() => {
  class KeyValuePipe {
    differs;
    constructor(differs) {
      this.differs = differs;
    }
    differ;
    keyValues = [];
    compareFn = (() => defaultComparator)();
    transform(input, compareFn = defaultComparator) {
      if (!input || !(input instanceof Map) && typeof input !== 'object') {
        return null;
      }
      // make a differ for whatever type we've been passed in
      this.differ ??= this.differs.find(input).create();
      const differChanges = this.differ.diff(input);
      const compareFnChanged = compareFn !== this.compareFn;
      if (differChanges) {
        this.keyValues = [];
        differChanges.forEachItem(r => {
          this.keyValues.push(makeKeyValuePair(r.key, r.currentValue));
        });
      }
      if (differChanges || compareFnChanged) {
        if (compareFn) {
          this.keyValues.sort(compareFn);
        }
        this.compareFn = compareFn;
      }
      return this.keyValues;
    }
    static ɵfac = (() => function KeyValuePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || KeyValuePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.KeyValueDiffers, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "keyvalue",
      type: KeyValuePipe,
      pure: false
    }))();
  }
  return KeyValuePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function defaultComparator(keyValueA, keyValueB) {
  const a = keyValueA.key;
  const b = keyValueB.key;
  // if same exit with 0;
  if (a === b) return 0;
  // make sure that undefined are at the end of the sort.
  if (a === undefined) return 1;
  if (b === undefined) return -1;
  // make sure that nulls are at the end of the sort.
  if (a === null) return 1;
  if (b === null) return -1;
  if (typeof a == 'string' && typeof b == 'string') {
    return a < b ? -1 : 1;
  }
  if (typeof a == 'number' && typeof b == 'number') {
    return a - b;
  }
  if (typeof a == 'boolean' && typeof b == 'boolean') {
    return a < b ? -1 : 1;
  }
  // `a` and `b` are of different types. Compare their string values.
  const aString = String(a);
  const bString = String(b);
  return aString == bString ? 0 : aString < bString ? -1 : 1;
}

/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a value according to digit options and locale rules.
 * Locale determines group sizing and separator,
 * decimal point character, and other locale-specific configurations.
 *
 * @see {@link formatNumber}
 *
 * @usageNotes
 *
 * ### digitsInfo
 *
 * The value's decimal representation is specified by the `digitsInfo`
 * parameter, written in the following format:<br>
 *
 * ```
 * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
 * ```
 *
 *  - `minIntegerDigits`:
 * The minimum number of integer digits before the decimal point.
 * Default is 1.
 *
 * - `minFractionDigits`:
 * The minimum number of digits after the decimal point.
 * Default is 0.
 *
 *  - `maxFractionDigits`:
 * The maximum number of digits after the decimal point.
 * Default is 3.
 *
 * If the formatted value is truncated it will be rounded using the "to-nearest" method:
 *
 * ```
 * {{3.6 | number: '1.0-0'}}
 * <!--will output '4'-->
 *
 * {{-3.6 | number:'1.0-0'}}
 * <!--will output '-4'-->
 * ```
 *
 * ### locale
 *
 * `locale` will format a value according to locale rules.
 * Locale determines group sizing and separator,
 * decimal point character, and other locale-specific configurations.
 *
 * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
 *
 * See [Setting your app locale](guide/i18n/locale-id).
 *
 * ### Example
 *
 * The following code shows how the pipe transforms values
 * according to various format specifications,
 * where the caller's default locale is `en-US`.
 *
 * <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example>
 *
 * @publicApi
 */
let DecimalPipe = /*#__PURE__*/(() => {
  class DecimalPipe {
    _locale;
    constructor(_locale) {
      this._locale = _locale;
    }
    transform(value, digitsInfo, locale) {
      if (!isValue(value)) return null;
      locale ||= this._locale;
      try {
        const num = strToNumber(value);
        return formatNumber(num, locale, digitsInfo);
      } catch (error) {
        throw invalidPipeArgumentError(DecimalPipe, error.message);
      }
    }
    static ɵfac = (() => function DecimalPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DecimalPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "number",
      type: DecimalPipe,
      pure: true
    }))();
  }
  return DecimalPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @ngModule CommonModule
 * @description
 *
 * Transforms a number to a percentage
 * string, formatted according to locale rules that determine group sizing and
 * separator, decimal-point character, and other locale-specific
 * configurations.
 *
 * @see {@link formatPercent}
 *
 * @usageNotes
 * The following code shows how the pipe transforms numbers
 * into text strings, according to various format specifications,
 * where the caller's default locale is `en-US`.
 *
 * <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example>
 *
 * @publicApi
 */
let PercentPipe = /*#__PURE__*/(() => {
  class PercentPipe {
    _locale;
    constructor(_locale) {
      this._locale = _locale;
    }
    /**
     *
     * @param value The number to be formatted as a percentage.
     * @param digitsInfo Decimal representation options, specified by a string
     * in the following format:<br>
     * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
     *   - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
     * Default is `1`.
     *   - `minFractionDigits`: The minimum number of digits after the decimal point.
     * Default is `0`.
     *   - `maxFractionDigits`: The maximum number of digits after the decimal point.
     * Default is `0`.
     * @param locale A locale code for the locale format rules to use.
     * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
     * See [Setting your app locale](guide/i18n/locale-id).
     */
    transform(value, digitsInfo, locale) {
      if (!isValue(value)) return null;
      locale ||= this._locale;
      try {
        const num = strToNumber(value);
        return formatPercent(num, locale, digitsInfo);
      } catch (error) {
        throw invalidPipeArgumentError(PercentPipe, error.message);
      }
    }
    static ɵfac = (() => function PercentPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PercentPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "percent",
      type: PercentPipe,
      pure: true
    }))();
  }
  return PercentPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @ngModule CommonModule
 * @description
 *
 * Transforms a number to a currency string, formatted according to locale rules
 * that determine group sizing and separator, decimal-point character,
 * and other locale-specific configurations.
 *
 *
 * @see {@link getCurrencySymbol}
 * @see {@link formatCurrency}
 *
 * @usageNotes
 * The following code shows how the pipe transforms numbers
 * into text strings, according to various format specifications,
 * where the caller's default locale is `en-US`.
 *
 * <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example>
 *
 * @publicApi
 */
let CurrencyPipe = /*#__PURE__*/(() => {
  class CurrencyPipe {
    _locale;
    _defaultCurrencyCode;
    constructor(_locale, _defaultCurrencyCode = 'USD') {
      this._locale = _locale;
      this._defaultCurrencyCode = _defaultCurrencyCode;
    }
    transform(value, currencyCode = this._defaultCurrencyCode, display = 'symbol', digitsInfo, locale) {
      if (!isValue(value)) return null;
      locale ||= this._locale;
      if (typeof display === 'boolean') {
        if ((typeof ngDevMode === 'undefined' || ngDevMode) && console && console.warn) {
          console.warn(`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`);
        }
        display = display ? 'symbol' : 'code';
      }
      let currency = currencyCode || this._defaultCurrencyCode;
      if (display !== 'code') {
        if (display === 'symbol' || display === 'symbol-narrow') {
          currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);
        } else {
          currency = display;
        }
      }
      try {
        const num = strToNumber(value);
        return formatCurrency(num, locale, currency, currencyCode, digitsInfo);
      } catch (error) {
        throw invalidPipeArgumentError(CurrencyPipe, error.message);
      }
    }
    static ɵfac = (() => function CurrencyPipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || CurrencyPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.LOCALE_ID, 16), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_CURRENCY_CODE, 16));
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "currency",
      type: CurrencyPipe,
      pure: true
    }))();
  }
  return CurrencyPipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function isValue(value) {
  return !(value == null || value === '' || value !== value);
}
/**
 * Transforms a string into a number (if needed).
 */
function strToNumber(value) {
  // Convert strings to numbers
  if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
    return Number(value);
  }
  if (typeof value !== 'number') {
    throw new Error(`${value} is not a number`);
  }
  return value;
}

/**
 * @ngModule CommonModule
 * @description
 *
 * Creates a new `Array` or `String` containing a subset (slice) of the elements.
 *
 * @usageNotes
 *
 * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`
 * and `String.prototype.slice()`.
 *
 * When operating on an `Array`, the returned `Array` is always a copy even when all
 * the elements are being returned.
 *
 * When operating on a blank value, the pipe returns the blank value.
 *
 * ### List Example
 *
 * This `ngFor` example:
 *
 * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}
 *
 * produces the following:
 *
 * ```html
 * <li>b</li>
 * <li>c</li>
 * ```
 *
 * ### String Examples
 *
 * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'}
 *
 * @publicApi
 */
let SlicePipe = /*#__PURE__*/(() => {
  class SlicePipe {
    transform(value, start, end) {
      if (value == null) return null;
      if (!this.supports(value)) {
        throw invalidPipeArgumentError(SlicePipe, value);
      }
      return value.slice(start, end);
    }
    supports(obj) {
      return typeof obj === 'string' || Array.isArray(obj);
    }
    static ɵfac = (() => function SlicePipe_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || SlicePipe)();
    })();
    static ɵpipe = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefinePipe"]({
      name: "slice",
      type: SlicePipe,
      pure: false
    }))();
  }
  return SlicePipe;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @module
 * @description
 * This module provides a set of common Pipes.
 */
/**
 * A collection of Angular pipes that are likely to be used in each and every application.
 */
const COMMON_PIPES = [AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe];

// Note: This does not contain the location providers,
// as they need some platform specific implementations to work.
/**
 * Exports all the basic Angular directives and pipes,
 * such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on.
 * Re-exported by `BrowserModule`, which is included automatically in the root
 * `AppModule` when you create a new app with the CLI `new` command.
 *
 * @publicApi
 */
let CommonModule = /*#__PURE__*/(() => {
  class CommonModule {
    static ɵfac = (() => function CommonModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || CommonModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({
      type: CommonModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({}))();
  }
  return CommonModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const PLATFORM_BROWSER_ID = 'browser';
const PLATFORM_SERVER_ID = 'server';
/**
 * Returns whether a platform id represents a browser platform.
 * @publicApi
 */
function isPlatformBrowser(platformId) {
  return platformId === PLATFORM_BROWSER_ID;
}
/**
 * Returns whether a platform id represents a server platform.
 * @publicApi
 */
function isPlatformServer(platformId) {
  return platformId === PLATFORM_SERVER_ID;
}

/**
 * @module
 * @description
 * Entry point for all public APIs of the common package.
 */
/**
 * @publicApi
 */
const VERSION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.Version('19.0.0');

/**
 * Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
 *
 * @publicApi
 */
let ViewportScroller = /*#__PURE__*/(() => {
  class ViewportScroller {
    // De-sugared tree-shakable injection
    // See #23917
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"])({
      token: ViewportScroller,
      providedIn: 'root',
      factory: () => isPlatformBrowser((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID)) ? new BrowserViewportScroller((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT), window) : new NullViewportScroller()
    }))();
  }
  return ViewportScroller;
})();
/**
 * Manages the scroll position for a browser window.
 */
class BrowserViewportScroller {
  document;
  window;
  offset = () => [0, 0];
  constructor(document, window) {
    this.document = document;
    this.window = window;
  }
  /**
   * Configures the top offset used when scrolling to an anchor.
   * @param offset A position in screen coordinates (a tuple with x and y values)
   * or a function that returns the top offset position.
   *
   */
  setOffset(offset) {
    if (Array.isArray(offset)) {
      this.offset = () => offset;
    } else {
      this.offset = offset;
    }
  }
  /**
   * Retrieves the current scroll position.
   * @returns The position in screen coordinates.
   */
  getScrollPosition() {
    return [this.window.scrollX, this.window.scrollY];
  }
  /**
   * Sets the scroll position.
   * @param position The new position in screen coordinates.
   */
  scrollToPosition(position) {
    this.window.scrollTo(position[0], position[1]);
  }
  /**
   * Scrolls to an element and attempts to focus the element.
   *
   * Note that the function name here is misleading in that the target string may be an ID for a
   * non-anchor element.
   *
   * @param target The ID of an element or name of the anchor.
   *
   * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document
   * @see https://html.spec.whatwg.org/#scroll-to-fragid
   */
  scrollToAnchor(target) {
    const elSelected = findAnchorFromDocument(this.document, target);
    if (elSelected) {
      this.scrollToElement(elSelected);
      // After scrolling to the element, the spec dictates that we follow the focus steps for the
      // target. Rather than following the robust steps, simply attempt focus.
      //
      // @see https://html.spec.whatwg.org/#get-the-focusable-area
      // @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus
      // @see https://html.spec.whatwg.org/#focusable-area
      elSelected.focus();
    }
  }
  /**
   * Disables automatic scroll restoration provided by the browser.
   */
  setHistoryScrollRestoration(scrollRestoration) {
    this.window.history.scrollRestoration = scrollRestoration;
  }
  /**
   * Scrolls to an element using the native offset and the specified offset set on this scroller.
   *
   * The offset can be used when we know that there is a floating header and scrolling naively to an
   * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header.
   */
  scrollToElement(el) {
    const rect = el.getBoundingClientRect();
    const left = rect.left + this.window.pageXOffset;
    const top = rect.top + this.window.pageYOffset;
    const offset = this.offset();
    this.window.scrollTo(left - offset[0], top - offset[1]);
  }
}
function findAnchorFromDocument(document, target) {
  const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
  if (documentResult) {
    return documentResult;
  }
  // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we
  // have to traverse the DOM manually and do the lookup through the shadow roots.
  if (typeof document.createTreeWalker === 'function' && document.body && typeof document.body.attachShadow === 'function') {
    const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
    let currentNode = treeWalker.currentNode;
    while (currentNode) {
      const shadowRoot = currentNode.shadowRoot;
      if (shadowRoot) {
        // Note that `ShadowRoot` doesn't support `getElementsByName`
        // so we have to fall back to `querySelector`.
        const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
        if (result) {
          return result;
        }
      }
      currentNode = treeWalker.nextNode();
    }
  }
  return null;
}
/**
 * Provides an empty implementation of the viewport scroller.
 */
class NullViewportScroller {
  /**
   * Empty implementation
   */
  setOffset(offset) {}
  /**
   * Empty implementation
   */
  getScrollPosition() {
    return [0, 0];
  }
  /**
   * Empty implementation
   */
  scrollToPosition(position) {}
  /**
   * Empty implementation
   */
  scrollToAnchor(anchor) {}
  /**
   * Empty implementation
   */
  setHistoryScrollRestoration(scrollRestoration) {}
}

/**
 * A wrapper around the `XMLHttpRequest` constructor.
 *
 * @publicApi
 */
class XhrFactory {}

/**
 * Value (out of 100) of the requested quality for placeholder images.
 */
const PLACEHOLDER_QUALITY = '20';

// Converts a string that represents a URL into a URL class instance.
function getUrl(src, win) {
  // Don't use a base URL is the URL is absolute.
  return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href);
}
// Checks whether a URL is absolute (i.e. starts with `http://` or `https://`).
function isAbsoluteUrl(src) {
  return /^https?:\/\//.test(src);
}
// Given a URL, extract the hostname part.
// If a URL is a relative one - the URL is returned as is.
function extractHostname(url) {
  return isAbsoluteUrl(url) ? new URL(url).hostname : url;
}
function isValidPath(path) {
  const isString = typeof path === 'string';
  if (!isString || path.trim() === '') {
    return false;
  }
  // Calling new URL() will throw if the path string is malformed
  try {
    const url = new URL(path);
    return true;
  } catch {
    return false;
  }
}
function normalizePath(path) {
  return path.endsWith('/') ? path.slice(0, -1) : path;
}
function normalizeSrc(src) {
  return src.startsWith('/') ? src.slice(1) : src;
}

/**
 * Noop image loader that does no transformation to the original src and just returns it as is.
 * This loader is used as a default one if more specific logic is not provided in an app config.
 *
 * @see {@link ImageLoader}
 * @see {@link NgOptimizedImage}
 */
const noopImageLoader = config => config.src;
/**
 * Injection token that configures the image loader function.
 *
 * @see {@link ImageLoader}
 * @see {@link NgOptimizedImage}
 * @publicApi
 */
const IMAGE_LOADER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'ImageLoader' : '', {
  providedIn: 'root',
  factory: () => noopImageLoader
});
/**
 * Internal helper function that makes it easier to introduce custom image loaders for the
 * `NgOptimizedImage` directive. It is enough to specify a URL builder function to obtain full DI
 * configuration for a given loader: a DI token corresponding to the actual loader function, plus DI
 * tokens managing preconnect check functionality.
 * @param buildUrlFn a function returning a full URL based on loader's configuration
 * @param exampleUrls example of full URLs for a given loader (used in error messages)
 * @returns a set of DI providers corresponding to the configured image loader
 */
function createImageLoader(buildUrlFn, exampleUrls) {
  return function provideImageLoader(path) {
    if (!isValidPath(path)) {
      throwInvalidPathError(path, exampleUrls || []);
    }
    // The trailing / is stripped (if provided) to make URL construction (concatenation) easier in
    // the individual loader functions.
    path = normalizePath(path);
    const loaderFn = config => {
      if (isAbsoluteUrl(config.src)) {
        // Image loader functions expect an image file name (e.g. `my-image.png`)
        // or a relative path + a file name (e.g. `/a/b/c/my-image.png`) as an input,
        // so the final absolute URL can be constructed.
        // When an absolute URL is provided instead - the loader can not
        // build a final URL, thus the error is thrown to indicate that.
        throwUnexpectedAbsoluteUrlError(path, config.src);
      }
      return buildUrlFn(path, {
        ...config,
        src: normalizeSrc(config.src)
      });
    };
    const providers = [{
      provide: IMAGE_LOADER,
      useValue: loaderFn
    }];
    return providers;
  };
}
function throwInvalidPathError(path, exampleUrls) {
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode && `Image loader has detected an invalid path (\`${path}\`). ` + `To fix this, supply a path using one of the following formats: ${exampleUrls.join(' or ')}`);
}
function throwUnexpectedAbsoluteUrlError(path, url) {
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode && `Image loader has detected a \`<img>\` tag with an invalid \`ngSrc\` attribute: ${url}. ` + `This image loader expects \`ngSrc\` to be a relative URL - ` + `however the provided value is an absolute URL. ` + `To fix this, provide \`ngSrc\` as a path relative to the base URL ` + `configured for this loader (\`${path}\`).`);
}

/**
 * Function that generates an ImageLoader for [Cloudflare Image
 * Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular
 * provider. Note: Cloudflare has multiple image products - this provider is specifically for
 * Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish.
 *
 * @param path Your domain name, e.g. https://mysite.com
 * @returns Provider that provides an ImageLoader function
 *
 * @publicApi
 */
const provideCloudflareLoader = /*#__PURE__*/createImageLoader(createCloudflareUrl, ngDevMode ? ['https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>'] : undefined);
function createCloudflareUrl(path, config) {
  let params = `format=auto`;
  if (config.width) {
    params += `,width=${config.width}`;
  }
  // When requesting a placeholder image we ask for a low quality image to reduce the load time.
  if (config.isPlaceholder) {
    params += `,quality=${PLACEHOLDER_QUALITY}`;
  }
  // Cloudflare image URLs format:
  // https://developers.cloudflare.com/images/image-resizing/url-format/
  return `${path}/cdn-cgi/image/${params}/${config.src}`;
}

/**
 * Name and URL tester for Cloudinary.
 */
const cloudinaryLoaderInfo = {
  name: 'Cloudinary',
  testUrl: isCloudinaryUrl
};
const CLOUDINARY_LOADER_REGEX = /https?\:\/\/[^\/]+\.cloudinary\.com\/.+/;
/**
 * Tests whether a URL is from Cloudinary CDN.
 */
function isCloudinaryUrl(url) {
  return CLOUDINARY_LOADER_REGEX.test(url);
}
/**
 * Function that generates an ImageLoader for Cloudinary and turns it into an Angular provider.
 *
 * @param path Base URL of your Cloudinary images
 * This URL should match one of the following formats:
 * https://res.cloudinary.com/mysite
 * https://mysite.cloudinary.com
 * https://subdomain.mysite.com
 * @returns Set of providers to configure the Cloudinary loader.
 *
 * @publicApi
 */
const provideCloudinaryLoader = /*#__PURE__*/createImageLoader(createCloudinaryUrl, ngDevMode ? ['https://res.cloudinary.com/mysite', 'https://mysite.cloudinary.com', 'https://subdomain.mysite.com'] : undefined);
function createCloudinaryUrl(path, config) {
  // Cloudinary image URLformat:
  // https://cloudinary.com/documentation/image_transformations#transformation_url_structure
  // Example of a Cloudinary image URL:
  // https://res.cloudinary.com/mysite/image/upload/c_scale,f_auto,q_auto,w_600/marketing/tile-topics-m.png
  // For a placeholder image, we use the lowest image setting available to reduce the load time
  // else we use the auto size
  const quality = config.isPlaceholder ? 'q_auto:low' : 'q_auto';
  let params = `f_auto,${quality}`;
  if (config.width) {
    params += `,w_${config.width}`;
  }
  if (config.loaderParams?.['rounded']) {
    params += `,r_max`;
  }
  return `${path}/image/upload/${params}/${config.src}`;
}

/**
 * Name and URL tester for ImageKit.
 */
const imageKitLoaderInfo = {
  name: 'ImageKit',
  testUrl: isImageKitUrl
};
const IMAGE_KIT_LOADER_REGEX = /https?\:\/\/[^\/]+\.imagekit\.io\/.+/;
/**
 * Tests whether a URL is from ImageKit CDN.
 */
function isImageKitUrl(url) {
  return IMAGE_KIT_LOADER_REGEX.test(url);
}
/**
 * Function that generates an ImageLoader for ImageKit and turns it into an Angular provider.
 *
 * @param path Base URL of your ImageKit images
 * This URL should match one of the following formats:
 * https://ik.imagekit.io/myaccount
 * https://subdomain.mysite.com
 * @returns Set of providers to configure the ImageKit loader.
 *
 * @publicApi
 */
const provideImageKitLoader = /*#__PURE__*/createImageLoader(createImagekitUrl, ngDevMode ? ['https://ik.imagekit.io/mysite', 'https://subdomain.mysite.com'] : undefined);
function createImagekitUrl(path, config) {
  // Example of an ImageKit image URL:
  // https://ik.imagekit.io/demo/tr:w-300,h-300/medium_cafe_B1iTdD0C.jpg
  const {
    src,
    width
  } = config;
  const params = [];
  if (width) {
    params.push(`w-${width}`);
  }
  // When requesting a placeholder image we ask for a low quality image to reduce the load time.
  if (config.isPlaceholder) {
    params.push(`q-${PLACEHOLDER_QUALITY}`);
  }
  const urlSegments = params.length ? [path, `tr:${params.join(',')}`, src] : [path, src];
  const url = new URL(urlSegments.join('/'));
  return url.href;
}

/**
 * Name and URL tester for Imgix.
 */
const imgixLoaderInfo = {
  name: 'Imgix',
  testUrl: isImgixUrl
};
const IMGIX_LOADER_REGEX = /https?\:\/\/[^\/]+\.imgix\.net\/.+/;
/**
 * Tests whether a URL is from Imgix CDN.
 */
function isImgixUrl(url) {
  return IMGIX_LOADER_REGEX.test(url);
}
/**
 * Function that generates an ImageLoader for Imgix and turns it into an Angular provider.
 *
 * @param path path to the desired Imgix origin,
 * e.g. https://somepath.imgix.net or https://images.mysite.com
 * @returns Set of providers to configure the Imgix loader.
 *
 * @publicApi
 */
const provideImgixLoader = /*#__PURE__*/createImageLoader(createImgixUrl, ngDevMode ? ['https://somepath.imgix.net/'] : undefined);
function createImgixUrl(path, config) {
  const url = new URL(`${path}/${config.src}`);
  // This setting ensures the smallest allowable format is set.
  url.searchParams.set('auto', 'format');
  if (config.width) {
    url.searchParams.set('w', config.width.toString());
  }
  // When requesting a placeholder image we ask a low quality image to reduce the load time.
  if (config.isPlaceholder) {
    url.searchParams.set('q', PLACEHOLDER_QUALITY);
  }
  return url.href;
}

/**
 * Name and URL tester for Netlify.
 */
const netlifyLoaderInfo = {
  name: 'Netlify',
  testUrl: isNetlifyUrl
};
const NETLIFY_LOADER_REGEX = /https?\:\/\/[^\/]+\.netlify\.app\/.+/;
/**
 * Tests whether a URL is from a Netlify site. This won't catch sites with a custom domain,
 * but it's a good start for sites in development. This is only used to warn users who haven't
 * configured an image loader.
 */
function isNetlifyUrl(url) {
  return NETLIFY_LOADER_REGEX.test(url);
}
/**
 * Function that generates an ImageLoader for Netlify and turns it into an Angular provider.
 *
 * @param path optional URL of the desired Netlify site. Defaults to the current site.
 * @returns Set of providers to configure the Netlify loader.
 *
 * @publicApi
 */
function provideNetlifyLoader(path) {
  if (path && !isValidPath(path)) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode && `Image loader has detected an invalid path (\`${path}\`). ` + `To fix this, supply either the full URL to the Netlify site, or leave it empty to use the current site.`);
  }
  if (path) {
    const url = new URL(path);
    path = url.origin;
  }
  const loaderFn = config => {
    return createNetlifyUrl(config, path);
  };
  const providers = [{
    provide: IMAGE_LOADER,
    useValue: loaderFn
  }];
  return providers;
}
const validParams = /*#__PURE__*/new Map([['height', 'h'], ['fit', 'fit'], ['quality', 'q'], ['q', 'q'], ['position', 'position']]);
function createNetlifyUrl(config, path) {
  // Note: `path` can be undefined, in which case we use a fake one to construct a `URL` instance.
  const url = new URL(path ?? 'https://a/');
  url.pathname = '/.netlify/images';
  if (!isAbsoluteUrl(config.src) && !config.src.startsWith('/')) {
    config.src = '/' + config.src;
  }
  url.searchParams.set('url', config.src);
  if (config.width) {
    url.searchParams.set('w', config.width.toString());
  }
  // When requesting a placeholder image we ask for a low quality image to reduce the load time.
  // If the quality is specified in the loader config - always use provided value.
  const configQuality = config.loaderParams?.['quality'] ?? config.loaderParams?.['q'];
  if (config.isPlaceholder && !configQuality) {
    url.searchParams.set('q', PLACEHOLDER_QUALITY);
  }
  for (const [param, value] of Object.entries(config.loaderParams ?? {})) {
    if (validParams.has(param)) {
      url.searchParams.set(validParams.get(param), value.toString());
    } else {
      if (ngDevMode) {
        console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, `The Netlify image loader has detected an \`<img>\` tag with the unsupported attribute "\`${param}\`".`));
      }
    }
  }
  // The "a" hostname is used for relative URLs, so we can remove it from the final URL.
  return url.hostname === 'a' ? url.href.replace(url.origin, '') : url.href;
}

// Assembles directive details string, useful for error messages.
function imgDirectiveDetails(ngSrc, includeNgSrc = true) {
  const ngSrcInfo = includeNgSrc ? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) ` : '';
  return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;
}

/**
 * Asserts that the application is in development mode. Throws an error if the application is in
 * production mode. This assert can be used to make sure that there is no dev-mode code invoked in
 * the prod mode accidentally.
 */
function assertDevMode(checkName) {
  if (!ngDevMode) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2958 /* RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE */, `Unexpected invocation of the ${checkName} in the prod mode. ` + `Please make sure that the prod mode is enabled for production builds.`);
  }
}

/**
 * Observer that detects whether an image with `NgOptimizedImage`
 * is treated as a Largest Contentful Paint (LCP) element. If so,
 * asserts that the image has the `priority` attribute.
 *
 * Note: this is a dev-mode only class and it does not appear in prod bundles,
 * thus there is no `ngDevMode` use in the code.
 *
 * Based on https://web.dev/lcp/#measure-lcp-in-javascript.
 */
let LCPImageObserver = /*#__PURE__*/(() => {
  class LCPImageObserver {
    // Map of full image URLs -> original `ngSrc` values.
    images = (() => new Map())();
    window = null;
    observer = null;
    constructor() {
      const isBrowser = isPlatformBrowser((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID));
      assertDevMode('LCP checker');
      const win = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT).defaultView;
      if (isBrowser && typeof PerformanceObserver !== 'undefined') {
        this.window = win;
        this.observer = this.initPerformanceObserver();
      }
    }
    /**
     * Inits PerformanceObserver and subscribes to LCP events.
     * Based on https://web.dev/lcp/#measure-lcp-in-javascript
     */
    initPerformanceObserver() {
      const observer = new PerformanceObserver(entryList => {
        const entries = entryList.getEntries();
        if (entries.length === 0) return;
        // We use the latest entry produced by the `PerformanceObserver` as the best
        // signal on which element is actually an LCP one. As an example, the first image to load on
        // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
        // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
        const lcpElement = entries[entries.length - 1];
        // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
        // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
        const imgSrc = lcpElement.element?.src ?? '';
        // Exclude `data:` and `blob:` URLs, since they are not supported by the directive.
        if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:')) return;
        const img = this.images.get(imgSrc);
        if (!img) return;
        if (!img.priority && !img.alreadyWarnedPriority) {
          img.alreadyWarnedPriority = true;
          logMissingPriorityError(imgSrc);
        }
        if (img.modified && !img.alreadyWarnedModified) {
          img.alreadyWarnedModified = true;
          logModifiedWarning(imgSrc);
        }
      });
      observer.observe({
        type: 'largest-contentful-paint',
        buffered: true
      });
      return observer;
    }
    registerImage(rewrittenSrc, originalNgSrc, isPriority) {
      if (!this.observer) return;
      const newObservedImageState = {
        priority: isPriority,
        modified: false,
        alreadyWarnedModified: false,
        alreadyWarnedPriority: false
      };
      this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);
    }
    unregisterImage(rewrittenSrc) {
      if (!this.observer) return;
      this.images.delete(getUrl(rewrittenSrc, this.window).href);
    }
    updateImage(originalSrc, newSrc) {
      if (!this.observer) return;
      const originalUrl = getUrl(originalSrc, this.window).href;
      const img = this.images.get(originalUrl);
      if (img) {
        img.modified = true;
        this.images.set(getUrl(newSrc, this.window).href, img);
        this.images.delete(originalUrl);
      }
    }
    ngOnDestroy() {
      if (!this.observer) return;
      this.observer.disconnect();
      this.images.clear();
    }
    static ɵfac = (() => function LCPImageObserver_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || LCPImageObserver)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: LCPImageObserver,
      factory: LCPImageObserver.ɵfac,
      providedIn: 'root'
    }))();
  }
  return LCPImageObserver;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function logMissingPriorityError(ngSrc) {
  const directiveDetails = imgDirectiveDetails(ngSrc);
  console.error((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2955 /* RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element but was not marked "priority". This image should be marked ` + `"priority" in order to prioritize its loading. ` + `To fix this, add the "priority" attribute.`));
}
function logModifiedWarning(ngSrc) {
  const directiveDetails = imgDirectiveDetails(ngSrc);
  console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2964 /* RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element and has had its "ngSrc" attribute modified. This can cause ` + `slower loading performance. It is recommended not to modify the "ngSrc" ` + `property on any image which could be the LCP element.`));
}

// Set of origins that are always excluded from the preconnect checks.
const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = /*#__PURE__*/new Set(['localhost', '127.0.0.1', '0.0.0.0']);
/**
 * Injection token to configure which origins should be excluded
 * from the preconnect checks. It can either be a single string or an array of strings
 * to represent a group of origins, for example:
 *
 * ```typescript
 *  {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}
 * ```
 *
 * or:
 *
 * ```typescript
 *  {provide: PRECONNECT_CHECK_BLOCKLIST,
 *   useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']}
 * ```
 *
 * @publicApi
 */
const PRECONNECT_CHECK_BLOCKLIST = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'PRECONNECT_CHECK_BLOCKLIST' : '');
/**
 * Contains the logic to detect whether an image, marked with the "priority" attribute
 * has a corresponding `<link rel="preconnect">` tag in the `document.head`.
 *
 * Note: this is a dev-mode only class, which should not appear in prod bundles,
 * thus there is no `ngDevMode` use in the code.
 */
let PreconnectLinkChecker = /*#__PURE__*/(() => {
  class PreconnectLinkChecker {
    document = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT))();
    isServer = (() => isPlatformServer((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID)))();
    /**
     * Set of <link rel="preconnect"> tags found on this page.
     * The `null` value indicates that there was no DOM query operation performed.
     */
    preconnectLinks = null;
    /*
     * Keep track of all already seen origin URLs to avoid repeating the same check.
     */
    alreadySeen = (() => new Set())();
    window = null;
    blocklist = (() => new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST))();
    constructor() {
      assertDevMode('preconnect link checker');
      const win = this.document.defaultView;
      if (typeof win !== 'undefined') {
        this.window = win;
      }
      const blocklist = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(PRECONNECT_CHECK_BLOCKLIST, {
        optional: true
      });
      if (blocklist) {
        this.populateBlocklist(blocklist);
      }
    }
    populateBlocklist(origins) {
      if (Array.isArray(origins)) {
        deepForEach(origins, origin => {
          this.blocklist.add(extractHostname(origin));
        });
      } else {
        this.blocklist.add(extractHostname(origins));
      }
    }
    /**
     * Checks that a preconnect resource hint exists in the head for the
     * given src.
     *
     * @param rewrittenSrc src formatted with loader
     * @param originalNgSrc ngSrc value
     */
    assertPreconnect(rewrittenSrc, originalNgSrc) {
      if (this.isServer) return;
      const imgUrl = getUrl(rewrittenSrc, this.window);
      if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin)) return;
      // Register this origin as seen, so we don't check it again later.
      this.alreadySeen.add(imgUrl.origin);
      // Note: we query for preconnect links only *once* and cache the results
      // for the entire lifespan of an application, since it's unlikely that the
      // list would change frequently. This allows to make sure there are no
      // performance implications of making extra DOM lookups for each image.
      this.preconnectLinks ??= this.queryPreconnectLinks();
      if (!this.preconnectLinks.has(imgUrl.origin)) {
        console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2956 /* RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG */, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` + `image. Preconnecting to the origin(s) that serve priority images ensures that these ` + `images are delivered as soon as possible. To fix this, please add the following ` + `element into the <head> of the document:\n` + `  <link rel="preconnect" href="${imgUrl.origin}">`));
      }
    }
    queryPreconnectLinks() {
      const preconnectUrls = new Set();
      const selector = 'link[rel=preconnect]';
      const links = Array.from(this.document.querySelectorAll(selector));
      for (let link of links) {
        const url = getUrl(link.href, this.window);
        preconnectUrls.add(url.origin);
      }
      return preconnectUrls;
    }
    ngOnDestroy() {
      this.preconnectLinks?.clear();
      this.alreadySeen.clear();
    }
    static ɵfac = (() => function PreconnectLinkChecker_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PreconnectLinkChecker)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PreconnectLinkChecker,
      factory: PreconnectLinkChecker.ɵfac,
      providedIn: 'root'
    }))();
  }
  return PreconnectLinkChecker;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Invokes a callback for each element in the array. Also invokes a callback
 * recursively for each nested array.
 */
function deepForEach(input, fn) {
  for (let value of input) {
    Array.isArray(value) ? deepForEach(value, fn) : fn(value);
  }
}

/**
 * In SSR scenarios, a preload `<link>` element is generated for priority images.
 * Having a large number of preload tags may negatively affect the performance,
 * so we warn developers (by throwing an error) if the number of preloaded images
 * is above a certain threshold. This const specifies this threshold.
 */
const DEFAULT_PRELOADED_IMAGES_LIMIT = 5;
/**
 * Helps to keep track of priority images that already have a corresponding
 * preload tag (to avoid generating multiple preload tags with the same URL).
 *
 * This Set tracks the original src passed into the `ngSrc` input not the src after it has been
 * run through the specified `IMAGE_LOADER`.
 */
const PRELOADED_IMAGES = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('NG_OPTIMIZED_PRELOADED_IMAGES', {
  providedIn: 'root',
  factory: () => new Set()
});

/**
 * @description Contains the logic needed to track and add preload link tags to the `<head>` tag. It
 * will also track what images have already had preload link tags added so as to not duplicate link
 * tags.
 *
 * In dev mode this service will validate that the number of preloaded images does not exceed the
 * configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}.
 */
let PreloadLinkCreator = /*#__PURE__*/(() => {
  class PreloadLinkCreator {
    preloadedImages = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(PRELOADED_IMAGES))();
    document = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DOCUMENT))();
    /**
     * @description Add a preload `<link>` to the `<head>` of the `index.html` that is served from the
     * server while using Angular Universal and SSR to kick off image loads for high priority images.
     *
     * The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`)
     * properties used to set the corresponding attributes, `imagesizes` and `imagesrcset`
     * respectively, on the preload `<link>` tag so that the correctly sized image is preloaded from
     * the CDN.
     *
     * {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes}
     *
     * @param renderer The `Renderer2` passed in from the directive
     * @param src The original src of the image that is set on the `ngSrc` input.
     * @param srcset The parsed and formatted srcset created from the `ngSrcset` input
     * @param sizes The value of the `sizes` attribute passed in to the `<img>` tag
     */
    createPreloadLinkTag(renderer, src, srcset, sizes) {
      if (ngDevMode) {
        if (this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
          throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2961 /* RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES */, ngDevMode && `The \`NgOptimizedImage\` directive has detected that more than ` + `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` + `This might negatively affect an overall performance of the page. ` + `To fix this, remove the "priority" attribute from images with less priority.`);
        }
      }
      if (this.preloadedImages.has(src)) {
        return;
      }
      this.preloadedImages.add(src);
      const preload = renderer.createElement('link');
      renderer.setAttribute(preload, 'as', 'image');
      renderer.setAttribute(preload, 'href', src);
      renderer.setAttribute(preload, 'rel', 'preload');
      renderer.setAttribute(preload, 'fetchpriority', 'high');
      if (sizes) {
        renderer.setAttribute(preload, 'imageSizes', sizes);
      }
      if (srcset) {
        renderer.setAttribute(preload, 'imageSrcset', srcset);
      }
      renderer.appendChild(this.document.head, preload);
    }
    static ɵfac = (() => function PreloadLinkCreator_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PreloadLinkCreator)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PreloadLinkCreator,
      factory: PreloadLinkCreator.ɵfac,
      providedIn: 'root'
    }))();
  }
  return PreloadLinkCreator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,
 * an error is thrown. The image content (as a string) might be very long, thus making
 * it hard to read an error message if the entire string is included. This const defines
 * the number of characters that should be included into the error message. The rest
 * of the content is truncated.
 */
const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;
/**
 * RegExpr to determine whether a src in a srcset is using width descriptors.
 * Should match something like: "100w, 200w".
 */
const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/;
/**
 * RegExpr to determine whether a src in a srcset is using density descriptors.
 * Should match something like: "1x, 2x, 50x". Also supports decimals like "1.5x, 1.50x".
 */
const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d+(\.\d+)?x\s*(,|$)){1,})$/;
/**
 * Srcset values with a density descriptor higher than this value will actively
 * throw an error. Such densities are not permitted as they cause image sizes
 * to be unreasonably large and slow down LCP.
 */
const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
/**
 * Used only in error message text to communicate best practices, as we will
 * only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.
 */
const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
/**
 * Used in generating automatic density-based srcsets
 */
const DENSITY_SRCSET_MULTIPLIERS = [1, 2];
/**
 * Used to determine which breakpoints to use on full-width images
 */
const VIEWPORT_BREAKPOINT_CUTOFF = 640;
/**
 * Used to determine whether two aspect ratios are similar in value.
 */
const ASPECT_RATIO_TOLERANCE = 0.1;
/**
 * Used to determine whether the image has been requested at an overly
 * large size compared to the actual rendered image size (after taking
 * into account a typical device pixel ratio). In pixels.
 */
const OVERSIZED_IMAGE_TOLERANCE = 1000;
/**
 * Used to limit automatic srcset generation of very large sources for
 * fixed-size images. In pixels.
 */
const FIXED_SRCSET_WIDTH_LIMIT = 1920;
const FIXED_SRCSET_HEIGHT_LIMIT = 1080;
/**
 * Default blur radius of the CSS filter used on placeholder images, in pixels
 */
const PLACEHOLDER_BLUR_AMOUNT = 15;
/**
 * Placeholder dimension (height or width) limit in pixels. Angular produces a warning
 * when this limit is crossed.
 */
const PLACEHOLDER_DIMENSION_LIMIT = 1000;
/**
 * Used to warn or error when the user provides an overly large dataURL for the placeholder
 * attribute.
 * Character count of Base64 images is 1 character per byte, and base64 encoding is approximately
 * 33% larger than base images, so 4000 characters is around 3KB on disk and 10000 characters is
 * around 7.7KB. Experimentally, 4000 characters is about 20x20px in PNG or medium-quality JPEG
 * format, and 10,000 is around 50x50px, but there's quite a bit of variation depending on how the
 * image is saved.
 */
const DATA_URL_WARN_LIMIT = 4000;
const DATA_URL_ERROR_LIMIT = 10000;
/** Info about built-in loaders we can test for. */
const BUILT_IN_LOADERS = [imgixLoaderInfo, imageKitLoaderInfo, cloudinaryLoaderInfo, netlifyLoaderInfo];
/**
 * Threshold for the PRIORITY_TRUE_COUNT
 */
const PRIORITY_COUNT_THRESHOLD = 10;
/**
 * This count is used to log a devMode warning
 * when the count of directive instances with priority=true
 * exceeds the threshold PRIORITY_COUNT_THRESHOLD
 */
let IMGS_WITH_PRIORITY_ATTR_COUNT = 0;
/**
 * This function is for testing purpose.
 */
function resetImagePriorityCount() {
  IMGS_WITH_PRIORITY_ATTR_COUNT = 0;
}
/**
 * Directive that improves image loading performance by enforcing best practices.
 *
 * `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is
 * prioritized by:
 * - Automatically setting the `fetchpriority` attribute on the `<img>` tag
 * - Lazy loading non-priority images by default
 * - Automatically generating a preconnect link tag in the document head
 *
 * In addition, the directive:
 * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided
 * - Automatically generates a srcset
 * - Requires that `width` and `height` are set
 * - Warns if `width` or `height` have been set incorrectly
 * - Warns if the image will be visually distorted when rendered
 *
 * @usageNotes
 * The `NgOptimizedImage` directive is marked as [standalone](guide/components/importing) and can
 * be imported directly.
 *
 * Follow the steps below to enable and use the directive:
 * 1. Import it into the necessary NgModule or a standalone Component.
 * 2. Optionally provide an `ImageLoader` if you use an image hosting service.
 * 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `ngSrc`.
 * Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image
 * download.
 *
 * Step 1: import the `NgOptimizedImage` directive.
 *
 * ```typescript
 * import { NgOptimizedImage } from '@angular/common';
 *
 * // Include it into the necessary NgModule
 * @NgModule({
 *   imports: [NgOptimizedImage],
 * })
 * class AppModule {}
 *
 * // ... or a standalone Component
 * @Component({
 *   standalone: true
 *   imports: [NgOptimizedImage],
 * })
 * class MyStandaloneComponent {}
 * ```
 *
 * Step 2: configure a loader.
 *
 * To use the **default loader**: no additional code changes are necessary. The URL returned by the
 * generic loader will always match the value of "src". In other words, this loader applies no
 * transformations to the resource URL and the value of the `ngSrc` attribute will be used as is.
 *
 * To use an existing loader for a **third-party image service**: add the provider factory for your
 * chosen service to the `providers` array. In the example below, the Imgix loader is used:
 *
 * ```typescript
 * import {provideImgixLoader} from '@angular/common';
 *
 * // Call the function and add the result to the `providers` array:
 * providers: [
 *   provideImgixLoader("https://my.base.url/"),
 * ],
 * ```
 *
 * The `NgOptimizedImage` directive provides the following functions:
 * - `provideCloudflareLoader`
 * - `provideCloudinaryLoader`
 * - `provideImageKitLoader`
 * - `provideImgixLoader`
 *
 * If you use a different image provider, you can create a custom loader function as described
 * below.
 *
 * To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI
 * token.
 *
 * ```typescript
 * import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';
 *
 * // Configure the loader using the `IMAGE_LOADER` token.
 * providers: [
 *   {
 *      provide: IMAGE_LOADER,
 *      useValue: (config: ImageLoaderConfig) => {
 *        return `https://example.com/${config.src}-${config.width}.jpg`;
 *      }
 *   },
 * ],
 * ```
 *
 * Step 3: update `<img>` tags in templates to use `ngSrc` instead of `src`.
 *
 * ```
 * <img ngSrc="logo.png" width="200" height="100">
 * ```
 *
 * @publicApi
 */
let NgOptimizedImage = /*#__PURE__*/(() => {
  class NgOptimizedImage {
    imageLoader = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(IMAGE_LOADER))();
    config = (() => processConfig((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵIMAGE_CONFIG"])))();
    renderer = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.Renderer2))();
    imgElement = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ElementRef).nativeElement)();
    injector = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.Injector))();
    isServer = (() => isPlatformServer((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID)))();
    preloadLinkCreator = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(PreloadLinkCreator))();
    // a LCP image observer - should be injected only in the dev mode
    lcpObserver = (() => ngDevMode ? this.injector.get(LCPImageObserver) : null)();
    /**
     * Calculate the rewritten `src` once and store it.
     * This is needed to avoid repetitive calculations and make sure the directive cleanup in the
     * `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
     * instance that might be already destroyed).
     */
    _renderedSrc = null;
    /**
     * Name of the source image.
     * Image name will be processed by the image loader and the final URL will be applied as the `src`
     * property of the image.
     */
    ngSrc;
    /**
     * A comma separated list of width or density descriptors.
     * The image name will be taken from `ngSrc` and combined with the list of width or density
     * descriptors to generate the final `srcset` property of the image.
     *
     * Example:
     * ```
     * <img ngSrc="hello.jpg" ngSrcset="100w, 200w" />  =>
     * <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" />
     * ```
     */
    ngSrcset;
    /**
     * The base `sizes` attribute passed through to the `<img>` element.
     * Providing sizes causes the image to create an automatic responsive srcset.
     */
    sizes;
    /**
     * For responsive images: the intrinsic width of the image in pixels.
     * For fixed size images: the desired rendered width of the image in pixels.
     */
    width;
    /**
     * For responsive images: the intrinsic height of the image in pixels.
     * For fixed size images: the desired rendered height of the image in pixels.
     */
    height;
    /**
     * The desired loading behavior (lazy, eager, or auto). Defaults to `lazy`,
     * which is recommended for most images.
     *
     * Warning: Setting images as loading="eager" or loading="auto" marks them
     * as non-priority images and can hurt loading performance. For images which
     * may be the LCP element, use the `priority` attribute instead of `loading`.
     */
    loading;
    /**
     * Indicates whether this image should have a high priority.
     */
    priority = false;
    /**
     * Data to pass through to custom loaders.
     */
    loaderParams;
    /**
     * Disables automatic srcset generation for this image.
     */
    disableOptimizedSrcset = false;
    /**
     * Sets the image to "fill mode", which eliminates the height/width requirement and adds
     * styles such that the image fills its containing element.
     */
    fill = false;
    /**
     * A URL or data URL for an image to be used as a placeholder while this image loads.
     */
    placeholder;
    /**
     * Configuration object for placeholder settings. Options:
     *   * blur: Setting this to false disables the automatic CSS blur.
     */
    placeholderConfig;
    /**
     * Value of the `src` attribute if set on the host `<img>` element.
     * This input is exclusively read to assert that `src` is not set in conflict
     * with `ngSrc` and that images don't start to load until a lazy loading strategy is set.
     * @internal
     */
    src;
    /**
     * Value of the `srcset` attribute if set on the host `<img>` element.
     * This input is exclusively read to assert that `srcset` is not set in conflict
     * with `ngSrcset` and that images don't start to load until a lazy loading strategy is set.
     * @internal
     */
    srcset;
    /** @nodoc */
    ngOnInit() {
      (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵperformanceMarkFeature"])('NgOptimizedImage');
      if (ngDevMode) {
        const ngZone = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
        assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
        assertValidNgSrcset(this, this.ngSrcset);
        assertNoConflictingSrc(this);
        if (this.ngSrcset) {
          assertNoConflictingSrcset(this);
        }
        assertNotBase64Image(this);
        assertNotBlobUrl(this);
        if (this.fill) {
          assertEmptyWidthAndHeight(this);
          // This leaves the Angular zone to avoid triggering unnecessary change detection cycles when
          // `load` tasks are invoked on images.
          ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));
        } else {
          assertNonEmptyWidthAndHeight(this);
          if (this.height !== undefined) {
            assertGreaterThanZero(this, this.height, 'height');
          }
          if (this.width !== undefined) {
            assertGreaterThanZero(this, this.width, 'width');
          }
          // Only check for distorted images when not in fill mode, where
          // images may be intentionally stretched, cropped or letterboxed.
          ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));
        }
        assertValidLoadingInput(this);
        if (!this.ngSrcset) {
          assertNoComplexSizes(this);
        }
        assertValidPlaceholder(this, this.imageLoader);
        assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
        assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
        assertNoLoaderParamsWithoutLoader(this, this.imageLoader);
        if (this.lcpObserver !== null) {
          const ngZone = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
          ngZone.runOutsideAngular(() => {
            this.lcpObserver.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);
          });
        }
        if (this.priority) {
          const checker = this.injector.get(PreconnectLinkChecker);
          checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
          if (!this.isServer) {
            const applicationRef = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ApplicationRef);
            assetPriorityCountBelowThreshold(applicationRef);
          }
        }
      }
      if (this.placeholder) {
        this.removePlaceholderOnLoad(this.imgElement);
      }
      this.setHostAttributes();
    }
    setHostAttributes() {
      // Must set width/height explicitly in case they are bound (in which case they will
      // only be reflected and not found by the browser)
      if (this.fill) {
        this.sizes ||= '100vw';
      } else {
        this.setHostAttribute('width', this.width.toString());
        this.setHostAttribute('height', this.height.toString());
      }
      this.setHostAttribute('loading', this.getLoadingBehavior());
      this.setHostAttribute('fetchpriority', this.getFetchPriority());
      // The `data-ng-img` attribute flags an image as using the directive, to allow
      // for analysis of the directive's performance.
      this.setHostAttribute('ng-img', 'true');
      // The `src` and `srcset` attributes should be set last since other attributes
      // could affect the image's loading behavior.
      const rewrittenSrcset = this.updateSrcAndSrcset();
      if (this.sizes) {
        if (this.getLoadingBehavior() === 'lazy') {
          this.setHostAttribute('sizes', 'auto, ' + this.sizes);
        } else {
          this.setHostAttribute('sizes', this.sizes);
        }
      } else {
        if (this.ngSrcset && VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset) && this.getLoadingBehavior() === 'lazy') {
          this.setHostAttribute('sizes', 'auto, 100vw');
        }
      }
      if (this.isServer && this.priority) {
        this.preloadLinkCreator.createPreloadLinkTag(this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes);
      }
    }
    /** @nodoc */
    ngOnChanges(changes) {
      if (ngDevMode) {
        assertNoPostInitInputChange(this, changes, ['ngSrcset', 'width', 'height', 'priority', 'fill', 'loading', 'sizes', 'loaderParams', 'disableOptimizedSrcset']);
      }
      if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) {
        const oldSrc = this._renderedSrc;
        this.updateSrcAndSrcset(true);
        const newSrc = this._renderedSrc;
        if (this.lcpObserver !== null && oldSrc && newSrc && oldSrc !== newSrc) {
          const ngZone = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
          ngZone.runOutsideAngular(() => {
            this.lcpObserver?.updateImage(oldSrc, newSrc);
          });
        }
      }
      if (ngDevMode && changes['placeholder']?.currentValue && !this.isServer) {
        assertPlaceholderDimensions(this, this.imgElement);
      }
    }
    callImageLoader(configWithoutCustomParams) {
      let augmentedConfig = configWithoutCustomParams;
      if (this.loaderParams) {
        augmentedConfig.loaderParams = this.loaderParams;
      }
      return this.imageLoader(augmentedConfig);
    }
    getLoadingBehavior() {
      if (!this.priority && this.loading !== undefined) {
        return this.loading;
      }
      return this.priority ? 'eager' : 'lazy';
    }
    getFetchPriority() {
      return this.priority ? 'high' : 'auto';
    }
    getRewrittenSrc() {
      // ImageLoaderConfig supports setting a width property. However, we're not setting width here
      // because if the developer uses rendered width instead of intrinsic width in the HTML width
      // attribute, the image requested may be too small for 2x+ screens.
      if (!this._renderedSrc) {
        const imgConfig = {
          src: this.ngSrc
        };
        // Cache calculated image src to reuse it later in the code.
        this._renderedSrc = this.callImageLoader(imgConfig);
      }
      return this._renderedSrc;
    }
    getRewrittenSrcset() {
      const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset);
      const finalSrcs = this.ngSrcset.split(',').filter(src => src !== '').map(srcStr => {
        srcStr = srcStr.trim();
        const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width;
        return `${this.callImageLoader({
          src: this.ngSrc,
          width
        })} ${srcStr}`;
      });
      return finalSrcs.join(', ');
    }
    getAutomaticSrcset() {
      if (this.sizes) {
        return this.getResponsiveSrcset();
      } else {
        return this.getFixedSrcset();
      }
    }
    getResponsiveSrcset() {
      const {
        breakpoints
      } = this.config;
      let filteredBreakpoints = breakpoints;
      if (this.sizes?.trim() === '100vw') {
        // Since this is a full-screen-width image, our srcset only needs to include
        // breakpoints with full viewport widths.
        filteredBreakpoints = breakpoints.filter(bp => bp >= VIEWPORT_BREAKPOINT_CUTOFF);
      }
      const finalSrcs = filteredBreakpoints.map(bp => `${this.callImageLoader({
        src: this.ngSrc,
        width: bp
      })} ${bp}w`);
      return finalSrcs.join(', ');
    }
    updateSrcAndSrcset(forceSrcRecalc = false) {
      if (forceSrcRecalc) {
        // Reset cached value, so that the followup `getRewrittenSrc()` call
        // will recalculate it and update the cache.
        this._renderedSrc = null;
      }
      const rewrittenSrc = this.getRewrittenSrc();
      this.setHostAttribute('src', rewrittenSrc);
      let rewrittenSrcset = undefined;
      if (this.ngSrcset) {
        rewrittenSrcset = this.getRewrittenSrcset();
      } else if (this.shouldGenerateAutomaticSrcset()) {
        rewrittenSrcset = this.getAutomaticSrcset();
      }
      if (rewrittenSrcset) {
        this.setHostAttribute('srcset', rewrittenSrcset);
      }
      return rewrittenSrcset;
    }
    getFixedSrcset() {
      const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map(multiplier => `${this.callImageLoader({
        src: this.ngSrc,
        width: this.width * multiplier
      })} ${multiplier}x`);
      return finalSrcs.join(', ');
    }
    shouldGenerateAutomaticSrcset() {
      let oversizedImage = false;
      if (!this.sizes) {
        oversizedImage = this.width > FIXED_SRCSET_WIDTH_LIMIT || this.height > FIXED_SRCSET_HEIGHT_LIMIT;
      }
      return !this.disableOptimizedSrcset && !this.srcset && this.imageLoader !== noopImageLoader && !oversizedImage;
    }
    /**
     * Returns an image url formatted for use with the CSS background-image property. Expects one of:
     * * A base64 encoded image, which is wrapped and passed through.
     * * A boolean. If true, calls the image loader to generate a small placeholder url.
     */
    generatePlaceholder(placeholderInput) {
      const {
        placeholderResolution
      } = this.config;
      if (placeholderInput === true) {
        return `url(${this.callImageLoader({
          src: this.ngSrc,
          width: placeholderResolution,
          isPlaceholder: true
        })})`;
      } else if (typeof placeholderInput === 'string') {
        return `url(${placeholderInput})`;
      }
      return null;
    }
    /**
     * Determines if blur should be applied, based on an optional boolean
     * property `blur` within the optional configuration object `placeholderConfig`.
     */
    shouldBlurPlaceholder(placeholderConfig) {
      if (!placeholderConfig || !placeholderConfig.hasOwnProperty('blur')) {
        return true;
      }
      return Boolean(placeholderConfig.blur);
    }
    removePlaceholderOnLoad(img) {
      const callback = () => {
        const changeDetectorRef = this.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ChangeDetectorRef);
        removeLoadListenerFn();
        removeErrorListenerFn();
        this.placeholder = false;
        changeDetectorRef.markForCheck();
      };
      const removeLoadListenerFn = this.renderer.listen(img, 'load', callback);
      const removeErrorListenerFn = this.renderer.listen(img, 'error', callback);
      callOnLoadIfImageIsLoaded(img, callback);
    }
    /** @nodoc */
    ngOnDestroy() {
      if (ngDevMode) {
        if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) {
          this.lcpObserver.unregisterImage(this._renderedSrc);
        }
      }
    }
    setHostAttribute(name, value) {
      this.renderer.setAttribute(this.imgElement, name, value);
    }
    static ɵfac = (() => function NgOptimizedImage_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgOptimizedImage)();
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: NgOptimizedImage,
      selectors: [["img", "ngSrc", ""]],
      hostVars: 18,
      hostBindings: function NgOptimizedImage_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵstyleProp"]("position", ctx.fill ? "absolute" : null)("width", ctx.fill ? "100%" : null)("height", ctx.fill ? "100%" : null)("inset", ctx.fill ? "0" : null)("background-size", ctx.placeholder ? "cover" : null)("background-position", ctx.placeholder ? "50% 50%" : null)("background-repeat", ctx.placeholder ? "no-repeat" : null)("background-image", ctx.placeholder ? ctx.generatePlaceholder(ctx.placeholder) : null)("filter", ctx.placeholder && ctx.shouldBlurPlaceholder(ctx.placeholderConfig) ? "blur(15px)" : null);
        }
      },
      inputs: {
        ngSrc: [2, "ngSrc", "ngSrc", unwrapSafeUrl],
        ngSrcset: "ngSrcset",
        sizes: "sizes",
        width: [2, "width", "width", _angular_core__WEBPACK_IMPORTED_MODULE_1__.numberAttribute],
        height: [2, "height", "height", _angular_core__WEBPACK_IMPORTED_MODULE_1__.numberAttribute],
        loading: "loading",
        priority: [2, "priority", "priority", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        loaderParams: "loaderParams",
        disableOptimizedSrcset: [2, "disableOptimizedSrcset", "disableOptimizedSrcset", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        fill: [2, "fill", "fill", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        placeholder: [2, "placeholder", "placeholder", booleanOrUrlAttribute],
        placeholderConfig: "placeholderConfig",
        src: "src",
        srcset: "srcset"
      },
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵInputTransformsFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return NgOptimizedImage;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/***** Helpers *****/
/**
 * Sorts provided config breakpoints and uses defaults.
 */
function processConfig(config) {
  let sortedBreakpoints = {};
  if (config.breakpoints) {
    sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);
  }
  return Object.assign({}, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵIMAGE_CONFIG_DEFAULTS"], config, sortedBreakpoints);
}
/***** Assert functions *****/
/**
 * Verifies that there is no `src` set on a host element.
 */
function assertNoConflictingSrc(dir) {
  if (dir.src) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2950 /* RuntimeErrorCode.UNEXPECTED_SRC_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`src\` and \`ngSrc\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`src\` itself based on the value of \`ngSrc\`. ` + `To fix this, please remove the \`src\` attribute.`);
  }
}
/**
 * Verifies that there is no `srcset` set on a host element.
 */
function assertNoConflictingSrcset(dir) {
  if (dir.srcset) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2951 /* RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`srcset\` and \`ngSrcset\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`srcset\` itself based on the value of ` + `\`ngSrcset\`. To fix this, please remove the \`srcset\` attribute.`);
  }
}
/**
 * Verifies that the `ngSrc` is not a Base64-encoded image.
 */
function assertNotBase64Image(dir) {
  let ngSrc = dir.ngSrc.trim();
  if (ngSrc.startsWith('data:')) {
    if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {
      ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';
    }
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`ngSrc\` is a Base64-encoded string ` + `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a standard \`src\` attribute instead.`);
  }
}
/**
 * Verifies that the 'sizes' only includes responsive values.
 */
function assertNoComplexSizes(dir) {
  let sizes = dir.sizes;
  if (sizes?.match(/((\)|,)\s|^)\d+px/)) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` + `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` + `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` + `To fix this, modify the \`sizes\` attribute, or provide your own \`ngSrcset\` value directly.`);
  }
}
function assertValidPlaceholder(dir, imageLoader) {
  assertNoPlaceholderConfigWithoutPlaceholder(dir);
  assertNoRelativePlaceholderWithoutLoader(dir, imageLoader);
  assertNoOversizedDataUrl(dir);
}
/**
 * Verifies that placeholderConfig isn't being used without placeholder
 */
function assertNoPlaceholderConfigWithoutPlaceholder(dir) {
  if (dir.placeholderConfig && !dir.placeholder) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`placeholderConfig\` options were provided for an ` + `image that does not use the \`placeholder\` attribute, and will have no effect.`);
  }
}
/**
 * Warns if a relative URL placeholder is specified, but no loader is present to provide the small
 * image.
 */
function assertNoRelativePlaceholderWithoutLoader(dir, imageLoader) {
  if (dir.placeholder === true && imageLoader === noopImageLoader) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to true but ` + `no image loader is configured (i.e. the default one is being used), ` + `which would result in the same image being used for the primary image and its placeholder. ` + `To fix this, provide a loader or remove the \`placeholder\` attribute from the image.`);
  }
}
/**
 * Warns or throws an error if an oversized dataURL placeholder is provided.
 */
function assertNoOversizedDataUrl(dir) {
  if (dir.placeholder && typeof dir.placeholder === 'string' && dir.placeholder.startsWith('data:')) {
    if (dir.placeholder.length > DATA_URL_ERROR_LIMIT) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_ERROR_LIMIT} characters. This is strongly discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. To fix this, generate ` + `a smaller data URL placeholder.`);
    }
    if (dir.placeholder.length > DATA_URL_WARN_LIMIT) {
      console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_WARN_LIMIT} characters. This is discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. For better loading performance, ` + `generate a smaller data URL placeholder.`));
    }
  }
}
/**
 * Verifies that the `ngSrc` is not a Blob URL.
 */
function assertNotBlobUrl(dir) {
  const ngSrc = dir.ngSrc.trim();
  if (ngSrc.startsWith('blob:')) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrc\` was set to a blob URL (${ngSrc}). ` + `Blob URLs are not supported by the NgOptimizedImage directive. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a regular \`src\` attribute instead.`);
  }
}
/**
 * Verifies that the input is set to a non-empty string.
 */
function assertNonEmptyInput(dir, name, value) {
  const isString = typeof value === 'string';
  const isEmptyString = isString && value.trim() === '';
  if (!isString || isEmptyString) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${name}\` has an invalid value ` + `(\`${value}\`). To fix this, change the value to a non-empty string.`);
  }
}
/**
 * Verifies that the `ngSrcset` is in a valid format, e.g. "100w, 200w" or "1x, 2x".
 */
function assertValidNgSrcset(dir, value) {
  if (value == null) return;
  assertNonEmptyInput(dir, 'ngSrcset', value);
  const stringVal = value;
  const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);
  const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);
  if (isValidDensityDescriptor) {
    assertUnderDensityCap(dir, stringVal);
  }
  const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;
  if (!isValidSrcset) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrcset\` has an invalid value (\`${value}\`). ` + `To fix this, supply \`ngSrcset\` using a comma-separated list of one or more width ` + `descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`);
  }
}
function assertUnderDensityCap(dir, value) {
  const underDensityCap = value.split(',').every(num => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);
  if (!underDensityCap) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` contains an unsupported image density:` + `\`${value}\`. NgOptimizedImage generally recommends a max image density of ` + `${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` + `${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` + `greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` + `most use cases. Images that will be pinch-zoomed are typically the primary use case for ` + `${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`);
  }
}
/**
 * Creates a `RuntimeError` instance to represent a situation when an input is set after
 * the directive has initialized.
 */
function postInitInputChangeError(dir, inputName) {
  let reason;
  if (inputName === 'width' || inputName === 'height') {
    reason = `Changing \`${inputName}\` may result in different attribute value ` + `applied to the underlying image element and cause layout shifts on a page.`;
  } else {
    reason = `Changing the \`${inputName}\` would have no effect on the underlying ` + `image element, because the resource loading has already occurred.`;
  }
  return new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2953 /* RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` was updated after initialization. ` + `The NgOptimizedImage directive will not react to this input change. ${reason} ` + `To fix this, either switch \`${inputName}\` to a static value ` + `or wrap the image element in an *ngIf that is gated on the necessary value.`);
}
/**
 * Verify that none of the listed inputs has changed.
 */
function assertNoPostInitInputChange(dir, changes, inputs) {
  inputs.forEach(input => {
    const isUpdated = changes.hasOwnProperty(input);
    if (isUpdated && !changes[input].isFirstChange()) {
      if (input === 'ngSrc') {
        // When the `ngSrc` input changes, we detect that only in the
        // `ngOnChanges` hook, thus the `ngSrc` is already set. We use
        // `ngSrc` in the error message, so we use a previous value, but
        // not the updated one in it.
        dir = {
          ngSrc: changes[input].previousValue
        };
      }
      throw postInitInputChangeError(dir, input);
    }
  });
}
/**
 * Verifies that a specified input is a number greater than 0.
 */
function assertGreaterThanZero(dir, inputValue, inputName) {
  const validNumber = typeof inputValue === 'number' && inputValue > 0;
  const validString = typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;
  if (!validNumber && !validString) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` has an invalid value. ` + `To fix this, provide \`${inputName}\` as a number greater than 0.`);
  }
}
/**
 * Verifies that the rendered image is not visually distorted. Effectively this is checking:
 * - Whether the "width" and "height" attributes reflect the actual dimensions of the image.
 * - Whether image styling is "correct" (see below for a longer explanation).
 */
function assertNoImageDistortion(dir, img, renderer) {
  const callback = () => {
    removeLoadListenerFn();
    removeErrorListenerFn();
    const computedStyle = window.getComputedStyle(img);
    let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
    let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
    const boxSizing = computedStyle.getPropertyValue('box-sizing');
    if (boxSizing === 'border-box') {
      const paddingTop = computedStyle.getPropertyValue('padding-top');
      const paddingRight = computedStyle.getPropertyValue('padding-right');
      const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
      const paddingLeft = computedStyle.getPropertyValue('padding-left');
      renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
      renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
    }
    const renderedAspectRatio = renderedWidth / renderedHeight;
    const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;
    const intrinsicWidth = img.naturalWidth;
    const intrinsicHeight = img.naturalHeight;
    const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;
    const suppliedWidth = dir.width;
    const suppliedHeight = dir.height;
    const suppliedAspectRatio = suppliedWidth / suppliedHeight;
    // Tolerance is used to account for the impact of subpixel rendering.
    // Due to subpixel rendering, the rendered, intrinsic, and supplied
    // aspect ratios of a correctly configured image may not exactly match.
    // For example, a `width=4030 height=3020` image might have a rendered
    // size of "1062w, 796.48h". (An aspect ratio of 1.334... vs. 1.333...)
    const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;
    const stylingDistortion = nonZeroRenderedDimensions && Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;
    if (inaccurateDimensions) {
      console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` + `the aspect ratio indicated by the width and height attributes. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nSupplied width and height attributes: ` + `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round(suppliedAspectRatio)}). ` + `\nTo fix this, update the width and height attributes.`));
    } else if (stylingDistortion) {
      console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` + `does not match the image's intrinsic aspect ratio. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nRendered image size: ` + `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` + `${round(renderedAspectRatio)}). \nThis issue can occur if "width" and "height" ` + `attributes are added to an image without updating the corresponding ` + `image styling. To fix this, adjust image styling. In most cases, ` + `adding "height: auto" or "width: auto" to the image styling will fix ` + `this issue.`));
    } else if (!dir.ngSrcset && nonZeroRenderedDimensions) {
      // If `ngSrcset` hasn't been set, sanity check the intrinsic size.
      const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth;
      const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight;
      const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
      const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
      if (oversizedWidth || oversizedHeight) {
        console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2960 /* RuntimeErrorCode.OVERSIZED_IMAGE */, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` + `larger than necessary. ` + `\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` + `\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` + `\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` + `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` + `or consider using the "ngSrcset" and "sizes" attributes.`));
      }
    }
  };
  const removeLoadListenerFn = renderer.listen(img, 'load', callback);
  // We only listen to the `error` event to remove the `load` event listener because it will not be
  // fired if the image fails to load. This is done to prevent memory leaks in development mode
  // because image elements aren't garbage-collected properly. It happens because zone.js stores the
  // event listener directly on the element and closures capture `dir`.
  const removeErrorListenerFn = renderer.listen(img, 'error', () => {
    removeLoadListenerFn();
    removeErrorListenerFn();
  });
  callOnLoadIfImageIsLoaded(img, callback);
}
/**
 * Verifies that a specified input is set.
 */
function assertNonEmptyWidthAndHeight(dir) {
  let missingAttributes = [];
  if (dir.width === undefined) missingAttributes.push('width');
  if (dir.height === undefined) missingAttributes.push('height');
  if (missingAttributes.length > 0) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2954 /* RuntimeErrorCode.REQUIRED_INPUT_MISSING */, `${imgDirectiveDetails(dir.ngSrc)} these required attributes ` + `are missing: ${missingAttributes.map(attr => `"${attr}"`).join(', ')}. ` + `Including "width" and "height" attributes will prevent image-related layout shifts. ` + `To fix this, include "width" and "height" attributes on the image tag or turn on ` + `"fill" mode with the \`fill\` attribute.`);
  }
}
/**
 * Verifies that width and height are not set. Used in fill mode, where those attributes don't make
 * sense.
 */
function assertEmptyWidthAndHeight(dir) {
  if (dir.width || dir.height) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the attributes \`height\` and/or \`width\` are present ` + `along with the \`fill\` attribute. Because \`fill\` mode causes an image to fill its containing ` + `element, the size attributes have no effect and should be removed.`);
  }
}
/**
 * Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides
 * guidance that this can be caused by the containing element's CSS position property.
 */
function assertNonZeroRenderedHeight(dir, img, renderer) {
  const callback = () => {
    removeLoadListenerFn();
    removeErrorListenerFn();
    const renderedHeight = img.clientHeight;
    if (dir.fill && renderedHeight === 0) {
      console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` + `This is likely because the containing element does not have the CSS 'position' ` + `property set to one of the following: "relative", "fixed", or "absolute". ` + `To fix this problem, make sure the container element has the CSS 'position' ` + `property defined and the height of the element is not zero.`));
    }
  };
  const removeLoadListenerFn = renderer.listen(img, 'load', callback);
  // See comments in the `assertNoImageDistortion`.
  const removeErrorListenerFn = renderer.listen(img, 'error', () => {
    removeLoadListenerFn();
    removeErrorListenerFn();
  });
  callOnLoadIfImageIsLoaded(img, callback);
}
/**
 * Verifies that the `loading` attribute is set to a valid input &
 * is not used on priority images.
 */
function assertValidLoadingInput(dir) {
  if (dir.loading && dir.priority) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` + `was used on an image that was marked "priority". ` + `Setting \`loading\` on priority images is not allowed ` + `because these images will always be eagerly loaded. ` + `To fix this, remove the “loading” attribute from the priority image.`);
  }
  const validInputs = ['auto', 'eager', 'lazy'];
  if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` + `has an invalid value (\`${dir.loading}\`). ` + `To fix this, provide a valid value ("lazy", "eager", or "auto").`);
  }
}
/**
 * Warns if NOT using a loader (falling back to the generic loader) and
 * the image appears to be hosted on one of the image CDNs for which
 * we do have a built-in image loader. Suggests switching to the
 * built-in loader.
 *
 * @param ngSrc Value of the ngSrc attribute
 * @param imageLoader ImageLoader provided
 */
function assertNotMissingBuiltInLoader(ngSrc, imageLoader) {
  if (imageLoader === noopImageLoader) {
    let builtInLoaderName = '';
    for (const loader of BUILT_IN_LOADERS) {
      if (loader.testUrl(ngSrc)) {
        builtInLoaderName = loader.name;
        break;
      }
    }
    if (builtInLoaderName) {
      console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2962 /* RuntimeErrorCode.MISSING_BUILTIN_LOADER */, `NgOptimizedImage: It looks like your images may be hosted on the ` + `${builtInLoaderName} CDN, but your app is not using Angular's ` + `built-in loader for that CDN. We recommend switching to use ` + `the built-in by calling \`provide${builtInLoaderName}Loader()\` ` + `in your \`providers\` and passing it your instance's base URL. ` + `If you don't want to use the built-in loader, define a custom ` + `loader function using IMAGE_LOADER to silence this warning.`));
    }
  }
}
/**
 * Warns if ngSrcset is present and no loader is configured (i.e. the default one is being used).
 */
function assertNoNgSrcsetWithoutLoader(dir, imageLoader) {
  if (dir.ngSrcset && imageLoader === noopImageLoader) {
    console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` attribute is present but ` + `no image loader is configured (i.e. the default one is being used), ` + `which would result in the same image being used for all configured sizes. ` + `To fix this, provide a loader or remove the \`ngSrcset\` attribute from the image.`));
  }
}
/**
 * Warns if loaderParams is present and no loader is configured (i.e. the default one is being
 * used).
 */
function assertNoLoaderParamsWithoutLoader(dir, imageLoader) {
  if (dir.loaderParams && imageLoader === noopImageLoader) {
    console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`loaderParams\` attribute is present but ` + `no image loader is configured (i.e. the default one is being used), ` + `which means that the loaderParams data will not be consumed and will not affect the URL. ` + `To fix this, provide a custom loader or remove the \`loaderParams\` attribute from the image.`));
  }
}
/**
 * Warns if the priority attribute is used too often on page load
 */
function assetPriorityCountBelowThreshold(_x) {
  return _assetPriorityCountBelowThreshold.apply(this, arguments);
}
/**
 * Warns if placeholder's dimension are over a threshold.
 *
 * This assert function is meant to only run on the browser.
 */
function _assetPriorityCountBelowThreshold() {
  _assetPriorityCountBelowThreshold = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (appRef) {
    if (IMGS_WITH_PRIORITY_ATTR_COUNT === 0) {
      IMGS_WITH_PRIORITY_ATTR_COUNT++;
      yield (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵwhenStable"])(appRef);
      if (IMGS_WITH_PRIORITY_ATTR_COUNT > PRIORITY_COUNT_THRESHOLD) {
        console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2966 /* RuntimeErrorCode.TOO_MANY_PRIORITY_ATTRIBUTES */, `NgOptimizedImage: The "priority" attribute is set to true more than ${PRIORITY_COUNT_THRESHOLD} times (${IMGS_WITH_PRIORITY_ATTR_COUNT} times). ` + `Marking too many images as "high" priority can hurt your application's LCP (https://web.dev/lcp). ` + `"Priority" should only be set on the image expected to be the page's LCP element.`));
      }
    } else {
      IMGS_WITH_PRIORITY_ATTR_COUNT++;
    }
  });
  return _assetPriorityCountBelowThreshold.apply(this, arguments);
}
function assertPlaceholderDimensions(dir, imgElement) {
  const computedStyle = window.getComputedStyle(imgElement);
  let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
  let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
  if (renderedWidth > PLACEHOLDER_DIMENSION_LIMIT || renderedHeight > PLACEHOLDER_DIMENSION_LIMIT) {
    console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(2967 /* RuntimeErrorCode.PLACEHOLDER_DIMENSION_LIMIT_EXCEEDED */, `${imgDirectiveDetails(dir.ngSrc)} it uses a placeholder image, but at least one ` + `of the dimensions attribute (height or width) exceeds the limit of ${PLACEHOLDER_DIMENSION_LIMIT}px. ` + `To fix this, use a smaller image as a placeholder.`));
  }
}
function callOnLoadIfImageIsLoaded(img, callback) {
  // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-complete
  // The spec defines that `complete` is truthy once its request state is fully available.
  // The image may already be available if it’s loaded from the browser cache.
  // In that case, the `load` event will not fire at all, meaning that all setup
  // callbacks listening for the `load` event will not be invoked.
  // In Safari, there is a known behavior where the `complete` property of an
  // `HTMLImageElement` may sometimes return `true` even when the image is not fully loaded.
  // Checking both `img.complete` and `img.naturalWidth` is the most reliable way to
  // determine if an image has been fully loaded, especially in browsers where the
  // `complete` property may return `true` prematurely.
  if (img.complete && img.naturalWidth) {
    callback();
  }
}
function round(input) {
  return Number.isInteger(input) ? input : input.toFixed(2);
}
// Transform function to handle SafeValue input for ngSrc. This doesn't do any sanitization,
// as that is not needed for img.src and img.srcset. This transform is purely for compatibility.
function unwrapSafeUrl(value) {
  if (typeof value === 'string') {
    return value;
  }
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
}
// Transform function to handle inputs which may be booleans, strings, or string representations
// of boolean values. Used for the placeholder attribute.
function booleanOrUrlAttribute(value) {
  if (typeof value === 'string' && value !== 'true' && value !== 'false' && value !== '') {
    return value;
  }
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute)(value);
}

/**
 * @module
 * @description
 * Entry point for all public APIs of the common package.
 */

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
// This file only reexports content of the `src` folder. Keep it that way.

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 8143:
/*!*************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+common@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0__rxjs@7.8.1/node_modules/@angular/common/fesm2022/http.mjs ***!
  \*************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FetchBackend: () => (/* binding */ FetchBackend),
/* harmony export */   HTTP_INTERCEPTORS: () => (/* binding */ HTTP_INTERCEPTORS),
/* harmony export */   HTTP_TRANSFER_CACHE_ORIGIN_MAP: () => (/* binding */ HTTP_TRANSFER_CACHE_ORIGIN_MAP),
/* harmony export */   HttpBackend: () => (/* binding */ HttpBackend),
/* harmony export */   HttpClient: () => (/* binding */ HttpClient),
/* harmony export */   HttpClientJsonpModule: () => (/* binding */ HttpClientJsonpModule),
/* harmony export */   HttpClientModule: () => (/* binding */ HttpClientModule),
/* harmony export */   HttpClientXsrfModule: () => (/* binding */ HttpClientXsrfModule),
/* harmony export */   HttpContext: () => (/* binding */ HttpContext),
/* harmony export */   HttpContextToken: () => (/* binding */ HttpContextToken),
/* harmony export */   HttpErrorResponse: () => (/* binding */ HttpErrorResponse),
/* harmony export */   HttpEventType: () => (/* binding */ HttpEventType),
/* harmony export */   HttpFeatureKind: () => (/* binding */ HttpFeatureKind),
/* harmony export */   HttpHandler: () => (/* binding */ HttpHandler),
/* harmony export */   HttpHeaderResponse: () => (/* binding */ HttpHeaderResponse),
/* harmony export */   HttpHeaders: () => (/* binding */ HttpHeaders),
/* harmony export */   HttpParams: () => (/* binding */ HttpParams),
/* harmony export */   HttpRequest: () => (/* binding */ HttpRequest),
/* harmony export */   HttpResponse: () => (/* binding */ HttpResponse),
/* harmony export */   HttpResponseBase: () => (/* binding */ HttpResponseBase),
/* harmony export */   HttpStatusCode: () => (/* binding */ HttpStatusCode),
/* harmony export */   HttpUrlEncodingCodec: () => (/* binding */ HttpUrlEncodingCodec),
/* harmony export */   HttpXhrBackend: () => (/* binding */ HttpXhrBackend),
/* harmony export */   HttpXsrfTokenExtractor: () => (/* binding */ HttpXsrfTokenExtractor),
/* harmony export */   JsonpClientBackend: () => (/* binding */ JsonpClientBackend),
/* harmony export */   JsonpInterceptor: () => (/* binding */ JsonpInterceptor),
/* harmony export */   provideHttpClient: () => (/* binding */ provideHttpClient),
/* harmony export */   withFetch: () => (/* binding */ withFetch),
/* harmony export */   withInterceptors: () => (/* binding */ withInterceptors),
/* harmony export */   withInterceptorsFromDi: () => (/* binding */ withInterceptorsFromDi),
/* harmony export */   withJsonpSupport: () => (/* binding */ withJsonpSupport),
/* harmony export */   withNoXsrfProtection: () => (/* binding */ withNoXsrfProtection),
/* harmony export */   withRequestsMadeViaParent: () => (/* binding */ withRequestsMadeViaParent),
/* harmony export */   withXsrfConfiguration: () => (/* binding */ withXsrfConfiguration),
/* harmony export */   "ɵHTTP_ROOT_INTERCEPTOR_FNS": () => (/* binding */ HTTP_ROOT_INTERCEPTOR_FNS),
/* harmony export */   "ɵHttpInterceptingHandler": () => (/* binding */ HttpInterceptorHandler),
/* harmony export */   "ɵHttpInterceptorHandler": () => (/* binding */ HttpInterceptorHandler),
/* harmony export */   "ɵREQUESTS_CONTRIBUTE_TO_STABILITY": () => (/* binding */ REQUESTS_CONTRIBUTE_TO_STABILITY),
/* harmony export */   "ɵwithHttpTransferCache": () => (/* binding */ withHttpTransferCache)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ 2049);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 2921);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rxjs */ 580);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs/operators */ 826);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ 4484);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs/operators */ 6634);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs/operators */ 5996);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! rxjs/operators */ 462);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! rxjs/operators */ 4997);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/common */ 6216);

/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */








/**
 * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a
 * `HttpResponse`.
 *
 * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the
 * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the
 * `HttpBackend`.
 *
 * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain.
 *
 * @publicApi
 */
class HttpHandler {}
/**
 * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend.
 *
 * Interceptors sit between the `HttpClient` interface and the `HttpBackend`.
 *
 * When injected, `HttpBackend` dispatches requests directly to the backend, without going
 * through the interceptor chain.
 *
 * @publicApi
 */
class HttpBackend {}

/**
 * Represents the header configuration options for an HTTP request.
 * Instances are immutable. Modifying methods return a cloned
 * instance with the change. The original object is never changed.
 *
 * @publicApi
 */
class HttpHeaders {
  /**
   * Internal map of lowercase header names to values.
   */
  // TODO(issue/24571): remove '!'.
  headers;
  /**
   * Internal map of lowercased header names to the normalized
   * form of the name (the form seen first).
   */
  normalizedNames = /*#__PURE__*/(() => new Map())();
  /**
   * Complete the lazy initialization of this object (needed before reading).
   */
  lazyInit;
  /**
   * Queued updates to be materialized the next initialization.
   */
  lazyUpdate = null;
  /**  Constructs a new HTTP header object with the given values.*/
  constructor(headers) {
    if (!headers) {
      this.headers = new Map();
    } else if (typeof headers === 'string') {
      this.lazyInit = () => {
        this.headers = new Map();
        headers.split('\n').forEach(line => {
          const index = line.indexOf(':');
          if (index > 0) {
            const name = line.slice(0, index);
            const value = line.slice(index + 1).trim();
            this.addHeaderEntry(name, value);
          }
        });
      };
    } else if (typeof Headers !== 'undefined' && headers instanceof Headers) {
      this.headers = new Map();
      headers.forEach((value, name) => {
        this.addHeaderEntry(name, value);
      });
    } else {
      this.lazyInit = () => {
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          assertValidHeaders(headers);
        }
        this.headers = new Map();
        Object.entries(headers).forEach(([name, values]) => {
          this.setHeaderEntries(name, values);
        });
      };
    }
  }
  /**
   * Checks for existence of a given header.
   *
   * @param name The header name to check for existence.
   *
   * @returns True if the header exists, false otherwise.
   */
  has(name) {
    this.init();
    return this.headers.has(name.toLowerCase());
  }
  /**
   * Retrieves the first value of a given header.
   *
   * @param name The header name.
   *
   * @returns The value string if the header exists, null otherwise
   */
  get(name) {
    this.init();
    const values = this.headers.get(name.toLowerCase());
    return values && values.length > 0 ? values[0] : null;
  }
  /**
   * Retrieves the names of the headers.
   *
   * @returns A list of header names.
   */
  keys() {
    this.init();
    return Array.from(this.normalizedNames.values());
  }
  /**
   * Retrieves a list of values for a given header.
   *
   * @param name The header name from which to retrieve values.
   *
   * @returns A string of values if the header exists, null otherwise.
   */
  getAll(name) {
    this.init();
    return this.headers.get(name.toLowerCase()) || null;
  }
  /**
   * Appends a new value to the existing set of values for a header
   * and returns them in a clone of the original instance.
   *
   * @param name The header name for which to append the values.
   * @param value The value to append.
   *
   * @returns A clone of the HTTP headers object with the value appended to the given header.
   */
  append(name, value) {
    return this.clone({
      name,
      value,
      op: 'a'
    });
  }
  /**
   * Sets or modifies a value for a given header in a clone of the original instance.
   * If the header already exists, its value is replaced with the given value
   * in the returned object.
   *
   * @param name The header name.
   * @param value The value or values to set or override for the given header.
   *
   * @returns A clone of the HTTP headers object with the newly set header value.
   */
  set(name, value) {
    return this.clone({
      name,
      value,
      op: 's'
    });
  }
  /**
   * Deletes values for a given header in a clone of the original instance.
   *
   * @param name The header name.
   * @param value The value or values to delete for the given header.
   *
   * @returns A clone of the HTTP headers object with the given value deleted.
   */
  delete(name, value) {
    return this.clone({
      name,
      value,
      op: 'd'
    });
  }
  maybeSetNormalizedName(name, lcName) {
    if (!this.normalizedNames.has(lcName)) {
      this.normalizedNames.set(lcName, name);
    }
  }
  init() {
    if (!!this.lazyInit) {
      if (this.lazyInit instanceof HttpHeaders) {
        this.copyFrom(this.lazyInit);
      } else {
        this.lazyInit();
      }
      this.lazyInit = null;
      if (!!this.lazyUpdate) {
        this.lazyUpdate.forEach(update => this.applyUpdate(update));
        this.lazyUpdate = null;
      }
    }
  }
  copyFrom(other) {
    other.init();
    Array.from(other.headers.keys()).forEach(key => {
      this.headers.set(key, other.headers.get(key));
      this.normalizedNames.set(key, other.normalizedNames.get(key));
    });
  }
  clone(update) {
    const clone = new HttpHeaders();
    clone.lazyInit = !!this.lazyInit && this.lazyInit instanceof HttpHeaders ? this.lazyInit : this;
    clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
    return clone;
  }
  applyUpdate(update) {
    const key = update.name.toLowerCase();
    switch (update.op) {
      case 'a':
      case 's':
        let value = update.value;
        if (typeof value === 'string') {
          value = [value];
        }
        if (value.length === 0) {
          return;
        }
        this.maybeSetNormalizedName(update.name, key);
        const base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];
        base.push(...value);
        this.headers.set(key, base);
        break;
      case 'd':
        const toDelete = update.value;
        if (!toDelete) {
          this.headers.delete(key);
          this.normalizedNames.delete(key);
        } else {
          let existing = this.headers.get(key);
          if (!existing) {
            return;
          }
          existing = existing.filter(value => toDelete.indexOf(value) === -1);
          if (existing.length === 0) {
            this.headers.delete(key);
            this.normalizedNames.delete(key);
          } else {
            this.headers.set(key, existing);
          }
        }
        break;
    }
  }
  addHeaderEntry(name, value) {
    const key = name.toLowerCase();
    this.maybeSetNormalizedName(name, key);
    if (this.headers.has(key)) {
      this.headers.get(key).push(value);
    } else {
      this.headers.set(key, [value]);
    }
  }
  setHeaderEntries(name, values) {
    const headerValues = (Array.isArray(values) ? values : [values]).map(value => value.toString());
    const key = name.toLowerCase();
    this.headers.set(key, headerValues);
    this.maybeSetNormalizedName(name, key);
  }
  /**
   * @internal
   */
  forEach(fn) {
    this.init();
    Array.from(this.normalizedNames.keys()).forEach(key => fn(this.normalizedNames.get(key), this.headers.get(key)));
  }
}
/**
 * Verifies that the headers object has the right shape: the values
 * must be either strings, numbers or arrays. Throws an error if an invalid
 * header value is present.
 */
function assertValidHeaders(headers) {
  for (const [key, value] of Object.entries(headers)) {
    if (!(typeof value === 'string' || typeof value === 'number') && !Array.isArray(value)) {
      throw new Error(`Unexpected value of the \`${key}\` header provided. ` + `Expecting either a string, a number or an array, but got: \`${value}\`.`);
    }
  }
}

/**
 * Provides encoding and decoding of URL parameter and query-string values.
 *
 * Serializes and parses URL parameter keys and values to encode and decode them.
 * If you pass URL query parameters without encoding,
 * the query parameters can be misinterpreted at the receiving end.
 *
 *
 * @publicApi
 */
class HttpUrlEncodingCodec {
  /**
   * Encodes a key name for a URL parameter or query-string.
   * @param key The key name.
   * @returns The encoded key name.
   */
  encodeKey(key) {
    return standardEncoding(key);
  }
  /**
   * Encodes the value of a URL parameter or query-string.
   * @param value The value.
   * @returns The encoded value.
   */
  encodeValue(value) {
    return standardEncoding(value);
  }
  /**
   * Decodes an encoded URL parameter or query-string key.
   * @param key The encoded key name.
   * @returns The decoded key name.
   */
  decodeKey(key) {
    return decodeURIComponent(key);
  }
  /**
   * Decodes an encoded URL parameter or query-string value.
   * @param value The encoded value.
   * @returns The decoded value.
   */
  decodeValue(value) {
    return decodeURIComponent(value);
  }
}
function paramParser(rawParams, codec) {
  const map = new Map();
  if (rawParams.length > 0) {
    // The `window.location.search` can be used while creating an instance of the `HttpParams` class
    // (e.g. `new HttpParams({ fromString: window.location.search })`). The `window.location.search`
    // may start with the `?` char, so we strip it if it's present.
    const params = rawParams.replace(/^\?/, '').split('&');
    params.forEach(param => {
      const eqIdx = param.indexOf('=');
      const [key, val] = eqIdx == -1 ? [codec.decodeKey(param), ''] : [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))];
      const list = map.get(key) || [];
      list.push(val);
      map.set(key, list);
    });
  }
  return map;
}
/**
 * Encode input string with standard encodeURIComponent and then un-encode specific characters.
 */
const STANDARD_ENCODING_REGEX = /%(\d[a-f0-9])/gi;
const STANDARD_ENCODING_REPLACEMENTS = {
  '40': '@',
  '3A': ':',
  '24': '$',
  '2C': ',',
  '3B': ';',
  '3D': '=',
  '3F': '?',
  '2F': '/'
};
function standardEncoding(v) {
  return encodeURIComponent(v).replace(STANDARD_ENCODING_REGEX, (s, t) => STANDARD_ENCODING_REPLACEMENTS[t] ?? s);
}
function valueToString(value) {
  return `${value}`;
}
/**
 * An HTTP request/response body that represents serialized parameters,
 * per the MIME type `application/x-www-form-urlencoded`.
 *
 * This class is immutable; all mutation operations return a new instance.
 *
 * @publicApi
 */
class HttpParams {
  map;
  encoder;
  updates = null;
  cloneFrom = null;
  constructor(options = {}) {
    this.encoder = options.encoder || new HttpUrlEncodingCodec();
    if (!!options.fromString) {
      if (!!options.fromObject) {
        throw new Error(`Cannot specify both fromString and fromObject.`);
      }
      this.map = paramParser(options.fromString, this.encoder);
    } else if (!!options.fromObject) {
      this.map = new Map();
      Object.keys(options.fromObject).forEach(key => {
        const value = options.fromObject[key];
        // convert the values to strings
        const values = Array.isArray(value) ? value.map(valueToString) : [valueToString(value)];
        this.map.set(key, values);
      });
    } else {
      this.map = null;
    }
  }
  /**
   * Reports whether the body includes one or more values for a given parameter.
   * @param param The parameter name.
   * @returns True if the parameter has one or more values,
   * false if it has no value or is not present.
   */
  has(param) {
    this.init();
    return this.map.has(param);
  }
  /**
   * Retrieves the first value for a parameter.
   * @param param The parameter name.
   * @returns The first value of the given parameter,
   * or `null` if the parameter is not present.
   */
  get(param) {
    this.init();
    const res = this.map.get(param);
    return !!res ? res[0] : null;
  }
  /**
   * Retrieves all values for a  parameter.
   * @param param The parameter name.
   * @returns All values in a string array,
   * or `null` if the parameter not present.
   */
  getAll(param) {
    this.init();
    return this.map.get(param) || null;
  }
  /**
   * Retrieves all the parameters for this body.
   * @returns The parameter names in a string array.
   */
  keys() {
    this.init();
    return Array.from(this.map.keys());
  }
  /**
   * Appends a new value to existing values for a parameter.
   * @param param The parameter name.
   * @param value The new value to add.
   * @return A new body with the appended value.
   */
  append(param, value) {
    return this.clone({
      param,
      value,
      op: 'a'
    });
  }
  /**
   * Constructs a new body with appended values for the given parameter name.
   * @param params parameters and values
   * @return A new body with the new value.
   */
  appendAll(params) {
    const updates = [];
    Object.keys(params).forEach(param => {
      const value = params[param];
      if (Array.isArray(value)) {
        value.forEach(_value => {
          updates.push({
            param,
            value: _value,
            op: 'a'
          });
        });
      } else {
        updates.push({
          param,
          value: value,
          op: 'a'
        });
      }
    });
    return this.clone(updates);
  }
  /**
   * Replaces the value for a parameter.
   * @param param The parameter name.
   * @param value The new value.
   * @return A new body with the new value.
   */
  set(param, value) {
    return this.clone({
      param,
      value,
      op: 's'
    });
  }
  /**
   * Removes a given value or all values from a parameter.
   * @param param The parameter name.
   * @param value The value to remove, if provided.
   * @return A new body with the given value removed, or with all values
   * removed if no value is specified.
   */
  delete(param, value) {
    return this.clone({
      param,
      value,
      op: 'd'
    });
  }
  /**
   * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are
   * separated by `&`s.
   */
  toString() {
    this.init();
    return this.keys().map(key => {
      const eKey = this.encoder.encodeKey(key);
      // `a: ['1']` produces `'a=1'`
      // `b: []` produces `''`
      // `c: ['1', '2']` produces `'c=1&c=2'`
      return this.map.get(key).map(value => eKey + '=' + this.encoder.encodeValue(value)).join('&');
    })
    // filter out empty values because `b: []` produces `''`
    // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't
    .filter(param => param !== '').join('&');
  }
  clone(update) {
    const clone = new HttpParams({
      encoder: this.encoder
    });
    clone.cloneFrom = this.cloneFrom || this;
    clone.updates = (this.updates || []).concat(update);
    return clone;
  }
  init() {
    if (this.map === null) {
      this.map = new Map();
    }
    if (this.cloneFrom !== null) {
      this.cloneFrom.init();
      this.cloneFrom.keys().forEach(key => this.map.set(key, this.cloneFrom.map.get(key)));
      this.updates.forEach(update => {
        switch (update.op) {
          case 'a':
          case 's':
            const base = (update.op === 'a' ? this.map.get(update.param) : undefined) || [];
            base.push(valueToString(update.value));
            this.map.set(update.param, base);
            break;
          case 'd':
            if (update.value !== undefined) {
              let base = this.map.get(update.param) || [];
              const idx = base.indexOf(valueToString(update.value));
              if (idx !== -1) {
                base.splice(idx, 1);
              }
              if (base.length > 0) {
                this.map.set(update.param, base);
              } else {
                this.map.delete(update.param);
              }
            } else {
              this.map.delete(update.param);
              break;
            }
        }
      });
      this.cloneFrom = this.updates = null;
    }
  }
}

/**
 * A token used to manipulate and access values stored in `HttpContext`.
 *
 * @publicApi
 */
class HttpContextToken {
  defaultValue;
  constructor(defaultValue) {
    this.defaultValue = defaultValue;
  }
}
/**
 * Http context stores arbitrary user defined values and ensures type safety without
 * actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash.
 *
 * This context is mutable and is shared between cloned requests unless explicitly specified.
 *
 * @usageNotes
 *
 * ### Usage Example
 *
 * ```typescript
 * // inside cache.interceptors.ts
 * export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false);
 *
 * export class CacheInterceptor implements HttpInterceptor {
 *
 *   intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
 *     if (req.context.get(IS_CACHE_ENABLED) === true) {
 *       return ...;
 *     }
 *     return delegate.handle(req);
 *   }
 * }
 *
 * // inside a service
 *
 * this.httpClient.get('/api/weather', {
 *   context: new HttpContext().set(IS_CACHE_ENABLED, true)
 * }).subscribe(...);
 * ```
 *
 * @publicApi
 */
class HttpContext {
  map = /*#__PURE__*/(() => new Map())();
  /**
   * Store a value in the context. If a value is already present it will be overwritten.
   *
   * @param token The reference to an instance of `HttpContextToken`.
   * @param value The value to store.
   *
   * @returns A reference to itself for easy chaining.
   */
  set(token, value) {
    this.map.set(token, value);
    return this;
  }
  /**
   * Retrieve the value associated with the given token.
   *
   * @param token The reference to an instance of `HttpContextToken`.
   *
   * @returns The stored value or default if one is defined.
   */
  get(token) {
    if (!this.map.has(token)) {
      this.map.set(token, token.defaultValue());
    }
    return this.map.get(token);
  }
  /**
   * Delete the value associated with the given token.
   *
   * @param token The reference to an instance of `HttpContextToken`.
   *
   * @returns A reference to itself for easy chaining.
   */
  delete(token) {
    this.map.delete(token);
    return this;
  }
  /**
   * Checks for existence of a given token.
   *
   * @param token The reference to an instance of `HttpContextToken`.
   *
   * @returns True if the token exists, false otherwise.
   */
  has(token) {
    return this.map.has(token);
  }
  /**
   * @returns a list of tokens currently stored in the context.
   */
  keys() {
    return this.map.keys();
  }
}

/**
 * Determine whether the given HTTP method may include a body.
 */
function mightHaveBody(method) {
  switch (method) {
    case 'DELETE':
    case 'GET':
    case 'HEAD':
    case 'OPTIONS':
    case 'JSONP':
      return false;
    default:
      return true;
  }
}
/**
 * Safely assert whether the given value is an ArrayBuffer.
 *
 * In some execution environments ArrayBuffer is not defined.
 */
function isArrayBuffer(value) {
  return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
}
/**
 * Safely assert whether the given value is a Blob.
 *
 * In some execution environments Blob is not defined.
 */
function isBlob(value) {
  return typeof Blob !== 'undefined' && value instanceof Blob;
}
/**
 * Safely assert whether the given value is a FormData instance.
 *
 * In some execution environments FormData is not defined.
 */
function isFormData(value) {
  return typeof FormData !== 'undefined' && value instanceof FormData;
}
/**
 * Safely assert whether the given value is a URLSearchParams instance.
 *
 * In some execution environments URLSearchParams is not defined.
 */
function isUrlSearchParams(value) {
  return typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;
}
/**
 * An outgoing HTTP request with an optional typed body.
 *
 * `HttpRequest` represents an outgoing request, including URL, method,
 * headers, body, and other request configuration options. Instances should be
 * assumed to be immutable. To modify a `HttpRequest`, the `clone`
 * method should be used.
 *
 * @publicApi
 */
class HttpRequest {
  url;
  /**
   * The request body, or `null` if one isn't set.
   *
   * Bodies are not enforced to be immutable, as they can include a reference to any
   * user-defined data type. However, interceptors should take care to preserve
   * idempotence by treating them as such.
   */
  body = null;
  /**
   * Outgoing headers for this request.
   */
  // TODO(issue/24571): remove '!'.
  headers;
  /**
   * Shared and mutable context that can be used by interceptors
   */
  context;
  /**
   * Whether this request should be made in a way that exposes progress events.
   *
   * Progress events are expensive (change detection runs on each event) and so
   * they should only be requested if the consumer intends to monitor them.
   *
   * Note: The `FetchBackend` doesn't support progress report on uploads.
   */
  reportProgress = false;
  /**
   * Whether this request should be sent with outgoing credentials (cookies).
   */
  withCredentials = false;
  /**
   * The expected response type of the server.
   *
   * This is used to parse the response appropriately before returning it to
   * the requestee.
   */
  responseType = 'json';
  /**
   * The outgoing HTTP request method.
   */
  method;
  /**
   * Outgoing URL parameters.
   *
   * To pass a string representation of HTTP parameters in the URL-query-string format,
   * the `HttpParamsOptions`' `fromString` may be used. For example:
   *
   * ```
   * new HttpParams({fromString: 'angular=awesome'})
   * ```
   */
  // TODO(issue/24571): remove '!'.
  params;
  /**
   * The outgoing URL with all URL parameters set.
   */
  urlWithParams;
  /**
   * The HttpTransferCache option for the request
   */
  transferCache;
  constructor(method, url, third, fourth) {
    this.url = url;
    this.method = method.toUpperCase();
    // Next, need to figure out which argument holds the HttpRequestInit
    // options, if any.
    let options;
    // Check whether a body argument is expected. The only valid way to omit
    // the body argument is to use a known no-body method like GET.
    if (mightHaveBody(this.method) || !!fourth) {
      // Body is the third argument, options are the fourth.
      this.body = third !== undefined ? third : null;
      options = fourth;
    } else {
      // No body required, options are the third argument. The body stays null.
      options = third;
    }
    // If options have been passed, interpret them.
    if (options) {
      // Normalize reportProgress and withCredentials.
      this.reportProgress = !!options.reportProgress;
      this.withCredentials = !!options.withCredentials;
      // Override default response type of 'json' if one is provided.
      if (!!options.responseType) {
        this.responseType = options.responseType;
      }
      // Override headers if they're provided.
      if (!!options.headers) {
        this.headers = options.headers;
      }
      if (!!options.context) {
        this.context = options.context;
      }
      if (!!options.params) {
        this.params = options.params;
      }
      // We do want to assign transferCache even if it's falsy (false is valid value)
      this.transferCache = options.transferCache;
    }
    // If no headers have been passed in, construct a new HttpHeaders instance.
    this.headers ??= new HttpHeaders();
    // If no context have been passed in, construct a new HttpContext instance.
    this.context ??= new HttpContext();
    // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance.
    if (!this.params) {
      this.params = new HttpParams();
      this.urlWithParams = url;
    } else {
      // Encode the parameters to a string in preparation for inclusion in the URL.
      const params = this.params.toString();
      if (params.length === 0) {
        // No parameters, the visible URL is just the URL given at creation time.
        this.urlWithParams = url;
      } else {
        // Does the URL already have query parameters? Look for '?'.
        const qIdx = url.indexOf('?');
        // There are 3 cases to handle:
        // 1) No existing parameters -> append '?' followed by params.
        // 2) '?' exists and is followed by existing query string ->
        //    append '&' followed by params.
        // 3) '?' exists at the end of the url -> append params directly.
        // This basically amounts to determining the character, if any, with
        // which to join the URL and parameters.
        const sep = qIdx === -1 ? '?' : qIdx < url.length - 1 ? '&' : '';
        this.urlWithParams = url + sep + params;
      }
    }
  }
  /**
   * Transform the free-form body into a serialized format suitable for
   * transmission to the server.
   */
  serializeBody() {
    // If no body is present, no need to serialize it.
    if (this.body === null) {
      return null;
    }
    // Check whether the body is already in a serialized form. If so,
    // it can just be returned directly.
    if (typeof this.body === 'string' || isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) || isUrlSearchParams(this.body)) {
      return this.body;
    }
    // Check whether the body is an instance of HttpUrlEncodedParams.
    if (this.body instanceof HttpParams) {
      return this.body.toString();
    }
    // Check whether the body is an object or array, and serialize with JSON if so.
    if (typeof this.body === 'object' || typeof this.body === 'boolean' || Array.isArray(this.body)) {
      return JSON.stringify(this.body);
    }
    // Fall back on toString() for everything else.
    return this.body.toString();
  }
  /**
   * Examine the body and attempt to infer an appropriate MIME type
   * for it.
   *
   * If no such type can be inferred, this method will return `null`.
   */
  detectContentTypeHeader() {
    // An empty body has no content type.
    if (this.body === null) {
      return null;
    }
    // FormData bodies rely on the browser's content type assignment.
    if (isFormData(this.body)) {
      return null;
    }
    // Blobs usually have their own content type. If it doesn't, then
    // no type can be inferred.
    if (isBlob(this.body)) {
      return this.body.type || null;
    }
    // Array buffers have unknown contents and thus no type can be inferred.
    if (isArrayBuffer(this.body)) {
      return null;
    }
    // Technically, strings could be a form of JSON data, but it's safe enough
    // to assume they're plain strings.
    if (typeof this.body === 'string') {
      return 'text/plain';
    }
    // `HttpUrlEncodedParams` has its own content-type.
    if (this.body instanceof HttpParams) {
      return 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    // Arrays, objects, boolean and numbers will be encoded as JSON.
    if (typeof this.body === 'object' || typeof this.body === 'number' || typeof this.body === 'boolean') {
      return 'application/json';
    }
    // No type could be inferred.
    return null;
  }
  clone(update = {}) {
    // For method, url, and responseType, take the current value unless
    // it is overridden in the update hash.
    const method = update.method || this.method;
    const url = update.url || this.url;
    const responseType = update.responseType || this.responseType;
    // Carefully handle the transferCache to differentiate between
    // `false` and `undefined` in the update args.
    const transferCache = update.transferCache ?? this.transferCache;
    // The body is somewhat special - a `null` value in update.body means
    // whatever current body is present is being overridden with an empty
    // body, whereas an `undefined` value in update.body implies no
    // override.
    const body = update.body !== undefined ? update.body : this.body;
    // Carefully handle the boolean options to differentiate between
    // `false` and `undefined` in the update args.
    const withCredentials = update.withCredentials ?? this.withCredentials;
    const reportProgress = update.reportProgress ?? this.reportProgress;
    // Headers and params may be appended to if `setHeaders` or
    // `setParams` are used.
    let headers = update.headers || this.headers;
    let params = update.params || this.params;
    // Pass on context if needed
    const context = update.context ?? this.context;
    // Check whether the caller has asked to add headers.
    if (update.setHeaders !== undefined) {
      // Set every requested header.
      headers = Object.keys(update.setHeaders).reduce((headers, name) => headers.set(name, update.setHeaders[name]), headers);
    }
    // Check whether the caller has asked to set params.
    if (update.setParams) {
      // Set every requested param.
      params = Object.keys(update.setParams).reduce((params, param) => params.set(param, update.setParams[param]), params);
    }
    // Finally, construct the new HttpRequest using the pieces from above.
    return new HttpRequest(method, url, body, {
      params,
      headers,
      context,
      reportProgress,
      responseType,
      withCredentials,
      transferCache
    });
  }
}

/**
 * Type enumeration for the different kinds of `HttpEvent`.
 *
 * @publicApi
 */
var HttpEventType = /*#__PURE__*/function (HttpEventType) {
  /**
   * The request was sent out over the wire.
   */
  HttpEventType[HttpEventType["Sent"] = 0] = "Sent";
  /**
   * An upload progress event was received.
   *
   * Note: The `FetchBackend` doesn't support progress report on uploads.
   */
  HttpEventType[HttpEventType["UploadProgress"] = 1] = "UploadProgress";
  /**
   * The response status code and headers were received.
   */
  HttpEventType[HttpEventType["ResponseHeader"] = 2] = "ResponseHeader";
  /**
   * A download progress event was received.
   */
  HttpEventType[HttpEventType["DownloadProgress"] = 3] = "DownloadProgress";
  /**
   * The full response including the body was received.
   */
  HttpEventType[HttpEventType["Response"] = 4] = "Response";
  /**
   * A custom event from an interceptor or a backend.
   */
  HttpEventType[HttpEventType["User"] = 5] = "User";
  return HttpEventType;
}(HttpEventType || {});
/**
 * Base class for both `HttpResponse` and `HttpHeaderResponse`.
 *
 * @publicApi
 */
class HttpResponseBase {
  /**
   * All response headers.
   */
  headers;
  /**
   * Response status code.
   */
  status;
  /**
   * Textual description of response status code, defaults to OK.
   *
   * Do not depend on this.
   */
  statusText;
  /**
   * URL of the resource retrieved, or null if not available.
   */
  url;
  /**
   * Whether the status code falls in the 2xx range.
   */
  ok;
  /**
   * Type of the response, narrowed to either the full response or the header.
   */
  // TODO(issue/24571): remove '!'.
  type;
  /**
   * Super-constructor for all responses.
   *
   * The single parameter accepted is an initialization hash. Any properties
   * of the response passed there will override the default values.
   */
  constructor(init, defaultStatus = 200, defaultStatusText = 'OK') {
    // If the hash has values passed, use them to initialize the response.
    // Otherwise use the default values.
    this.headers = init.headers || new HttpHeaders();
    this.status = init.status !== undefined ? init.status : defaultStatus;
    this.statusText = init.statusText || defaultStatusText;
    this.url = init.url || null;
    // Cache the ok value to avoid defining a getter.
    this.ok = this.status >= 200 && this.status < 300;
  }
}
/**
 * A partial HTTP response which only includes the status and header data,
 * but no response body.
 *
 * `HttpHeaderResponse` is a `HttpEvent` available on the response
 * event stream, only when progress events are requested.
 *
 * @publicApi
 */
class HttpHeaderResponse extends HttpResponseBase {
  /**
   * Create a new `HttpHeaderResponse` with the given parameters.
   */
  constructor(init = {}) {
    super(init);
  }
  type = /*#__PURE__*/(() => HttpEventType.ResponseHeader)();
  /**
   * Copy this `HttpHeaderResponse`, overriding its contents with the
   * given parameter hash.
   */
  clone(update = {}) {
    // Perform a straightforward initialization of the new HttpHeaderResponse,
    // overriding the current parameters with new ones if given.
    return new HttpHeaderResponse({
      headers: update.headers || this.headers,
      status: update.status !== undefined ? update.status : this.status,
      statusText: update.statusText || this.statusText,
      url: update.url || this.url || undefined
    });
  }
}
/**
 * A full HTTP response, including a typed response body (which may be `null`
 * if one was not returned).
 *
 * `HttpResponse` is a `HttpEvent` available on the response event
 * stream.
 *
 * @publicApi
 */
class HttpResponse extends HttpResponseBase {
  /**
   * The response body, or `null` if one was not returned.
   */
  body;
  /**
   * Construct a new `HttpResponse`.
   */
  constructor(init = {}) {
    super(init);
    this.body = init.body !== undefined ? init.body : null;
  }
  type = /*#__PURE__*/(() => HttpEventType.Response)();
  clone(update = {}) {
    return new HttpResponse({
      body: update.body !== undefined ? update.body : this.body,
      headers: update.headers || this.headers,
      status: update.status !== undefined ? update.status : this.status,
      statusText: update.statusText || this.statusText,
      url: update.url || this.url || undefined
    });
  }
}
/**
 * A response that represents an error or failure, either from a
 * non-successful HTTP status, an error while executing the request,
 * or some other failure which occurred during the parsing of the response.
 *
 * Any error returned on the `Observable` response stream will be
 * wrapped in an `HttpErrorResponse` to provide additional context about
 * the state of the HTTP layer when the error occurred. The error property
 * will contain either a wrapped Error object or the error response returned
 * from the server.
 *
 * @publicApi
 */
class HttpErrorResponse extends HttpResponseBase {
  name = 'HttpErrorResponse';
  message;
  error;
  /**
   * Errors are never okay, even when the status code is in the 2xx success range.
   */
  ok = false;
  constructor(init) {
    // Initialize with a default status of 0 / Unknown Error.
    super(init, 0, 'Unknown Error');
    // If the response was successful, then this was a parse error. Otherwise, it was
    // a protocol-level failure of some sort. Either the request failed in transit
    // or the server returned an unsuccessful status code.
    if (this.status >= 200 && this.status < 300) {
      this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`;
    } else {
      this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`;
    }
    this.error = init.error || null;
  }
}
/**
 * We use these constant to prevent pulling the whole HttpStatusCode enum
 * Those are the only ones referenced directly by the framework
 */
const HTTP_STATUS_CODE_OK = 200;
const HTTP_STATUS_CODE_NO_CONTENT = 204;
/**
 * Http status codes.
 * As per https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
 * @publicApi
 */
var HttpStatusCode = /*#__PURE__*/function (HttpStatusCode) {
  HttpStatusCode[HttpStatusCode["Continue"] = 100] = "Continue";
  HttpStatusCode[HttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
  HttpStatusCode[HttpStatusCode["Processing"] = 102] = "Processing";
  HttpStatusCode[HttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
  HttpStatusCode[HttpStatusCode["Ok"] = 200] = "Ok";
  HttpStatusCode[HttpStatusCode["Created"] = 201] = "Created";
  HttpStatusCode[HttpStatusCode["Accepted"] = 202] = "Accepted";
  HttpStatusCode[HttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
  HttpStatusCode[HttpStatusCode["NoContent"] = 204] = "NoContent";
  HttpStatusCode[HttpStatusCode["ResetContent"] = 205] = "ResetContent";
  HttpStatusCode[HttpStatusCode["PartialContent"] = 206] = "PartialContent";
  HttpStatusCode[HttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
  HttpStatusCode[HttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
  HttpStatusCode[HttpStatusCode["ImUsed"] = 226] = "ImUsed";
  HttpStatusCode[HttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
  HttpStatusCode[HttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
  HttpStatusCode[HttpStatusCode["Found"] = 302] = "Found";
  HttpStatusCode[HttpStatusCode["SeeOther"] = 303] = "SeeOther";
  HttpStatusCode[HttpStatusCode["NotModified"] = 304] = "NotModified";
  HttpStatusCode[HttpStatusCode["UseProxy"] = 305] = "UseProxy";
  HttpStatusCode[HttpStatusCode["Unused"] = 306] = "Unused";
  HttpStatusCode[HttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
  HttpStatusCode[HttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
  HttpStatusCode[HttpStatusCode["BadRequest"] = 400] = "BadRequest";
  HttpStatusCode[HttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
  HttpStatusCode[HttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
  HttpStatusCode[HttpStatusCode["Forbidden"] = 403] = "Forbidden";
  HttpStatusCode[HttpStatusCode["NotFound"] = 404] = "NotFound";
  HttpStatusCode[HttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
  HttpStatusCode[HttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
  HttpStatusCode[HttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
  HttpStatusCode[HttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
  HttpStatusCode[HttpStatusCode["Conflict"] = 409] = "Conflict";
  HttpStatusCode[HttpStatusCode["Gone"] = 410] = "Gone";
  HttpStatusCode[HttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
  HttpStatusCode[HttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
  HttpStatusCode[HttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
  HttpStatusCode[HttpStatusCode["UriTooLong"] = 414] = "UriTooLong";
  HttpStatusCode[HttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
  HttpStatusCode[HttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
  HttpStatusCode[HttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
  HttpStatusCode[HttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
  HttpStatusCode[HttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
  HttpStatusCode[HttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
  HttpStatusCode[HttpStatusCode["Locked"] = 423] = "Locked";
  HttpStatusCode[HttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
  HttpStatusCode[HttpStatusCode["TooEarly"] = 425] = "TooEarly";
  HttpStatusCode[HttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
  HttpStatusCode[HttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
  HttpStatusCode[HttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
  HttpStatusCode[HttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
  HttpStatusCode[HttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
  HttpStatusCode[HttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
  HttpStatusCode[HttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
  HttpStatusCode[HttpStatusCode["BadGateway"] = 502] = "BadGateway";
  HttpStatusCode[HttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
  HttpStatusCode[HttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
  HttpStatusCode[HttpStatusCode["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
  HttpStatusCode[HttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
  HttpStatusCode[HttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
  HttpStatusCode[HttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
  HttpStatusCode[HttpStatusCode["NotExtended"] = 510] = "NotExtended";
  HttpStatusCode[HttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
  return HttpStatusCode;
}(HttpStatusCode || {});
/**
 * Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
 * the given `body`. This function clones the object and adds the body.
 *
 * Note that the `responseType` *options* value is a String that identifies the
 * single data type of the response.
 * A single overload version of the method handles each response type.
 * The value of `responseType` cannot be a union, as the combined signature could imply.
 *
 */
function addBody(options, body) {
  return {
    body,
    headers: options.headers,
    context: options.context,
    observe: options.observe,
    params: options.params,
    reportProgress: options.reportProgress,
    responseType: options.responseType,
    withCredentials: options.withCredentials,
    transferCache: options.transferCache
  };
}
/**
 * Performs HTTP requests.
 * This service is available as an injectable class, with methods to perform HTTP requests.
 * Each request method has multiple signatures, and the return type varies based on
 * the signature that is called (mainly the values of `observe` and `responseType`).
 *
 * Note that the `responseType` *options* value is a String that identifies the
 * single data type of the response.
 * A single overload version of the method handles each response type.
 * The value of `responseType` cannot be a union, as the combined signature could imply.

 * TODO(adev): review
 * @usageNotes
 *
 * ### HTTP Request Example
 *
 * ```
 *  // GET heroes whose name contains search term
 * searchHeroes(term: string): observable<Hero[]>{
 *
 *  const params = new HttpParams({fromString: 'name=term'});
 *    return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params});
 * }
 * ```
 *
 * Alternatively, the parameter string can be used without invoking HttpParams
 * by directly joining to the URL.
 * ```
 * this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'});
 * ```
 *
 *
 * ### JSONP Example
 * ```
 * requestJsonp(url, callback = 'callback') {
 *  return this.httpClient.jsonp(this.heroesURL, callback);
 * }
 * ```
 *
 * ### PATCH Example
 * ```
 * // PATCH one of the heroes' name
 * patchHero (id: number, heroName: string): Observable<{}> {
 * const url = `${this.heroesUrl}/${id}`;   // PATCH api/heroes/42
 *  return this.httpClient.patch(url, {name: heroName}, httpOptions)
 *    .pipe(catchError(this.handleError('patchHero')));
 * }
 * ```
 *
 * @see [HTTP Guide](guide/http)
 * @see [HTTP Request](api/common/http/HttpRequest)
 *
 * @publicApi
 */
let HttpClient = /*#__PURE__*/(() => {
  class HttpClient {
    handler;
    constructor(handler) {
      this.handler = handler;
    }
    /**
     * Constructs an observable for a generic HTTP request that, when subscribed,
     * fires the request through the chain of registered interceptors and on to the
     * server.
     *
     * You can pass an `HttpRequest` directly as the only parameter. In this case,
     * the call returns an observable of the raw `HttpEvent` stream.
     *
     * Alternatively you can pass an HTTP method as the first parameter,
     * a URL string as the second, and an options hash containing the request body as the third.
     * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the
     * type of returned observable.
     *   * The `responseType` value determines how a successful response body is parsed.
     *   * If `responseType` is the default `json`, you can pass a type interface for the resulting
     * object as a type parameter to the call.
     *
     * The `observe` value determines the return type, according to what you are interested in
     * observing.
     *   * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including
     * progress events by default.
     *   * An `observe` value of response returns an observable of `HttpResponse<T>`,
     * where the `T` parameter depends on the `responseType` and any optionally provided type
     * parameter.
     *   * An `observe` value of body returns an observable of `<T>` with the same `T` body type.
     *
     */
    request(first, url, options = {}) {
      let req;
      // First, check whether the primary argument is an instance of `HttpRequest`.
      if (first instanceof HttpRequest) {
        // It is. The other arguments must be undefined (per the signatures) and can be
        // ignored.
        req = first;
      } else {
        // It's a string, so it represents a URL. Construct a request based on it,
        // and incorporate the remaining arguments (assuming `GET` unless a method is
        // provided.
        // Figure out the headers.
        let headers = undefined;
        if (options.headers instanceof HttpHeaders) {
          headers = options.headers;
        } else {
          headers = new HttpHeaders(options.headers);
        }
        // Sort out parameters.
        let params = undefined;
        if (!!options.params) {
          if (options.params instanceof HttpParams) {
            params = options.params;
          } else {
            params = new HttpParams({
              fromObject: options.params
            });
          }
        }
        // Construct the request.
        req = new HttpRequest(first, url, options.body !== undefined ? options.body : null, {
          headers,
          context: options.context,
          params,
          reportProgress: options.reportProgress,
          // By default, JSON is assumed to be returned for all calls.
          responseType: options.responseType || 'json',
          withCredentials: options.withCredentials,
          transferCache: options.transferCache
        });
      }
      // Start with an Observable.of() the initial request, and run the handler (which
      // includes all interceptors) inside a concatMap(). This way, the handler runs
      // inside an Observable chain, which causes interceptors to be re-run on every
      // subscription (this also makes retries re-run the handler, including interceptors).
      const events$ = (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.of)(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.concatMap)(req => this.handler.handle(req)));
      // If coming via the API signature which accepts a previously constructed HttpRequest,
      // the only option is to get the event stream. Otherwise, return the event stream if
      // that is what was requested.
      if (first instanceof HttpRequest || options.observe === 'events') {
        return events$;
      }
      // The requested stream contains either the full response or the body. In either
      // case, the first step is to filter the event stream to extract a stream of
      // responses(s).
      const res$ = events$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(event => event instanceof HttpResponse));
      // Decide which stream to return.
      switch (options.observe || 'body') {
        case 'body':
          // The requested stream is the body. Map the response stream to the response
          // body. This could be done more simply, but a misbehaving interceptor might
          // transform the response body into a different format and ignore the requested
          // responseType. Guard against this by validating that the response is of the
          // requested type.
          switch (req.responseType) {
            case 'arraybuffer':
              return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(res => {
                // Validate that the body is an ArrayBuffer.
                if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
                  throw new Error('Response is not an ArrayBuffer.');
                }
                return res.body;
              }));
            case 'blob':
              return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(res => {
                // Validate that the body is a Blob.
                if (res.body !== null && !(res.body instanceof Blob)) {
                  throw new Error('Response is not a Blob.');
                }
                return res.body;
              }));
            case 'text':
              return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(res => {
                // Validate that the body is a string.
                if (res.body !== null && typeof res.body !== 'string') {
                  throw new Error('Response is not a string.');
                }
                return res.body;
              }));
            case 'json':
            default:
              // No validation needed for JSON responses, as they can be of any type.
              return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(res => res.body));
          }
        case 'response':
          // The response stream was requested directly, so return it.
          return res$;
        default:
          // Guard against new future observe types being added.
          throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);
      }
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `DELETE` request to execute on the server. See the individual overloads for
     * details on the return type.
     *
     * @param url     The endpoint URL.
     * @param options The HTTP options to send with the request.
     *
     */
    delete(url, options = {}) {
      return this.request('DELETE', url, options);
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `GET` request to execute on the server. See the individual overloads for
     * details on the return type.
     */
    get(url, options = {}) {
      return this.request('GET', url, options);
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `HEAD` request to execute on the server. The `HEAD` method returns
     * meta information about the resource without transferring the
     * resource itself. See the individual overloads for
     * details on the return type.
     */
    head(url, options = {}) {
      return this.request('HEAD', url, options);
    }
    /**
     * Constructs an `Observable` that, when subscribed, causes a request with the special method
     * `JSONP` to be dispatched via the interceptor pipeline.
     * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain
     * API endpoints that don't support newer,
     * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol.
     * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the
     * requests even if the API endpoint is not located on the same domain (origin) as the client-side
     * application making the request.
     * The endpoint API must support JSONP callback for JSONP requests to work.
     * The resource API returns the JSON response wrapped in a callback function.
     * You can pass the callback function name as one of the query parameters.
     * Note that JSONP requests can only be used with `GET` requests.
     *
     * @param url The resource URL.
     * @param callbackParam The callback function name.
     *
     */
    jsonp(url, callbackParam) {
      return this.request('JSONP', url, {
        params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'),
        observe: 'body',
        responseType: 'json'
      });
    }
    /**
     * Constructs an `Observable` that, when subscribed, causes the configured
     * `OPTIONS` request to execute on the server. This method allows the client
     * to determine the supported HTTP methods and other capabilities of an endpoint,
     * without implying a resource action. See the individual overloads for
     * details on the return type.
     */
    options(url, options = {}) {
      return this.request('OPTIONS', url, options);
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `PATCH` request to execute on the server. See the individual overloads for
     * details on the return type.
     */
    patch(url, body, options = {}) {
      return this.request('PATCH', url, addBody(options, body));
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `POST` request to execute on the server. The server responds with the location of
     * the replaced resource. See the individual overloads for
     * details on the return type.
     */
    post(url, body, options = {}) {
      return this.request('POST', url, addBody(options, body));
    }
    /**
     * Constructs an observable that, when subscribed, causes the configured
     * `PUT` request to execute on the server. The `PUT` method replaces an existing resource
     * with a new set of values.
     * See the individual overloads for details on the return type.
     */
    put(url, body, options = {}) {
      return this.request('PUT', url, addBody(options, body));
    }
    static ɵfac = (() => function HttpClient_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpClient)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](HttpHandler));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: HttpClient,
      factory: HttpClient.ɵfac
    }))();
  }
  return HttpClient;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const XSSI_PREFIX$1 = /^\)\]\}',?\n/;
const REQUEST_URL_HEADER = `X-Request-URL`;
/**
 * Determine an appropriate URL for the response, by checking either
 * response url or the X-Request-URL header.
 */
function getResponseUrl$1(response) {
  if (response.url) {
    return response.url;
  }
  // stored as lowercase in the map
  const xRequestUrl = REQUEST_URL_HEADER.toLocaleLowerCase();
  return response.headers.get(xRequestUrl);
}
/**
 * Uses `fetch` to send requests to a backend server.
 *
 * This `FetchBackend` requires the support of the
 * [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) which is available on all
 * supported browsers and on Node.js v18 or later.
 *
 * @see {@link HttpHandler}
 *
 * @publicApi
 */
let FetchBackend = /*#__PURE__*/(() => {
  class FetchBackend {
    // We use an arrow function to always reference the current global implementation of `fetch`.
    // This is helpful for cases when the global `fetch` implementation is modified by external code,
    // see https://github.com/angular/angular/issues/57527.
    fetchImpl = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(FetchFactory, {
      optional: true
    })?.fetch ?? ((...args) => globalThis.fetch(...args)))();
    ngZone = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__.NgZone))();
    handle(request) {
      return new rxjs__WEBPACK_IMPORTED_MODULE_6__.Observable(observer => {
        const aborter = new AbortController();
        this.doRequest(request, aborter.signal, observer).then(noop, error => observer.error(new HttpErrorResponse({
          error
        })));
        return () => aborter.abort();
      });
    }
    doRequest(request, signal, observer) {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const init = _this.createRequestInit(request);
        let response;
        try {
          // Run fetch outside of Angular zone.
          // This is due to Node.js fetch implementation (Undici) which uses a number of setTimeouts to check if
          // the response should eventually timeout which causes extra CD cycles every 500ms
          const fetchPromise = _this.ngZone.runOutsideAngular(() => _this.fetchImpl(request.urlWithParams, {
            signal,
            ...init
          }));
          // Make sure Zone.js doesn't trigger false-positive unhandled promise
          // error in case the Promise is rejected synchronously. See function
          // description for additional information.
          silenceSuperfluousUnhandledPromiseRejection(fetchPromise);
          // Send the `Sent` event before awaiting the response.
          observer.next({
            type: HttpEventType.Sent
          });
          response = yield fetchPromise;
        } catch (error) {
          observer.error(new HttpErrorResponse({
            error,
            status: error.status ?? 0,
            statusText: error.statusText,
            url: request.urlWithParams,
            headers: error.headers
          }));
          return;
        }
        const headers = new HttpHeaders(response.headers);
        const statusText = response.statusText;
        const url = getResponseUrl$1(response) ?? request.urlWithParams;
        let status = response.status;
        let body = null;
        if (request.reportProgress) {
          observer.next(new HttpHeaderResponse({
            headers,
            status,
            statusText,
            url
          }));
        }
        if (response.body) {
          // Read Progress
          const contentLength = response.headers.get('content-length');
          const chunks = [];
          const reader = response.body.getReader();
          let receivedLength = 0;
          let decoder;
          let partialText;
          // We have to check whether the Zone is defined in the global scope because this may be called
          // when the zone is nooped.
          const reqZone = typeof Zone !== 'undefined' && Zone.current;
          // Perform response processing outside of Angular zone to
          // ensure no excessive change detection runs are executed
          // Here calling the async ReadableStreamDefaultReader.read() is responsible for triggering CD
          yield _this.ngZone.runOutsideAngular(/*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
            while (true) {
              const {
                done,
                value
              } = yield reader.read();
              if (done) {
                break;
              }
              chunks.push(value);
              receivedLength += value.length;
              if (request.reportProgress) {
                partialText = request.responseType === 'text' ? (partialText ?? '') + (decoder ??= new TextDecoder()).decode(value, {
                  stream: true
                }) : undefined;
                const reportProgress = () => observer.next({
                  type: HttpEventType.DownloadProgress,
                  total: contentLength ? +contentLength : undefined,
                  loaded: receivedLength,
                  partialText
                });
                reqZone ? reqZone.run(reportProgress) : reportProgress();
              }
            }
          }));
          // Combine all chunks.
          const chunksAll = _this.concatChunks(chunks, receivedLength);
          try {
            const contentType = response.headers.get('Content-Type') ?? '';
            body = _this.parseBody(request, chunksAll, contentType);
          } catch (error) {
            // Body loading or parsing failed
            observer.error(new HttpErrorResponse({
              error,
              headers: new HttpHeaders(response.headers),
              status: response.status,
              statusText: response.statusText,
              url: getResponseUrl$1(response) ?? request.urlWithParams
            }));
            return;
          }
        }
        // Same behavior as the XhrBackend
        if (status === 0) {
          status = body ? HTTP_STATUS_CODE_OK : 0;
        }
        // ok determines whether the response will be transmitted on the event or
        // error channel. Unsuccessful status codes (not 2xx) will always be errors,
        // but a successful status code can still result in an error if the user
        // asked for JSON data and the body cannot be parsed as such.
        const ok = status >= 200 && status < 300;
        if (ok) {
          observer.next(new HttpResponse({
            body,
            headers,
            status,
            statusText,
            url
          }));
          // The full body has been received and delivered, no further events
          // are possible. This request is complete.
          observer.complete();
        } else {
          observer.error(new HttpErrorResponse({
            error: body,
            headers,
            status,
            statusText,
            url
          }));
        }
      })();
    }
    parseBody(request, binContent, contentType) {
      switch (request.responseType) {
        case 'json':
          // stripping the XSSI when present
          const text = new TextDecoder().decode(binContent).replace(XSSI_PREFIX$1, '');
          return text === '' ? null : JSON.parse(text);
        case 'text':
          return new TextDecoder().decode(binContent);
        case 'blob':
          return new Blob([binContent], {
            type: contentType
          });
        case 'arraybuffer':
          return binContent.buffer;
      }
    }
    createRequestInit(req) {
      // We could share some of this logic with the XhrBackend
      const headers = {};
      const credentials = req.withCredentials ? 'include' : undefined;
      // Setting all the requested headers.
      req.headers.forEach((name, values) => headers[name] = values.join(','));
      // Add an Accept header if one isn't present already.
      if (!req.headers.has('Accept')) {
        headers['Accept'] = 'application/json, text/plain, */*';
      }
      // Auto-detect the Content-Type header if one isn't present already.
      if (!req.headers.has('Content-Type')) {
        const detectedType = req.detectContentTypeHeader();
        // Sometimes Content-Type detection fails.
        if (detectedType !== null) {
          headers['Content-Type'] = detectedType;
        }
      }
      return {
        body: req.serializeBody(),
        method: req.method,
        headers,
        credentials
      };
    }
    concatChunks(chunks, totalLength) {
      const chunksAll = new Uint8Array(totalLength);
      let position = 0;
      for (const chunk of chunks) {
        chunksAll.set(chunk, position);
        position += chunk.length;
      }
      return chunksAll;
    }
    static ɵfac = (() => function FetchBackend_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FetchBackend)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: FetchBackend,
      factory: FetchBackend.ɵfac
    }))();
  }
  return FetchBackend;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Abstract class to provide a mocked implementation of `fetch()`
 */
class FetchFactory {}
function noop() {}
/**
 * Zone.js treats a rejected promise that has not yet been awaited
 * as an unhandled error. This function adds a noop `.then` to make
 * sure that Zone.js doesn't throw an error if the Promise is rejected
 * synchronously.
 */
function silenceSuperfluousUnhandledPromiseRejection(promise) {
  promise.then(noop, noop);
}
function interceptorChainEndFn(req, finalHandlerFn) {
  return finalHandlerFn(req);
}
/**
 * Constructs a `ChainedInterceptorFn` which adapts a legacy `HttpInterceptor` to the
 * `ChainedInterceptorFn` interface.
 */
function adaptLegacyInterceptorToChain(chainTailFn, interceptor) {
  return (initialRequest, finalHandlerFn) => interceptor.intercept(initialRequest, {
    handle: downstreamRequest => chainTailFn(downstreamRequest, finalHandlerFn)
  });
}
/**
 * Constructs a `ChainedInterceptorFn` which wraps and invokes a functional interceptor in the given
 * injector.
 */
function chainedInterceptorFn(chainTailFn, interceptorFn, injector) {
  return (initialRequest, finalHandlerFn) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.runInInjectionContext)(injector, () => interceptorFn(initialRequest, downstreamRequest => chainTailFn(downstreamRequest, finalHandlerFn)));
}
/**
 * A multi-provider token that represents the array of registered
 * `HttpInterceptor` objects.
 *
 * @publicApi
 */
const HTTP_INTERCEPTORS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'HTTP_INTERCEPTORS' : '');
/**
 * A multi-provided token of `HttpInterceptorFn`s.
 */
const HTTP_INTERCEPTOR_FNS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'HTTP_INTERCEPTOR_FNS' : '');
/**
 * A multi-provided token of `HttpInterceptorFn`s that are only set in root.
 */
const HTTP_ROOT_INTERCEPTOR_FNS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'HTTP_ROOT_INTERCEPTOR_FNS' : '');
// TODO(atscott): We need a larger discussion about stability and what should contribute to stability.
// Should the whole interceptor chain contribute to stability or just the backend request #55075?
// Should HttpClient contribute to stability automatically at all?
const REQUESTS_CONTRIBUTE_TO_STABILITY = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'REQUESTS_CONTRIBUTE_TO_STABILITY' : '', {
  providedIn: 'root',
  factory: () => true
});
/**
 * Creates an `HttpInterceptorFn` which lazily initializes an interceptor chain from the legacy
 * class-based interceptors and runs the request through it.
 */
function legacyInterceptorFnFactory() {
  let chain = null;
  return (req, handler) => {
    if (chain === null) {
      const interceptors = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(HTTP_INTERCEPTORS, {
        optional: true
      }) ?? [];
      // Note: interceptors are wrapped right-to-left so that final execution order is
      // left-to-right. That is, if `interceptors` is the array `[a, b, c]`, we want to
      // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside
      // out.
      chain = interceptors.reduceRight(adaptLegacyInterceptorToChain, interceptorChainEndFn);
    }
    const pendingTasks = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵPendingTasks"]);
    const contributeToStability = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(REQUESTS_CONTRIBUTE_TO_STABILITY);
    if (contributeToStability) {
      const taskId = pendingTasks.add();
      return chain(req, handler).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.finalize)(() => pendingTasks.remove(taskId)));
    } else {
      return chain(req, handler);
    }
  };
}
let fetchBackendWarningDisplayed = false;
/** Internal function to reset the flag in tests */
function resetFetchBackendWarningFlag() {
  fetchBackendWarningDisplayed = false;
}
let HttpInterceptorHandler = /*#__PURE__*/(() => {
  class HttpInterceptorHandler extends HttpHandler {
    backend;
    injector;
    chain = null;
    pendingTasks = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵPendingTasks"]))();
    contributeToStability = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(REQUESTS_CONTRIBUTE_TO_STABILITY))();
    constructor(backend, injector) {
      super();
      this.backend = backend;
      this.injector = injector;
      // We strongly recommend using fetch backend for HTTP calls when SSR is used
      // for an application. The logic below checks if that's the case and produces
      // a warning otherwise.
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && !fetchBackendWarningDisplayed) {
        const isServer = (0,_angular_common__WEBPACK_IMPORTED_MODULE_8__.isPlatformServer)(injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_5__.PLATFORM_ID));
        if (isServer && !(this.backend instanceof FetchBackend)) {
          fetchBackendWarningDisplayed = true;
          injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵConsole"]).warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵformatRuntimeError"])(2801 /* RuntimeErrorCode.NOT_USING_FETCH_BACKEND_IN_SSR */, 'Angular detected that `HttpClient` is not configured ' + "to use `fetch` APIs. It's strongly recommended to " + 'enable `fetch` for applications that use Server-Side Rendering ' + 'for better performance and compatibility. ' + 'To enable `fetch`, add the `withFetch()` to the `provideHttpClient()` ' + 'call at the root of the application.'));
        }
      }
    }
    handle(initialRequest) {
      if (this.chain === null) {
        const dedupedInterceptorFns = Array.from(new Set([...this.injector.get(HTTP_INTERCEPTOR_FNS), ...this.injector.get(HTTP_ROOT_INTERCEPTOR_FNS, [])]));
        // Note: interceptors are wrapped right-to-left so that final execution order is
        // left-to-right. That is, if `dedupedInterceptorFns` is the array `[a, b, c]`, we want to
        // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside
        // out.
        this.chain = dedupedInterceptorFns.reduceRight((nextSequencedFn, interceptorFn) => chainedInterceptorFn(nextSequencedFn, interceptorFn, this.injector), interceptorChainEndFn);
      }
      if (this.contributeToStability) {
        const taskId = this.pendingTasks.add();
        return this.chain(initialRequest, downstreamRequest => this.backend.handle(downstreamRequest)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.finalize)(() => this.pendingTasks.remove(taskId)));
      } else {
        return this.chain(initialRequest, downstreamRequest => this.backend.handle(downstreamRequest));
      }
    }
    static ɵfac = (() => function HttpInterceptorHandler_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpInterceptorHandler)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](HttpBackend), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_5__.EnvironmentInjector));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: HttpInterceptorHandler,
      factory: HttpInterceptorHandler.ɵfac
    }))();
  }
  return HttpInterceptorHandler;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

// Every request made through JSONP needs a callback name that's unique across the
// whole page. Each request is assigned an id and the callback name is constructed
// from that. The next id to be assigned is tracked in a global variable here that
// is shared among all applications on the page.
let nextRequestId = 0;
/**
 * When a pending <script> is unsubscribed we'll move it to this document, so it won't be
 * executed.
 */
let foreignDocument;
// Error text given when a JSONP script is injected, but doesn't invoke the callback
// passed in its URL.
const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
// Error text given when a request is passed to the JsonpClientBackend that doesn't
// have a request method JSONP.
const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.';
const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.';
// Error text given when a request is passed to the JsonpClientBackend that has
// headers set
const JSONP_ERR_HEADERS_NOT_SUPPORTED = 'JSONP requests do not support headers.';
/**
 * DI token/abstract type representing a map of JSONP callbacks.
 *
 * In the browser, this should always be the `window` object.
 *
 *
 */
class JsonpCallbackContext {}
/**
 * Factory function that determines where to store JSONP callbacks.
 *
 * Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist
 * in test environments. In that case, callbacks are stored on an anonymous object instead.
 *
 *
 */
function jsonpCallbackContext() {
  if (typeof window === 'object') {
    return window;
  }
  return {};
}
/**
 * Processes an `HttpRequest` with the JSONP method,
 * by performing JSONP style requests.
 * @see {@link HttpHandler}
 * @see {@link HttpXhrBackend}
 *
 * @publicApi
 */
let JsonpClientBackend = /*#__PURE__*/(() => {
  class JsonpClientBackend {
    callbackMap;
    document;
    /**
     * A resolved promise that can be used to schedule microtasks in the event handlers.
     */
    resolvedPromise = (() => Promise.resolve())();
    constructor(callbackMap, document) {
      this.callbackMap = callbackMap;
      this.document = document;
    }
    /**
     * Get the name of the next callback method, by incrementing the global `nextRequestId`.
     */
    nextCallback() {
      return `ng_jsonp_callback_${nextRequestId++}`;
    }
    /**
     * Processes a JSONP request and returns an event stream of the results.
     * @param req The request object.
     * @returns An observable of the response events.
     *
     */
    handle(req) {
      // Firstly, check both the method and response type. If either doesn't match
      // then the request was improperly routed here and cannot be handled.
      if (req.method !== 'JSONP') {
        throw new Error(JSONP_ERR_WRONG_METHOD);
      } else if (req.responseType !== 'json') {
        throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE);
      }
      // Check the request headers. JSONP doesn't support headers and
      // cannot set any that were supplied.
      if (req.headers.keys().length > 0) {
        throw new Error(JSONP_ERR_HEADERS_NOT_SUPPORTED);
      }
      // Everything else happens inside the Observable boundary.
      return new rxjs__WEBPACK_IMPORTED_MODULE_6__.Observable(observer => {
        // The first step to make a request is to generate the callback name, and replace the
        // callback placeholder in the URL with the name. Care has to be taken here to ensure
        // a trailing &, if matched, gets inserted back into the URL in the correct place.
        const callback = this.nextCallback();
        const url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`);
        // Construct the <script> tag and point it at the URL.
        const node = this.document.createElement('script');
        node.src = url;
        // A JSONP request requires waiting for multiple callbacks. These variables
        // are closed over and track state across those callbacks.
        // The response object, if one has been received, or null otherwise.
        let body = null;
        // Whether the response callback has been called.
        let finished = false;
        // Set the response callback in this.callbackMap (which will be the window
        // object in the browser. The script being loaded via the <script> tag will
        // eventually call this callback.
        this.callbackMap[callback] = data => {
          // Data has been received from the JSONP script. Firstly, delete this callback.
          delete this.callbackMap[callback];
          // Set state to indicate data was received.
          body = data;
          finished = true;
        };
        // cleanup() is a utility closure that removes the <script> from the page and
        // the response callback from the window. This logic is used in both the
        // success, error, and cancellation paths, so it's extracted out for convenience.
        const cleanup = () => {
          node.removeEventListener('load', onLoad);
          node.removeEventListener('error', onError);
          // Remove the <script> tag if it's still on the page.
          node.remove();
          // Remove the response callback from the callbackMap (window object in the
          // browser).
          delete this.callbackMap[callback];
        };
        // onLoad() is the success callback which runs after the response callback
        // if the JSONP script loads successfully. The event itself is unimportant.
        // If something went wrong, onLoad() may run without the response callback
        // having been invoked.
        const onLoad = event => {
          // We wrap it in an extra Promise, to ensure the microtask
          // is scheduled after the loaded endpoint has executed any potential microtask itself,
          // which is not guaranteed in Internet Explorer and EdgeHTML. See issue #39496
          this.resolvedPromise.then(() => {
            // Cleanup the page.
            cleanup();
            // Check whether the response callback has run.
            if (!finished) {
              // It hasn't, something went wrong with the request. Return an error via
              // the Observable error path. All JSONP errors have status 0.
              observer.error(new HttpErrorResponse({
                url,
                status: 0,
                statusText: 'JSONP Error',
                error: new Error(JSONP_ERR_NO_CALLBACK)
              }));
              return;
            }
            // Success. body either contains the response body or null if none was
            // returned.
            observer.next(new HttpResponse({
              body,
              status: HTTP_STATUS_CODE_OK,
              statusText: 'OK',
              url
            }));
            // Complete the stream, the response is over.
            observer.complete();
          });
        };
        // onError() is the error callback, which runs if the script returned generates
        // a Javascript error. It emits the error via the Observable error channel as
        // a HttpErrorResponse.
        const onError = error => {
          cleanup();
          // Wrap the error in a HttpErrorResponse.
          observer.error(new HttpErrorResponse({
            error,
            status: 0,
            statusText: 'JSONP Error',
            url
          }));
        };
        // Subscribe to both the success (load) and error events on the <script> tag,
        // and add it to the page.
        node.addEventListener('load', onLoad);
        node.addEventListener('error', onError);
        this.document.body.appendChild(node);
        // The request has now been successfully sent.
        observer.next({
          type: HttpEventType.Sent
        });
        // Cancellation handler.
        return () => {
          if (!finished) {
            this.removeListeners(node);
          }
          // And finally, clean up the page.
          cleanup();
        };
      });
    }
    removeListeners(script) {
      // Issue #34818
      // Changing <script>'s ownerDocument will prevent it from execution.
      // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
      foreignDocument ??= this.document.implementation.createHTMLDocument();
      foreignDocument.adoptNode(script);
    }
    static ɵfac = (() => function JsonpClientBackend_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || JsonpClientBackend)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](JsonpCallbackContext), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_8__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: JsonpClientBackend,
      factory: JsonpClientBackend.ɵfac
    }))();
  }
  return JsonpClientBackend;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Identifies requests with the method JSONP and shifts them to the `JsonpClientBackend`.
 */
function jsonpInterceptorFn(req, next) {
  if (req.method === 'JSONP') {
    return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(JsonpClientBackend).handle(req);
  }
  // Fall through for normal HTTP requests.
  return next(req);
}
/**
 * Identifies requests with the method JSONP and
 * shifts them to the `JsonpClientBackend`.
 *
 * @see {@link HttpInterceptor}
 *
 * @publicApi
 */
let JsonpInterceptor = /*#__PURE__*/(() => {
  class JsonpInterceptor {
    injector;
    constructor(injector) {
      this.injector = injector;
    }
    /**
     * Identifies and handles a given JSONP request.
     * @param initialRequest The outgoing request object to handle.
     * @param next The next interceptor in the chain, or the backend
     * if no interceptors remain in the chain.
     * @returns An observable of the event stream.
     */
    intercept(initialRequest, next) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.runInInjectionContext)(this.injector, () => jsonpInterceptorFn(initialRequest, downstreamRequest => next.handle(downstreamRequest)));
    }
    static ɵfac = (() => function JsonpInterceptor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || JsonpInterceptor)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_5__.EnvironmentInjector));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: JsonpInterceptor,
      factory: JsonpInterceptor.ɵfac
    }))();
  }
  return JsonpInterceptor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const XSSI_PREFIX = /^\)\]\}',?\n/;
/**
 * Determine an appropriate URL for the response, by checking either
 * XMLHttpRequest.responseURL or the X-Request-URL header.
 */
function getResponseUrl(xhr) {
  if ('responseURL' in xhr && xhr.responseURL) {
    return xhr.responseURL;
  }
  if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
    return xhr.getResponseHeader('X-Request-URL');
  }
  return null;
}
/**
 * Uses `XMLHttpRequest` to send requests to a backend server.
 * @see {@link HttpHandler}
 * @see {@link JsonpClientBackend}
 *
 * @publicApi
 */
let HttpXhrBackend = /*#__PURE__*/(() => {
  class HttpXhrBackend {
    xhrFactory;
    constructor(xhrFactory) {
      this.xhrFactory = xhrFactory;
    }
    /**
     * Processes a request and returns a stream of response events.
     * @param req The request object.
     * @returns An observable of the response events.
     */
    handle(req) {
      // Quick check to give a better error message when a user attempts to use
      // HttpClient.jsonp() without installing the HttpClientJsonpModule
      if (req.method === 'JSONP') {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵRuntimeError"](-2800 /* RuntimeErrorCode.MISSING_JSONP_MODULE */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot make a JSONP request without JSONP support. To fix the problem, either add the \`withJsonpSupport()\` call (if \`provideHttpClient()\` is used) or import the \`HttpClientJsonpModule\` in the root NgModule.`);
      }
      // Check whether this factory has a special function to load an XHR implementation
      // for various non-browser environments. We currently limit it to only `ServerXhr`
      // class, which needs to load an XHR implementation.
      const xhrFactory = this.xhrFactory;
      const source = xhrFactory.ɵloadImpl ? (0,rxjs__WEBPACK_IMPORTED_MODULE_9__.from)(xhrFactory.ɵloadImpl()) : (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.of)(null);
      return source.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_10__.switchMap)(() => {
        // Everything happens on Observable subscription.
        return new rxjs__WEBPACK_IMPORTED_MODULE_6__.Observable(observer => {
          // Start by setting up the XHR object with request method, URL, and withCredentials
          // flag.
          const xhr = xhrFactory.build();
          xhr.open(req.method, req.urlWithParams);
          if (req.withCredentials) {
            xhr.withCredentials = true;
          }
          // Add all the requested headers.
          req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));
          // Add an Accept header if one isn't present already.
          if (!req.headers.has('Accept')) {
            xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
          }
          // Auto-detect the Content-Type header if one isn't present already.
          if (!req.headers.has('Content-Type')) {
            const detectedType = req.detectContentTypeHeader();
            // Sometimes Content-Type detection fails.
            if (detectedType !== null) {
              xhr.setRequestHeader('Content-Type', detectedType);
            }
          }
          // Set the responseType if one was requested.
          if (req.responseType) {
            const responseType = req.responseType.toLowerCase();
            // JSON responses need to be processed as text. This is because if the server
            // returns an XSSI-prefixed JSON response, the browser will fail to parse it,
            // xhr.response will be null, and xhr.responseText cannot be accessed to
            // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON
            // is parsed by first requesting text and then applying JSON.parse.
            xhr.responseType = responseType !== 'json' ? responseType : 'text';
          }
          // Serialize the request body if one is present. If not, this will be set to null.
          const reqBody = req.serializeBody();
          // If progress events are enabled, response headers will be delivered
          // in two events - the HttpHeaderResponse event and the full HttpResponse
          // event. However, since response headers don't change in between these
          // two events, it doesn't make sense to parse them twice. So headerResponse
          // caches the data extracted from the response whenever it's first parsed,
          // to ensure parsing isn't duplicated.
          let headerResponse = null;
          // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest
          // state, and memoizes it into headerResponse.
          const partialFromXhr = () => {
            if (headerResponse !== null) {
              return headerResponse;
            }
            const statusText = xhr.statusText || 'OK';
            // Parse headers from XMLHttpRequest - this step is lazy.
            const headers = new HttpHeaders(xhr.getAllResponseHeaders());
            // Read the response URL from the XMLHttpResponse instance and fall back on the
            // request URL.
            const url = getResponseUrl(xhr) || req.url;
            // Construct the HttpHeaderResponse and memoize it.
            headerResponse = new HttpHeaderResponse({
              headers,
              status: xhr.status,
              statusText,
              url
            });
            return headerResponse;
          };
          // Next, a few closures are defined for the various events which XMLHttpRequest can
          // emit. This allows them to be unregistered as event listeners later.
          // First up is the load event, which represents a response being fully available.
          const onLoad = () => {
            // Read response state from the memoized partial data.
            let {
              headers,
              status,
              statusText,
              url
            } = partialFromXhr();
            // The body will be read out if present.
            let body = null;
            if (status !== HTTP_STATUS_CODE_NO_CONTENT) {
              // Use XMLHttpRequest.response if set, responseText otherwise.
              body = typeof xhr.response === 'undefined' ? xhr.responseText : xhr.response;
            }
            // Normalize another potential bug (this one comes from CORS).
            if (status === 0) {
              status = !!body ? HTTP_STATUS_CODE_OK : 0;
            }
            // ok determines whether the response will be transmitted on the event or
            // error channel. Unsuccessful status codes (not 2xx) will always be errors,
            // but a successful status code can still result in an error if the user
            // asked for JSON data and the body cannot be parsed as such.
            let ok = status >= 200 && status < 300;
            // Check whether the body needs to be parsed as JSON (in many cases the browser
            // will have done that already).
            if (req.responseType === 'json' && typeof body === 'string') {
              // Save the original body, before attempting XSSI prefix stripping.
              const originalBody = body;
              body = body.replace(XSSI_PREFIX, '');
              try {
                // Attempt the parse. If it fails, a parse error should be delivered to the
                // user.
                body = body !== '' ? JSON.parse(body) : null;
              } catch (error) {
                // Since the JSON.parse failed, it's reasonable to assume this might not have
                // been a JSON response. Restore the original body (including any XSSI prefix)
                // to deliver a better error response.
                body = originalBody;
                // If this was an error request to begin with, leave it as a string, it
                // probably just isn't JSON. Otherwise, deliver the parsing error to the user.
                if (ok) {
                  // Even though the response status was 2xx, this is still an error.
                  ok = false;
                  // The parse error contains the text of the body that failed to parse.
                  body = {
                    error,
                    text: body
                  };
                }
              }
            }
            if (ok) {
              // A successful response is delivered on the event stream.
              observer.next(new HttpResponse({
                body,
                headers,
                status,
                statusText,
                url: url || undefined
              }));
              // The full body has been received and delivered, no further events
              // are possible. This request is complete.
              observer.complete();
            } else {
              // An unsuccessful request is delivered on the error channel.
              observer.error(new HttpErrorResponse({
                // The error in this case is the response body (error from the server).
                error: body,
                headers,
                status,
                statusText,
                url: url || undefined
              }));
            }
          };
          // The onError callback is called when something goes wrong at the network level.
          // Connection timeout, DNS error, offline, etc. These are actual errors, and are
          // transmitted on the error channel.
          const onError = error => {
            const {
              url
            } = partialFromXhr();
            const res = new HttpErrorResponse({
              error,
              status: xhr.status || 0,
              statusText: xhr.statusText || 'Unknown Error',
              url: url || undefined
            });
            observer.error(res);
          };
          // The sentHeaders flag tracks whether the HttpResponseHeaders event
          // has been sent on the stream. This is necessary to track if progress
          // is enabled since the event will be sent on only the first download
          // progress event.
          let sentHeaders = false;
          // The download progress event handler, which is only registered if
          // progress events are enabled.
          const onDownProgress = event => {
            // Send the HttpResponseHeaders event if it hasn't been sent already.
            if (!sentHeaders) {
              observer.next(partialFromXhr());
              sentHeaders = true;
            }
            // Start building the download progress event to deliver on the response
            // event stream.
            let progressEvent = {
              type: HttpEventType.DownloadProgress,
              loaded: event.loaded
            };
            // Set the total number of bytes in the event if it's available.
            if (event.lengthComputable) {
              progressEvent.total = event.total;
            }
            // If the request was for text content and a partial response is
            // available on XMLHttpRequest, include it in the progress event
            // to allow for streaming reads.
            if (req.responseType === 'text' && !!xhr.responseText) {
              progressEvent.partialText = xhr.responseText;
            }
            // Finally, fire the event.
            observer.next(progressEvent);
          };
          // The upload progress event handler, which is only registered if
          // progress events are enabled.
          const onUpProgress = event => {
            // Upload progress events are simpler. Begin building the progress
            // event.
            let progress = {
              type: HttpEventType.UploadProgress,
              loaded: event.loaded
            };
            // If the total number of bytes being uploaded is available, include
            // it.
            if (event.lengthComputable) {
              progress.total = event.total;
            }
            // Send the event.
            observer.next(progress);
          };
          // By default, register for load and error events.
          xhr.addEventListener('load', onLoad);
          xhr.addEventListener('error', onError);
          xhr.addEventListener('timeout', onError);
          xhr.addEventListener('abort', onError);
          // Progress events are only enabled if requested.
          if (req.reportProgress) {
            // Download progress is always enabled if requested.
            xhr.addEventListener('progress', onDownProgress);
            // Upload progress depends on whether there is a body to upload.
            if (reqBody !== null && xhr.upload) {
              xhr.upload.addEventListener('progress', onUpProgress);
            }
          }
          // Fire the request, and notify the event stream that it was fired.
          xhr.send(reqBody);
          observer.next({
            type: HttpEventType.Sent
          });
          // This is the return from the Observable function, which is the
          // request cancellation handler.
          return () => {
            // On a cancellation, remove all registered event listeners.
            xhr.removeEventListener('error', onError);
            xhr.removeEventListener('abort', onError);
            xhr.removeEventListener('load', onLoad);
            xhr.removeEventListener('timeout', onError);
            if (req.reportProgress) {
              xhr.removeEventListener('progress', onDownProgress);
              if (reqBody !== null && xhr.upload) {
                xhr.upload.removeEventListener('progress', onUpProgress);
              }
            }
            // Finally, abort the in-flight request.
            if (xhr.readyState !== xhr.DONE) {
              xhr.abort();
            }
          };
        });
      }));
    }
    static ɵfac = (() => function HttpXhrBackend_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpXhrBackend)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_8__.XhrFactory));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: HttpXhrBackend,
      factory: HttpXhrBackend.ɵfac
    }))();
  }
  return HttpXhrBackend;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const XSRF_ENABLED = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'XSRF_ENABLED' : '');
const XSRF_DEFAULT_COOKIE_NAME = 'XSRF-TOKEN';
const XSRF_COOKIE_NAME = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'XSRF_COOKIE_NAME' : '', {
  providedIn: 'root',
  factory: () => XSRF_DEFAULT_COOKIE_NAME
});
const XSRF_DEFAULT_HEADER_NAME = 'X-XSRF-TOKEN';
const XSRF_HEADER_NAME = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'XSRF_HEADER_NAME' : '', {
  providedIn: 'root',
  factory: () => XSRF_DEFAULT_HEADER_NAME
});
/**
 * Retrieves the current XSRF token to use with the next outgoing request.
 *
 * @publicApi
 */
class HttpXsrfTokenExtractor {}
/**
 * `HttpXsrfTokenExtractor` which retrieves the token from a cookie.
 */
let HttpXsrfCookieExtractor = /*#__PURE__*/(() => {
  class HttpXsrfCookieExtractor {
    doc;
    platform;
    cookieName;
    lastCookieString = '';
    lastToken = null;
    /**
     * @internal for testing
     */
    parseCount = 0;
    constructor(doc, platform, cookieName) {
      this.doc = doc;
      this.platform = platform;
      this.cookieName = cookieName;
    }
    getToken() {
      if (this.platform === 'server') {
        return null;
      }
      const cookieString = this.doc.cookie || '';
      if (cookieString !== this.lastCookieString) {
        this.parseCount++;
        this.lastToken = (0,_angular_common__WEBPACK_IMPORTED_MODULE_8__["ɵparseCookieValue"])(cookieString, this.cookieName);
        this.lastCookieString = cookieString;
      }
      return this.lastToken;
    }
    static ɵfac = (() => function HttpXsrfCookieExtractor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpXsrfCookieExtractor)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_8__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_5__.PLATFORM_ID), _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](XSRF_COOKIE_NAME));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: HttpXsrfCookieExtractor,
      factory: HttpXsrfCookieExtractor.ɵfac
    }))();
  }
  return HttpXsrfCookieExtractor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function xsrfInterceptorFn(req, next) {
  const lcUrl = req.url.toLowerCase();
  // Skip both non-mutating requests and absolute URLs.
  // Non-mutating requests don't require a token, and absolute URLs require special handling
  // anyway as the cookie set
  // on our origin is not the same as the token expected by another origin.
  if (!(0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(XSRF_ENABLED) || req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') || lcUrl.startsWith('https://')) {
    return next(req);
  }
  const token = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(HttpXsrfTokenExtractor).getToken();
  const headerName = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(XSRF_HEADER_NAME);
  // Be careful not to overwrite an existing header of the same name.
  if (token != null && !req.headers.has(headerName)) {
    req = req.clone({
      headers: req.headers.set(headerName, token)
    });
  }
  return next(req);
}
/**
 * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests.
 */
let HttpXsrfInterceptor = /*#__PURE__*/(() => {
  class HttpXsrfInterceptor {
    injector;
    constructor(injector) {
      this.injector = injector;
    }
    intercept(initialRequest, next) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.runInInjectionContext)(this.injector, () => xsrfInterceptorFn(initialRequest, downstreamRequest => next.handle(downstreamRequest)));
    }
    static ɵfac = (() => function HttpXsrfInterceptor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpXsrfInterceptor)(_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_5__.EnvironmentInjector));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjectable"]({
      token: HttpXsrfInterceptor,
      factory: HttpXsrfInterceptor.ɵfac
    }))();
  }
  return HttpXsrfInterceptor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Identifies a particular kind of `HttpFeature`.
 *
 * @publicApi
 */
var HttpFeatureKind = /*#__PURE__*/function (HttpFeatureKind) {
  HttpFeatureKind[HttpFeatureKind["Interceptors"] = 0] = "Interceptors";
  HttpFeatureKind[HttpFeatureKind["LegacyInterceptors"] = 1] = "LegacyInterceptors";
  HttpFeatureKind[HttpFeatureKind["CustomXsrfConfiguration"] = 2] = "CustomXsrfConfiguration";
  HttpFeatureKind[HttpFeatureKind["NoXsrfProtection"] = 3] = "NoXsrfProtection";
  HttpFeatureKind[HttpFeatureKind["JsonpSupport"] = 4] = "JsonpSupport";
  HttpFeatureKind[HttpFeatureKind["RequestsMadeViaParent"] = 5] = "RequestsMadeViaParent";
  HttpFeatureKind[HttpFeatureKind["Fetch"] = 6] = "Fetch";
  return HttpFeatureKind;
}(HttpFeatureKind || {});
function makeHttpFeature(kind, providers) {
  return {
    ɵkind: kind,
    ɵproviders: providers
  };
}
/**
 * Configures Angular's `HttpClient` service to be available for injection.
 *
 * By default, `HttpClient` will be configured for injection with its default options for XSRF
 * protection of outgoing requests. Additional configuration options can be provided by passing
 * feature functions to `provideHttpClient`. For example, HTTP interceptors can be added using the
 * `withInterceptors(...)` feature.
 *
 * <div class="alert is-helpful">
 *
 * It's strongly recommended to enable
 * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for applications that use
 * Server-Side Rendering for better performance and compatibility. To enable `fetch`, add
 * `withFetch()` feature to the `provideHttpClient()` call at the root of the application:
 *
 * ```
 * provideHttpClient(withFetch());
 * ```
 *
 * </div>
 *
 * @see {@link withInterceptors}
 * @see {@link withInterceptorsFromDi}
 * @see {@link withXsrfConfiguration}
 * @see {@link withNoXsrfProtection}
 * @see {@link withJsonpSupport}
 * @see {@link withRequestsMadeViaParent}
 * @see {@link withFetch}
 */
function provideHttpClient(...features) {
  if (ngDevMode) {
    const featureKinds = new Set(features.map(f => f.ɵkind));
    if (featureKinds.has(HttpFeatureKind.NoXsrfProtection) && featureKinds.has(HttpFeatureKind.CustomXsrfConfiguration)) {
      throw new Error(ngDevMode ? `Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.` : '');
    }
  }
  const providers = [HttpClient, HttpXhrBackend, HttpInterceptorHandler, {
    provide: HttpHandler,
    useExisting: HttpInterceptorHandler
  }, {
    provide: HttpBackend,
    useFactory: () => {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(FetchBackend, {
        optional: true
      }) ?? (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(HttpXhrBackend);
    }
  }, {
    provide: HTTP_INTERCEPTOR_FNS,
    useValue: xsrfInterceptorFn,
    multi: true
  }, {
    provide: XSRF_ENABLED,
    useValue: true
  }, {
    provide: HttpXsrfTokenExtractor,
    useClass: HttpXsrfCookieExtractor
  }];
  for (const feature of features) {
    providers.push(...feature.ɵproviders);
  }
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.makeEnvironmentProviders)(providers);
}
/**
 * Adds one or more functional-style HTTP interceptors to the configuration of the `HttpClient`
 * instance.
 *
 * @see {@link HttpInterceptorFn}
 * @see {@link provideHttpClient}
 * @publicApi
 */
function withInterceptors(interceptorFns) {
  return makeHttpFeature(HttpFeatureKind.Interceptors, interceptorFns.map(interceptorFn => {
    return {
      provide: HTTP_INTERCEPTOR_FNS,
      useValue: interceptorFn,
      multi: true
    };
  }));
}
const LEGACY_INTERCEPTOR_FN = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'LEGACY_INTERCEPTOR_FN' : '');
/**
 * Includes class-based interceptors configured using a multi-provider in the current injector into
 * the configured `HttpClient` instance.
 *
 * Prefer `withInterceptors` and functional interceptors instead, as support for DI-provided
 * interceptors may be phased out in a later release.
 *
 * @see {@link HttpInterceptor}
 * @see {@link HTTP_INTERCEPTORS}
 * @see {@link provideHttpClient}
 */
function withInterceptorsFromDi() {
  // Note: the legacy interceptor function is provided here via an intermediate token
  // (`LEGACY_INTERCEPTOR_FN`), using a pattern which guarantees that if these providers are
  // included multiple times, all of the multi-provider entries will have the same instance of the
  // interceptor function. That way, the `HttpINterceptorHandler` will dedup them and legacy
  // interceptors will not run multiple times.
  return makeHttpFeature(HttpFeatureKind.LegacyInterceptors, [{
    provide: LEGACY_INTERCEPTOR_FN,
    useFactory: legacyInterceptorFnFactory
  }, {
    provide: HTTP_INTERCEPTOR_FNS,
    useExisting: LEGACY_INTERCEPTOR_FN,
    multi: true
  }]);
}
/**
 * Customizes the XSRF protection for the configuration of the current `HttpClient` instance.
 *
 * This feature is incompatible with the `withNoXsrfProtection` feature.
 *
 * @see {@link provideHttpClient}
 */
function withXsrfConfiguration({
  cookieName,
  headerName
}) {
  const providers = [];
  if (cookieName !== undefined) {
    providers.push({
      provide: XSRF_COOKIE_NAME,
      useValue: cookieName
    });
  }
  if (headerName !== undefined) {
    providers.push({
      provide: XSRF_HEADER_NAME,
      useValue: headerName
    });
  }
  return makeHttpFeature(HttpFeatureKind.CustomXsrfConfiguration, providers);
}
/**
 * Disables XSRF protection in the configuration of the current `HttpClient` instance.
 *
 * This feature is incompatible with the `withXsrfConfiguration` feature.
 *
 * @see {@link provideHttpClient}
 */
function withNoXsrfProtection() {
  return makeHttpFeature(HttpFeatureKind.NoXsrfProtection, [{
    provide: XSRF_ENABLED,
    useValue: false
  }]);
}
/**
 * Add JSONP support to the configuration of the current `HttpClient` instance.
 *
 * @see {@link provideHttpClient}
 */
function withJsonpSupport() {
  return makeHttpFeature(HttpFeatureKind.JsonpSupport, [JsonpClientBackend, {
    provide: JsonpCallbackContext,
    useFactory: jsonpCallbackContext
  }, {
    provide: HTTP_INTERCEPTOR_FNS,
    useValue: jsonpInterceptorFn,
    multi: true
  }]);
}
/**
 * Configures the current `HttpClient` instance to make requests via the parent injector's
 * `HttpClient` instead of directly.
 *
 * By default, `provideHttpClient` configures `HttpClient` in its injector to be an independent
 * instance. For example, even if `HttpClient` is configured in the parent injector with
 * one or more interceptors, they will not intercept requests made via this instance.
 *
 * With this option enabled, once the request has passed through the current injector's
 * interceptors, it will be delegated to the parent injector's `HttpClient` chain instead of
 * dispatched directly, and interceptors in the parent configuration will be applied to the request.
 *
 * If there are several `HttpClient` instances in the injector hierarchy, it's possible for
 * `withRequestsMadeViaParent` to be used at multiple levels, which will cause the request to
 * "bubble up" until either reaching the root level or an `HttpClient` which was not configured with
 * this option.
 *
 * @see {@link provideHttpClient}
 * @publicApi
 */
function withRequestsMadeViaParent() {
  return makeHttpFeature(HttpFeatureKind.RequestsMadeViaParent, [{
    provide: HttpBackend,
    useFactory: () => {
      const handlerFromParent = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(HttpHandler, {
        skipSelf: true,
        optional: true
      });
      if (ngDevMode && handlerFromParent === null) {
        throw new Error('withRequestsMadeViaParent() can only be used when the parent injector also configures HttpClient');
      }
      return handlerFromParent;
    }
  }]);
}
/**
 * Configures the current `HttpClient` instance to make requests using the fetch API.
 *
 * Note: The Fetch API doesn't support progress report on uploads.
 *
 * @publicApi
 */
function withFetch() {
  return makeHttpFeature(HttpFeatureKind.Fetch, [FetchBackend, {
    provide: HttpBackend,
    useExisting: FetchBackend
  }]);
}

/**
 * Configures XSRF protection support for outgoing requests.
 *
 * For a server that supports a cookie-based XSRF protection system,
 * use directly to configure XSRF protection with the correct
 * cookie and header names.
 *
 * If no names are supplied, the default cookie name is `XSRF-TOKEN`
 * and the default header name is `X-XSRF-TOKEN`.
 *
 * @publicApi
 * @deprecated Use withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'}) as
 *     providers instead or `withNoXsrfProtection` if you want to disabled XSRF protection.
 */
let HttpClientXsrfModule = /*#__PURE__*/(() => {
  class HttpClientXsrfModule {
    /**
     * Disable the default XSRF protection.
     */
    static disable() {
      return {
        ngModule: HttpClientXsrfModule,
        providers: [withNoXsrfProtection().ɵproviders]
      };
    }
    /**
     * Configure XSRF protection.
     * @param options An object that can specify either or both
     * cookie name or header name.
     * - Cookie name default is `XSRF-TOKEN`.
     * - Header name default is `X-XSRF-TOKEN`.
     *
     */
    static withOptions(options = {}) {
      return {
        ngModule: HttpClientXsrfModule,
        providers: withXsrfConfiguration(options).ɵproviders
      };
    }
    static ɵfac = (() => function HttpClientXsrfModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpClientXsrfModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineNgModule"]({
      type: HttpClientXsrfModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjector"]({
      providers: [HttpXsrfInterceptor, {
        provide: HTTP_INTERCEPTORS,
        useExisting: HttpXsrfInterceptor,
        multi: true
      }, {
        provide: HttpXsrfTokenExtractor,
        useClass: HttpXsrfCookieExtractor
      }, withXsrfConfiguration({
        cookieName: XSRF_DEFAULT_COOKIE_NAME,
        headerName: XSRF_DEFAULT_HEADER_NAME
      }).ɵproviders, {
        provide: XSRF_ENABLED,
        useValue: true
      }]
    }))();
  }
  return HttpClientXsrfModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Configures the dependency injector for `HttpClient`
 * with supporting services for XSRF. Automatically imported by `HttpClientModule`.
 *
 * You can add interceptors to the chain behind `HttpClient` by binding them to the
 * multiprovider for built-in DI token `HTTP_INTERCEPTORS`.
 *
 * @publicApi
 * @deprecated use `provideHttpClient(withInterceptorsFromDi())` as providers instead
 */
let HttpClientModule = /*#__PURE__*/(() => {
  class HttpClientModule {
    static ɵfac = (() => function HttpClientModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpClientModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineNgModule"]({
      type: HttpClientModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjector"]({
      providers: [provideHttpClient(withInterceptorsFromDi())]
    }))();
  }
  return HttpClientModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Configures the dependency injector for `HttpClient`
 * with supporting services for JSONP.
 * Without this module, Jsonp requests reach the backend
 * with method JSONP, where they are rejected.
 *
 * @publicApi
 * @deprecated `withJsonpSupport()` as providers instead
 */
let HttpClientJsonpModule = /*#__PURE__*/(() => {
  class HttpClientJsonpModule {
    static ɵfac = (() => function HttpClientJsonpModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HttpClientJsonpModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineNgModule"]({
      type: HttpClientJsonpModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵɵdefineInjector"]({
      providers: [withJsonpSupport().ɵproviders]
    }))();
  }
  return HttpClientJsonpModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * If your application uses different HTTP origins to make API calls (via `HttpClient`) on the server and
 * on the client, the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token allows you to establish a mapping
 * between those origins, so that `HttpTransferCache` feature can recognize those requests as the same
 * ones and reuse the data cached on the server during hydration on the client.
 *
 * **Important note**: the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token should *only* be provided in
 * the *server* code of your application (typically in the `app.server.config.ts` script). Angular throws an
 * error if it detects that the token is defined while running on the client.
 *
 * @usageNotes
 *
 * When the same API endpoint is accessed via `http://internal-domain.com:8080` on the server and
 * via `https://external-domain.com` on the client, you can use the following configuration:
 * ```typescript
 * // in app.server.config.ts
 * {
 *     provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP,
 *     useValue: {
 *         'http://internal-domain.com:8080': 'https://external-domain.com'
 *     }
 * }
 * ```
 *
 * @publicApi
 */
const HTTP_TRANSFER_CACHE_ORIGIN_MAP = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'HTTP_TRANSFER_CACHE_ORIGIN_MAP' : '');
/**
 * Keys within cached response data structure.
 */
const BODY = 'b';
const HEADERS = 'h';
const STATUS = 's';
const STATUS_TEXT = 'st';
const REQ_URL = 'u';
const RESPONSE_TYPE = 'rt';
const CACHE_OPTIONS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_5__.InjectionToken(ngDevMode ? 'HTTP_TRANSFER_STATE_CACHE_OPTIONS' : '');
/**
 * A list of allowed HTTP methods to cache.
 */
const ALLOWED_METHODS = ['GET', 'HEAD'];
function transferCacheInterceptorFn(req, next) {
  const {
    isCacheActive,
    ...globalOptions
  } = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(CACHE_OPTIONS);
  const {
    transferCache: requestOptions,
    method: requestMethod
  } = req;
  // In the following situations we do not want to cache the request
  if (!isCacheActive || requestOptions === false ||
  // POST requests are allowed either globally or at request level
  requestMethod === 'POST' && !globalOptions.includePostRequests && !requestOptions || requestMethod !== 'POST' && !ALLOWED_METHODS.includes(requestMethod) ||
  // Do not cache request that require authorization when includeRequestsWithAuthHeaders is falsey
  !globalOptions.includeRequestsWithAuthHeaders && hasAuthHeaders(req) || globalOptions.filter?.(req) === false) {
    return next(req);
  }
  const transferState = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__.TransferState);
  const originMap = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(HTTP_TRANSFER_CACHE_ORIGIN_MAP, {
    optional: true
  });
  const isServer = (0,_angular_common__WEBPACK_IMPORTED_MODULE_8__.isPlatformServer)((0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__.PLATFORM_ID));
  if (originMap && !isServer) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵRuntimeError"](2803 /* RuntimeErrorCode.HTTP_ORIGIN_MAP_USED_IN_CLIENT */, ngDevMode && 'Angular detected that the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token is configured and ' + 'present in the client side code. Please ensure that this token is only provided in the ' + 'server code of the application.');
  }
  const requestUrl = isServer && originMap ? mapRequestOriginUrl(req.url, originMap) : req.url;
  const storeKey = makeCacheKey(req, requestUrl);
  const response = transferState.get(storeKey, null);
  let headersToInclude = globalOptions.includeHeaders;
  if (typeof requestOptions === 'object' && requestOptions.includeHeaders) {
    // Request-specific config takes precedence over the global config.
    headersToInclude = requestOptions.includeHeaders;
  }
  if (response) {
    const {
      [BODY]: undecodedBody,
      [RESPONSE_TYPE]: responseType,
      [HEADERS]: httpHeaders,
      [STATUS]: status,
      [STATUS_TEXT]: statusText,
      [REQ_URL]: url
    } = response;
    // Request found in cache. Respond using it.
    let body = undecodedBody;
    switch (responseType) {
      case 'arraybuffer':
        body = new TextEncoder().encode(undecodedBody).buffer;
        break;
      case 'blob':
        body = new Blob([undecodedBody]);
        break;
    }
    // We want to warn users accessing a header provided from the cache
    // That HttpTransferCache alters the headers
    // The warning will be logged a single time by HttpHeaders instance
    let headers = new HttpHeaders(httpHeaders);
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      // Append extra logic in dev mode to produce a warning when a header
      // that was not transferred to the client is accessed in the code via `get`
      // and `has` calls.
      headers = appendMissingHeadersDetection(req.url, headers, headersToInclude ?? []);
    }
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.of)(new HttpResponse({
      body,
      headers,
      status,
      statusText,
      url
    }));
  }
  // Request not found in cache. Make the request and cache it if on the server.
  return next(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.tap)(event => {
    if (event instanceof HttpResponse && isServer) {
      transferState.set(storeKey, {
        [BODY]: event.body,
        [HEADERS]: getFilteredHeaders(event.headers, headersToInclude),
        [STATUS]: event.status,
        [STATUS_TEXT]: event.statusText,
        [REQ_URL]: requestUrl,
        [RESPONSE_TYPE]: req.responseType
      });
    }
  }));
}
/** @returns true when the requests contains autorization related headers. */
function hasAuthHeaders(req) {
  return req.headers.has('authorization') || req.headers.has('proxy-authorization');
}
function getFilteredHeaders(headers, includeHeaders) {
  if (!includeHeaders) {
    return {};
  }
  const headersMap = {};
  for (const key of includeHeaders) {
    const values = headers.getAll(key);
    if (values !== null) {
      headersMap[key] = values;
    }
  }
  return headersMap;
}
function sortAndConcatParams(params) {
  return [...params.keys()].sort().map(k => `${k}=${params.getAll(k)}`).join('&');
}
function makeCacheKey(request, mappedRequestUrl) {
  // make the params encoded same as a url so it's easy to identify
  const {
    params,
    method,
    responseType
  } = request;
  const encodedParams = sortAndConcatParams(params);
  let serializedBody = request.serializeBody();
  if (serializedBody instanceof URLSearchParams) {
    serializedBody = sortAndConcatParams(serializedBody);
  } else if (typeof serializedBody !== 'string') {
    serializedBody = '';
  }
  const key = [method, responseType, mappedRequestUrl, serializedBody, encodedParams].join('|');
  const hash = generateHash(key);
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.makeStateKey)(hash);
}
/**
 * A method that returns a hash representation of a string using a variant of DJB2 hash
 * algorithm.
 *
 * This is the same hashing logic that is used to generate component ids.
 */
function generateHash(value) {
  let hash = 0;
  for (const char of value) {
    hash = Math.imul(31, hash) + char.charCodeAt(0) << 0;
  }
  // Force positive number hash.
  // 2147483647 = equivalent of Integer.MAX_VALUE.
  hash += 2147483647 + 1;
  return hash.toString();
}
/**
 * Returns the DI providers needed to enable HTTP transfer cache.
 *
 * By default, when using server rendering, requests are performed twice: once on the server and
 * other one on the browser.
 *
 * When these providers are added, requests performed on the server are cached and reused during the
 * bootstrapping of the application in the browser thus avoiding duplicate requests and reducing
 * load time.
 *
 */
function withHttpTransferCache(cacheOptions) {
  return [{
    provide: CACHE_OPTIONS,
    useFactory: () => {
      (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵperformanceMarkFeature"])('NgHttpTransferCache');
      return {
        isCacheActive: true,
        ...cacheOptions
      };
    }
  }, {
    provide: HTTP_ROOT_INTERCEPTOR_FNS,
    useValue: transferCacheInterceptorFn,
    multi: true,
    deps: [_angular_core__WEBPACK_IMPORTED_MODULE_5__.TransferState, CACHE_OPTIONS]
  }, {
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_5__.APP_BOOTSTRAP_LISTENER,
    multi: true,
    useFactory: () => {
      const appRef = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_5__.ApplicationRef);
      const cacheState = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__.inject)(CACHE_OPTIONS);
      return () => {
        (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵwhenStable"])(appRef).then(() => {
          cacheState.isCacheActive = false;
        });
      };
    }
  }];
}
/**
 * This function will add a proxy to an HttpHeader to intercept calls to get/has
 * and log a warning if the header entry requested has been removed
 */
function appendMissingHeadersDetection(url, headers, headersToInclude) {
  const warningProduced = new Set();
  return new Proxy(headers, {
    get(target, prop) {
      const value = Reflect.get(target, prop);
      const methods = new Set(['get', 'has', 'getAll']);
      if (typeof value !== 'function' || !methods.has(prop)) {
        return value;
      }
      return headerName => {
        // We log when the key has been removed and a warning hasn't been produced for the header
        const key = (prop + ':' + headerName).toLowerCase(); // e.g. `get:cache-control`
        if (!headersToInclude.includes(headerName) && !warningProduced.has(key)) {
          warningProduced.add(key);
          const truncatedUrl = (0,_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵtruncateMiddle"])(url);
          // TODO: create Error guide for this warning
          console.warn((0,_angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵformatRuntimeError"])(2802 /* RuntimeErrorCode.HEADERS_ALTERED_BY_TRANSFER_CACHE */, `Angular detected that the \`${headerName}\` header is accessed, but the value of the header ` + `was not transferred from the server to the client by the HttpTransferCache. ` + `To include the value of the \`${headerName}\` header for the \`${truncatedUrl}\` request, ` + `use the \`includeHeaders\` list. The \`includeHeaders\` can be defined either ` + `on a request level by adding the \`transferCache\` parameter, or on an application ` + `level by adding the \`httpCacheTransfer.includeHeaders\` argument to the ` + `\`provideClientHydration()\` call. `));
        }
        // invoking the original method
        return value.apply(target, [headerName]);
      };
    }
  });
}
function mapRequestOriginUrl(url, originMap) {
  const origin = new URL(url, 'resolve://').origin;
  const mappedOrigin = originMap[origin];
  if (!mappedOrigin) {
    return url;
  }
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    verifyMappedOrigin(mappedOrigin);
  }
  return url.replace(origin, mappedOrigin);
}
function verifyMappedOrigin(url) {
  if (new URL(url, 'resolve://').pathname !== '/') {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_5__["ɵRuntimeError"](2804 /* RuntimeErrorCode.HTTP_ORIGIN_MAP_CONTAINS_PATH */, 'Angular detected a URL with a path segment in the value provided for the ' + `\`HTTP_TRANSFER_CACHE_ORIGIN_MAP\` token: ${url}. The map should only contain origins ` + 'without any other segments.');
  }
}

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 4380:
/*!************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0/node_modules/@angular/core/fesm2022/core.mjs ***!
  \************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ANIMATION_MODULE_TYPE: () => (/* binding */ ANIMATION_MODULE_TYPE),
/* harmony export */   APP_BOOTSTRAP_LISTENER: () => (/* binding */ APP_BOOTSTRAP_LISTENER),
/* harmony export */   APP_ID: () => (/* binding */ APP_ID),
/* harmony export */   APP_INITIALIZER: () => (/* binding */ APP_INITIALIZER),
/* harmony export */   AfterRenderPhase: () => (/* binding */ AfterRenderPhase),
/* harmony export */   ApplicationInitStatus: () => (/* binding */ ApplicationInitStatus),
/* harmony export */   ApplicationModule: () => (/* binding */ ApplicationModule),
/* harmony export */   ApplicationRef: () => (/* binding */ ApplicationRef),
/* harmony export */   Attribute: () => (/* binding */ Attribute),
/* harmony export */   COMPILER_OPTIONS: () => (/* binding */ COMPILER_OPTIONS),
/* harmony export */   CSP_NONCE: () => (/* binding */ CSP_NONCE),
/* harmony export */   CUSTOM_ELEMENTS_SCHEMA: () => (/* binding */ CUSTOM_ELEMENTS_SCHEMA),
/* harmony export */   ChangeDetectionStrategy: () => (/* binding */ ChangeDetectionStrategy),
/* harmony export */   ChangeDetectorRef: () => (/* binding */ ChangeDetectorRef),
/* harmony export */   Compiler: () => (/* binding */ Compiler),
/* harmony export */   CompilerFactory: () => (/* binding */ CompilerFactory),
/* harmony export */   Component: () => (/* binding */ Component),
/* harmony export */   ComponentFactory: () => (/* binding */ ComponentFactory$1),
/* harmony export */   ComponentFactoryResolver: () => (/* binding */ ComponentFactoryResolver$1),
/* harmony export */   ComponentRef: () => (/* binding */ ComponentRef$1),
/* harmony export */   ContentChild: () => (/* binding */ ContentChild),
/* harmony export */   ContentChildren: () => (/* binding */ ContentChildren),
/* harmony export */   DEFAULT_CURRENCY_CODE: () => (/* binding */ DEFAULT_CURRENCY_CODE),
/* harmony export */   DebugElement: () => (/* binding */ DebugElement),
/* harmony export */   DebugEventListener: () => (/* binding */ DebugEventListener),
/* harmony export */   DebugNode: () => (/* binding */ DebugNode),
/* harmony export */   DefaultIterableDiffer: () => (/* binding */ DefaultIterableDiffer),
/* harmony export */   DestroyRef: () => (/* binding */ DestroyRef),
/* harmony export */   Directive: () => (/* binding */ Directive),
/* harmony export */   ENVIRONMENT_INITIALIZER: () => (/* binding */ ENVIRONMENT_INITIALIZER),
/* harmony export */   ElementRef: () => (/* binding */ ElementRef),
/* harmony export */   EmbeddedViewRef: () => (/* binding */ EmbeddedViewRef),
/* harmony export */   EnvironmentInjector: () => (/* binding */ EnvironmentInjector),
/* harmony export */   ErrorHandler: () => (/* binding */ ErrorHandler),
/* harmony export */   EventEmitter: () => (/* binding */ EventEmitter),
/* harmony export */   HOST_TAG_NAME: () => (/* binding */ HOST_TAG_NAME),
/* harmony export */   Host: () => (/* binding */ Host),
/* harmony export */   HostAttributeToken: () => (/* binding */ HostAttributeToken),
/* harmony export */   HostBinding: () => (/* binding */ HostBinding),
/* harmony export */   HostListener: () => (/* binding */ HostListener),
/* harmony export */   INJECTOR: () => (/* binding */ INJECTOR$1),
/* harmony export */   Inject: () => (/* binding */ Inject),
/* harmony export */   InjectFlags: () => (/* binding */ InjectFlags),
/* harmony export */   Injectable: () => (/* binding */ Injectable),
/* harmony export */   InjectionToken: () => (/* binding */ InjectionToken),
/* harmony export */   Injector: () => (/* binding */ Injector),
/* harmony export */   Input: () => (/* binding */ Input),
/* harmony export */   IterableDiffers: () => (/* binding */ IterableDiffers),
/* harmony export */   KeyValueDiffers: () => (/* binding */ KeyValueDiffers),
/* harmony export */   LOCALE_ID: () => (/* binding */ LOCALE_ID),
/* harmony export */   MissingTranslationStrategy: () => (/* binding */ MissingTranslationStrategy),
/* harmony export */   ModuleWithComponentFactories: () => (/* binding */ ModuleWithComponentFactories),
/* harmony export */   NO_ERRORS_SCHEMA: () => (/* binding */ NO_ERRORS_SCHEMA),
/* harmony export */   NgModule: () => (/* binding */ NgModule),
/* harmony export */   NgModuleFactory: () => (/* binding */ NgModuleFactory$1),
/* harmony export */   NgModuleRef: () => (/* binding */ NgModuleRef$1),
/* harmony export */   NgProbeToken: () => (/* binding */ NgProbeToken),
/* harmony export */   NgZone: () => (/* binding */ NgZone),
/* harmony export */   Optional: () => (/* binding */ Optional),
/* harmony export */   Output: () => (/* binding */ Output),
/* harmony export */   OutputEmitterRef: () => (/* binding */ OutputEmitterRef),
/* harmony export */   PACKAGE_ROOT_URL: () => (/* binding */ PACKAGE_ROOT_URL),
/* harmony export */   PLATFORM_ID: () => (/* binding */ PLATFORM_ID),
/* harmony export */   PLATFORM_INITIALIZER: () => (/* binding */ PLATFORM_INITIALIZER),
/* harmony export */   PendingTasks: () => (/* binding */ PendingTasks),
/* harmony export */   Pipe: () => (/* binding */ Pipe),
/* harmony export */   PlatformRef: () => (/* binding */ PlatformRef),
/* harmony export */   Query: () => (/* binding */ Query),
/* harmony export */   QueryList: () => (/* binding */ QueryList),
/* harmony export */   REQUEST: () => (/* binding */ REQUEST),
/* harmony export */   REQUEST_CONTEXT: () => (/* binding */ REQUEST_CONTEXT),
/* harmony export */   RESPONSE_INIT: () => (/* binding */ RESPONSE_INIT),
/* harmony export */   Renderer2: () => (/* binding */ Renderer2),
/* harmony export */   RendererFactory2: () => (/* binding */ RendererFactory2),
/* harmony export */   RendererStyleFlags2: () => (/* binding */ RendererStyleFlags2),
/* harmony export */   ResourceStatus: () => (/* binding */ ResourceStatus),
/* harmony export */   Sanitizer: () => (/* binding */ Sanitizer),
/* harmony export */   SecurityContext: () => (/* binding */ SecurityContext),
/* harmony export */   Self: () => (/* binding */ Self),
/* harmony export */   SimpleChange: () => (/* binding */ SimpleChange),
/* harmony export */   SkipSelf: () => (/* binding */ SkipSelf),
/* harmony export */   TRANSLATIONS: () => (/* binding */ TRANSLATIONS),
/* harmony export */   TRANSLATIONS_FORMAT: () => (/* binding */ TRANSLATIONS_FORMAT),
/* harmony export */   TemplateRef: () => (/* binding */ TemplateRef),
/* harmony export */   Testability: () => (/* binding */ Testability),
/* harmony export */   TestabilityRegistry: () => (/* binding */ TestabilityRegistry),
/* harmony export */   TransferState: () => (/* binding */ TransferState),
/* harmony export */   Type: () => (/* binding */ Type),
/* harmony export */   VERSION: () => (/* binding */ VERSION),
/* harmony export */   Version: () => (/* binding */ Version),
/* harmony export */   ViewChild: () => (/* binding */ ViewChild),
/* harmony export */   ViewChildren: () => (/* binding */ ViewChildren),
/* harmony export */   ViewContainerRef: () => (/* binding */ ViewContainerRef),
/* harmony export */   ViewEncapsulation: () => (/* binding */ ViewEncapsulation),
/* harmony export */   ViewRef: () => (/* binding */ ViewRef),
/* harmony export */   afterNextRender: () => (/* binding */ afterNextRender),
/* harmony export */   afterRender: () => (/* binding */ afterRender),
/* harmony export */   afterRenderEffect: () => (/* binding */ afterRenderEffect),
/* harmony export */   asNativeElements: () => (/* binding */ asNativeElements),
/* harmony export */   assertInInjectionContext: () => (/* binding */ assertInInjectionContext),
/* harmony export */   assertNotInReactiveContext: () => (/* binding */ assertNotInReactiveContext),
/* harmony export */   assertPlatform: () => (/* binding */ assertPlatform),
/* harmony export */   booleanAttribute: () => (/* binding */ booleanAttribute),
/* harmony export */   computed: () => (/* binding */ computed),
/* harmony export */   contentChild: () => (/* binding */ contentChild),
/* harmony export */   contentChildren: () => (/* binding */ contentChildren),
/* harmony export */   createComponent: () => (/* binding */ createComponent),
/* harmony export */   createEnvironmentInjector: () => (/* binding */ createEnvironmentInjector),
/* harmony export */   createNgModule: () => (/* binding */ createNgModule),
/* harmony export */   createNgModuleRef: () => (/* binding */ createNgModuleRef),
/* harmony export */   createPlatform: () => (/* binding */ createPlatform),
/* harmony export */   createPlatformFactory: () => (/* binding */ createPlatformFactory),
/* harmony export */   defineInjectable: () => (/* binding */ defineInjectable),
/* harmony export */   destroyPlatform: () => (/* binding */ destroyPlatform),
/* harmony export */   effect: () => (/* binding */ effect),
/* harmony export */   enableProdMode: () => (/* binding */ enableProdMode),
/* harmony export */   forwardRef: () => (/* binding */ forwardRef),
/* harmony export */   getDebugNode: () => (/* binding */ getDebugNode),
/* harmony export */   getModuleFactory: () => (/* binding */ getModuleFactory),
/* harmony export */   getNgModuleById: () => (/* binding */ getNgModuleById),
/* harmony export */   getPlatform: () => (/* binding */ getPlatform),
/* harmony export */   importProvidersFrom: () => (/* binding */ importProvidersFrom),
/* harmony export */   inject: () => (/* binding */ inject),
/* harmony export */   input: () => (/* binding */ input),
/* harmony export */   isDevMode: () => (/* binding */ isDevMode),
/* harmony export */   isSignal: () => (/* binding */ isSignal),
/* harmony export */   isStandalone: () => (/* binding */ isStandalone),
/* harmony export */   linkedSignal: () => (/* binding */ linkedSignal),
/* harmony export */   makeEnvironmentProviders: () => (/* binding */ makeEnvironmentProviders),
/* harmony export */   makeStateKey: () => (/* binding */ makeStateKey),
/* harmony export */   mergeApplicationConfig: () => (/* binding */ mergeApplicationConfig),
/* harmony export */   model: () => (/* binding */ model),
/* harmony export */   numberAttribute: () => (/* binding */ numberAttribute),
/* harmony export */   output: () => (/* binding */ output),
/* harmony export */   platformCore: () => (/* binding */ platformCore),
/* harmony export */   provideAppInitializer: () => (/* binding */ provideAppInitializer),
/* harmony export */   provideEnvironmentInitializer: () => (/* binding */ provideEnvironmentInitializer),
/* harmony export */   provideExperimentalCheckNoChangesForDebug: () => (/* binding */ provideExperimentalCheckNoChangesForDebug),
/* harmony export */   provideExperimentalZonelessChangeDetection: () => (/* binding */ provideExperimentalZonelessChangeDetection),
/* harmony export */   providePlatformInitializer: () => (/* binding */ providePlatformInitializer),
/* harmony export */   provideZoneChangeDetection: () => (/* binding */ provideZoneChangeDetection),
/* harmony export */   reflectComponentType: () => (/* binding */ reflectComponentType),
/* harmony export */   resolveForwardRef: () => (/* binding */ resolveForwardRef),
/* harmony export */   resource: () => (/* binding */ resource),
/* harmony export */   runInInjectionContext: () => (/* binding */ runInInjectionContext),
/* harmony export */   setTestabilityGetter: () => (/* binding */ setTestabilityGetter),
/* harmony export */   signal: () => (/* binding */ signal),
/* harmony export */   untracked: () => (/* binding */ untracked),
/* harmony export */   viewChild: () => (/* binding */ viewChild),
/* harmony export */   viewChildren: () => (/* binding */ viewChildren),
/* harmony export */   "ɵALLOW_MULTIPLE_PLATFORMS": () => (/* binding */ ALLOW_MULTIPLE_PLATFORMS),
/* harmony export */   "ɵAfterRenderManager": () => (/* binding */ AfterRenderManager),
/* harmony export */   "ɵCONTAINER_HEADER_OFFSET": () => (/* binding */ CONTAINER_HEADER_OFFSET),
/* harmony export */   "ɵChangeDetectionScheduler": () => (/* binding */ ChangeDetectionScheduler),
/* harmony export */   "ɵChangeDetectionSchedulerImpl": () => (/* binding */ ChangeDetectionSchedulerImpl),
/* harmony export */   "ɵComponentFactory": () => (/* binding */ ComponentFactory$1),
/* harmony export */   "ɵConsole": () => (/* binding */ Console),
/* harmony export */   "ɵDEFAULT_LOCALE_ID": () => (/* binding */ DEFAULT_LOCALE_ID),
/* harmony export */   "ɵDEFER_BLOCK_CONFIG": () => (/* binding */ DEFER_BLOCK_CONFIG),
/* harmony export */   "ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR": () => (/* binding */ DEFER_BLOCK_DEPENDENCY_INTERCEPTOR),
/* harmony export */   "ɵDeferBlockBehavior": () => (/* binding */ DeferBlockBehavior),
/* harmony export */   "ɵDeferBlockState": () => (/* binding */ DeferBlockState),
/* harmony export */   "ɵEffectScheduler": () => (/* binding */ EffectScheduler),
/* harmony export */   "ɵIMAGE_CONFIG": () => (/* binding */ IMAGE_CONFIG),
/* harmony export */   "ɵIMAGE_CONFIG_DEFAULTS": () => (/* binding */ IMAGE_CONFIG_DEFAULTS),
/* harmony export */   "ɵINJECTOR_SCOPE": () => (/* binding */ INJECTOR_SCOPE),
/* harmony export */   "ɵINPUT_SIGNAL_BRAND_WRITE_TYPE": () => (/* binding */ ɵINPUT_SIGNAL_BRAND_WRITE_TYPE),
/* harmony export */   "ɵINTERNAL_APPLICATION_ERROR_HANDLER": () => (/* binding */ INTERNAL_APPLICATION_ERROR_HANDLER),
/* harmony export */   "ɵIS_HYDRATION_DOM_REUSE_ENABLED": () => (/* binding */ IS_HYDRATION_DOM_REUSE_ENABLED),
/* harmony export */   "ɵIS_INCREMENTAL_HYDRATION_ENABLED": () => (/* binding */ IS_INCREMENTAL_HYDRATION_ENABLED),
/* harmony export */   "ɵJSACTION_EVENT_CONTRACT": () => (/* binding */ JSACTION_EVENT_CONTRACT),
/* harmony export */   "ɵLContext": () => (/* binding */ LContext),
/* harmony export */   "ɵLifecycleHooksFeature": () => (/* binding */ LifecycleHooksFeature),
/* harmony export */   "ɵLocaleDataIndex": () => (/* binding */ LocaleDataIndex),
/* harmony export */   "ɵMicrotaskEffectScheduler": () => (/* binding */ MicrotaskEffectScheduler),
/* harmony export */   "ɵNG_COMP_DEF": () => (/* binding */ NG_COMP_DEF),
/* harmony export */   "ɵNG_DIR_DEF": () => (/* binding */ NG_DIR_DEF),
/* harmony export */   "ɵNG_ELEMENT_ID": () => (/* binding */ NG_ELEMENT_ID),
/* harmony export */   "ɵNG_INJ_DEF": () => (/* binding */ NG_INJ_DEF),
/* harmony export */   "ɵNG_MOD_DEF": () => (/* binding */ NG_MOD_DEF),
/* harmony export */   "ɵNG_PIPE_DEF": () => (/* binding */ NG_PIPE_DEF),
/* harmony export */   "ɵNG_PROV_DEF": () => (/* binding */ NG_PROV_DEF),
/* harmony export */   "ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR": () => (/* binding */ NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR),
/* harmony export */   "ɵNO_CHANGE": () => (/* binding */ NO_CHANGE),
/* harmony export */   "ɵNgModuleFactory": () => (/* binding */ NgModuleFactory),
/* harmony export */   "ɵNoopNgZone": () => (/* binding */ NoopNgZone),
/* harmony export */   "ɵPERFORMANCE_MARK_PREFIX": () => (/* binding */ PERFORMANCE_MARK_PREFIX),
/* harmony export */   "ɵPROVIDED_NG_ZONE": () => (/* binding */ PROVIDED_NG_ZONE),
/* harmony export */   "ɵPendingTasks": () => (/* binding */ PendingTasksInternal),
/* harmony export */   "ɵPendingTasksInternal": () => (/* binding */ PendingTasksInternal),
/* harmony export */   "ɵReflectionCapabilities": () => (/* binding */ ReflectionCapabilities),
/* harmony export */   "ɵRender3ComponentFactory": () => (/* binding */ ComponentFactory),
/* harmony export */   "ɵRender3ComponentRef": () => (/* binding */ ComponentRef),
/* harmony export */   "ɵRender3NgModuleRef": () => (/* binding */ NgModuleRef),
/* harmony export */   "ɵRuntimeError": () => (/* binding */ RuntimeError),
/* harmony export */   "ɵSIGNAL": () => (/* reexport safe */ _angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL),
/* harmony export */   "ɵSSR_CONTENT_INTEGRITY_MARKER": () => (/* binding */ SSR_CONTENT_INTEGRITY_MARKER),
/* harmony export */   "ɵTESTABILITY": () => (/* binding */ TESTABILITY),
/* harmony export */   "ɵTESTABILITY_GETTER": () => (/* binding */ TESTABILITY_GETTER),
/* harmony export */   "ɵUSE_RUNTIME_DEPS_TRACKER_FOR_JIT": () => (/* binding */ USE_RUNTIME_DEPS_TRACKER_FOR_JIT),
/* harmony export */   "ɵViewRef": () => (/* binding */ ViewRef$1),
/* harmony export */   "ɵXSS_SECURITY_URL": () => (/* binding */ XSS_SECURITY_URL),
/* harmony export */   "ɵZONELESS_ENABLED": () => (/* binding */ ZONELESS_ENABLED),
/* harmony export */   "ɵ_sanitizeHtml": () => (/* binding */ _sanitizeHtml),
/* harmony export */   "ɵ_sanitizeUrl": () => (/* binding */ _sanitizeUrl),
/* harmony export */   "ɵallowSanitizationBypassAndThrow": () => (/* binding */ allowSanitizationBypassAndThrow),
/* harmony export */   "ɵannotateForHydration": () => (/* binding */ annotateForHydration),
/* harmony export */   "ɵbypassSanitizationTrustHtml": () => (/* binding */ bypassSanitizationTrustHtml),
/* harmony export */   "ɵbypassSanitizationTrustResourceUrl": () => (/* binding */ bypassSanitizationTrustResourceUrl),
/* harmony export */   "ɵbypassSanitizationTrustScript": () => (/* binding */ bypassSanitizationTrustScript),
/* harmony export */   "ɵbypassSanitizationTrustStyle": () => (/* binding */ bypassSanitizationTrustStyle),
/* harmony export */   "ɵbypassSanitizationTrustUrl": () => (/* binding */ bypassSanitizationTrustUrl),
/* harmony export */   "ɵclearResolutionOfComponentResourcesQueue": () => (/* binding */ clearResolutionOfComponentResourcesQueue),
/* harmony export */   "ɵcompileComponent": () => (/* binding */ compileComponent),
/* harmony export */   "ɵcompileDirective": () => (/* binding */ compileDirective),
/* harmony export */   "ɵcompileNgModule": () => (/* binding */ compileNgModule),
/* harmony export */   "ɵcompileNgModuleDefs": () => (/* binding */ compileNgModuleDefs),
/* harmony export */   "ɵcompileNgModuleFactory": () => (/* binding */ compileNgModuleFactory),
/* harmony export */   "ɵcompilePipe": () => (/* binding */ compilePipe),
/* harmony export */   "ɵconvertToBitFlags": () => (/* binding */ convertToBitFlags),
/* harmony export */   "ɵcreateInjector": () => (/* binding */ createInjector),
/* harmony export */   "ɵdefaultIterableDiffers": () => (/* binding */ defaultIterableDiffers),
/* harmony export */   "ɵdefaultKeyValueDiffers": () => (/* binding */ defaultKeyValueDiffers),
/* harmony export */   "ɵdepsTracker": () => (/* binding */ depsTracker),
/* harmony export */   "ɵdetectChangesInViewIfRequired": () => (/* binding */ detectChangesInViewIfRequired),
/* harmony export */   "ɵdevModeEqual": () => (/* binding */ devModeEqual),
/* harmony export */   "ɵdisableProfiling": () => (/* binding */ disableProfiling),
/* harmony export */   "ɵenableProfiling": () => (/* binding */ enableProfiling),
/* harmony export */   "ɵfindLocaleData": () => (/* binding */ findLocaleData),
/* harmony export */   "ɵflushModuleScopingQueueAsMuchAsPossible": () => (/* binding */ flushModuleScopingQueueAsMuchAsPossible),
/* harmony export */   "ɵformatRuntimeError": () => (/* binding */ formatRuntimeError),
/* harmony export */   "ɵgenerateStandaloneInDeclarationsError": () => (/* binding */ generateStandaloneInDeclarationsError),
/* harmony export */   "ɵgetAsyncClassMetadataFn": () => (/* binding */ getAsyncClassMetadataFn),
/* harmony export */   "ɵgetClosestComponentName": () => (/* binding */ getClosestComponentName),
/* harmony export */   "ɵgetDebugNode": () => (/* binding */ getDebugNode),
/* harmony export */   "ɵgetDeferBlocks": () => (/* binding */ getDeferBlocks),
/* harmony export */   "ɵgetDirectives": () => (/* binding */ getDirectives),
/* harmony export */   "ɵgetHostElement": () => (/* binding */ getHostElement),
/* harmony export */   "ɵgetInjectableDef": () => (/* binding */ getInjectableDef),
/* harmony export */   "ɵgetLContext": () => (/* binding */ getLContext),
/* harmony export */   "ɵgetLocaleCurrencyCode": () => (/* binding */ getLocaleCurrencyCode),
/* harmony export */   "ɵgetLocalePluralCase": () => (/* binding */ getLocalePluralCase),
/* harmony export */   "ɵgetOutputDestroyRef": () => (/* binding */ getOutputDestroyRef),
/* harmony export */   "ɵgetSanitizationBypassType": () => (/* binding */ getSanitizationBypassType),
/* harmony export */   "ɵgetUnknownElementStrictMode": () => (/* binding */ ɵgetUnknownElementStrictMode),
/* harmony export */   "ɵgetUnknownPropertyStrictMode": () => (/* binding */ ɵgetUnknownPropertyStrictMode),
/* harmony export */   "ɵglobal": () => (/* binding */ _global),
/* harmony export */   "ɵinjectChangeDetectorRef": () => (/* binding */ injectChangeDetectorRef),
/* harmony export */   "ɵinternalCreateApplication": () => (/* binding */ internalCreateApplication),
/* harmony export */   "ɵinternalProvideZoneChangeDetection": () => (/* binding */ internalProvideZoneChangeDetection),
/* harmony export */   "ɵisBoundToModule": () => (/* binding */ isBoundToModule),
/* harmony export */   "ɵisComponentDefPendingResolution": () => (/* binding */ isComponentDefPendingResolution),
/* harmony export */   "ɵisEnvironmentProviders": () => (/* binding */ isEnvironmentProviders),
/* harmony export */   "ɵisInjectable": () => (/* binding */ isInjectable),
/* harmony export */   "ɵisNgModule": () => (/* binding */ isNgModule),
/* harmony export */   "ɵisPromise": () => (/* binding */ isPromise),
/* harmony export */   "ɵisSubscribable": () => (/* binding */ isSubscribable),
/* harmony export */   "ɵmicrotaskEffect": () => (/* binding */ microtaskEffect),
/* harmony export */   "ɵnoSideEffects": () => (/* binding */ noSideEffects),
/* harmony export */   "ɵpatchComponentDefWithScope": () => (/* binding */ patchComponentDefWithScope),
/* harmony export */   "ɵperformanceMarkFeature": () => (/* binding */ performanceMarkFeature),
/* harmony export */   "ɵpublishExternalGlobalUtil": () => (/* binding */ publishExternalGlobalUtil),
/* harmony export */   "ɵreadHydrationInfo": () => (/* binding */ readHydrationInfo),
/* harmony export */   "ɵregisterLocaleData": () => (/* binding */ registerLocaleData),
/* harmony export */   "ɵrenderDeferBlockState": () => (/* binding */ renderDeferBlockState),
/* harmony export */   "ɵresetCompiledComponents": () => (/* binding */ resetCompiledComponents),
/* harmony export */   "ɵresetJitOptions": () => (/* binding */ resetJitOptions),
/* harmony export */   "ɵresolveComponentResources": () => (/* binding */ resolveComponentResources),
/* harmony export */   "ɵrestoreComponentResolutionQueue": () => (/* binding */ restoreComponentResolutionQueue),
/* harmony export */   "ɵsetAllowDuplicateNgModuleIdsForTest": () => (/* binding */ setAllowDuplicateNgModuleIdsForTest),
/* harmony export */   "ɵsetAlternateWeakRefImpl": () => (/* binding */ setAlternateWeakRefImpl),
/* harmony export */   "ɵsetClassDebugInfo": () => (/* binding */ ɵsetClassDebugInfo),
/* harmony export */   "ɵsetClassMetadata": () => (/* binding */ setClassMetadata),
/* harmony export */   "ɵsetClassMetadataAsync": () => (/* binding */ setClassMetadataAsync),
/* harmony export */   "ɵsetCurrentInjector": () => (/* binding */ setCurrentInjector),
/* harmony export */   "ɵsetDocument": () => (/* binding */ setDocument),
/* harmony export */   "ɵsetInjectorProfilerContext": () => (/* binding */ setInjectorProfilerContext),
/* harmony export */   "ɵsetLocaleId": () => (/* binding */ setLocaleId),
/* harmony export */   "ɵsetUnknownElementStrictMode": () => (/* binding */ ɵsetUnknownElementStrictMode),
/* harmony export */   "ɵsetUnknownPropertyStrictMode": () => (/* binding */ ɵsetUnknownPropertyStrictMode),
/* harmony export */   "ɵstartMeasuring": () => (/* binding */ startMeasuring),
/* harmony export */   "ɵstopMeasuring": () => (/* binding */ stopMeasuring),
/* harmony export */   "ɵstore": () => (/* binding */ store),
/* harmony export */   "ɵstringify": () => (/* binding */ stringify),
/* harmony export */   "ɵtransitiveScopesFor": () => (/* binding */ transitiveScopesFor),
/* harmony export */   "ɵtriggerResourceLoading": () => (/* binding */ triggerResourceLoading),
/* harmony export */   "ɵtruncateMiddle": () => (/* binding */ truncateMiddle),
/* harmony export */   "ɵunregisterLocaleData": () => (/* binding */ unregisterAllLocaleData),
/* harmony export */   "ɵunwrapSafeValue": () => (/* binding */ unwrapSafeValue),
/* harmony export */   "ɵunwrapWritableSignal": () => (/* binding */ ɵunwrapWritableSignal),
/* harmony export */   "ɵwhenStable": () => (/* binding */ whenStable),
/* harmony export */   "ɵwithDomHydration": () => (/* binding */ withDomHydration),
/* harmony export */   "ɵwithEventReplay": () => (/* binding */ withEventReplay),
/* harmony export */   "ɵwithI18nSupport": () => (/* binding */ withI18nSupport),
/* harmony export */   "ɵwithIncrementalHydration": () => (/* binding */ withIncrementalHydration),
/* harmony export */   "ɵɵCopyDefinitionFeature": () => (/* binding */ ɵɵCopyDefinitionFeature),
/* harmony export */   "ɵɵExternalStylesFeature": () => (/* binding */ ɵɵExternalStylesFeature),
/* harmony export */   "ɵɵFactoryTarget": () => (/* binding */ FactoryTarget),
/* harmony export */   "ɵɵHostDirectivesFeature": () => (/* binding */ ɵɵHostDirectivesFeature),
/* harmony export */   "ɵɵInheritDefinitionFeature": () => (/* binding */ ɵɵInheritDefinitionFeature),
/* harmony export */   "ɵɵInputTransformsFeature": () => (/* binding */ ɵɵInputTransformsFeature),
/* harmony export */   "ɵɵNgOnChangesFeature": () => (/* binding */ ɵɵNgOnChangesFeature),
/* harmony export */   "ɵɵProvidersFeature": () => (/* binding */ ɵɵProvidersFeature),
/* harmony export */   "ɵɵadvance": () => (/* binding */ ɵɵadvance),
/* harmony export */   "ɵɵattribute": () => (/* binding */ ɵɵattribute),
/* harmony export */   "ɵɵattributeInterpolate1": () => (/* binding */ ɵɵattributeInterpolate1),
/* harmony export */   "ɵɵattributeInterpolate2": () => (/* binding */ ɵɵattributeInterpolate2),
/* harmony export */   "ɵɵattributeInterpolate3": () => (/* binding */ ɵɵattributeInterpolate3),
/* harmony export */   "ɵɵattributeInterpolate4": () => (/* binding */ ɵɵattributeInterpolate4),
/* harmony export */   "ɵɵattributeInterpolate5": () => (/* binding */ ɵɵattributeInterpolate5),
/* harmony export */   "ɵɵattributeInterpolate6": () => (/* binding */ ɵɵattributeInterpolate6),
/* harmony export */   "ɵɵattributeInterpolate7": () => (/* binding */ ɵɵattributeInterpolate7),
/* harmony export */   "ɵɵattributeInterpolate8": () => (/* binding */ ɵɵattributeInterpolate8),
/* harmony export */   "ɵɵattributeInterpolateV": () => (/* binding */ ɵɵattributeInterpolateV),
/* harmony export */   "ɵɵclassMap": () => (/* binding */ ɵɵclassMap),
/* harmony export */   "ɵɵclassMapInterpolate1": () => (/* binding */ ɵɵclassMapInterpolate1),
/* harmony export */   "ɵɵclassMapInterpolate2": () => (/* binding */ ɵɵclassMapInterpolate2),
/* harmony export */   "ɵɵclassMapInterpolate3": () => (/* binding */ ɵɵclassMapInterpolate3),
/* harmony export */   "ɵɵclassMapInterpolate4": () => (/* binding */ ɵɵclassMapInterpolate4),
/* harmony export */   "ɵɵclassMapInterpolate5": () => (/* binding */ ɵɵclassMapInterpolate5),
/* harmony export */   "ɵɵclassMapInterpolate6": () => (/* binding */ ɵɵclassMapInterpolate6),
/* harmony export */   "ɵɵclassMapInterpolate7": () => (/* binding */ ɵɵclassMapInterpolate7),
/* harmony export */   "ɵɵclassMapInterpolate8": () => (/* binding */ ɵɵclassMapInterpolate8),
/* harmony export */   "ɵɵclassMapInterpolateV": () => (/* binding */ ɵɵclassMapInterpolateV),
/* harmony export */   "ɵɵclassProp": () => (/* binding */ ɵɵclassProp),
/* harmony export */   "ɵɵcomponentInstance": () => (/* binding */ ɵɵcomponentInstance),
/* harmony export */   "ɵɵconditional": () => (/* binding */ ɵɵconditional),
/* harmony export */   "ɵɵcontentQuery": () => (/* binding */ ɵɵcontentQuery),
/* harmony export */   "ɵɵcontentQuerySignal": () => (/* binding */ ɵɵcontentQuerySignal),
/* harmony export */   "ɵɵdeclareLet": () => (/* binding */ ɵɵdeclareLet),
/* harmony export */   "ɵɵdefer": () => (/* binding */ ɵɵdefer),
/* harmony export */   "ɵɵdeferEnableTimerScheduling": () => (/* binding */ ɵɵdeferEnableTimerScheduling),
/* harmony export */   "ɵɵdeferHydrateNever": () => (/* binding */ ɵɵdeferHydrateNever),
/* harmony export */   "ɵɵdeferHydrateOnHover": () => (/* binding */ ɵɵdeferHydrateOnHover),
/* harmony export */   "ɵɵdeferHydrateOnIdle": () => (/* binding */ ɵɵdeferHydrateOnIdle),
/* harmony export */   "ɵɵdeferHydrateOnImmediate": () => (/* binding */ ɵɵdeferHydrateOnImmediate),
/* harmony export */   "ɵɵdeferHydrateOnInteraction": () => (/* binding */ ɵɵdeferHydrateOnInteraction),
/* harmony export */   "ɵɵdeferHydrateOnTimer": () => (/* binding */ ɵɵdeferHydrateOnTimer),
/* harmony export */   "ɵɵdeferHydrateOnViewport": () => (/* binding */ ɵɵdeferHydrateOnViewport),
/* harmony export */   "ɵɵdeferHydrateWhen": () => (/* binding */ ɵɵdeferHydrateWhen),
/* harmony export */   "ɵɵdeferOnHover": () => (/* binding */ ɵɵdeferOnHover),
/* harmony export */   "ɵɵdeferOnIdle": () => (/* binding */ ɵɵdeferOnIdle),
/* harmony export */   "ɵɵdeferOnImmediate": () => (/* binding */ ɵɵdeferOnImmediate),
/* harmony export */   "ɵɵdeferOnInteraction": () => (/* binding */ ɵɵdeferOnInteraction),
/* harmony export */   "ɵɵdeferOnTimer": () => (/* binding */ ɵɵdeferOnTimer),
/* harmony export */   "ɵɵdeferOnViewport": () => (/* binding */ ɵɵdeferOnViewport),
/* harmony export */   "ɵɵdeferPrefetchOnHover": () => (/* binding */ ɵɵdeferPrefetchOnHover),
/* harmony export */   "ɵɵdeferPrefetchOnIdle": () => (/* binding */ ɵɵdeferPrefetchOnIdle),
/* harmony export */   "ɵɵdeferPrefetchOnImmediate": () => (/* binding */ ɵɵdeferPrefetchOnImmediate),
/* harmony export */   "ɵɵdeferPrefetchOnInteraction": () => (/* binding */ ɵɵdeferPrefetchOnInteraction),
/* harmony export */   "ɵɵdeferPrefetchOnTimer": () => (/* binding */ ɵɵdeferPrefetchOnTimer),
/* harmony export */   "ɵɵdeferPrefetchOnViewport": () => (/* binding */ ɵɵdeferPrefetchOnViewport),
/* harmony export */   "ɵɵdeferPrefetchWhen": () => (/* binding */ ɵɵdeferPrefetchWhen),
/* harmony export */   "ɵɵdeferWhen": () => (/* binding */ ɵɵdeferWhen),
/* harmony export */   "ɵɵdefineComponent": () => (/* binding */ ɵɵdefineComponent),
/* harmony export */   "ɵɵdefineDirective": () => (/* binding */ ɵɵdefineDirective),
/* harmony export */   "ɵɵdefineInjectable": () => (/* binding */ ɵɵdefineInjectable),
/* harmony export */   "ɵɵdefineInjector": () => (/* binding */ ɵɵdefineInjector),
/* harmony export */   "ɵɵdefineNgModule": () => (/* binding */ ɵɵdefineNgModule),
/* harmony export */   "ɵɵdefinePipe": () => (/* binding */ ɵɵdefinePipe),
/* harmony export */   "ɵɵdirectiveInject": () => (/* binding */ ɵɵdirectiveInject),
/* harmony export */   "ɵɵdisableBindings": () => (/* binding */ ɵɵdisableBindings),
/* harmony export */   "ɵɵelement": () => (/* binding */ ɵɵelement),
/* harmony export */   "ɵɵelementContainer": () => (/* binding */ ɵɵelementContainer),
/* harmony export */   "ɵɵelementContainerEnd": () => (/* binding */ ɵɵelementContainerEnd),
/* harmony export */   "ɵɵelementContainerStart": () => (/* binding */ ɵɵelementContainerStart),
/* harmony export */   "ɵɵelementEnd": () => (/* binding */ ɵɵelementEnd),
/* harmony export */   "ɵɵelementStart": () => (/* binding */ ɵɵelementStart),
/* harmony export */   "ɵɵenableBindings": () => (/* binding */ ɵɵenableBindings),
/* harmony export */   "ɵɵgetComponentDepsFactory": () => (/* binding */ ɵɵgetComponentDepsFactory),
/* harmony export */   "ɵɵgetCurrentView": () => (/* binding */ ɵɵgetCurrentView),
/* harmony export */   "ɵɵgetInheritedFactory": () => (/* binding */ ɵɵgetInheritedFactory),
/* harmony export */   "ɵɵhostProperty": () => (/* binding */ ɵɵhostProperty),
/* harmony export */   "ɵɵi18n": () => (/* binding */ ɵɵi18n),
/* harmony export */   "ɵɵi18nApply": () => (/* binding */ ɵɵi18nApply),
/* harmony export */   "ɵɵi18nAttributes": () => (/* binding */ ɵɵi18nAttributes),
/* harmony export */   "ɵɵi18nEnd": () => (/* binding */ ɵɵi18nEnd),
/* harmony export */   "ɵɵi18nExp": () => (/* binding */ ɵɵi18nExp),
/* harmony export */   "ɵɵi18nPostprocess": () => (/* binding */ ɵɵi18nPostprocess),
/* harmony export */   "ɵɵi18nStart": () => (/* binding */ ɵɵi18nStart),
/* harmony export */   "ɵɵinject": () => (/* binding */ ɵɵinject),
/* harmony export */   "ɵɵinjectAttribute": () => (/* binding */ ɵɵinjectAttribute),
/* harmony export */   "ɵɵinvalidFactory": () => (/* binding */ ɵɵinvalidFactory),
/* harmony export */   "ɵɵinvalidFactoryDep": () => (/* binding */ ɵɵinvalidFactoryDep),
/* harmony export */   "ɵɵlistener": () => (/* binding */ ɵɵlistener),
/* harmony export */   "ɵɵloadQuery": () => (/* binding */ ɵɵloadQuery),
/* harmony export */   "ɵɵnamespaceHTML": () => (/* binding */ ɵɵnamespaceHTML),
/* harmony export */   "ɵɵnamespaceMathML": () => (/* binding */ ɵɵnamespaceMathML),
/* harmony export */   "ɵɵnamespaceSVG": () => (/* binding */ ɵɵnamespaceSVG),
/* harmony export */   "ɵɵnextContext": () => (/* binding */ ɵɵnextContext),
/* harmony export */   "ɵɵngDeclareClassMetadata": () => (/* binding */ ɵɵngDeclareClassMetadata),
/* harmony export */   "ɵɵngDeclareClassMetadataAsync": () => (/* binding */ ɵɵngDeclareClassMetadataAsync),
/* harmony export */   "ɵɵngDeclareComponent": () => (/* binding */ ɵɵngDeclareComponent),
/* harmony export */   "ɵɵngDeclareDirective": () => (/* binding */ ɵɵngDeclareDirective),
/* harmony export */   "ɵɵngDeclareFactory": () => (/* binding */ ɵɵngDeclareFactory),
/* harmony export */   "ɵɵngDeclareInjectable": () => (/* binding */ ɵɵngDeclareInjectable),
/* harmony export */   "ɵɵngDeclareInjector": () => (/* binding */ ɵɵngDeclareInjector),
/* harmony export */   "ɵɵngDeclareNgModule": () => (/* binding */ ɵɵngDeclareNgModule),
/* harmony export */   "ɵɵngDeclarePipe": () => (/* binding */ ɵɵngDeclarePipe),
/* harmony export */   "ɵɵpipe": () => (/* binding */ ɵɵpipe),
/* harmony export */   "ɵɵpipeBind1": () => (/* binding */ ɵɵpipeBind1),
/* harmony export */   "ɵɵpipeBind2": () => (/* binding */ ɵɵpipeBind2),
/* harmony export */   "ɵɵpipeBind3": () => (/* binding */ ɵɵpipeBind3),
/* harmony export */   "ɵɵpipeBind4": () => (/* binding */ ɵɵpipeBind4),
/* harmony export */   "ɵɵpipeBindV": () => (/* binding */ ɵɵpipeBindV),
/* harmony export */   "ɵɵprojection": () => (/* binding */ ɵɵprojection),
/* harmony export */   "ɵɵprojectionDef": () => (/* binding */ ɵɵprojectionDef),
/* harmony export */   "ɵɵproperty": () => (/* binding */ ɵɵproperty),
/* harmony export */   "ɵɵpropertyInterpolate": () => (/* binding */ ɵɵpropertyInterpolate),
/* harmony export */   "ɵɵpropertyInterpolate1": () => (/* binding */ ɵɵpropertyInterpolate1),
/* harmony export */   "ɵɵpropertyInterpolate2": () => (/* binding */ ɵɵpropertyInterpolate2),
/* harmony export */   "ɵɵpropertyInterpolate3": () => (/* binding */ ɵɵpropertyInterpolate3),
/* harmony export */   "ɵɵpropertyInterpolate4": () => (/* binding */ ɵɵpropertyInterpolate4),
/* harmony export */   "ɵɵpropertyInterpolate5": () => (/* binding */ ɵɵpropertyInterpolate5),
/* harmony export */   "ɵɵpropertyInterpolate6": () => (/* binding */ ɵɵpropertyInterpolate6),
/* harmony export */   "ɵɵpropertyInterpolate7": () => (/* binding */ ɵɵpropertyInterpolate7),
/* harmony export */   "ɵɵpropertyInterpolate8": () => (/* binding */ ɵɵpropertyInterpolate8),
/* harmony export */   "ɵɵpropertyInterpolateV": () => (/* binding */ ɵɵpropertyInterpolateV),
/* harmony export */   "ɵɵpureFunction0": () => (/* binding */ ɵɵpureFunction0),
/* harmony export */   "ɵɵpureFunction1": () => (/* binding */ ɵɵpureFunction1),
/* harmony export */   "ɵɵpureFunction2": () => (/* binding */ ɵɵpureFunction2),
/* harmony export */   "ɵɵpureFunction3": () => (/* binding */ ɵɵpureFunction3),
/* harmony export */   "ɵɵpureFunction4": () => (/* binding */ ɵɵpureFunction4),
/* harmony export */   "ɵɵpureFunction5": () => (/* binding */ ɵɵpureFunction5),
/* harmony export */   "ɵɵpureFunction6": () => (/* binding */ ɵɵpureFunction6),
/* harmony export */   "ɵɵpureFunction7": () => (/* binding */ ɵɵpureFunction7),
/* harmony export */   "ɵɵpureFunction8": () => (/* binding */ ɵɵpureFunction8),
/* harmony export */   "ɵɵpureFunctionV": () => (/* binding */ ɵɵpureFunctionV),
/* harmony export */   "ɵɵqueryAdvance": () => (/* binding */ ɵɵqueryAdvance),
/* harmony export */   "ɵɵqueryRefresh": () => (/* binding */ ɵɵqueryRefresh),
/* harmony export */   "ɵɵreadContextLet": () => (/* binding */ ɵɵreadContextLet),
/* harmony export */   "ɵɵreference": () => (/* binding */ ɵɵreference),
/* harmony export */   "ɵɵregisterNgModuleType": () => (/* binding */ registerNgModuleType),
/* harmony export */   "ɵɵrepeater": () => (/* binding */ ɵɵrepeater),
/* harmony export */   "ɵɵrepeaterCreate": () => (/* binding */ ɵɵrepeaterCreate),
/* harmony export */   "ɵɵrepeaterTrackByIdentity": () => (/* binding */ ɵɵrepeaterTrackByIdentity),
/* harmony export */   "ɵɵrepeaterTrackByIndex": () => (/* binding */ ɵɵrepeaterTrackByIndex),
/* harmony export */   "ɵɵreplaceMetadata": () => (/* binding */ ɵɵreplaceMetadata),
/* harmony export */   "ɵɵresetView": () => (/* binding */ ɵɵresetView),
/* harmony export */   "ɵɵresolveBody": () => (/* binding */ ɵɵresolveBody),
/* harmony export */   "ɵɵresolveDocument": () => (/* binding */ ɵɵresolveDocument),
/* harmony export */   "ɵɵresolveWindow": () => (/* binding */ ɵɵresolveWindow),
/* harmony export */   "ɵɵrestoreView": () => (/* binding */ ɵɵrestoreView),
/* harmony export */   "ɵɵsanitizeHtml": () => (/* binding */ ɵɵsanitizeHtml),
/* harmony export */   "ɵɵsanitizeResourceUrl": () => (/* binding */ ɵɵsanitizeResourceUrl),
/* harmony export */   "ɵɵsanitizeScript": () => (/* binding */ ɵɵsanitizeScript),
/* harmony export */   "ɵɵsanitizeStyle": () => (/* binding */ ɵɵsanitizeStyle),
/* harmony export */   "ɵɵsanitizeUrl": () => (/* binding */ ɵɵsanitizeUrl),
/* harmony export */   "ɵɵsanitizeUrlOrResourceUrl": () => (/* binding */ ɵɵsanitizeUrlOrResourceUrl),
/* harmony export */   "ɵɵsetComponentScope": () => (/* binding */ ɵɵsetComponentScope),
/* harmony export */   "ɵɵsetNgModuleScope": () => (/* binding */ ɵɵsetNgModuleScope),
/* harmony export */   "ɵɵstoreLet": () => (/* binding */ ɵɵstoreLet),
/* harmony export */   "ɵɵstyleMap": () => (/* binding */ ɵɵstyleMap),
/* harmony export */   "ɵɵstyleMapInterpolate1": () => (/* binding */ ɵɵstyleMapInterpolate1),
/* harmony export */   "ɵɵstyleMapInterpolate2": () => (/* binding */ ɵɵstyleMapInterpolate2),
/* harmony export */   "ɵɵstyleMapInterpolate3": () => (/* binding */ ɵɵstyleMapInterpolate3),
/* harmony export */   "ɵɵstyleMapInterpolate4": () => (/* binding */ ɵɵstyleMapInterpolate4),
/* harmony export */   "ɵɵstyleMapInterpolate5": () => (/* binding */ ɵɵstyleMapInterpolate5),
/* harmony export */   "ɵɵstyleMapInterpolate6": () => (/* binding */ ɵɵstyleMapInterpolate6),
/* harmony export */   "ɵɵstyleMapInterpolate7": () => (/* binding */ ɵɵstyleMapInterpolate7),
/* harmony export */   "ɵɵstyleMapInterpolate8": () => (/* binding */ ɵɵstyleMapInterpolate8),
/* harmony export */   "ɵɵstyleMapInterpolateV": () => (/* binding */ ɵɵstyleMapInterpolateV),
/* harmony export */   "ɵɵstyleProp": () => (/* binding */ ɵɵstyleProp),
/* harmony export */   "ɵɵstylePropInterpolate1": () => (/* binding */ ɵɵstylePropInterpolate1),
/* harmony export */   "ɵɵstylePropInterpolate2": () => (/* binding */ ɵɵstylePropInterpolate2),
/* harmony export */   "ɵɵstylePropInterpolate3": () => (/* binding */ ɵɵstylePropInterpolate3),
/* harmony export */   "ɵɵstylePropInterpolate4": () => (/* binding */ ɵɵstylePropInterpolate4),
/* harmony export */   "ɵɵstylePropInterpolate5": () => (/* binding */ ɵɵstylePropInterpolate5),
/* harmony export */   "ɵɵstylePropInterpolate6": () => (/* binding */ ɵɵstylePropInterpolate6),
/* harmony export */   "ɵɵstylePropInterpolate7": () => (/* binding */ ɵɵstylePropInterpolate7),
/* harmony export */   "ɵɵstylePropInterpolate8": () => (/* binding */ ɵɵstylePropInterpolate8),
/* harmony export */   "ɵɵstylePropInterpolateV": () => (/* binding */ ɵɵstylePropInterpolateV),
/* harmony export */   "ɵɵsyntheticHostListener": () => (/* binding */ ɵɵsyntheticHostListener),
/* harmony export */   "ɵɵsyntheticHostProperty": () => (/* binding */ ɵɵsyntheticHostProperty),
/* harmony export */   "ɵɵtemplate": () => (/* binding */ ɵɵtemplate),
/* harmony export */   "ɵɵtemplateRefExtractor": () => (/* binding */ ɵɵtemplateRefExtractor),
/* harmony export */   "ɵɵtext": () => (/* binding */ ɵɵtext),
/* harmony export */   "ɵɵtextInterpolate": () => (/* binding */ ɵɵtextInterpolate),
/* harmony export */   "ɵɵtextInterpolate1": () => (/* binding */ ɵɵtextInterpolate1),
/* harmony export */   "ɵɵtextInterpolate2": () => (/* binding */ ɵɵtextInterpolate2),
/* harmony export */   "ɵɵtextInterpolate3": () => (/* binding */ ɵɵtextInterpolate3),
/* harmony export */   "ɵɵtextInterpolate4": () => (/* binding */ ɵɵtextInterpolate4),
/* harmony export */   "ɵɵtextInterpolate5": () => (/* binding */ ɵɵtextInterpolate5),
/* harmony export */   "ɵɵtextInterpolate6": () => (/* binding */ ɵɵtextInterpolate6),
/* harmony export */   "ɵɵtextInterpolate7": () => (/* binding */ ɵɵtextInterpolate7),
/* harmony export */   "ɵɵtextInterpolate8": () => (/* binding */ ɵɵtextInterpolate8),
/* harmony export */   "ɵɵtextInterpolateV": () => (/* binding */ ɵɵtextInterpolateV),
/* harmony export */   "ɵɵtrustConstantHtml": () => (/* binding */ ɵɵtrustConstantHtml),
/* harmony export */   "ɵɵtrustConstantResourceUrl": () => (/* binding */ ɵɵtrustConstantResourceUrl),
/* harmony export */   "ɵɵtwoWayBindingSet": () => (/* binding */ ɵɵtwoWayBindingSet),
/* harmony export */   "ɵɵtwoWayListener": () => (/* binding */ ɵɵtwoWayListener),
/* harmony export */   "ɵɵtwoWayProperty": () => (/* binding */ ɵɵtwoWayProperty),
/* harmony export */   "ɵɵvalidateIframeAttribute": () => (/* binding */ ɵɵvalidateIframeAttribute),
/* harmony export */   "ɵɵviewQuery": () => (/* binding */ ɵɵviewQuery),
/* harmony export */   "ɵɵviewQuerySignal": () => (/* binding */ ɵɵviewQuerySignal)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core/primitives/signals */ 2665);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs */ 2273);
/* harmony import */ var _angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/core/primitives/event-dispatch */ 4281);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs/operators */ 6634);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs/operators */ 8898);

/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */







/**
 * Base URL for the error details page.
 *
 * Keep this constant in sync across:
 *  - packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts
 *  - packages/core/src/error_details_base_url.ts
 */
const ERROR_DETAILS_PAGE_BASE_URL = 'https://angular.dev/errors';
/**
 * URL for the XSS security documentation.
 */
const XSS_SECURITY_URL = 'https://g.co/ng/security#xss';

/**
 * Class that represents a runtime error.
 * Formats and outputs the error message in a consistent way.
 *
 * Example:
 * ```
 *  throw new RuntimeError(
 *    RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
 *    ngDevMode && 'Injector has already been destroyed.');
 * ```
 *
 * Note: the `message` argument contains a descriptive error message as a string in development
 * mode (when the `ngDevMode` is defined). In production mode (after tree-shaking pass), the
 * `message` argument becomes `false`, thus we account for it in the typings and the runtime
 * logic.
 */
class RuntimeError extends Error {
  code;
  constructor(code, message) {
    super(formatRuntimeError(code, message));
    this.code = code;
  }
}
/**
 * Called to format a runtime error.
 * See additional info on the `message` argument type in the `RuntimeError` class description.
 */
function formatRuntimeError(code, message) {
  // Error code might be a negative number, which is a special marker that instructs the logic to
  // generate a link to the error details page on angular.io.
  // We also prepend `0` to non-compile-time errors.
  const fullCode = `NG0${Math.abs(code)}`;
  let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;
  if (ngDevMode && code < 0) {
    const addPeriodSeparator = !errorMessage.match(/[.,;!?\n]$/);
    const separator = addPeriodSeparator ? '.' : '';
    errorMessage = `${errorMessage}${separator} Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/${fullCode}`;
  }
  return errorMessage;
}
const REQUIRED_UNSET_VALUE = /* @__PURE__ */Symbol('InputSignalNode#UNSET');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const INPUT_SIGNAL_NODE = /* @__PURE__ */(() => {
  return {
    ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL_NODE,
    transformFn: undefined,
    applyValueToInputSignal(node, value) {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalSetFn)(node, value);
    }
  };
})();
const ɵINPUT_SIGNAL_BRAND_READ_TYPE = /* @__PURE__ */Symbol();
const ɵINPUT_SIGNAL_BRAND_WRITE_TYPE = /* @__PURE__ */Symbol();
/**
 * Creates an input signal.
 *
 * @param initialValue The initial value.
 *   Can be set to {@link REQUIRED_UNSET_VALUE} for required inputs.
 * @param options Additional options for the input. e.g. a transform, or an alias.
 */
function createInputSignal(initialValue, options) {
  const node = Object.create(INPUT_SIGNAL_NODE);
  node.value = initialValue;
  // Perf note: Always set `transformFn` here to ensure that `node` always
  // has the same v8 class shape, allowing monomorphic reads on input signals.
  node.transformFn = options?.transform;
  function inputValueFn() {
    // Record that someone looked at this signal.
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerAccessed)(node);
    if (node.value === REQUIRED_UNSET_VALUE) {
      throw new RuntimeError(-950 /* RuntimeErrorCode.REQUIRED_INPUT_NO_VALUE */, ngDevMode && 'Input is required but no value is available yet.');
    }
    return node.value;
  }
  inputValueFn[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
  if (ngDevMode) {
    inputValueFn.toString = () => `[Input Signal: ${inputValueFn()}]`;
    node.debugName = options?.debugName;
  }
  return inputValueFn;
}

/**
 * Convince closure compiler that the wrapped function has no side-effects.
 *
 * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
 * allow us to execute a function but have closure compiler mark the call as no-side-effects.
 * It is important that the return value for the `noSideEffects` function be assigned
 * to something which is retained otherwise the call to `noSideEffects` will be removed by closure
 * compiler.
 */
function noSideEffects(fn) {
  return {
    toString: fn
  }.toString();
}
const ANNOTATIONS = '__annotations__';
const PARAMETERS = '__parameters__';
const PROP_METADATA = '__prop__metadata__';
/**
 * @suppress {globalThis}
 */
function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
  return noSideEffects(() => {
    const metaCtor = makeMetadataCtor(props);
    function DecoratorFactory(...args) {
      if (this instanceof DecoratorFactory) {
        metaCtor.call(this, ...args);
        return this;
      }
      const annotationInstance = new DecoratorFactory(...args);
      return function TypeDecorator(cls) {
        if (typeFn) typeFn(cls, ...args);
        // Use of Object.defineProperty is important since it creates non-enumerable property which
        // prevents the property is copied during subclassing.
        const annotations = cls.hasOwnProperty(ANNOTATIONS) ? cls[ANNOTATIONS] : Object.defineProperty(cls, ANNOTATIONS, {
          value: []
        })[ANNOTATIONS];
        annotations.push(annotationInstance);
        if (additionalProcessing) additionalProcessing(cls);
        return cls;
      };
    }
    if (parentClass) {
      DecoratorFactory.prototype = Object.create(parentClass.prototype);
    }
    DecoratorFactory.prototype.ngMetadataName = name;
    DecoratorFactory.annotationCls = DecoratorFactory;
    return DecoratorFactory;
  });
}
function makeMetadataCtor(props) {
  return function ctor(...args) {
    if (props) {
      const values = props(...args);
      for (const propName in values) {
        this[propName] = values[propName];
      }
    }
  };
}
function makeParamDecorator(name, props, parentClass) {
  return noSideEffects(() => {
    const metaCtor = makeMetadataCtor(props);
    function ParamDecoratorFactory(...args) {
      if (this instanceof ParamDecoratorFactory) {
        metaCtor.apply(this, args);
        return this;
      }
      const annotationInstance = new ParamDecoratorFactory(...args);
      ParamDecorator.annotation = annotationInstance;
      return ParamDecorator;
      function ParamDecorator(cls, unusedKey, index) {
        // Use of Object.defineProperty is important since it creates non-enumerable property which
        // prevents the property is copied during subclassing.
        const parameters = cls.hasOwnProperty(PARAMETERS) ? cls[PARAMETERS] : Object.defineProperty(cls, PARAMETERS, {
          value: []
        })[PARAMETERS];
        // there might be gaps if some in between parameters do not have annotations.
        // we pad with nulls.
        while (parameters.length <= index) {
          parameters.push(null);
        }
        (parameters[index] = parameters[index] || []).push(annotationInstance);
        return cls;
      }
    }
    if (parentClass) {
      ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
    }
    ParamDecoratorFactory.prototype.ngMetadataName = name;
    ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
    return ParamDecoratorFactory;
  });
}
function makePropDecorator(name, props, parentClass, additionalProcessing) {
  return noSideEffects(() => {
    const metaCtor = makeMetadataCtor(props);
    function PropDecoratorFactory(...args) {
      if (this instanceof PropDecoratorFactory) {
        metaCtor.apply(this, args);
        return this;
      }
      const decoratorInstance = new PropDecoratorFactory(...args);
      function PropDecorator(target, name) {
        // target is undefined with standard decorators. This case is not supported and will throw
        // if this decorator is used in JIT mode with standard decorators.
        if (target === undefined) {
          throw new Error('Standard Angular field decorators are not supported in JIT mode.');
        }
        const constructor = target.constructor;
        // Use of Object.defineProperty is important because it creates a non-enumerable property
        // which prevents the property from being copied during subclassing.
        const meta = constructor.hasOwnProperty(PROP_METADATA) ? constructor[PROP_METADATA] : Object.defineProperty(constructor, PROP_METADATA, {
          value: {}
        })[PROP_METADATA];
        meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
        meta[name].unshift(decoratorInstance);
        if (additionalProcessing) additionalProcessing(target, name, ...args);
      }
      return PropDecorator;
    }
    if (parentClass) {
      PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
    }
    PropDecoratorFactory.prototype.ngMetadataName = name;
    PropDecoratorFactory.annotationCls = PropDecoratorFactory;
    return PropDecoratorFactory;
  });
}
const _global = globalThis;
function ngDevModeResetPerfCounters() {
  const locationString = typeof location !== 'undefined' ? location.toString() : '';
  const newCounters = {
    namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
    firstCreatePass: 0,
    tNode: 0,
    tView: 0,
    rendererCreateTextNode: 0,
    rendererSetText: 0,
    rendererCreateElement: 0,
    rendererAddEventListener: 0,
    rendererSetAttribute: 0,
    rendererRemoveAttribute: 0,
    rendererSetProperty: 0,
    rendererSetClassName: 0,
    rendererAddClass: 0,
    rendererRemoveClass: 0,
    rendererSetStyle: 0,
    rendererRemoveStyle: 0,
    rendererDestroy: 0,
    rendererDestroyNode: 0,
    rendererMoveNode: 0,
    rendererRemoveNode: 0,
    rendererAppendChild: 0,
    rendererInsertBefore: 0,
    rendererCreateComment: 0,
    hydratedNodes: 0,
    hydratedComponents: 0,
    dehydratedViewsRemoved: 0,
    dehydratedViewsCleanupRuns: 0,
    componentsSkippedHydration: 0
  };
  // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
  const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
  if (!allowNgDevModeTrue) {
    _global['ngDevMode'] = false;
  } else {
    if (typeof _global['ngDevMode'] !== 'object') {
      _global['ngDevMode'] = {};
    }
    Object.assign(_global['ngDevMode'], newCounters);
  }
  return newCounters;
}
/**
 * This function checks to see if the `ngDevMode` has been set. If yes,
 * then we honor it, otherwise we default to dev mode with additional checks.
 *
 * The idea is that unless we are doing production build where we explicitly
 * set `ngDevMode == false` we should be helping the developer by providing
 * as much early warning and errors as possible.
 *
 * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions
 * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode
 * is defined for the entire instruction set.
 *
 * When checking `ngDevMode` on toplevel, always init it before referencing it
 * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can
 *  get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.
 *
 * Details on possible values for `ngDevMode` can be found on its docstring.
 *
 * NOTE:
 * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
 */
function initNgDevMode() {
  // The below checks are to ensure that calling `initNgDevMode` multiple times does not
  // reset the counters.
  // If the `ngDevMode` is not an object, then it means we have not created the perf counters
  // yet.
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (typeof ngDevMode !== 'object' || Object.keys(ngDevMode).length === 0) {
      ngDevModeResetPerfCounters();
    }
    return typeof ngDevMode !== 'undefined' && !!ngDevMode;
  }
  return false;
}
function getClosureSafeProperty(objWithPropertyToExtract) {
  for (let key in objWithPropertyToExtract) {
    if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
      return key;
    }
  }
  throw Error('Could not find renamed property on target object.');
}
/**
 * Sets properties on a target object from a source object, but only if
 * the property doesn't already exist on the target object.
 * @param target The target to set properties on
 * @param source The source of the property keys and values to set
 */
function fillProperties(target, source) {
  for (const key in source) {
    if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
      target[key] = source[key];
    }
  }
}
function stringify(token) {
  if (typeof token === 'string') {
    return token;
  }
  if (Array.isArray(token)) {
    return '[' + token.map(stringify).join(', ') + ']';
  }
  if (token == null) {
    return '' + token;
  }
  if (token.overriddenName) {
    return `${token.overriddenName}`;
  }
  if (token.name) {
    return `${token.name}`;
  }
  const res = token.toString();
  if (res == null) {
    return '' + res;
  }
  const newLineIndex = res.indexOf('\n');
  return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
 * Concatenates two strings with separator, allocating new strings only when necessary.
 *
 * @param before before string.
 * @param separator separator string.
 * @param after after string.
 * @returns concatenated string.
 */
function concatStringsWithSpace(before, after) {
  return before == null || before === '' ? after === null ? '' : after : after == null || after === '' ? before : before + ' ' + after;
}
/**
 * Ellipses the string in the middle when longer than the max length
 *
 * @param string
 * @param maxLength of the output string
 * @returns ellipsed string with ... in the middle
 */
function truncateMiddle(str, maxLength = 100) {
  if (!str || maxLength < 1 || str.length <= maxLength) return str;
  if (maxLength == 1) return str.substring(0, 1) + '...';
  const halfLimit = Math.round(maxLength / 2);
  return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);
}
const __forward_ref__ = /*#__PURE__*/getClosureSafeProperty({
  __forward_ref__: getClosureSafeProperty
});
/**
 * Allows to refer to references which are not yet defined.
 *
 * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
 * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
 * a query is not yet defined.
 *
 * `forwardRef` is also used to break circularities in standalone components imports.
 *
 * @usageNotes
 * ### Circular dependency example
 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
 *
 * ### Circular standalone reference import example
 * ```ts
 * @Component({
 *   standalone: true,
 *   imports: [ChildComponent],
 *   selector: 'app-parent',
 *   template: `<app-child [hideParent]="hideParent"></app-child>`,
 * })
 * export class ParentComponent {
 *   @Input() hideParent: boolean;
 * }
 *
 *
 * @Component({
 *   standalone: true,
 *   imports: [CommonModule, forwardRef(() => ParentComponent)],
 *   selector: 'app-child',
 *   template: `<app-parent *ngIf="!hideParent"></app-parent>`,
 * })
 * export class ChildComponent {
 *   @Input() hideParent: boolean;
 * }
 * ```
 *
 * @publicApi
 */
function forwardRef(forwardRefFn) {
  forwardRefFn.__forward_ref__ = forwardRef;
  forwardRefFn.toString = function () {
    return stringify(this());
  };
  return forwardRefFn;
}
/**
 * Lazily retrieves the reference value from a forwardRef.
 *
 * Acts as the identity function when given a non-forward-ref value.
 *
 * @usageNotes
 * ### Example
 *
 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
 *
 * @see {@link forwardRef}
 * @publicApi
 */
function resolveForwardRef(type) {
  return isForwardRef(type) ? type() : type;
}
/** Checks whether a function is wrapped by a `forwardRef`. */
function isForwardRef(fn) {
  return typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) && fn.__forward_ref__ === forwardRef;
}

// The functions in this file verify that the assumptions we are making
function assertNumber(actual, msg) {
  if (!(typeof actual === 'number')) {
    throwError(msg, typeof actual, 'number', '===');
  }
}
function assertNumberInRange(actual, minInclusive, maxInclusive) {
  assertNumber(actual, 'Expected a number');
  assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
  assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
}
function assertString(actual, msg) {
  if (!(typeof actual === 'string')) {
    throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
  }
}
function assertFunction(actual, msg) {
  if (!(typeof actual === 'function')) {
    throwError(msg, actual === null ? 'null' : typeof actual, 'function', '===');
  }
}
function assertEqual(actual, expected, msg) {
  if (!(actual == expected)) {
    throwError(msg, actual, expected, '==');
  }
}
function assertNotEqual(actual, expected, msg) {
  if (!(actual != expected)) {
    throwError(msg, actual, expected, '!=');
  }
}
function assertSame(actual, expected, msg) {
  if (!(actual === expected)) {
    throwError(msg, actual, expected, '===');
  }
}
function assertNotSame(actual, expected, msg) {
  if (!(actual !== expected)) {
    throwError(msg, actual, expected, '!==');
  }
}
function assertLessThan(actual, expected, msg) {
  if (!(actual < expected)) {
    throwError(msg, actual, expected, '<');
  }
}
function assertLessThanOrEqual(actual, expected, msg) {
  if (!(actual <= expected)) {
    throwError(msg, actual, expected, '<=');
  }
}
function assertGreaterThan(actual, expected, msg) {
  if (!(actual > expected)) {
    throwError(msg, actual, expected, '>');
  }
}
function assertGreaterThanOrEqual(actual, expected, msg) {
  if (!(actual >= expected)) {
    throwError(msg, actual, expected, '>=');
  }
}
function assertNotDefined(actual, msg) {
  if (actual != null) {
    throwError(msg, actual, null, '==');
  }
}
function assertDefined(actual, msg) {
  if (actual == null) {
    throwError(msg, actual, null, '!=');
  }
}
function throwError(msg, actual, expected, comparison) {
  throw new Error(`ASSERTION ERROR: ${msg}` + (comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
}
function assertDomNode(node) {
  if (!(node instanceof Node)) {
    throwError(`The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
  }
}
function assertElement(node) {
  if (!(node instanceof Element)) {
    throwError(`The provided value must be an element but got ${stringify(node)}`);
  }
}
function assertIndexInRange(arr, index) {
  assertDefined(arr, 'Array must be defined.');
  const maxLen = arr.length;
  if (index < 0 || index >= maxLen) {
    throwError(`Index expected to be less than ${maxLen} but got ${index}`);
  }
}
function assertOneOf(value, ...validValues) {
  if (validValues.indexOf(value) !== -1) return true;
  throwError(`Expected value to be one of ${JSON.stringify(validValues)} but was ${JSON.stringify(value)}.`);
}
function assertNotReactive(fn) {
  if ((0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.getActiveConsumer)() !== null) {
    throwError(`${fn}() should never be called in a reactive context.`);
  }
}

/**
 * Construct an injectable definition which defines how a token will be constructed by the DI
 * system, and in which injectors (if any) it will be available.
 *
 * This should be assigned to a static `ɵprov` field on a type, which will then be an
 * `InjectableType`.
 *
 * Options:
 * * `providedIn` determines which injectors will include the injectable, by either associating it
 *   with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
 *   provided in the `'root'` injector, which will be the application-level injector in most apps.
 * * `factory` gives the zero argument function which will create an instance of the injectable.
 *   The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection
 * of dependencies.
 *
 * @codeGenApi
 * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.
 */
function ɵɵdefineInjectable(opts) {
  return {
    token: opts.token,
    providedIn: opts.providedIn || null,
    factory: opts.factory,
    value: undefined
  };
}
/**
 * @deprecated in v8, delete after v10. This API should be used only by generated code, and that
 * code should now use ɵɵdefineInjectable instead.
 * @publicApi
 */
const defineInjectable = ɵɵdefineInjectable;
/**
 * Construct an `InjectorDef` which configures an injector.
 *
 * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
 * `InjectorType`.
 *
 * Options:
 *
 * * `providers`: an optional array of providers to add to the injector. Each provider must
 *   either have a factory or point to a type which has a `ɵprov` static property (the
 *   type must be an `InjectableType`).
 * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
 *   whose providers will also be added to the injector. Locally provided types will override
 *   providers from imports.
 *
 * @codeGenApi
 */
function ɵɵdefineInjector(options) {
  return {
    providers: options.providers || [],
    imports: options.imports || []
  };
}
/**
 * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
 * inherited value.
 *
 * @param type A type which may have its own (non-inherited) `ɵprov`.
 */
function getInjectableDef(type) {
  return getOwnDefinition(type, NG_PROV_DEF) || getOwnDefinition(type, NG_INJECTABLE_DEF);
}
function isInjectable(type) {
  return getInjectableDef(type) !== null;
}
/**
 * Return definition only if it is defined directly on `type` and is not inherited from a base
 * class of `type`.
 */
function getOwnDefinition(type, field) {
  return type.hasOwnProperty(field) ? type[field] : null;
}
/**
 * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
 *
 * @param type A type which may have `ɵprov`, via inheritance.
 *
 * @deprecated Will be removed in a future version of Angular, where an error will occur in the
 *     scenario if we find the `ɵprov` on an ancestor only.
 */
function getInheritedInjectableDef(type) {
  const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF]);
  if (def) {
    ngDevMode && console.warn(`DEPRECATED: DI is instantiating a token "${type.name}" that inherits its @Injectable decorator but does not provide one itself.\n` + `This will become an error in a future version of Angular. Please add @Injectable() to the "${type.name}" class.`);
    return def;
  } else {
    return null;
  }
}
/**
 * Read the injector def type in a way which is immune to accidentally reading inherited value.
 *
 * @param type type which may have an injector def (`ɵinj`)
 */
function getInjectorDef(type) {
  return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF)) ? type[NG_INJ_DEF] : null;
}
const NG_PROV_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵprov: getClosureSafeProperty
});
const NG_INJ_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵinj: getClosureSafeProperty
});
// We need to keep these around so we can read off old defs if new defs are unavailable
const NG_INJECTABLE_DEF = /*#__PURE__*/getClosureSafeProperty({
  ngInjectableDef: getClosureSafeProperty
});
const NG_INJECTOR_DEF = /*#__PURE__*/getClosureSafeProperty({
  ngInjectorDef: getClosureSafeProperty
});

/**
 * Creates a token that can be used in a DI Provider.
 *
 * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
 * runtime representation) such as when injecting an interface, callable type, array or
 * parameterized type.
 *
 * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
 * the `Injector`. This provides an additional level of type safety.
 *
 * <div class="alert is-helpful">
 *
 * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
 * provider and the injection call. Creating a new instance of `InjectionToken` in different places,
 * even with the same description, will be treated as different tokens by Angular's DI system,
 * leading to a `NullInjectorError`.
 *
 * </div>
 *
 * <code-example format="typescript" language="typescript" path="injection-token/src/main.ts"
 * region="InjectionToken"></code-example>
 *
 * When creating an `InjectionToken`, you can optionally specify a factory function which returns
 * (possibly by creating) a default value of the parameterized type `T`. This sets up the
 * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
 * application's root injector. If the factory function, which takes zero arguments, needs to inject
 * dependencies, it can do so using the [`inject`](api/core/inject) function.
 * As you can see in the Tree-shakable InjectionToken example below.
 *
 * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
 * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:
 * this option is now deprecated). As mentioned above, `'root'` is the default value for
 * `providedIn`.
 *
 * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
 *
 * @usageNotes
 * ### Basic Examples
 *
 * ### Plain InjectionToken
 *
 * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
 *
 * ### Tree-shakable InjectionToken
 *
 * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
 *
 * @publicApi
 */
class InjectionToken {
  _desc;
  /** @internal */
  ngMetadataName = 'InjectionToken';
  ɵprov;
  /**
   * @param _desc   Description for the token,
   *                used only for debugging purposes,
   *                it should but does not need to be unique
   * @param options Options for the token's usage, as described above
   */
  constructor(_desc, options) {
    this._desc = _desc;
    this.ɵprov = undefined;
    if (typeof options == 'number') {
      (typeof ngDevMode === 'undefined' || ngDevMode) && assertLessThan(options, 0, 'Only negative numbers are supported here');
      // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
      // See `InjectorMarkers`
      this.__NG_ELEMENT_ID__ = options;
    } else if (options !== undefined) {
      this.ɵprov = ɵɵdefineInjectable({
        token: this,
        providedIn: options.providedIn || 'root',
        factory: options.factory
      });
    }
  }
  /**
   * @internal
   */
  get multi() {
    return this;
  }
  toString() {
    return `InjectionToken ${this._desc}`;
  }
}
let _injectorProfilerContext;
function getInjectorProfilerContext() {
  !ngDevMode && throwError('getInjectorProfilerContext should never be called in production mode');
  return _injectorProfilerContext;
}
function setInjectorProfilerContext(context) {
  !ngDevMode && throwError('setInjectorProfilerContext should never be called in production mode');
  const previous = _injectorProfilerContext;
  _injectorProfilerContext = context;
  return previous;
}
let injectorProfilerCallback = null;
/**
 * Sets the callback function which will be invoked during certain DI events within the
 * runtime (for example: injecting services, creating injectable instances, configuring providers)
 *
 * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
 * The contract of the function might be changed in any release and/or the function can be removed
 * completely.
 *
 * @param profiler function provided by the caller or null value to disable profiling.
 */
const setInjectorProfiler = injectorProfiler => {
  !ngDevMode && throwError('setInjectorProfiler should never be called in production mode');
  injectorProfilerCallback = injectorProfiler;
};
/**
 * Injector profiler function which emits on DI events executed by the runtime.
 *
 * @param event InjectorProfilerEvent corresponding to the DI event being emitted
 */
function injectorProfiler(event) {
  !ngDevMode && throwError('Injector profiler should never be called in production mode');
  if (injectorProfilerCallback != null /* both `null` and `undefined` */) {
    injectorProfilerCallback(event);
  }
}
/**
 * Emits an InjectorProfilerEventType.ProviderConfigured to the injector profiler. The data in the
 * emitted event includes the raw provider, as well as the token that provider is providing.
 *
 * @param eventProvider A provider object
 */
function emitProviderConfiguredEvent(eventProvider, isViewProvider = false) {
  !ngDevMode && throwError('Injector profiler should never be called in production mode');
  let token;
  // if the provider is a TypeProvider (typeof provider is function) then the token is the
  // provider itself
  if (typeof eventProvider === 'function') {
    token = eventProvider;
  }
  // if the provider is an injection token, then the token is the injection token.
  else if (eventProvider instanceof InjectionToken) {
    token = eventProvider;
  }
  // in all other cases we can access the token via the `provide` property of the provider
  else {
    token = resolveForwardRef(eventProvider.provide);
  }
  let provider = eventProvider;
  // Injection tokens may define their own default provider which gets attached to the token itself
  // as `ɵprov`. In this case, we want to emit the provider that is attached to the token, not the
  // token itself.
  if (eventProvider instanceof InjectionToken) {
    provider = eventProvider.ɵprov || eventProvider;
  }
  injectorProfiler({
    type: 2 /* InjectorProfilerEventType.ProviderConfigured */,
    context: getInjectorProfilerContext(),
    providerRecord: {
      token,
      provider,
      isViewProvider
    }
  });
}
/**
 * Emits an event to the injector profiler with the instance that was created. Note that
 * the injector associated with this emission can be accessed by using getDebugInjectContext()
 *
 * @param instance an object created by an injector
 */
function emitInstanceCreatedByInjectorEvent(instance) {
  !ngDevMode && throwError('Injector profiler should never be called in production mode');
  injectorProfiler({
    type: 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */,
    context: getInjectorProfilerContext(),
    instance: {
      value: instance
    }
  });
}
/**
 * @param token DI token associated with injected service
 * @param value the instance of the injected service (i.e the result of `inject(token)`)
 * @param flags the flags that the token was injected with
 */
function emitInjectEvent(token, value, flags) {
  !ngDevMode && throwError('Injector profiler should never be called in production mode');
  injectorProfiler({
    type: 0 /* InjectorProfilerEventType.Inject */,
    context: getInjectorProfilerContext(),
    service: {
      token,
      value,
      flags
    }
  });
}
function runInInjectorProfilerContext(injector, token, callback) {
  !ngDevMode && throwError('runInInjectorProfilerContext should never be called in production mode');
  const prevInjectContext = setInjectorProfilerContext({
    injector,
    token
  });
  try {
    callback();
  } finally {
    setInjectorProfilerContext(prevInjectContext);
  }
}
function isEnvironmentProviders(value) {
  return value && !!value.ɵproviders;
}
const NG_COMP_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵcmp: getClosureSafeProperty
});
const NG_DIR_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵdir: getClosureSafeProperty
});
const NG_PIPE_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵpipe: getClosureSafeProperty
});
const NG_MOD_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵmod: getClosureSafeProperty
});
const NG_FACTORY_DEF = /*#__PURE__*/getClosureSafeProperty({
  ɵfac: getClosureSafeProperty
});
/**
 * If a directive is diPublic, bloomAdd sets a property on the type with this constant as
 * the key and the directive's unique ID as the value. This allows us to map directives to their
 * bloom filter bit for DI.
 */
// TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
const NG_ELEMENT_ID = /*#__PURE__*/getClosureSafeProperty({
  __NG_ELEMENT_ID__: getClosureSafeProperty
});
/**
 * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`:
 * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution
 * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function.
 *
 * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and
 * improve tree-shaking.
 */
const NG_ENV_ID = /*#__PURE__*/getClosureSafeProperty({
  __NG_ENV_ID__: getClosureSafeProperty
});

/**
 * Used for stringify render output in Ivy.
 * Important! This function is very performance-sensitive and we should
 * be extra careful not to introduce megamorphic reads in it.
 * Check `core/test/render3/perf/render_stringify` for benchmarks and alternate implementations.
 */
function renderStringify(value) {
  if (typeof value === 'string') return value;
  if (value == null) return '';
  // Use `String` so that it invokes the `toString` method of the value. Note that this
  // appears to be faster than calling `value.toString` (see `render_stringify` benchmark).
  return String(value);
}
/**
 * Used to stringify a value so that it can be displayed in an error message.
 *
 * Important! This function contains a megamorphic read and should only be
 * used for error messages.
 */
function stringifyForError(value) {
  if (typeof value === 'function') return value.name || value.toString();
  if (typeof value === 'object' && value != null && typeof value.type === 'function') {
    return value.type.name || value.type.toString();
  }
  return renderStringify(value);
}
/**
 * Used to stringify a `Type` and including the file path and line number in which it is defined, if
 * possible, for better debugging experience.
 *
 * Important! This function contains a megamorphic read and should only be used for error messages.
 */
function debugStringifyTypeForError(type) {
  // TODO(pmvald): Do some refactoring so that we can use getComponentDef here without creating
  // circular deps.
  let componentDef = type[NG_COMP_DEF] || null;
  if (componentDef !== null && componentDef.debugInfo) {
    return stringifyTypeFromDebugInfo(componentDef.debugInfo);
  }
  return stringifyForError(type);
}
// TODO(pmvald): Do some refactoring so that we can use the type ClassDebugInfo for the param
// debugInfo here without creating circular deps.
function stringifyTypeFromDebugInfo(debugInfo) {
  if (!debugInfo.filePath || !debugInfo.lineNumber) {
    return debugInfo.className;
  } else {
    return `${debugInfo.className} (at ${debugInfo.filePath}:${debugInfo.lineNumber})`;
  }
}

/** Called when directives inject each other (creating a circular dependency) */
function throwCyclicDependencyError(token, path) {
  const depPath = path ? `. Dependency path: ${path.join(' > ')} > ${token}` : '';
  throw new RuntimeError(-200 /* RuntimeErrorCode.CYCLIC_DI_DEPENDENCY */, ngDevMode ? `Circular dependency in DI detected for ${token}${depPath}` : token);
}
function throwMixedMultiProviderError() {
  throw new Error(`Cannot mix multi providers and regular providers`);
}
function throwInvalidProviderError(ngModuleType, providers, provider) {
  if (ngModuleType && providers) {
    const providerDetail = providers.map(v => v == provider ? '?' + provider + '?' : '...');
    throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}' - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`);
  } else if (isEnvironmentProviders(provider)) {
    if (provider.ɵfromNgModule) {
      throw new RuntimeError(207 /* RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT */, `Invalid providers from 'importProvidersFrom' present in a non-environment injector. 'importProvidersFrom' can't be used for component providers.`);
    } else {
      throw new RuntimeError(207 /* RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT */, `Invalid providers present in a non-environment injector. 'EnvironmentProviders' can't be used for component providers.`);
    }
  } else {
    throw new Error('Invalid provider');
  }
}
/** Throws an error when a token is not found in DI. */
function throwProviderNotFoundError(token, injectorName) {
  const errorMessage = ngDevMode && `No provider for ${stringifyForError(token)} found${injectorName ? ` in ${injectorName}` : ''}`;
  throw new RuntimeError(-201 /* RuntimeErrorCode.PROVIDER_NOT_FOUND */, errorMessage);
}

/**
 * Injection flags for DI.
 *
 * @publicApi
 * @deprecated use an options object for [`inject`](api/core/inject) instead.
 */
var InjectFlags = /*#__PURE__*/function (InjectFlags) {
  // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer
  // writes exports of it into ngfactory files.
  /** Check self and check parent injector if needed */
  InjectFlags[InjectFlags["Default"] = 0] = "Default";
  /**
   * Specifies that an injector should retrieve a dependency from any injector until reaching the
   * host element of the current component. (Only used with Element Injector)
   */
  InjectFlags[InjectFlags["Host"] = 1] = "Host";
  /** Don't ascend to ancestors of the node requesting injection. */
  InjectFlags[InjectFlags["Self"] = 2] = "Self";
  /** Skip the node that is requesting injection. */
  InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
  /** Inject `defaultValue` instead if token not found. */
  InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
  return InjectFlags;
}(InjectFlags || {});
/**
 * Current implementation of inject.
 *
 * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
 * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
 * way for two reasons:
 *  1. `Injector` should not depend on ivy logic.
 *  2. To maintain tree shake-ability we don't want to bring in unnecessary code.
 */
let _injectImplementation;
function getInjectImplementation() {
  return _injectImplementation;
}
/**
 * Sets the current inject implementation.
 */
function setInjectImplementation(impl) {
  const previous = _injectImplementation;
  _injectImplementation = impl;
  return previous;
}
/**
 * Injects `root` tokens in limp mode.
 *
 * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
 * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
 * injectable definition.
 */
function injectRootLimpMode(token, notFoundValue, flags) {
  const injectableDef = getInjectableDef(token);
  if (injectableDef && injectableDef.providedIn == 'root') {
    return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() : injectableDef.value;
  }
  if (flags & InjectFlags.Optional) return null;
  if (notFoundValue !== undefined) return notFoundValue;
  throwProviderNotFoundError(token, 'Injector');
}
/**
 * Assert that `_injectImplementation` is not `fn`.
 *
 * This is useful, to prevent infinite recursion.
 *
 * @param fn Function which it should not equal to
 */
function assertInjectImplementationNotEqual(fn) {
  ngDevMode && assertNotEqual(_injectImplementation, fn, 'Calling ɵɵinject would cause infinite recursion');
}
const _THROW_IF_NOT_FOUND = {};
const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
/*
 * Name of a property (that we patch onto DI decorator), which is used as an annotation of which
 * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators
 * in the code, thus making them tree-shakable.
 */
const DI_DECORATOR_FLAG = '__NG_DI_FLAG__';
const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
const NG_TOKEN_PATH = 'ngTokenPath';
const NEW_LINE = /\n/gm;
const NO_NEW_LINE = 'ɵ';
const SOURCE = '__source';
/**
 * Current injector value used by `inject`.
 * - `undefined`: it is an error to call `inject`
 * - `null`: `inject` can be called but there is no injector (limp-mode).
 * - Injector instance: Use the injector for resolution.
 */
let _currentInjector = undefined;
function getCurrentInjector() {
  return _currentInjector;
}
function setCurrentInjector(injector) {
  const former = _currentInjector;
  _currentInjector = injector;
  return former;
}
function injectInjectorOnly(token, flags = InjectFlags.Default) {
  if (_currentInjector === undefined) {
    throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode && `inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with \`runInInjectionContext\`.`);
  } else if (_currentInjector === null) {
    return injectRootLimpMode(token, undefined, flags);
  } else {
    const value = _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
    ngDevMode && emitInjectEvent(token, value, flags);
    return value;
  }
}
function ɵɵinject(token, flags = InjectFlags.Default) {
  return (getInjectImplementation() || injectInjectorOnly)(resolveForwardRef(token), flags);
}
/**
 * Throws an error indicating that a factory function could not be generated by the compiler for a
 * particular class.
 *
 * The name of the class is not mentioned here, but will be in the generated factory function name
 * and thus in the stack trace.
 *
 * @codeGenApi
 */
function ɵɵinvalidFactoryDep(index) {
  throw new RuntimeError(202 /* RuntimeErrorCode.INVALID_FACTORY_DEPENDENCY */, ngDevMode && `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.

Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.`);
}
/**
 * Injects a token from the currently active injector.
 * `inject` is only supported in an [injection context](guide/di/dependency-injection-context). It
 * can be used during:
 * - Construction (via the `constructor`) of a class being instantiated by the DI system, such
 * as an `@Injectable` or `@Component`.
 * - In the initializer for fields of such classes.
 * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
 * - In the `factory` function specified for an `InjectionToken`.
 * - In a stackframe of a function call in a DI context
 *
 * @param token A token that represents a dependency that should be injected.
 * @param flags Optional flags that control how injection is executed.
 * The flags correspond to injection strategies that can be specified with
 * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`.
 * @returns the injected value if operation is successful, `null` otherwise.
 * @throws if called outside of a supported context.
 *
 * @usageNotes
 * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a
 * field initializer:
 *
 * ```typescript
 * @Injectable({providedIn: 'root'})
 * export class Car {
 *   radio: Radio|undefined;
 *   // OK: field initializer
 *   spareTyre = inject(Tyre);
 *
 *   constructor() {
 *     // OK: constructor body
 *     this.radio = inject(Radio);
 *   }
 * }
 * ```
 *
 * It is also legal to call `inject` from a provider's factory:
 *
 * ```typescript
 * providers: [
 *   {provide: Car, useFactory: () => {
 *     // OK: a class factory
 *     const engine = inject(Engine);
 *     return new Car(engine);
 *   }}
 * ]
 * ```
 *
 * Calls to the `inject()` function outside of the class creation context will result in error. Most
 * notably, calls to `inject()` are disallowed after a class instance was created, in methods
 * (including lifecycle hooks):
 *
 * ```typescript
 * @Component({ ... })
 * export class CarComponent {
 *   ngOnInit() {
 *     // ERROR: too late, the component instance was already created
 *     const engine = inject(Engine);
 *     engine.start();
 *   }
 * }
 * ```
 *
 * @publicApi
 */
function inject(token, flags = InjectFlags.Default) {
  // The `as any` here _shouldn't_ be necessary, but without it JSCompiler
  // throws a disambiguation  error due to the multiple signatures.
  return ɵɵinject(token, convertToBitFlags(flags));
}
// Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`).
function convertToBitFlags(flags) {
  if (typeof flags === 'undefined' || typeof flags === 'number') {
    return flags;
  }
  // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in
  // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from
  // `InjectOptions` to `InjectFlags`.
  return 0 /* InternalInjectFlags.Default */ | (
  // comment to force a line break in the formatter
  flags.optional && 8 /* InternalInjectFlags.Optional */) | (flags.host && 1 /* InternalInjectFlags.Host */) | (flags.self && 2 /* InternalInjectFlags.Self */) | (flags.skipSelf && 4 /* InternalInjectFlags.SkipSelf */);
}
function injectArgs(types) {
  const args = [];
  for (let i = 0; i < types.length; i++) {
    const arg = resolveForwardRef(types[i]);
    if (Array.isArray(arg)) {
      if (arg.length === 0) {
        throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && 'Arguments array must have arguments.');
      }
      let type = undefined;
      let flags = InjectFlags.Default;
      for (let j = 0; j < arg.length; j++) {
        const meta = arg[j];
        const flag = getInjectFlag(meta);
        if (typeof flag === 'number') {
          // Special case when we handle @Inject decorator.
          if (flag === -1 /* DecoratorFlags.Inject */) {
            type = meta.token;
          } else {
            flags |= flag;
          }
        } else {
          type = meta;
        }
      }
      args.push(ɵɵinject(type, flags));
    } else {
      args.push(ɵɵinject(arg));
    }
  }
  return args;
}
/**
 * Attaches a given InjectFlag to a given decorator using monkey-patching.
 * Since DI decorators can be used in providers `deps` array (when provider is configured using
 * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we
 * attach the flag to make it available both as a static property and as a field on decorator
 * instance.
 *
 * @param decorator Provided DI decorator.
 * @param flag InjectFlag that should be applied.
 */
function attachInjectFlag(decorator, flag) {
  decorator[DI_DECORATOR_FLAG] = flag;
  decorator.prototype[DI_DECORATOR_FLAG] = flag;
  return decorator;
}
/**
 * Reads monkey-patched property that contains InjectFlag attached to a decorator.
 *
 * @param token Token that may contain monkey-patched DI flags property.
 */
function getInjectFlag(token) {
  return token[DI_DECORATOR_FLAG];
}
function catchInjectorError(e, token, injectorErrorName, source) {
  const tokenPath = e[NG_TEMP_TOKEN_PATH];
  if (token[SOURCE]) {
    tokenPath.unshift(token[SOURCE]);
  }
  e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
  e[NG_TOKEN_PATH] = tokenPath;
  e[NG_TEMP_TOKEN_PATH] = null;
  throw e;
}
function formatError(text, obj, injectorErrorName, source = null) {
  text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.slice(2) : text;
  let context = stringify(obj);
  if (Array.isArray(obj)) {
    context = obj.map(stringify).join(' -> ');
  } else if (typeof obj === 'object') {
    let parts = [];
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        let value = obj[key];
        parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
      }
    }
    context = `{${parts.join(', ')}}`;
  }
  return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n  ')}`;
}

/**
 * Inject decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Inject = /*#__PURE__*/attachInjectFlag(
/*#__PURE__*/
// Disable tslint because `DecoratorFlags` is a const enum which gets inlined.
makeParamDecorator('Inject', token => ({
  token
})), -1 /* DecoratorFlags.Inject */);
/**
 * Optional decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Optional =
/*#__PURE__*/
// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
// tslint:disable-next-line: no-toplevel-property-access
attachInjectFlag(/*#__PURE__*/makeParamDecorator('Optional'), 8 /* InternalInjectFlags.Optional */);
/**
 * Self decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Self =
/*#__PURE__*/
// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
// tslint:disable-next-line: no-toplevel-property-access
attachInjectFlag(/*#__PURE__*/makeParamDecorator('Self'), 2 /* InternalInjectFlags.Self */);
/**
 * `SkipSelf` decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const SkipSelf =
/*#__PURE__*/
// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
// tslint:disable-next-line: no-toplevel-property-access
attachInjectFlag(/*#__PURE__*/makeParamDecorator('SkipSelf'), 4 /* InternalInjectFlags.SkipSelf */);
/**
 * Host decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Host =
/*#__PURE__*/
// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
// tslint:disable-next-line: no-toplevel-property-access
attachInjectFlag(/*#__PURE__*/makeParamDecorator('Host'), 1 /* InternalInjectFlags.Host */);
function getFactoryDef(type, throwNotFound) {
  const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);
  if (!hasFactoryDef && throwNotFound === true && ngDevMode) {
    throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);
  }
  return hasFactoryDef ? type[NG_FACTORY_DEF] : null;
}

/**
 * Determines if the contents of two arrays is identical
 *
 * @param a first array
 * @param b second array
 * @param identityAccessor Optional function for extracting stable object identity from a value in
 *     the array.
 */
function arrayEquals(a, b, identityAccessor) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    let valueA = a[i];
    let valueB = b[i];
    if (identityAccessor) {
      valueA = identityAccessor(valueA);
      valueB = identityAccessor(valueB);
    }
    if (valueB !== valueA) {
      return false;
    }
  }
  return true;
}
/**
 * Flattens an array.
 */
function flatten(list) {
  return list.flat(Number.POSITIVE_INFINITY);
}
function deepForEach(input, fn) {
  input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value));
}
function addToArray(arr, index, value) {
  // perf: array.push is faster than array.splice!
  if (index >= arr.length) {
    arr.push(value);
  } else {
    arr.splice(index, 0, value);
  }
}
function removeFromArray(arr, index) {
  // perf: array.pop is faster than array.splice!
  if (index >= arr.length - 1) {
    return arr.pop();
  } else {
    return arr.splice(index, 1)[0];
  }
}
function newArray(size, value) {
  const list = [];
  for (let i = 0; i < size; i++) {
    list.push(value);
  }
  return list;
}
/**
 * Remove item from array (Same as `Array.splice()` but faster.)
 *
 * `Array.splice()` is not as fast because it has to allocate an array for the elements which were
 * removed. This causes memory pressure and slows down code when most of the time we don't
 * care about the deleted items array.
 *
 * https://jsperf.com/fast-array-splice (About 20x faster)
 *
 * @param array Array to splice
 * @param index Index of element in array to remove.
 * @param count Number of items to remove.
 */
function arraySplice(array, index, count) {
  const length = array.length - count;
  while (index < length) {
    array[index] = array[index + count];
    index++;
  }
  while (count--) {
    array.pop(); // shrink the array
  }
}
/**
 * Same as `Array.splice(index, 0, value)` but faster.
 *
 * `Array.splice()` is not fast because it has to allocate an array for the elements which were
 * removed. This causes memory pressure and slows down code when most of the time we don't
 * care about the deleted items array.
 *
 * @param array Array to splice.
 * @param index Index in array where the `value` should be added.
 * @param value Value to add to array.
 */
function arrayInsert(array, index, value) {
  ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
  let end = array.length;
  while (end > index) {
    const previousEnd = end - 1;
    array[end] = array[previousEnd];
    end = previousEnd;
  }
  array[index] = value;
}
/**
 * Same as `Array.splice2(index, 0, value1, value2)` but faster.
 *
 * `Array.splice()` is not fast because it has to allocate an array for the elements which were
 * removed. This causes memory pressure and slows down code when most of the time we don't
 * care about the deleted items array.
 *
 * @param array Array to splice.
 * @param index Index in array where the `value` should be added.
 * @param value1 Value to add to array.
 * @param value2 Value to add to array.
 */
function arrayInsert2(array, index, value1, value2) {
  ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
  let end = array.length;
  if (end == index) {
    // inserting at the end.
    array.push(value1, value2);
  } else if (end === 1) {
    // corner case when we have less items in array than we have items to insert.
    array.push(value2, array[0]);
    array[0] = value1;
  } else {
    end--;
    array.push(array[end - 1], array[end]);
    while (end > index) {
      const previousEnd = end - 2;
      array[end] = array[previousEnd];
      end--;
    }
    array[index] = value1;
    array[index + 1] = value2;
  }
}
/**
 * Get an index of an `value` in a sorted `array`.
 *
 * NOTE:
 * - This uses binary search algorithm for fast removals.
 *
 * @param array A sorted array to binary search.
 * @param value The value to look for.
 * @returns index of the value.
 *   - positive index if value found.
 *   - negative index if value not found. (`~index` to get the value where it should have been
 *     located)
 */
function arrayIndexOfSorted(array, value) {
  return _arrayIndexOfSorted(array, value, 0);
}
/**
 * Set a `value` for a `key`.
 *
 * @param keyValueArray to modify.
 * @param key The key to locate or create.
 * @param value The value to set for a `key`.
 * @returns index (always even) of where the value vas set.
 */
function keyValueArraySet(keyValueArray, key, value) {
  let index = keyValueArrayIndexOf(keyValueArray, key);
  if (index >= 0) {
    // if we found it set it.
    keyValueArray[index | 1] = value;
  } else {
    index = ~index;
    arrayInsert2(keyValueArray, index, key, value);
  }
  return index;
}
/**
 * Retrieve a `value` for a `key` (on `undefined` if not found.)
 *
 * @param keyValueArray to search.
 * @param key The key to locate.
 * @return The `value` stored at the `key` location or `undefined if not found.
 */
function keyValueArrayGet(keyValueArray, key) {
  const index = keyValueArrayIndexOf(keyValueArray, key);
  if (index >= 0) {
    // if we found it retrieve it.
    return keyValueArray[index | 1];
  }
  return undefined;
}
/**
 * Retrieve a `key` index value in the array or `-1` if not found.
 *
 * @param keyValueArray to search.
 * @param key The key to locate.
 * @returns index of where the key is (or should have been.)
 *   - positive (even) index if key found.
 *   - negative index if key not found. (`~index` (even) to get the index where it should have
 *     been inserted.)
 */
function keyValueArrayIndexOf(keyValueArray, key) {
  return _arrayIndexOfSorted(keyValueArray, key, 1);
}
/**
 * Delete a `key` (and `value`) from the `KeyValueArray`.
 *
 * @param keyValueArray to modify.
 * @param key The key to locate or delete (if exist).
 * @returns index of where the key was (or should have been.)
 *   - positive (even) index if key found and deleted.
 *   - negative index if key not found. (`~index` (even) to get the index where it should have
 *     been.)
 */
function keyValueArrayDelete(keyValueArray, key) {
  const index = keyValueArrayIndexOf(keyValueArray, key);
  if (index >= 0) {
    // if we found it remove it.
    arraySplice(keyValueArray, index, 2);
  }
  return index;
}
/**
 * INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
 *
 * NOTE:
 * - This uses binary search algorithm for fast removals.
 *
 * @param array A sorted array to binary search.
 * @param value The value to look for.
 * @param shift grouping shift.
 *   - `0` means look at every location
 *   - `1` means only look at every other (even) location (the odd locations are to be ignored as
 *         they are values.)
 * @returns index of the value.
 *   - positive index if value found.
 *   - negative index if value not found. (`~index` to get the value where it should have been
 * inserted)
 */
function _arrayIndexOfSorted(array, value, shift) {
  ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
  let start = 0;
  let end = array.length >> shift;
  while (end !== start) {
    const middle = start + (end - start >> 1); // find the middle.
    const current = array[middle << shift];
    if (value === current) {
      return middle << shift;
    } else if (current > value) {
      end = middle;
    } else {
      start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
    }
  }
  return ~(end << shift);
}

/**
 * This file contains reuseable "empty" symbols that can be used as default return values
 * in different parts of the rendering code. Because the same symbols are returned, this
 * allows for identity checks against these values to be consistently used by the framework
 * code.
 */
const EMPTY_OBJ = {};
const EMPTY_ARRAY = [];
// freezing the values prevents any code from accidentally inserting new values in
if ((typeof ngDevMode === 'undefined' || ngDevMode) && /*#__PURE__*/initNgDevMode()) {
  // These property accesses can be ignored because ngDevMode will be set to false
  // when optimizing code and the whole if statement will be dropped.
  // tslint:disable-next-line:no-toplevel-property-access
  /*#__PURE__*/Object.freeze(EMPTY_OBJ);
  // tslint:disable-next-line:no-toplevel-property-access
  /*#__PURE__*/Object.freeze(EMPTY_ARRAY);
}

/**
 * A multi-provider token for initialization functions that will run upon construction of an
 * environment injector.
 *
 * @deprecated from v19.0.0, use provideEnvironmentInitializer instead
 *
 * @see {@link provideEnvironmentInitializer}
 *
 * Note: As opposed to the `APP_INITIALIZER` token, the `ENVIRONMENT_INITIALIZER` functions are not awaited,
 * hence they should not be `async`.
 *
 * @publicApi
 */
const ENVIRONMENT_INITIALIZER = /*#__PURE__*/new InjectionToken(ngDevMode ? 'ENVIRONMENT_INITIALIZER' : '');

/**
 * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
 *
 * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
 * project.
 *
 * @publicApi
 */
const INJECTOR$1 = /*#__PURE__*/new InjectionToken(ngDevMode ? 'INJECTOR' : '',
// Disable tslint because this is const enum which gets inlined not top level prop access.
// tslint:disable-next-line: no-toplevel-property-access
-1 /* InjectorMarkers.Injector */);
const INJECTOR_DEF_TYPES = /*#__PURE__*/new InjectionToken(ngDevMode ? 'INJECTOR_DEF_TYPES' : '');
class NullInjector {
  get(token, notFoundValue = THROW_IF_NOT_FOUND) {
    if (notFoundValue === THROW_IF_NOT_FOUND) {
      const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
      error.name = 'NullInjectorError';
      throw error;
    }
    return notFoundValue;
  }
}
function getNgModuleDef(type, throwNotFound) {
  const ngModuleDef = type[NG_MOD_DEF] || null;
  if (!ngModuleDef && throwNotFound === true) {
    throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);
  }
  return ngModuleDef;
}
/**
 * The following getter methods retrieve the definition from the type. Currently the retrieval
 * honors inheritance, but in the future we may change the rule to require that definitions are
 * explicit. This would require some sort of migration strategy.
 */
function getComponentDef(type) {
  return type[NG_COMP_DEF] || null;
}
function getDirectiveDef(type) {
  return type[NG_DIR_DEF] || null;
}
function getPipeDef$1(type) {
  return type[NG_PIPE_DEF] || null;
}
/**
 * Checks whether a given Component, Directive or Pipe is marked as standalone.
 * This will return false if passed anything other than a Component, Directive, or Pipe class
 * See [this guide](guide/components/importing) for additional information:
 *
 * @param type A reference to a Component, Directive or Pipe.
 * @publicApi
 */
function isStandalone(type) {
  const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  // TODO: standalone as default value (invert the condition)
  return def !== null ? def.standalone : false;
}

/**
 * Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally
 * referenced in `@Component` in a component injector.
 */
function makeEnvironmentProviders(providers) {
  return {
    ɵproviders: providers
  };
}
/**
 * @description
 * This function is used to provide initialization functions that will be executed upon construction
 * of an environment injector.
 *
 * Note that the provided initializer is run in the injection context.
 *
 * Previously, this was achieved using the `ENVIRONMENT_INITIALIZER` token which is now deprecated.
 *
 * @see {@link ENVIRONMENT_INITIALIZER}
 *
 * @usageNotes
 * The following example illustrates how to configure an initialization function using
 * `provideEnvironmentInitializer()`
 * ```
 * createEnvironmentInjector(
 *   [
 *     provideEnvironmentInitializer(() => {
 *       console.log('environment initialized');
 *     }),
 *   ],
 *   parentInjector
 * );
 * ```
 *
 * @publicApi
 */
function provideEnvironmentInitializer(initializerFn) {
  return makeEnvironmentProviders([{
    provide: ENVIRONMENT_INITIALIZER,
    multi: true,
    useValue: initializerFn
  }]);
}
/**
 * Collects providers from all NgModules and standalone components, including transitively imported
 * ones.
 *
 * Providers extracted via `importProvidersFrom` are only usable in an application injector or
 * another environment injector (such as a route injector). They should not be used in component
 * providers.
 *
 * More information about standalone components can be found in [this
 * guide](guide/components/importing).
 *
 * @usageNotes
 * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:
 *
 * ```typescript
 * await bootstrapApplication(RootComponent, {
 *   providers: [
 *     importProvidersFrom(NgModuleOne, NgModuleTwo)
 *   ]
 * });
 * ```
 *
 * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a
 * standalone component is used:
 *
 * ```typescript
 * export const ROUTES: Route[] = [
 *   {
 *     path: 'foo',
 *     providers: [
 *       importProvidersFrom(NgModuleOne, NgModuleTwo)
 *     ],
 *     component: YourStandaloneComponent
 *   }
 * ];
 * ```
 *
 * @returns Collected providers from the specified list of types.
 * @publicApi
 */
function importProvidersFrom(...sources) {
  return {
    ɵproviders: internalImportProvidersFrom(true, sources),
    ɵfromNgModule: true
  };
}
function internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {
  const providersOut = [];
  const dedup = new Set(); // already seen types
  let injectorTypesWithProviders;
  const collectProviders = provider => {
    providersOut.push(provider);
  };
  deepForEach(sources, source => {
    if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) {
      const cmpDef = getComponentDef(source);
      if (cmpDef?.standalone) {
        throw new RuntimeError(800 /* RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE */, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component "${stringifyForError(source)}"`);
      }
    }
    // Narrow `source` to access the internal type analogue for `ModuleWithProviders`.
    const internalSource = source;
    if (walkProviderTree(internalSource, collectProviders, [], dedup)) {
      injectorTypesWithProviders ||= [];
      injectorTypesWithProviders.push(internalSource);
    }
  });
  // Collect all providers from `ModuleWithProviders` types.
  if (injectorTypesWithProviders !== undefined) {
    processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders);
  }
  return providersOut;
}
/**
 * Collects all providers from the list of `ModuleWithProviders` and appends them to the provided
 * array.
 */
function processInjectorTypesWithProviders(typesWithProviders, visitor) {
  for (let i = 0; i < typesWithProviders.length; i++) {
    const {
      ngModule,
      providers
    } = typesWithProviders[i];
    deepForEachProvider(providers, provider => {
      ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule);
      visitor(provider, ngModule);
    });
  }
}
/**
 * The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone
 * `ComponentType`, and all of its transitive providers and collects providers.
 *
 * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
 * the function will return "true" to indicate that the providers of the type definition need
 * to be processed. This allows us to process providers of injector types after all imports of
 * an injector definition are processed. (following View Engine semantics: see FW-1349)
 */
function walkProviderTree(container, visitor, parents, dedup) {
  container = resolveForwardRef(container);
  if (!container) return false;
  // The actual type which had the definition. Usually `container`, but may be an unwrapped type
  // from `InjectorTypeWithProviders`.
  let defType = null;
  let injDef = getInjectorDef(container);
  const cmpDef = !injDef && getComponentDef(container);
  if (!injDef && !cmpDef) {
    // `container` is not an injector type or a component type. It might be:
    //  * An `InjectorTypeWithProviders` that wraps an injector type.
    //  * A standalone directive or pipe that got pulled in from a standalone component's
    //    dependencies.
    // Try to unwrap it as an `InjectorTypeWithProviders` first.
    const ngModule = container.ngModule;
    injDef = getInjectorDef(ngModule);
    if (injDef) {
      defType = ngModule;
    } else {
      // Not a component or injector type, so ignore it.
      return false;
    }
  } else if (cmpDef && !cmpDef.standalone) {
    return false;
  } else {
    defType = container;
  }
  // Check for circular dependencies.
  if (ngDevMode && parents.indexOf(defType) !== -1) {
    const defName = stringify(defType);
    const path = parents.map(stringify);
    throwCyclicDependencyError(defName, path);
  }
  // Check for multiple imports of the same module
  const isDuplicate = dedup.has(defType);
  if (cmpDef) {
    if (isDuplicate) {
      // This component definition has already been processed.
      return false;
    }
    dedup.add(defType);
    if (cmpDef.dependencies) {
      const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies;
      for (const dep of deps) {
        walkProviderTree(dep, visitor, parents, dedup);
      }
    }
  } else if (injDef) {
    // First, include providers from any imports.
    if (injDef.imports != null && !isDuplicate) {
      // Before processing defType's imports, add it to the set of parents. This way, if it ends
      // up deeply importing itself, this can be detected.
      ngDevMode && parents.push(defType);
      // Add it to the set of dedups. This way we can detect multiple imports of the same module
      dedup.add(defType);
      let importTypesWithProviders;
      try {
        deepForEach(injDef.imports, imported => {
          if (walkProviderTree(imported, visitor, parents, dedup)) {
            importTypesWithProviders ||= [];
            // If the processed import is an injector type with providers, we store it in the
            // list of import types with providers, so that we can process those afterwards.
            importTypesWithProviders.push(imported);
          }
        });
      } finally {
        // Remove it from the parents set when finished.
        ngDevMode && parents.pop();
      }
      // Imports which are declared with providers (TypeWithProviders) need to be processed
      // after all imported modules are processed. This is similar to how View Engine
      // processes/merges module imports in the metadata resolver. See: FW-1349.
      if (importTypesWithProviders !== undefined) {
        processInjectorTypesWithProviders(importTypesWithProviders, visitor);
      }
    }
    if (!isDuplicate) {
      // Track the InjectorType and add a provider for it.
      // It's important that this is done after the def's imports.
      const factory = getFactoryDef(defType) || (() => new defType());
      // Append extra providers to make more info available for consumers (to retrieve an injector
      // type), as well as internally (to calculate an injection scope correctly and eagerly
      // instantiate a `defType` when an injector is created).
      // Provider to create `defType` using its factory.
      visitor({
        provide: defType,
        useFactory: factory,
        deps: EMPTY_ARRAY
      }, defType);
      // Make this `defType` available to an internal logic that calculates injector scope.
      visitor({
        provide: INJECTOR_DEF_TYPES,
        useValue: defType,
        multi: true
      }, defType);
      // Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`.
      visitor({
        provide: ENVIRONMENT_INITIALIZER,
        useValue: () => ɵɵinject(defType),
        multi: true
      }, defType);
    }
    // Next, include providers listed on the definition itself.
    const defProviders = injDef.providers;
    if (defProviders != null && !isDuplicate) {
      const injectorType = container;
      deepForEachProvider(defProviders, provider => {
        ngDevMode && validateProvider(provider, defProviders, injectorType);
        visitor(provider, injectorType);
      });
    }
  } else {
    // Should not happen, but just in case.
    return false;
  }
  return defType !== container && container.providers !== undefined;
}
function validateProvider(provider, providers, containerType) {
  if (isTypeProvider(provider) || isValueProvider(provider) || isFactoryProvider(provider) || isExistingProvider(provider)) {
    return;
  }
  // Here we expect the provider to be a `useClass` provider (by elimination).
  const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));
  if (!classRef) {
    throwInvalidProviderError(containerType, providers, provider);
  }
}
function deepForEachProvider(providers, fn) {
  for (let provider of providers) {
    if (isEnvironmentProviders(provider)) {
      provider = provider.ɵproviders;
    }
    if (Array.isArray(provider)) {
      deepForEachProvider(provider, fn);
    } else {
      fn(provider);
    }
  }
}
const USE_VALUE$1 = /*#__PURE__*/getClosureSafeProperty({
  provide: String,
  useValue: getClosureSafeProperty
});
function isValueProvider(value) {
  return value !== null && typeof value == 'object' && USE_VALUE$1 in value;
}
function isExistingProvider(value) {
  return !!(value && value.useExisting);
}
function isFactoryProvider(value) {
  return !!(value && value.useFactory);
}
function isTypeProvider(value) {
  return typeof value === 'function';
}
function isClassProvider(value) {
  return !!value.useClass;
}

/**
 * An internal token whose presence in an injector indicates that the injector should treat itself
 * as a root scoped injector when processing requests for unknown tokens which may indicate
 * they are provided in the root scope.
 */
const INJECTOR_SCOPE = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Set Injector scope.' : '');

/**
 * Marker which indicates that a value has not yet been created from the factory function.
 */
const NOT_YET = {};
/**
 * Marker which indicates that the factory function for a token is in the process of being called.
 *
 * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
 * injection of a dependency has recursively attempted to inject the original token, and there is
 * a circular dependency among the providers.
 */
const CIRCULAR = {};
/**
 * A lazily initialized NullInjector.
 */
let NULL_INJECTOR = undefined;
function getNullInjector() {
  if (NULL_INJECTOR === undefined) {
    NULL_INJECTOR = new NullInjector();
  }
  return NULL_INJECTOR;
}
/**
 * An `Injector` that's part of the environment injector hierarchy, which exists outside of the
 * component tree.
 */
class EnvironmentInjector {}
class R3Injector extends EnvironmentInjector {
  parent;
  source;
  scopes;
  /**
   * Map of tokens to records which contain the instances of those tokens.
   * - `null` value implies that we don't have the record. Used by tree-shakable injectors
   * to prevent further searches.
   */
  records = /*#__PURE__*/(() => new Map())();
  /**
   * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
   */
  _ngOnDestroyHooks = /*#__PURE__*/(() => new Set())();
  _onDestroyHooks = [];
  /**
   * Flag indicating that this injector was previously destroyed.
   */
  get destroyed() {
    return this._destroyed;
  }
  _destroyed = false;
  injectorDefTypes;
  constructor(providers, parent, source, scopes) {
    super();
    this.parent = parent;
    this.source = source;
    this.scopes = scopes;
    // Start off by creating Records for every provider.
    forEachSingleProvider(providers, provider => this.processProvider(provider));
    // Make sure the INJECTOR token provides this injector.
    this.records.set(INJECTOR$1, makeRecord(undefined, this));
    // And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
    if (scopes.has('environment')) {
      this.records.set(EnvironmentInjector, makeRecord(undefined, this));
    }
    // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
    // any injectable scoped to APP_ROOT_SCOPE.
    const record = this.records.get(INJECTOR_SCOPE);
    if (record != null && typeof record.value === 'string') {
      this.scopes.add(record.value);
    }
    this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));
  }
  /**
   * Destroy the injector and release references to every instance or provider associated with it.
   *
   * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
   * hook was found.
   */
  destroy() {
    assertNotDestroyed(this);
    // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
    this._destroyed = true;
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      // Call all the lifecycle hooks.
      for (const service of this._ngOnDestroyHooks) {
        service.ngOnDestroy();
      }
      const onDestroyHooks = this._onDestroyHooks;
      // Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
      // themselves from mutating the array during iteration.
      this._onDestroyHooks = [];
      for (const hook of onDestroyHooks) {
        hook();
      }
    } finally {
      // Release all references.
      this.records.clear();
      this._ngOnDestroyHooks.clear();
      this.injectorDefTypes.clear();
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
  onDestroy(callback) {
    assertNotDestroyed(this);
    this._onDestroyHooks.push(callback);
    return () => this.removeOnDestroy(callback);
  }
  runInContext(fn) {
    assertNotDestroyed(this);
    const previousInjector = setCurrentInjector(this);
    const previousInjectImplementation = setInjectImplementation(undefined);
    let prevInjectContext;
    if (ngDevMode) {
      prevInjectContext = setInjectorProfilerContext({
        injector: this,
        token: null
      });
    }
    try {
      return fn();
    } finally {
      setCurrentInjector(previousInjector);
      setInjectImplementation(previousInjectImplementation);
      ngDevMode && setInjectorProfilerContext(prevInjectContext);
    }
  }
  get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
    assertNotDestroyed(this);
    if (token.hasOwnProperty(NG_ENV_ID)) {
      return token[NG_ENV_ID](this);
    }
    flags = convertToBitFlags(flags);
    // Set the injection context.
    let prevInjectContext;
    if (ngDevMode) {
      prevInjectContext = setInjectorProfilerContext({
        injector: this,
        token: token
      });
    }
    const previousInjector = setCurrentInjector(this);
    const previousInjectImplementation = setInjectImplementation(undefined);
    try {
      // Check for the SkipSelf flag.
      if (!(flags & InjectFlags.SkipSelf)) {
        // SkipSelf isn't set, check if the record belongs to this injector.
        let record = this.records.get(token);
        if (record === undefined) {
          // No record, but maybe the token is scoped to this injector. Look for an injectable
          // def with a scope matching this injector.
          const def = couldBeInjectableType(token) && getInjectableDef(token);
          if (def && this.injectableDefInScope(def)) {
            // Found an injectable def and it's scoped to this injector. Pretend as if it was here
            // all along.
            if (ngDevMode) {
              runInInjectorProfilerContext(this, token, () => {
                emitProviderConfiguredEvent(token);
              });
            }
            record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
          } else {
            record = null;
          }
          this.records.set(token, record);
        }
        // If a record was found, get the instance for it and return it.
        if (record != null /* NOT null || undefined */) {
          return this.hydrate(token, record);
        }
      }
      // Select the next injector based on the Self flag - if self is set, the next injector is
      // the NullInjector, otherwise it's the parent.
      const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
      // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
      // is undefined, the value is null, otherwise it's the notFoundValue.
      notFoundValue = flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND ? null : notFoundValue;
      return nextInjector.get(token, notFoundValue);
    } catch (e) {
      if (e.name === 'NullInjectorError') {
        const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
        path.unshift(stringify(token));
        if (previousInjector) {
          // We still have a parent injector, keep throwing
          throw e;
        } else {
          // Format & throw the final error message when we don't have any previous injector
          return catchInjectorError(e, token, 'R3InjectorError', this.source);
        }
      } else {
        throw e;
      }
    } finally {
      // Lastly, restore the previous injection context.
      setInjectImplementation(previousInjectImplementation);
      setCurrentInjector(previousInjector);
      ngDevMode && setInjectorProfilerContext(prevInjectContext);
    }
  }
  /** @internal */
  resolveInjectorInitializers() {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    const previousInjector = setCurrentInjector(this);
    const previousInjectImplementation = setInjectImplementation(undefined);
    let prevInjectContext;
    if (ngDevMode) {
      prevInjectContext = setInjectorProfilerContext({
        injector: this,
        token: null
      });
    }
    try {
      const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);
      if (ngDevMode && !Array.isArray(initializers)) {
        throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' + `(expected an array, but got ${typeof initializers}). ` + 'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' + '`multi: true` provider.');
      }
      for (const initializer of initializers) {
        initializer();
      }
    } finally {
      setCurrentInjector(previousInjector);
      setInjectImplementation(previousInjectImplementation);
      ngDevMode && setInjectorProfilerContext(prevInjectContext);
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
  toString() {
    const tokens = [];
    const records = this.records;
    for (const token of records.keys()) {
      tokens.push(stringify(token));
    }
    return `R3Injector[${tokens.join(', ')}]`;
  }
  /**
   * Process a `SingleProvider` and add it.
   */
  processProvider(provider) {
    // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
    // property.
    provider = resolveForwardRef(provider);
    let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);
    // Construct a `Record` for the provider.
    const record = providerToRecord(provider);
    if (ngDevMode) {
      runInInjectorProfilerContext(this, token, () => {
        // Emit InjectorProfilerEventType.Create if provider is a value provider because
        // these are the only providers that do not go through the value hydration logic
        // where this event would normally be emitted from.
        if (isValueProvider(provider)) {
          emitInstanceCreatedByInjectorEvent(provider.useValue);
        }
        emitProviderConfiguredEvent(provider);
      });
    }
    if (!isTypeProvider(provider) && provider.multi === true) {
      // If the provider indicates that it's a multi-provider, process it specially.
      // First check whether it's been defined already.
      let multiRecord = this.records.get(token);
      if (multiRecord) {
        // It has. Throw a nice error if
        if (ngDevMode && multiRecord.multi === undefined) {
          throwMixedMultiProviderError();
        }
      } else {
        multiRecord = makeRecord(undefined, NOT_YET, true);
        multiRecord.factory = () => injectArgs(multiRecord.multi);
        this.records.set(token, multiRecord);
      }
      token = provider;
      multiRecord.multi.push(provider);
    } else {
      if (ngDevMode) {
        const existing = this.records.get(token);
        if (existing && existing.multi !== undefined) {
          throwMixedMultiProviderError();
        }
      }
    }
    this.records.set(token, record);
  }
  hydrate(token, record) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      if (ngDevMode && record.value === CIRCULAR) {
        throwCyclicDependencyError(stringify(token));
      } else if (record.value === NOT_YET) {
        record.value = CIRCULAR;
        if (ngDevMode) {
          runInInjectorProfilerContext(this, token, () => {
            record.value = record.factory();
            emitInstanceCreatedByInjectorEvent(record.value);
          });
        } else {
          record.value = record.factory();
        }
      }
      if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
        this._ngOnDestroyHooks.add(record.value);
      }
      return record.value;
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
  injectableDefInScope(def) {
    if (!def.providedIn) {
      return false;
    }
    const providedIn = resolveForwardRef(def.providedIn);
    if (typeof providedIn === 'string') {
      return providedIn === 'any' || this.scopes.has(providedIn);
    } else {
      return this.injectorDefTypes.has(providedIn);
    }
  }
  removeOnDestroy(callback) {
    const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
    if (destroyCBIdx !== -1) {
      this._onDestroyHooks.splice(destroyCBIdx, 1);
    }
  }
}
function injectableDefOrInjectorDefFactory(token) {
  // Most tokens will have an injectable def directly on them, which specifies a factory directly.
  const injectableDef = getInjectableDef(token);
  const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
  if (factory !== null) {
    return factory;
  }
  // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
  // If it's missing that, it's an error.
  if (token instanceof InjectionToken) {
    throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`);
  }
  // Undecorated types can sometimes be created if they have no constructor arguments.
  if (token instanceof Function) {
    return getUndecoratedInjectableFactory(token);
  }
  // There was no way to resolve a factory for this token.
  throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'unreachable');
}
function getUndecoratedInjectableFactory(token) {
  // If the token has parameters then it has dependencies that we cannot resolve implicitly.
  const paramLength = token.length;
  if (paramLength > 0) {
    throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Can't resolve all parameters for ${stringify(token)}: (${newArray(paramLength, '?').join(', ')}).`);
  }
  // The constructor function appears to have no parameters.
  // This might be because it inherits from a super-class. In which case, use an injectable
  // def from an ancestor if there is one.
  // Otherwise this really is a simple class with no dependencies, so return a factory that
  // just instantiates the zero-arg constructor.
  const inheritedInjectableDef = getInheritedInjectableDef(token);
  if (inheritedInjectableDef !== null) {
    return () => inheritedInjectableDef.factory(token);
  } else {
    return () => new token();
  }
}
function providerToRecord(provider) {
  if (isValueProvider(provider)) {
    return makeRecord(undefined, provider.useValue);
  } else {
    const factory = providerToFactory(provider);
    return makeRecord(factory, NOT_YET);
  }
}
/**
 * Converts a `SingleProvider` into a factory function.
 *
 * @param provider provider to convert to factory
 */
function providerToFactory(provider, ngModuleType, providers) {
  let factory = undefined;
  if (ngDevMode && isEnvironmentProviders(provider)) {
    throwInvalidProviderError(undefined, providers, provider);
  }
  if (isTypeProvider(provider)) {
    const unwrappedProvider = resolveForwardRef(provider);
    return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
  } else {
    if (isValueProvider(provider)) {
      factory = () => resolveForwardRef(provider.useValue);
    } else if (isFactoryProvider(provider)) {
      factory = () => provider.useFactory(...injectArgs(provider.deps || []));
    } else if (isExistingProvider(provider)) {
      factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
    } else {
      const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));
      if (ngDevMode && !classRef) {
        throwInvalidProviderError(ngModuleType, providers, provider);
      }
      if (hasDeps(provider)) {
        factory = () => new classRef(...injectArgs(provider.deps));
      } else {
        return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
      }
    }
  }
  return factory;
}
function assertNotDestroyed(injector) {
  if (injector.destroyed) {
    throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, ngDevMode && 'Injector has already been destroyed.');
  }
}
function makeRecord(factory, value, multi = false) {
  return {
    factory: factory,
    value: value,
    multi: multi ? [] : undefined
  };
}
function hasDeps(value) {
  return !!value.deps;
}
function hasOnDestroy(value) {
  return value !== null && typeof value === 'object' && typeof value.ngOnDestroy === 'function';
}
function couldBeInjectableType(value) {
  return typeof value === 'function' || typeof value === 'object' && value instanceof InjectionToken;
}
function forEachSingleProvider(providers, fn) {
  for (const provider of providers) {
    if (Array.isArray(provider)) {
      forEachSingleProvider(provider, fn);
    } else if (provider && isEnvironmentProviders(provider)) {
      forEachSingleProvider(provider.ɵproviders, fn);
    } else {
      fn(provider);
    }
  }
}

/**
 * Runs the given function in the [context](guide/di/dependency-injection-context) of the given
 * `Injector`.
 *
 * Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies
 * from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in
 * any asynchronous callbacks or after any `await` points.
 *
 * @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`
 *     is executing
 * @param fn the closure to be run in the context of `injector`
 * @returns the return value of the function, if any
 * @publicApi
 */
function runInInjectionContext(injector, fn) {
  if (injector instanceof R3Injector) {
    assertNotDestroyed(injector);
  }
  let prevInjectorProfilerContext;
  if (ngDevMode) {
    prevInjectorProfilerContext = setInjectorProfilerContext({
      injector,
      token: null
    });
  }
  const prevInjector = setCurrentInjector(injector);
  const previousInjectImplementation = setInjectImplementation(undefined);
  try {
    return fn();
  } finally {
    setCurrentInjector(prevInjector);
    ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext);
    setInjectImplementation(previousInjectImplementation);
  }
}
/**
 * Whether the current stack frame is inside an injection context.
 */
function isInInjectionContext() {
  return getInjectImplementation() !== undefined || getCurrentInjector() != null;
}
/**
 * Asserts that the current stack frame is within an [injection
 * context](guide/di/dependency-injection-context) and has access to `inject`.
 *
 * @param debugFn a reference to the function making the assertion (used for the error message).
 *
 * @publicApi
 */
function assertInInjectionContext(debugFn) {
  // Taking a `Function` instead of a string name here prevents the unminified name of the function
  // from being retained in the bundle regardless of minification.
  if (!isInInjectionContext()) {
    throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode && debugFn.name + '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`');
  }
}
var FactoryTarget = /*#__PURE__*/function (FactoryTarget) {
  FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive";
  FactoryTarget[FactoryTarget["Component"] = 1] = "Component";
  FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable";
  FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe";
  FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule";
  return FactoryTarget;
}(FactoryTarget || {});
var R3TemplateDependencyKind = /*#__PURE__*/function (R3TemplateDependencyKind) {
  R3TemplateDependencyKind[R3TemplateDependencyKind["Directive"] = 0] = "Directive";
  R3TemplateDependencyKind[R3TemplateDependencyKind["Pipe"] = 1] = "Pipe";
  R3TemplateDependencyKind[R3TemplateDependencyKind["NgModule"] = 2] = "NgModule";
  return R3TemplateDependencyKind;
}(R3TemplateDependencyKind || {});
var ViewEncapsulation$1 = /*#__PURE__*/function (ViewEncapsulation) {
  ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  return ViewEncapsulation;
}(ViewEncapsulation$1 || {});
function getCompilerFacade(request) {
  const globalNg = _global['ng'];
  if (globalNg && globalNg.ɵcompilerFacade) {
    return globalNg.ɵcompilerFacade;
  }
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    // Log the type as an error so that a developer can easily navigate to the type from the
    // console.
    console.error(`JIT compilation failed for ${request.kind}`, request.type);
    let message = `The ${request.kind} '${request.type.name}' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.\n\n`;
    if (request.usage === 1 /* JitCompilerUsage.PartialDeclaration */) {
      message += `The ${request.kind} is part of a library that has been partially compiled.\n`;
      message += `However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.\n`;
      message += '\n';
      message += `Ideally, the library is processed using the Angular Linker to become fully AOT compiled.\n`;
    } else {
      message += `JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.\n`;
    }
    message += `Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',\n`;
    message += `or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`;
    throw new Error(message);
  } else {
    throw new Error('JIT compiler unavailable');
  }
}

/**
 * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
 *
 * This should be kept up to date with the public exports of @angular/core.
 */
const angularCoreDiEnv = {
  'ɵɵdefineInjectable': ɵɵdefineInjectable,
  'ɵɵdefineInjector': ɵɵdefineInjector,
  'ɵɵinject': ɵɵinject,
  'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  'resolveForwardRef': resolveForwardRef
};

/**
 * @description
 *
 * Represents a type that a Component or other object is instances of.
 *
 * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
 * the `MyCustomComponent` constructor function.
 *
 * @publicApi
 */
const Type = Function;
function isType(v) {
  return typeof v === 'function';
}

/*
 * #########################
 * Attention: These Regular expressions have to hold even if the code is minified!
 * ##########################
 */
/**
 * Regular expression that detects pass-through constructors for ES5 output. This Regex
 * intends to capture the common delegation pattern emitted by TypeScript and Babel. Also
 * it intends to capture the pattern where existing constructors have been downleveled from
 * ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.
 *
 * ```
 *   function MyClass() {
 *     var _this = _super.apply(this, arguments) || this;
 * ```
 *
 * downleveled to ES5 with `downlevelIteration` for TypeScript < 4.2:
 * ```
 *   function MyClass() {
 *     var _this = _super.apply(this, __spread(arguments)) || this;
 * ```
 *
 * or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2:
 * ```
 *   function MyClass() {
 *     var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
 * ```
 *
 * More details can be found in: https://github.com/angular/angular/issues/38453.
 */
const ES5_DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\).*)\)/;
/** Regular expression that detects ES2015 classes which extend from other classes. */
const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
/**
 * Regular expression that detects ES2015 classes which extend from other classes and
 * have an explicit constructor defined.
 */
const ES2015_INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
/**
 * Regular expression that detects ES2015 classes which extend from other classes
 * and inherit a constructor.
 */
const ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{[^}]*super\(\.\.\.arguments\)/;
/**
 * Determine whether a stringified type is a class which delegates its constructor
 * to its parent.
 *
 * This is not trivial since compiled code can actually contain a constructor function
 * even if the original source code did not. For instance, when the child class contains
 * an initialized instance property.
 */
function isDelegateCtor(typeStr) {
  return ES5_DELEGATE_CTOR.test(typeStr) || ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) || ES2015_INHERITED_CLASS.test(typeStr) && !ES2015_INHERITED_CLASS_WITH_CTOR.test(typeStr);
}
class ReflectionCapabilities {
  _reflect;
  constructor(reflect) {
    this._reflect = reflect || _global['Reflect'];
  }
  factory(t) {
    return (...args) => new t(...args);
  }
  /** @internal */
  _zipTypesAndAnnotations(paramTypes, paramAnnotations) {
    let result;
    if (typeof paramTypes === 'undefined') {
      result = newArray(paramAnnotations.length);
    } else {
      result = newArray(paramTypes.length);
    }
    for (let i = 0; i < result.length; i++) {
      // TS outputs Object for parameters without types, while Traceur omits
      // the annotations. For now we preserve the Traceur behavior to aid
      // migration, but this can be revisited.
      if (typeof paramTypes === 'undefined') {
        result[i] = [];
      } else if (paramTypes[i] && paramTypes[i] != Object) {
        result[i] = [paramTypes[i]];
      } else {
        result[i] = [];
      }
      if (paramAnnotations && paramAnnotations[i] != null) {
        result[i] = result[i].concat(paramAnnotations[i]);
      }
    }
    return result;
  }
  _ownParameters(type, parentCtor) {
    const typeStr = type.toString();
    // If we have no decorators, we only have function.length as metadata.
    // In that case, to detect whether a child class declared an own constructor or not,
    // we need to look inside of that constructor to check whether it is
    // just calling the parent.
    // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
    // that sets 'design:paramtypes' to []
    // if a class inherits from another class but has no ctor declared itself.
    if (isDelegateCtor(typeStr)) {
      return null;
    }
    // Prefer the direct API.
    if (type.parameters && type.parameters !== parentCtor.parameters) {
      return type.parameters;
    }
    // API of tsickle for lowering decorators to properties on the class.
    const tsickleCtorParams = type.ctorParameters;
    if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
      // Newer tsickle uses a function closure
      // Retain the non-function case for compatibility with older tsickle
      const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
      const paramTypes = ctorParameters.map(ctorParam => ctorParam && ctorParam.type);
      const paramAnnotations = ctorParameters.map(ctorParam => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
      return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
    }
    // API for metadata created by invoking the decorators.
    const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
    const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type);
    if (paramTypes || paramAnnotations) {
      return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
    }
    // If a class has no decorators, at least create metadata
    // based on function.length.
    // Note: We know that this is a real constructor as we checked
    // the content of the constructor above.
    return newArray(type.length);
  }
  parameters(type) {
    // Note: only report metadata if we have at least one class decorator
    // to stay in sync with the static reflector.
    if (!isType(type)) {
      return [];
    }
    const parentCtor = getParentCtor(type);
    let parameters = this._ownParameters(type, parentCtor);
    if (!parameters && parentCtor !== Object) {
      parameters = this.parameters(parentCtor);
    }
    return parameters || [];
  }
  _ownAnnotations(typeOrFunc, parentCtor) {
    // Prefer the direct API.
    if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
      let annotations = typeOrFunc.annotations;
      if (typeof annotations === 'function' && annotations.annotations) {
        annotations = annotations.annotations;
      }
      return annotations;
    }
    // API of tsickle for lowering decorators to properties on the class.
    if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
      return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
    }
    // API for metadata created by invoking the decorators.
    if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
      return typeOrFunc[ANNOTATIONS];
    }
    return null;
  }
  annotations(typeOrFunc) {
    if (!isType(typeOrFunc)) {
      return [];
    }
    const parentCtor = getParentCtor(typeOrFunc);
    const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
    const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
    return parentAnnotations.concat(ownAnnotations);
  }
  _ownPropMetadata(typeOrFunc, parentCtor) {
    // Prefer the direct API.
    if (typeOrFunc.propMetadata && typeOrFunc.propMetadata !== parentCtor.propMetadata) {
      let propMetadata = typeOrFunc.propMetadata;
      if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
        propMetadata = propMetadata.propMetadata;
      }
      return propMetadata;
    }
    // API of tsickle for lowering decorators to properties on the class.
    if (typeOrFunc.propDecorators && typeOrFunc.propDecorators !== parentCtor.propDecorators) {
      const propDecorators = typeOrFunc.propDecorators;
      const propMetadata = {};
      Object.keys(propDecorators).forEach(prop => {
        propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
      });
      return propMetadata;
    }
    // API for metadata created by invoking the decorators.
    if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
      return typeOrFunc[PROP_METADATA];
    }
    return null;
  }
  propMetadata(typeOrFunc) {
    if (!isType(typeOrFunc)) {
      return {};
    }
    const parentCtor = getParentCtor(typeOrFunc);
    const propMetadata = {};
    if (parentCtor !== Object) {
      const parentPropMetadata = this.propMetadata(parentCtor);
      Object.keys(parentPropMetadata).forEach(propName => {
        propMetadata[propName] = parentPropMetadata[propName];
      });
    }
    const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
    if (ownPropMetadata) {
      Object.keys(ownPropMetadata).forEach(propName => {
        const decorators = [];
        if (propMetadata.hasOwnProperty(propName)) {
          decorators.push(...propMetadata[propName]);
        }
        decorators.push(...ownPropMetadata[propName]);
        propMetadata[propName] = decorators;
      });
    }
    return propMetadata;
  }
  ownPropMetadata(typeOrFunc) {
    if (!isType(typeOrFunc)) {
      return {};
    }
    return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
  }
  hasLifecycleHook(type, lcProperty) {
    return type instanceof Type && lcProperty in type.prototype;
  }
}
function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
  if (!decoratorInvocations) {
    return [];
  }
  return decoratorInvocations.map(decoratorInvocation => {
    const decoratorType = decoratorInvocation.type;
    const annotationCls = decoratorType.annotationCls;
    const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
    return new annotationCls(...annotationArgs);
  });
}
function getParentCtor(ctor) {
  const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
  const parentCtor = parentProto ? parentProto.constructor : null;
  // Note: We always use `Object` as the null value
  // to simplify checking later on.
  return parentCtor || Object;
}

// Below are constants for LView indices to help us look up LView members
// without having to remember the specific indices.
// Uglify will inline these when minifying so there shouldn't be a cost.
const HOST = 0;
const TVIEW = 1;
// Shared with LContainer
const FLAGS = 2;
const PARENT = 3;
const NEXT = 4;
const T_HOST = 5;
// End shared with LContainer
const HYDRATION = 6;
const CLEANUP = 7;
const CONTEXT = 8;
const INJECTOR = 9;
const ENVIRONMENT = 10;
const RENDERER = 11;
const CHILD_HEAD = 12;
const CHILD_TAIL = 13;
// FIXME(misko): Investigate if the three declarations aren't all same thing.
const DECLARATION_VIEW = 14;
const DECLARATION_COMPONENT_VIEW = 15;
const DECLARATION_LCONTAINER = 16;
const PREORDER_HOOK_FLAGS = 17;
const QUERIES = 18;
const ID = 19;
const EMBEDDED_VIEW_INJECTOR = 20;
const ON_DESTROY_HOOKS = 21;
const EFFECTS_TO_SCHEDULE = 22;
const EFFECTS = 23;
const REACTIVE_TEMPLATE_CONSUMER = 24;
/**
 * Size of LView's header. Necessary to adjust for it when setting slots.
 *
 * IMPORTANT: `HEADER_OFFSET` should only be referred to the in the `ɵɵ*` instructions to translate
 * instruction index into `LView` index. All other indexes should be in the `LView` index space and
 * there should be no need to refer to `HEADER_OFFSET` anywhere else.
 */
const HEADER_OFFSET = 25;

/**
 * Special location which allows easy identification of type. If we have an array which was
 * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
 * `LContainer`.
 */
const TYPE = 1;
/**
 * Below are constants for LContainer indices to help us look up LContainer members
 * without having to remember the specific indices.
 * Uglify will inline these when minifying so there shouldn't be a cost.
 */
// FLAGS, PARENT, NEXT, and T_HOST are indices 2, 3, 4, and 5
// As we already have these constants in LView, we don't need to re-create them.
const DEHYDRATED_VIEWS = 6;
const NATIVE = 7;
const VIEW_REFS = 8;
const MOVED_VIEWS = 9;
/**
 * Size of LContainer's header. Represents the index after which all views in the
 * container will be inserted. We need to keep a record of current views so we know
 * which views are already in the DOM (and don't need to be re-added) and so we can
 * remove views from the DOM when they are no longer required.
 */
const CONTAINER_HEADER_OFFSET = 10;
/** Flags associated with an LContainer (saved in LContainer[FLAGS]) */
var LContainerFlags = /*#__PURE__*/function (LContainerFlags) {
  LContainerFlags[LContainerFlags["None"] = 0] = "None";
  /**
   * Flag to signify that this `LContainer` may have transplanted views which need to be change
   * detected. (see: `LView[DECLARATION_COMPONENT_VIEW])`.
   *
   * This flag, once set, is never unset for the `LContainer`.
   */
  LContainerFlags[LContainerFlags["HasTransplantedViews"] = 2] = "HasTransplantedViews";
  return LContainerFlags;
}(LContainerFlags || {});
/**
 * True if `value` is `LView`.
 * @param value wrapped value of `RNode`, `LView`, `LContainer`
 */
function isLView(value) {
  return Array.isArray(value) && typeof value[TYPE] === 'object';
}
/**
 * True if `value` is `LContainer`.
 * @param value wrapped value of `RNode`, `LView`, `LContainer`
 */
function isLContainer(value) {
  return Array.isArray(value) && value[TYPE] === true;
}
function isContentQueryHost(tNode) {
  return (tNode.flags & 4 /* TNodeFlags.hasContentQuery */) !== 0;
}
function isComponentHost(tNode) {
  return tNode.componentOffset > -1;
}
function isDirectiveHost(tNode) {
  return (tNode.flags & 1 /* TNodeFlags.isDirectiveHost */) === 1 /* TNodeFlags.isDirectiveHost */;
}
function isComponentDef(def) {
  return !!def.template;
}
function isRootView(target) {
  return (target[FLAGS] & 512 /* LViewFlags.IsRoot */) !== 0;
}
function isProjectionTNode(tNode) {
  return (tNode.type & 16 /* TNodeType.Projection */) === 16 /* TNodeType.Projection */;
}
function hasI18n(lView) {
  return (lView[FLAGS] & 32 /* LViewFlags.HasI18n */) === 32 /* LViewFlags.HasI18n */;
}
function isDestroyed(lView) {
  return (lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */;
}

// [Assert functions do not constraint type when they are guarded by a truthy
// expression.](https://github.com/microsoft/TypeScript/issues/37295)
function assertTNodeForLView(tNode, lView) {
  assertTNodeForTView(tNode, lView[TVIEW]);
}
function assertTNodeForTView(tNode, tView) {
  assertTNode(tNode);
  const tData = tView.data;
  for (let i = HEADER_OFFSET; i < tData.length; i++) {
    if (tData[i] === tNode) {
      return;
    }
  }
  throwError('This TNode does not belong to this TView.');
}
function assertTNode(tNode) {
  assertDefined(tNode, 'TNode must be defined');
  if (!(tNode && typeof tNode === 'object' && tNode.hasOwnProperty('directiveStylingLast'))) {
    throwError('Not of type TNode, got: ' + tNode);
  }
}
function assertTIcu(tIcu) {
  assertDefined(tIcu, 'Expected TIcu to be defined');
  if (!(typeof tIcu.currentCaseLViewIndex === 'number')) {
    throwError('Object is not of TIcu type.');
  }
}
function assertComponentType(actual, msg = "Type passed in is not ComponentType, it does not have 'ɵcmp' property.") {
  if (!getComponentDef(actual)) {
    throwError(msg);
  }
}
function assertNgModuleType(actual, msg = "Type passed in is not NgModuleType, it does not have 'ɵmod' property.") {
  if (!getNgModuleDef(actual)) {
    throwError(msg);
  }
}
function assertCurrentTNodeIsParent(isParent) {
  assertEqual(isParent, true, 'currentTNode should be a parent');
}
function assertHasParent(tNode) {
  assertDefined(tNode, 'currentTNode should exist!');
  assertDefined(tNode.parent, 'currentTNode should have a parent');
}
function assertLContainer(value) {
  assertDefined(value, 'LContainer must be defined');
  assertEqual(isLContainer(value), true, 'Expecting LContainer');
}
function assertLViewOrUndefined(value) {
  value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
}
function assertLView(value) {
  assertDefined(value, 'LView must be defined');
  assertEqual(isLView(value), true, 'Expecting LView');
}
function assertFirstCreatePass(tView, errMessage) {
  assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');
}
function assertFirstUpdatePass(tView, errMessage) {
  assertEqual(tView.firstUpdatePass, true, errMessage || 'Should only be called in first update pass.');
}
/**
 * This is a basic sanity check that an object is probably a directive def. DirectiveDef is
 * an interface, so we can't do a direct instanceof check.
 */
function assertDirectiveDef(obj) {
  if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {
    throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);
  }
}
function assertIndexInDeclRange(tView, index) {
  assertBetween(HEADER_OFFSET, tView.bindingStartIndex, index);
}
function assertIndexInExpandoRange(lView, index) {
  const tView = lView[1];
  assertBetween(tView.expandoStartIndex, lView.length, index);
}
function assertBetween(lower, upper, index) {
  if (!(lower <= index && index < upper)) {
    throwError(`Index out of range (expecting ${lower} <= ${index} < ${upper})`);
  }
}
function assertProjectionSlots(lView, errMessage) {
  assertDefined(lView[DECLARATION_COMPONENT_VIEW], 'Component views should exist.');
  assertDefined(lView[DECLARATION_COMPONENT_VIEW][T_HOST].projection, errMessage || 'Components with projection nodes (<ng-content>) must have projection slots defined.');
}
function assertParentView(lView, errMessage) {
  assertDefined(lView, errMessage || "Component views should always have a parent view (component's host view)");
}
function assertNoDuplicateDirectives(directives) {
  // The array needs at least two elements in order to have duplicates.
  if (directives.length < 2) {
    return;
  }
  const seenDirectives = new Set();
  for (const current of directives) {
    if (seenDirectives.has(current)) {
      throw new RuntimeError(309 /* RuntimeErrorCode.DUPLICATE_DIRECTIVE */, `Directive ${current.type.name} matches multiple times on the same element. ` + `Directives can only match an element once.`);
    }
    seenDirectives.add(current);
  }
}
/**
 * This is a basic sanity check that the `injectorIndex` seems to point to what looks like a
 * NodeInjector data structure.
 *
 * @param lView `LView` which should be checked.
 * @param injectorIndex index into the `LView` where the `NodeInjector` is expected.
 */
function assertNodeInjector(lView, injectorIndex) {
  assertIndexInExpandoRange(lView, injectorIndex);
  assertIndexInExpandoRange(lView, injectorIndex + 8 /* NodeInjectorOffset.PARENT */);
  assertNumber(lView[injectorIndex + 0], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 1], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 2], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 3], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 4], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 5], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 6], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 7], 'injectorIndex should point to a bloom filter');
  assertNumber(lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */], 'injectorIndex should point to parent injector');
}

/**
 * Represents a basic change from a previous to a new value for a single
 * property on a directive instance. Passed as a value in a
 * {@link SimpleChanges} object to the `ngOnChanges` hook.
 *
 * @see {@link OnChanges}
 *
 * @publicApi
 */
class SimpleChange {
  previousValue;
  currentValue;
  firstChange;
  constructor(previousValue, currentValue, firstChange) {
    this.previousValue = previousValue;
    this.currentValue = currentValue;
    this.firstChange = firstChange;
  }
  /**
   * Check whether the new value is the first value assigned.
   */
  isFirstChange() {
    return this.firstChange;
  }
}
function applyValueToInputField(instance, inputSignalNode, privateName, value) {
  if (inputSignalNode !== null) {
    inputSignalNode.applyValueToInputSignal(inputSignalNode, value);
  } else {
    instance[privateName] = value;
  }
}

/**
 * The NgOnChangesFeature decorates a component with support for the ngOnChanges
 * lifecycle hook, so it should be included in any component that implements
 * that hook.
 *
 * If the component or directive uses inheritance, the NgOnChangesFeature MUST
 * be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise
 * inherited properties will not be propagated to the ngOnChanges lifecycle
 * hook.
 *
 * Example usage:
 *
 * ```
 * static ɵcmp = defineComponent({
 *   ...
 *   inputs: {name: 'publicName'},
 *   features: [NgOnChangesFeature]
 * });
 * ```
 *
 * @codeGenApi
 */
const ɵɵNgOnChangesFeature = /* @__PURE__ */(() => {
  const ɵɵNgOnChangesFeatureImpl = () => NgOnChangesFeatureImpl;
  // This option ensures that the ngOnChanges lifecycle hook will be inherited
  // from superclasses (in InheritDefinitionFeature).
  /** @nocollapse */
  ɵɵNgOnChangesFeatureImpl.ngInherit = true;
  return ɵɵNgOnChangesFeatureImpl;
})();
function NgOnChangesFeatureImpl(definition) {
  if (definition.type.prototype.ngOnChanges) {
    definition.setInput = ngOnChangesSetInput;
  }
  return rememberChangeHistoryAndInvokeOnChangesHook;
}
/**
 * This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate
 * `ngOnChanges`.
 *
 * The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are
 * found it invokes `ngOnChanges` on the component instance.
 *
 * @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,
 *     it is guaranteed to be called with component instance.
 */
function rememberChangeHistoryAndInvokeOnChangesHook() {
  const simpleChangesStore = getSimpleChangesStore(this);
  const current = simpleChangesStore?.current;
  if (current) {
    const previous = simpleChangesStore.previous;
    if (previous === EMPTY_OBJ) {
      simpleChangesStore.previous = current;
    } else {
      // New changes are copied to the previous store, so that we don't lose history for inputs
      // which were not changed this time
      for (let key in current) {
        previous[key] = current[key];
      }
    }
    simpleChangesStore.current = null;
    this.ngOnChanges(current);
  }
}
function ngOnChangesSetInput(instance, inputSignalNode, value, publicName, privateName) {
  const declaredName = this.declaredInputs[publicName];
  ngDevMode && assertString(declaredName, 'Name of input in ngOnChanges has to be a string');
  const simpleChangesStore = getSimpleChangesStore(instance) || setSimpleChangesStore(instance, {
    previous: EMPTY_OBJ,
    current: null
  });
  const current = simpleChangesStore.current || (simpleChangesStore.current = {});
  const previous = simpleChangesStore.previous;
  const previousChange = previous[declaredName];
  current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);
  applyValueToInputField(instance, inputSignalNode, privateName, value);
}
const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
function getSimpleChangesStore(instance) {
  return instance[SIMPLE_CHANGES_STORE] || null;
}
function setSimpleChangesStore(instance, store) {
  return instance[SIMPLE_CHANGES_STORE] = store;
}
let profilerCallback = null;
/**
 * Sets the callback function which will be invoked before and after performing certain actions at
 * runtime (for example, before and after running change detection).
 *
 * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
 * The contract of the function might be changed in any release and/or the function can be removed
 * completely.
 *
 * @param profiler function provided by the caller or null value to disable profiling.
 */
const setProfiler = profiler => {
  profilerCallback = profiler;
};
/**
 * Profiler function which wraps user code executed by the runtime.
 *
 * @param event ProfilerEvent corresponding to the execution context
 * @param instance component instance
 * @param hookOrListener lifecycle hook function or output listener. The value depends on the
 *  execution context
 * @returns
 */
const profiler = function (event, instance, hookOrListener) {
  if (profilerCallback != null /* both `null` and `undefined` */) {
    profilerCallback(event, instance, hookOrListener);
  }
};
const SVG_NAMESPACE = 'svg';
const MATH_ML_NAMESPACE = 'math';

/**
 * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
 * in same location in `LView`. This is because we don't want to pre-allocate space for it
 * because the storage is sparse. This file contains utilities for dealing with such data types.
 *
 * How do we know what is stored at a given location in `LView`.
 * - `Array.isArray(value) === false` => `RNode` (The normal storage value)
 * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
 *   - `typeof value[TYPE] === 'object'` => `LView`
 *      - This happens when we have a component at a given location
 *   - `typeof value[TYPE] === true` => `LContainer`
 *      - This happens when we have `LContainer` binding at a given location.
 *
 *
 * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
 */
/**
 * Returns `RNode`.
 * @param value wrapped value of `RNode`, `LView`, `LContainer`
 */
function unwrapRNode(value) {
  while (Array.isArray(value)) {
    value = value[HOST];
  }
  return value;
}
/**
 * Returns `LView` or `null` if not found.
 * @param value wrapped value of `RNode`, `LView`, `LContainer`
 */
function unwrapLView(value) {
  while (Array.isArray(value)) {
    // This check is same as `isLView()` but we don't call at as we don't want to call
    // `Array.isArray()` twice and give JITer more work for inlining.
    if (typeof value[TYPE] === 'object') return value;
    value = value[HOST];
  }
  return null;
}
/**
 * Retrieves an element value from the provided `viewData`, by unwrapping
 * from any containers, component views, or style contexts.
 */
function getNativeByIndex(index, lView) {
  ngDevMode && assertIndexInRange(lView, index);
  ngDevMode && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Expected to be past HEADER_OFFSET');
  return unwrapRNode(lView[index]);
}
/**
 * Retrieve an `RNode` for a given `TNode` and `LView`.
 *
 * This function guarantees in dev mode to retrieve a non-null `RNode`.
 *
 * @param tNode
 * @param lView
 */
function getNativeByTNode(tNode, lView) {
  ngDevMode && assertTNodeForLView(tNode, lView);
  ngDevMode && assertIndexInRange(lView, tNode.index);
  const node = unwrapRNode(lView[tNode.index]);
  return node;
}
/**
 * Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
 *
 * Some `TNode`s don't have associated `RNode`s. For example `Projection`
 *
 * @param tNode
 * @param lView
 */
function getNativeByTNodeOrNull(tNode, lView) {
  const index = tNode === null ? -1 : tNode.index;
  if (index !== -1) {
    ngDevMode && assertTNodeForLView(tNode, lView);
    const node = unwrapRNode(lView[index]);
    return node;
  }
  return null;
}
// fixme(misko): The return Type should be `TNode|null`
function getTNode(tView, index) {
  ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
  ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
  const tNode = tView.data[index];
  ngDevMode && tNode !== null && assertTNode(tNode);
  return tNode;
}
/** Retrieves a value from any `LView` or `TData`. */
function load(view, index) {
  ngDevMode && assertIndexInRange(view, index);
  return view[index];
}
function getComponentLViewByIndex(nodeIndex, hostView) {
  // Could be an LView or an LContainer. If LContainer, unwrap to find LView.
  ngDevMode && assertIndexInRange(hostView, nodeIndex);
  const slotValue = hostView[nodeIndex];
  const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
  return lView;
}
/** Checks whether a given view is in creation mode */
function isCreationMode(view) {
  return (view[FLAGS] & 4 /* LViewFlags.CreationMode */) === 4 /* LViewFlags.CreationMode */;
}
/**
 * Returns a boolean for whether the view is attached to the change detection tree.
 *
 * Note: This determines whether a view should be checked, not whether it's inserted
 * into a container. For that, you'll want `viewAttachedToContainer` below.
 */
function viewAttachedToChangeDetector(view) {
  return (view[FLAGS] & 128 /* LViewFlags.Attached */) === 128 /* LViewFlags.Attached */;
}
/** Returns a boolean for whether the view is attached to a container. */
function viewAttachedToContainer(view) {
  return isLContainer(view[PARENT]);
}
function getConstant(consts, index) {
  if (index === null || index === undefined) return null;
  ngDevMode && assertIndexInRange(consts, index);
  return consts[index];
}
/**
 * Resets the pre-order hook flags of the view.
 * @param lView the LView on which the flags are reset
 */
function resetPreOrderHookFlags(lView) {
  lView[PREORDER_HOOK_FLAGS] = 0;
}
/**
 * Adds the `RefreshView` flag from the lView and updates HAS_CHILD_VIEWS_TO_REFRESH flag of
 * parents.
 */
function markViewForRefresh(lView) {
  if (lView[FLAGS] & 1024 /* LViewFlags.RefreshView */) {
    return;
  }
  lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  if (viewAttachedToChangeDetector(lView)) {
    markAncestorsForTraversal(lView);
  }
}
/**
 * Walks up the LView hierarchy.
 * @param nestingLevel Number of times to walk up in hierarchy.
 * @param currentView View from which to start the lookup.
 */
function walkUpViews(nestingLevel, currentView) {
  while (nestingLevel > 0) {
    ngDevMode && assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');
    currentView = currentView[DECLARATION_VIEW];
    nestingLevel--;
  }
  return currentView;
}
function requiresRefreshOrTraversal(lView) {
  return !!(lView[FLAGS] & (1024 /* LViewFlags.RefreshView */ | 8192 /* LViewFlags.HasChildViewsToRefresh */) || lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty);
}
/**
 * Updates the `HasChildViewsToRefresh` flag on the parents of the `LView` as well as the
 * parents above.
 */
function updateAncestorTraversalFlagsOnAttach(lView) {
  lView[ENVIRONMENT].changeDetectionScheduler?.notify(9 /* NotificationSource.ViewAttached */);
  if (lView[FLAGS] & 64 /* LViewFlags.Dirty */) {
    lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  }
  if (requiresRefreshOrTraversal(lView)) {
    markAncestorsForTraversal(lView);
  }
}
/**
 * Ensures views above the given `lView` are traversed during change detection even when they are
 * not dirty.
 *
 * This is done by setting the `HAS_CHILD_VIEWS_TO_REFRESH` flag up to the root, stopping when the
 * flag is already `true` or the `lView` is detached.
 */
function markAncestorsForTraversal(lView) {
  lView[ENVIRONMENT].changeDetectionScheduler?.notify(0 /* NotificationSource.MarkAncestorsForTraversal */);
  let parent = getLViewParent(lView);
  while (parent !== null) {
    // We stop adding markers to the ancestors once we reach one that already has the marker. This
    // is to avoid needlessly traversing all the way to the root when the marker already exists.
    if (parent[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
      break;
    }
    parent[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
    if (!viewAttachedToChangeDetector(parent)) {
      break;
    }
    parent = getLViewParent(parent);
  }
}
/**
 * Stores a LView-specific destroy callback.
 */
function storeLViewOnDestroy(lView, onDestroyCallback) {
  if ((lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */) {
    throw new RuntimeError(911 /* RuntimeErrorCode.VIEW_ALREADY_DESTROYED */, ngDevMode && 'View has already been destroyed.');
  }
  if (lView[ON_DESTROY_HOOKS] === null) {
    lView[ON_DESTROY_HOOKS] = [];
  }
  lView[ON_DESTROY_HOOKS].push(onDestroyCallback);
}
/**
 * Removes previously registered LView-specific destroy callback.
 */
function removeLViewOnDestroy(lView, onDestroyCallback) {
  if (lView[ON_DESTROY_HOOKS] === null) return;
  const destroyCBIdx = lView[ON_DESTROY_HOOKS].indexOf(onDestroyCallback);
  if (destroyCBIdx !== -1) {
    lView[ON_DESTROY_HOOKS].splice(destroyCBIdx, 1);
  }
}
/**
 * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
 * that LContainer, which is an LView
 * @param lView the lView whose parent to get
 */
function getLViewParent(lView) {
  ngDevMode && assertLView(lView);
  const parent = lView[PARENT];
  return isLContainer(parent) ? parent[PARENT] : parent;
}
const instructionState = {
  lFrame: /*#__PURE__*/createLFrame(null),
  bindingsEnabled: true,
  skipHydrationRootTNode: null
};
var CheckNoChangesMode = /*#__PURE__*/function (CheckNoChangesMode) {
  CheckNoChangesMode[CheckNoChangesMode["Off"] = 0] = "Off";
  CheckNoChangesMode[CheckNoChangesMode["Exhaustive"] = 1] = "Exhaustive";
  CheckNoChangesMode[CheckNoChangesMode["OnlyDirtyViews"] = 2] = "OnlyDirtyViews";
  return CheckNoChangesMode;
}(CheckNoChangesMode || {});
/**
 * In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.
 *
 * Necessary to support ChangeDetectorRef.checkNoChanges().
 *
 * The `checkNoChanges` function is invoked only in ngDevMode=true and verifies that no unintended
 * changes exist in the change detector or its children.
 */
let _checkNoChangesMode = 0; /* CheckNoChangesMode.Off */
/**
 * Flag used to indicate that we are in the middle running change detection on a view
 *
 * @see detectChangesInViewWhileDirty
 */
let _isRefreshingViews = false;
/**
 * Returns true if the instruction state stack is empty.
 *
 * Intended to be called from tests only (tree shaken otherwise).
 */
function specOnlyIsInstructionStateEmpty() {
  return instructionState.lFrame.parent === null;
}
function getElementDepthCount() {
  return instructionState.lFrame.elementDepthCount;
}
function increaseElementDepthCount() {
  instructionState.lFrame.elementDepthCount++;
}
function decreaseElementDepthCount() {
  instructionState.lFrame.elementDepthCount--;
}
function getBindingsEnabled() {
  return instructionState.bindingsEnabled;
}
/**
 * Returns true if currently inside a skip hydration block.
 * @returns boolean
 */
function isInSkipHydrationBlock$1() {
  return instructionState.skipHydrationRootTNode !== null;
}
/**
 * Returns true if this is the root TNode of the skip hydration block.
 * @param tNode the current TNode
 * @returns boolean
 */
function isSkipHydrationRootTNode(tNode) {
  return instructionState.skipHydrationRootTNode === tNode;
}
/**
 * Enables directive matching on elements.
 *
 *  * Example:
 * ```
 * <my-comp my-directive>
 *   Should match component / directive.
 * </my-comp>
 * <div ngNonBindable>
 *   <!-- ɵɵdisableBindings() -->
 *   <my-comp my-directive>
 *     Should not match component / directive because we are in ngNonBindable.
 *   </my-comp>
 *   <!-- ɵɵenableBindings() -->
 * </div>
 * ```
 *
 * @codeGenApi
 */
function ɵɵenableBindings() {
  instructionState.bindingsEnabled = true;
}
/**
 * Sets a flag to specify that the TNode is in a skip hydration block.
 * @param tNode the current TNode
 */
function enterSkipHydrationBlock(tNode) {
  instructionState.skipHydrationRootTNode = tNode;
}
/**
 * Disables directive matching on element.
 *
 *  * Example:
 * ```
 * <my-comp my-directive>
 *   Should match component / directive.
 * </my-comp>
 * <div ngNonBindable>
 *   <!-- ɵɵdisableBindings() -->
 *   <my-comp my-directive>
 *     Should not match component / directive because we are in ngNonBindable.
 *   </my-comp>
 *   <!-- ɵɵenableBindings() -->
 * </div>
 * ```
 *
 * @codeGenApi
 */
function ɵɵdisableBindings() {
  instructionState.bindingsEnabled = false;
}
/**
 * Clears the root skip hydration node when leaving a skip hydration block.
 */
function leaveSkipHydrationBlock() {
  instructionState.skipHydrationRootTNode = null;
}
/**
 * Return the current `LView`.
 */
function getLView() {
  return instructionState.lFrame.lView;
}
/**
 * Return the current `TView`.
 */
function getTView() {
  return instructionState.lFrame.tView;
}
/**
 * Restores `contextViewData` to the given OpaqueViewState instance.
 *
 * Used in conjunction with the getCurrentView() instruction to save a snapshot
 * of the current view and restore it when listeners are invoked. This allows
 * walking the declaration view tree in listeners to get vars from parent views.
 *
 * @param viewToRestore The OpaqueViewState instance to restore.
 * @returns Context of the restored OpaqueViewState instance.
 *
 * @codeGenApi
 */
function ɵɵrestoreView(viewToRestore) {
  instructionState.lFrame.contextLView = viewToRestore;
  return viewToRestore[CONTEXT];
}
/**
 * Clears the view set in `ɵɵrestoreView` from memory. Returns the passed in
 * value so that it can be used as a return value of an instruction.
 *
 * @codeGenApi
 */
function ɵɵresetView(value) {
  instructionState.lFrame.contextLView = null;
  return value;
}
function getCurrentTNode() {
  let currentTNode = getCurrentTNodePlaceholderOk();
  while (currentTNode !== null && currentTNode.type === 64 /* TNodeType.Placeholder */) {
    currentTNode = currentTNode.parent;
  }
  return currentTNode;
}
function getCurrentTNodePlaceholderOk() {
  return instructionState.lFrame.currentTNode;
}
function getCurrentParentTNode() {
  const lFrame = instructionState.lFrame;
  const currentTNode = lFrame.currentTNode;
  return lFrame.isParent ? currentTNode : currentTNode.parent;
}
function setCurrentTNode(tNode, isParent) {
  ngDevMode && tNode && assertTNodeForTView(tNode, instructionState.lFrame.tView);
  const lFrame = instructionState.lFrame;
  lFrame.currentTNode = tNode;
  lFrame.isParent = isParent;
}
function isCurrentTNodeParent() {
  return instructionState.lFrame.isParent;
}
function setCurrentTNodeAsNotParent() {
  instructionState.lFrame.isParent = false;
}
function getContextLView() {
  const contextLView = instructionState.lFrame.contextLView;
  ngDevMode && assertDefined(contextLView, 'contextLView must be defined.');
  return contextLView;
}
function isInCheckNoChangesMode() {
  !ngDevMode && throwError('Must never be called in production mode');
  return _checkNoChangesMode !== CheckNoChangesMode.Off;
}
function isExhaustiveCheckNoChanges() {
  !ngDevMode && throwError('Must never be called in production mode');
  return _checkNoChangesMode === CheckNoChangesMode.Exhaustive;
}
function setIsInCheckNoChangesMode(mode) {
  !ngDevMode && throwError('Must never be called in production mode');
  _checkNoChangesMode = mode;
}
function isRefreshingViews() {
  return _isRefreshingViews;
}
function setIsRefreshingViews(mode) {
  const prev = _isRefreshingViews;
  _isRefreshingViews = mode;
  return prev;
}
// top level variables should not be exported for performance reasons (PERF_NOTES.md)
function getBindingRoot() {
  const lFrame = instructionState.lFrame;
  let index = lFrame.bindingRootIndex;
  if (index === -1) {
    index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
  }
  return index;
}
function getBindingIndex() {
  return instructionState.lFrame.bindingIndex;
}
function setBindingIndex(value) {
  return instructionState.lFrame.bindingIndex = value;
}
function nextBindingIndex() {
  return instructionState.lFrame.bindingIndex++;
}
function incrementBindingIndex(count) {
  const lFrame = instructionState.lFrame;
  const index = lFrame.bindingIndex;
  lFrame.bindingIndex = lFrame.bindingIndex + count;
  return index;
}
function isInI18nBlock() {
  return instructionState.lFrame.inI18n;
}
function setInI18nBlock(isInI18nBlock) {
  instructionState.lFrame.inI18n = isInI18nBlock;
}
/**
 * Set a new binding root index so that host template functions can execute.
 *
 * Bindings inside the host template are 0 index. But because we don't know ahead of time
 * how many host bindings we have we can't pre-compute them. For this reason they are all
 * 0 index and we just shift the root so that they match next available location in the LView.
 *
 * @param bindingRootIndex Root index for `hostBindings`
 * @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
 *        whose `hostBindings` are being processed.
 */
function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
  const lFrame = instructionState.lFrame;
  lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
  setCurrentDirectiveIndex(currentDirectiveIndex);
}
/**
 * When host binding is executing this points to the directive index.
 * `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
 * `LView[getCurrentDirectiveIndex()]` is directive instance.
 */
function getCurrentDirectiveIndex() {
  return instructionState.lFrame.currentDirectiveIndex;
}
/**
 * Sets an index of a directive whose `hostBindings` are being processed.
 *
 * @param currentDirectiveIndex `TData` index where current directive instance can be found.
 */
function setCurrentDirectiveIndex(currentDirectiveIndex) {
  instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
}
/**
 * Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
 * executed.
 *
 * @param tData Current `TData` where the `DirectiveDef` will be looked up at.
 */
function getCurrentDirectiveDef(tData) {
  const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
  return currentDirectiveIndex === -1 ? null : tData[currentDirectiveIndex];
}
function getCurrentQueryIndex() {
  return instructionState.lFrame.currentQueryIndex;
}
function setCurrentQueryIndex(value) {
  instructionState.lFrame.currentQueryIndex = value;
}
/**
 * Returns a `TNode` of the location where the current `LView` is declared at.
 *
 * @param lView an `LView` that we want to find parent `TNode` for.
 */
function getDeclarationTNode(lView) {
  const tView = lView[TVIEW];
  // Return the declaration parent for embedded views
  if (tView.type === 2 /* TViewType.Embedded */) {
    ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
    return tView.declTNode;
  }
  // Components don't have `TView.declTNode` because each instance of component could be
  // inserted in different location, hence `TView.declTNode` is meaningless.
  // Falling back to `T_HOST` in case we cross component boundary.
  if (tView.type === 1 /* TViewType.Component */) {
    return lView[T_HOST];
  }
  // Remaining TNode type is `TViewType.Root` which doesn't have a parent TNode.
  return null;
}
/**
 * This is a light weight version of the `enterView` which is needed by the DI system.
 *
 * @param lView `LView` location of the DI context.
 * @param tNode `TNode` for DI context
 * @param flags DI context flags. if `SkipSelf` flag is set than we walk up the declaration
 *     tree from `tNode`  until we find parent declared `TElementNode`.
 * @returns `true` if we have successfully entered DI associated with `tNode` (or with declared
 *     `TNode` if `flags` has  `SkipSelf`). Failing to enter DI implies that no associated
 *     `NodeInjector` can be found and we should instead use `ModuleInjector`.
 *     - If `true` than this call must be fallowed by `leaveDI`
 *     - If `false` than this call failed and we should NOT call `leaveDI`
 */
function enterDI(lView, tNode, flags) {
  ngDevMode && assertLViewOrUndefined(lView);
  if (flags & InjectFlags.SkipSelf) {
    ngDevMode && assertTNodeForTView(tNode, lView[TVIEW]);
    let parentTNode = tNode;
    let parentLView = lView;
    while (true) {
      ngDevMode && assertDefined(parentTNode, 'Parent TNode should be defined');
      parentTNode = parentTNode.parent;
      if (parentTNode === null && !(flags & InjectFlags.Host)) {
        parentTNode = getDeclarationTNode(parentLView);
        if (parentTNode === null) break;
        // In this case, a parent exists and is definitely an element. So it will definitely
        // have an existing lView as the declaration view, which is why we can assume it's defined.
        ngDevMode && assertDefined(parentLView, 'Parent LView should be defined');
        parentLView = parentLView[DECLARATION_VIEW];
        // In Ivy there are Comment nodes that correspond to ngIf and NgFor embedded directives
        // We want to skip those and look only at Elements and ElementContainers to ensure
        // we're looking at true parent nodes, and not content or other types.
        if (parentTNode.type & (2 /* TNodeType.Element */ | 8 /* TNodeType.ElementContainer */)) {
          break;
        }
      } else {
        break;
      }
    }
    if (parentTNode === null) {
      // If we failed to find a parent TNode this means that we should use module injector.
      return false;
    } else {
      tNode = parentTNode;
      lView = parentLView;
    }
  }
  ngDevMode && assertTNodeForLView(tNode, lView);
  const lFrame = instructionState.lFrame = allocLFrame();
  lFrame.currentTNode = tNode;
  lFrame.lView = lView;
  return true;
}
/**
 * Swap the current lView with a new lView.
 *
 * For performance reasons we store the lView in the top level of the module.
 * This way we minimize the number of properties to read. Whenever a new view
 * is entered we have to store the lView for later, and when the view is
 * exited the state has to be restored
 *
 * @param newView New lView to become active
 * @returns the previously active lView;
 */
function enterView(newView) {
  ngDevMode && assertNotEqual(newView[0], newView[1], '????');
  ngDevMode && assertLViewOrUndefined(newView);
  const newLFrame = allocLFrame();
  if (ngDevMode) {
    assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
    assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
    assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
    assertEqual(newLFrame.selectedIndex, -1, 'Expected clean LFrame');
    assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
    assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
    assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
    assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
    assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
  }
  const tView = newView[TVIEW];
  instructionState.lFrame = newLFrame;
  ngDevMode && tView.firstChild && assertTNodeForTView(tView.firstChild, tView);
  newLFrame.currentTNode = tView.firstChild;
  newLFrame.lView = newView;
  newLFrame.tView = tView;
  newLFrame.contextLView = newView;
  newLFrame.bindingIndex = tView.bindingStartIndex;
  newLFrame.inI18n = false;
}
/**
 * Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
 */
function allocLFrame() {
  const currentLFrame = instructionState.lFrame;
  const childLFrame = currentLFrame === null ? null : currentLFrame.child;
  const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
  return newLFrame;
}
function createLFrame(parent) {
  const lFrame = {
    currentTNode: null,
    isParent: true,
    lView: null,
    tView: null,
    selectedIndex: -1,
    contextLView: null,
    elementDepthCount: 0,
    currentNamespace: null,
    currentDirectiveIndex: -1,
    bindingRootIndex: -1,
    bindingIndex: -1,
    currentQueryIndex: 0,
    parent: parent,
    child: null,
    inI18n: false
  };
  parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
  return lFrame;
}
/**
 * A lightweight version of leave which is used with DI.
 *
 * This function only resets `currentTNode` and `LView` as those are the only properties
 * used with DI (`enterDI()`).
 *
 * NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
 * as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
 */
function leaveViewLight() {
  const oldLFrame = instructionState.lFrame;
  instructionState.lFrame = oldLFrame.parent;
  oldLFrame.currentTNode = null;
  oldLFrame.lView = null;
  return oldLFrame;
}
/**
 * This is a lightweight version of the `leaveView` which is needed by the DI system.
 *
 * NOTE: this function is an alias so that we can change the type of the function to have `void`
 * return type.
 */
const leaveDI = leaveViewLight;
/**
 * Leave the current `LView`
 *
 * This pops the `LFrame` with the associated `LView` from the stack.
 *
 * IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
 * because for performance reasons we don't release `LFrame` but rather keep it for next use.
 */
function leaveView() {
  const oldLFrame = leaveViewLight();
  oldLFrame.isParent = true;
  oldLFrame.tView = null;
  oldLFrame.selectedIndex = -1;
  oldLFrame.contextLView = null;
  oldLFrame.elementDepthCount = 0;
  oldLFrame.currentDirectiveIndex = -1;
  oldLFrame.currentNamespace = null;
  oldLFrame.bindingRootIndex = -1;
  oldLFrame.bindingIndex = -1;
  oldLFrame.currentQueryIndex = 0;
}
function nextContextImpl(level) {
  const contextLView = instructionState.lFrame.contextLView = walkUpViews(level, instructionState.lFrame.contextLView);
  return contextLView[CONTEXT];
}
/**
 * Gets the currently selected element index.
 *
 * Used with {@link property} instruction (and more in the future) to identify the index in the
 * current `LView` to act on.
 */
function getSelectedIndex() {
  return instructionState.lFrame.selectedIndex;
}
/**
 * Sets the most recent index passed to {@link select}
 *
 * Used with {@link property} instruction (and more in the future) to identify the index in the
 * current `LView` to act on.
 *
 * (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
 * run if and when the provided `index` value is different from the current selected index value.)
 */
function setSelectedIndex(index) {
  ngDevMode && index !== -1 && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Index must be past HEADER_OFFSET (or -1).');
  ngDevMode && assertLessThan(index, instructionState.lFrame.lView.length, "Can't set index passed end of LView");
  instructionState.lFrame.selectedIndex = index;
}
/**
 * Gets the `tNode` that represents currently selected element.
 */
function getSelectedTNode() {
  const lFrame = instructionState.lFrame;
  return getTNode(lFrame.tView, lFrame.selectedIndex);
}
/**
 * Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
 *
 * @codeGenApi
 */
function ɵɵnamespaceSVG() {
  instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
}
/**
 * Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
 *
 * @codeGenApi
 */
function ɵɵnamespaceMathML() {
  instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
}
/**
 * Sets the namespace used to create elements to `null`, which forces element creation to use
 * `createElement` rather than `createElementNS`.
 *
 * @codeGenApi
 */
function ɵɵnamespaceHTML() {
  namespaceHTMLInternal();
}
/**
 * Sets the namespace used to create elements to `null`, which forces element creation to use
 * `createElement` rather than `createElementNS`.
 */
function namespaceHTMLInternal() {
  instructionState.lFrame.currentNamespace = null;
}
function getNamespace$1() {
  return instructionState.lFrame.currentNamespace;
}
let _wasLastNodeCreated = true;
/**
 * Retrieves a global flag that indicates whether the most recent DOM node
 * was created or hydrated.
 */
function wasLastNodeCreated() {
  return _wasLastNodeCreated;
}
/**
 * Sets a global flag to indicate whether the most recent DOM node
 * was created or hydrated.
 */
function lastNodeWasCreated(flag) {
  _wasLastNodeCreated = flag;
}

/**
 * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
 *
 * Must be run *only* on the first template pass.
 *
 * Sets up the pre-order hooks on the provided `tView`,
 * see {@link HookData} for details about the data structure.
 *
 * @param directiveIndex The index of the directive in LView
 * @param directiveDef The definition containing the hooks to setup in tView
 * @param tView The current TView
 */
function registerPreOrderHooks(directiveIndex, directiveDef, tView) {
  ngDevMode && assertFirstCreatePass(tView);
  const {
    ngOnChanges,
    ngOnInit,
    ngDoCheck
  } = directiveDef.type.prototype;
  if (ngOnChanges) {
    const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef);
    (tView.preOrderHooks ??= []).push(directiveIndex, wrappedOnChanges);
    (tView.preOrderCheckHooks ??= []).push(directiveIndex, wrappedOnChanges);
  }
  if (ngOnInit) {
    (tView.preOrderHooks ??= []).push(0 - directiveIndex, ngOnInit);
  }
  if (ngDoCheck) {
    (tView.preOrderHooks ??= []).push(directiveIndex, ngDoCheck);
    (tView.preOrderCheckHooks ??= []).push(directiveIndex, ngDoCheck);
  }
}
/**
 *
 * Loops through the directives on the provided `tNode` and queues hooks to be
 * run that are not initialization hooks.
 *
 * Should be executed during `elementEnd()` and similar to
 * preserve hook execution order. Content, view, and destroy hooks for projected
 * components and directives must be called *before* their hosts.
 *
 * Sets up the content, view, and destroy hooks on the provided `tView`,
 * see {@link HookData} for details about the data structure.
 *
 * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
 * separately at `elementStart`.
 *
 * @param tView The current TView
 * @param tNode The TNode whose directives are to be searched for hooks to queue
 */
function registerPostOrderHooks(tView, tNode) {
  ngDevMode && assertFirstCreatePass(tView);
  // It's necessary to loop through the directives at elementEnd() (rather than processing in
  // directiveCreate) so we can preserve the current hook order. Content, view, and destroy
  // hooks for projected components and directives must be called *before* their hosts.
  for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
    const directiveDef = tView.data[i];
    ngDevMode && assertDefined(directiveDef, 'Expecting DirectiveDef');
    const lifecycleHooks = directiveDef.type.prototype;
    const {
      ngAfterContentInit,
      ngAfterContentChecked,
      ngAfterViewInit,
      ngAfterViewChecked,
      ngOnDestroy
    } = lifecycleHooks;
    if (ngAfterContentInit) {
      (tView.contentHooks ??= []).push(-i, ngAfterContentInit);
    }
    if (ngAfterContentChecked) {
      (tView.contentHooks ??= []).push(i, ngAfterContentChecked);
      (tView.contentCheckHooks ??= []).push(i, ngAfterContentChecked);
    }
    if (ngAfterViewInit) {
      (tView.viewHooks ??= []).push(-i, ngAfterViewInit);
    }
    if (ngAfterViewChecked) {
      (tView.viewHooks ??= []).push(i, ngAfterViewChecked);
      (tView.viewCheckHooks ??= []).push(i, ngAfterViewChecked);
    }
    if (ngOnDestroy != null) {
      (tView.destroyHooks ??= []).push(i, ngOnDestroy);
    }
  }
}
/**
 * Executing hooks requires complex logic as we need to deal with 2 constraints.
 *
 * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
 * once, across many change detection cycles. This must be true even if some hooks throw, or if
 * some recursively trigger a change detection cycle.
 * To solve that, it is required to track the state of the execution of these init hooks.
 * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
 * and the index within that phase. They can be seen as a cursor in the following structure:
 * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
 * They are stored as flags in LView[FLAGS].
 *
 * 2. Pre-order hooks can be executed in batches, because of the select instruction.
 * To be able to pause and resume their execution, we also need some state about the hook's array
 * that is being processed:
 * - the index of the next hook to be executed
 * - the number of init hooks already found in the processed part of the  array
 * They are stored as flags in LView[PREORDER_HOOK_FLAGS].
 */
/**
 * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were
 * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read
 * / write of the init-hooks related flags.
 * @param lView The LView where hooks are defined
 * @param hooks Hooks to be run
 * @param nodeIndex 3 cases depending on the value:
 * - undefined: all hooks from the array should be executed (post-order case)
 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
 * flushing the remaining hooks)
 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
 * case, when executing select(number))
 */
function executeCheckHooks(lView, hooks, nodeIndex) {
  callHooks(lView, hooks, 3 /* InitPhaseState.InitPhaseCompleted */, nodeIndex);
}
/**
 * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,
 * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.
 * @param lView The LView where hooks are defined
 * @param hooks Hooks to be run
 * @param initPhase A phase for which hooks should be run
 * @param nodeIndex 3 cases depending on the value:
 * - undefined: all hooks from the array should be executed (post-order case)
 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
 * flushing the remaining hooks)
 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
 * case, when executing select(number))
 */
function executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {
  ngDevMode && assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');
  if ((lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
    callHooks(lView, hooks, initPhase, nodeIndex);
  }
}
function incrementInitPhaseFlags(lView, initPhase) {
  ngDevMode && assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');
  let flags = lView[FLAGS];
  if ((flags & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
    flags &= 16383 /* LViewFlags.IndexWithinInitPhaseReset */;
    flags += 1 /* LViewFlags.InitPhaseStateIncrementer */;
    lView[FLAGS] = flags;
  }
}
/**
 * Calls lifecycle hooks with their contexts, skipping init hooks if it's not
 * the first LView pass
 *
 * @param currentView The current view
 * @param arr The array in which the hooks are found
 * @param initPhaseState the current state of the init phase
 * @param currentNodeIndex 3 cases depending on the value:
 * - undefined: all hooks from the array should be executed (post-order case)
 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
 * flushing the remaining hooks)
 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
 * case, when executing select(number))
 */
function callHooks(currentView, arr, initPhase, currentNodeIndex) {
  ngDevMode && assertEqual(isInCheckNoChangesMode(), false, 'Hooks should never be run when in check no changes mode.');
  const startIndex = currentNodeIndex !== undefined ? currentView[PREORDER_HOOK_FLAGS] & 65535 /* PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask */ : 0;
  const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
  const max = arr.length - 1; // Stop the loop at length - 1, because we look for the hook at i + 1
  let lastNodeIndexFound = 0;
  for (let i = startIndex; i < max; i++) {
    const hook = arr[i + 1];
    if (typeof hook === 'number') {
      lastNodeIndexFound = arr[i];
      if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
        break;
      }
    } else {
      const isInitHook = arr[i] < 0;
      if (isInitHook) {
        currentView[PREORDER_HOOK_FLAGS] += 65536 /* PreOrderHookFlags.NumberOfInitHooksCalledIncrementer */;
      }
      if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
        callHook(currentView, initPhase, arr, i);
        currentView[PREORDER_HOOK_FLAGS] = (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* PreOrderHookFlags.NumberOfInitHooksCalledMask */) + i + 2;
      }
      i++;
    }
  }
}
/**
 * Executes a single lifecycle hook, making sure that:
 * - it is called in the non-reactive context;
 * - profiling data are registered.
 */
function callHookInternal(directive, hook) {
  profiler(4 /* ProfilerEvent.LifecycleHookStart */, directive, hook);
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    hook.call(directive);
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    profiler(5 /* ProfilerEvent.LifecycleHookEnd */, directive, hook);
  }
}
/**
 * Execute one hook against the current `LView`.
 *
 * @param currentView The current view
 * @param initPhaseState the current state of the init phase
 * @param arr The array in which the hooks are found
 * @param i The current index within the hook data array
 */
function callHook(currentView, initPhase, arr, i) {
  const isInitHook = arr[i] < 0;
  const hook = arr[i + 1];
  const directiveIndex = isInitHook ? -arr[i] : arr[i];
  const directive = currentView[directiveIndex];
  if (isInitHook) {
    const indexWithintInitPhase = currentView[FLAGS] >> 14 /* LViewFlags.IndexWithinInitPhaseShift */;
    // The init phase state must be always checked here as it may have been recursively updated.
    if (indexWithintInitPhase < currentView[PREORDER_HOOK_FLAGS] >> 16 /* PreOrderHookFlags.NumberOfInitHooksCalledShift */ && (currentView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
      currentView[FLAGS] += 16384 /* LViewFlags.IndexWithinInitPhaseIncrementer */;
      callHookInternal(directive, hook);
    }
  } else {
    callHookInternal(directive, hook);
  }
}
const NO_PARENT_INJECTOR = -1;
/**
 * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
 * `TView.data`. This allows us to store information about the current node's tokens (which
 * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
 * shared, so they live in `LView`).
 *
 * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
 * determines whether a directive is available on the associated node or not. This prevents us
 * from searching the directives array at this level unless it's probable the directive is in it.
 *
 * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
 *
 * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
 * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
 * will differ based on where it is flattened into the main array, so it's not possible to know
 * the indices ahead of time and save their types here. The interfaces are still included here
 * for documentation purposes.
 *
 * export interface LInjector extends Array<any> {
 *
 *    // Cumulative bloom for directive IDs 0-31  (IDs are % BLOOM_SIZE)
 *    [0]: number;
 *
 *    // Cumulative bloom for directive IDs 32-63
 *    [1]: number;
 *
 *    // Cumulative bloom for directive IDs 64-95
 *    [2]: number;
 *
 *    // Cumulative bloom for directive IDs 96-127
 *    [3]: number;
 *
 *    // Cumulative bloom for directive IDs 128-159
 *    [4]: number;
 *
 *    // Cumulative bloom for directive IDs 160 - 191
 *    [5]: number;
 *
 *    // Cumulative bloom for directive IDs 192 - 223
 *    [6]: number;
 *
 *    // Cumulative bloom for directive IDs 224 - 255
 *    [7]: number;
 *
 *    // We need to store a reference to the injector's parent so DI can keep looking up
 *    // the injector tree until it finds the dependency it's looking for.
 *    [PARENT_INJECTOR]: number;
 * }
 *
 * export interface TInjector extends Array<any> {
 *
 *    // Shared node bloom for directive IDs 0-31  (IDs are % BLOOM_SIZE)
 *    [0]: number;
 *
 *    // Shared node bloom for directive IDs 32-63
 *    [1]: number;
 *
 *    // Shared node bloom for directive IDs 64-95
 *    [2]: number;
 *
 *    // Shared node bloom for directive IDs 96-127
 *    [3]: number;
 *
 *    // Shared node bloom for directive IDs 128-159
 *    [4]: number;
 *
 *    // Shared node bloom for directive IDs 160 - 191
 *    [5]: number;
 *
 *    // Shared node bloom for directive IDs 192 - 223
 *    [6]: number;
 *
 *    // Shared node bloom for directive IDs 224 - 255
 *    [7]: number;
 *
 *    // Necessary to find directive indices for a particular node.
 *    [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
 *  }
 */
/**
 * Factory for creating instances of injectors in the NodeInjector.
 *
 * This factory is complicated by the fact that it can resolve `multi` factories as well.
 *
 * NOTE: Some of the fields are optional which means that this class has two hidden classes.
 * - One without `multi` support (most common)
 * - One with `multi` values, (rare).
 *
 * Since VMs can cache up to 4 inline hidden classes this is OK.
 *
 * - Single factory: Only `resolving` and `factory` is defined.
 * - `providers` factory: `componentProviders` is a number and `index = -1`.
 * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
 */
class NodeInjectorFactory {
  factory;
  /**
   * The inject implementation to be activated when using the factory.
   */
  injectImpl;
  /**
   * Marker set to true during factory invocation to see if we get into recursive loop.
   * Recursive loop causes an error to be displayed.
   */
  resolving = false;
  /**
   * Marks that the token can see other Tokens declared in `viewProviders` on the same node.
   */
  canSeeViewProviders;
  /**
   * An array of factories to use in case of `multi` provider.
   */
  multi;
  /**
   * Number of `multi`-providers which belong to the component.
   *
   * This is needed because when multiple components and directives declare the `multi` provider
   * they have to be concatenated in the correct order.
   *
   * Example:
   *
   * If we have a component and directive active an a single element as declared here
   * ```
   * component:
   *   providers: [ {provide: String, useValue: 'component', multi: true} ],
   *   viewProviders: [ {provide: String, useValue: 'componentView', multi: true} ],
   *
   * directive:
   *   providers: [ {provide: String, useValue: 'directive', multi: true} ],
   * ```
   *
   * Then the expected results are:
   *
   * ```
   * providers: ['component', 'directive']
   * viewProviders: ['component', 'componentView', 'directive']
   * ```
   *
   * The way to think about it is that the `viewProviders` have been inserted after the component
   * but before the directives, which is why we need to know how many `multi`s have been declared by
   * the component.
   */
  componentProviders;
  /**
   * Current index of the Factory in the `data`. Needed for `viewProviders` and `providers` merging.
   * See `providerFactory`.
   */
  index;
  /**
   * Because the same `multi` provider can be declared in `providers` and `viewProviders` it is
   * possible for `viewProviders` to shadow the `providers`. For this reason we store the
   * `provideFactory` of the `providers` so that `providers` can be extended with `viewProviders`.
   *
   * Example:
   *
   * Given:
   * ```
   * providers: [ {provide: String, useValue: 'all', multi: true} ],
   * viewProviders: [ {provide: String, useValue: 'viewOnly', multi: true} ],
   * ```
   *
   * We have to return `['all']` in case of content injection, but `['all', 'viewOnly']` in case
   * of view injection. We further have to make sure that the shared instances (in our case
   * `all`) are the exact same instance in both the content as well as the view injection. (We
   * have to make sure that we don't double instantiate.) For this reason the `viewProviders`
   * `Factory` has a pointer to the shadowed `providers` factory so that it can instantiate the
   * `providers` (`['all']`) and then extend it with `viewProviders` (`['all'] + ['viewOnly'] =
   * ['all', 'viewOnly']`).
   */
  providerFactory;
  constructor(
  /**
   * Factory to invoke in order to create a new instance.
   */
  factory,
  /**
   * Set to `true` if the token is declared in `viewProviders` (or if it is component).
   */
  isViewProvider, injectImplementation) {
    this.factory = factory;
    ngDevMode && assertDefined(factory, 'Factory not specified');
    ngDevMode && assertEqual(typeof factory, 'function', 'Expected factory function.');
    this.canSeeViewProviders = isViewProvider;
    this.injectImpl = injectImplementation;
  }
}
function isFactory(obj) {
  return obj instanceof NodeInjectorFactory;
}

/**
 * Converts `TNodeType` into human readable text.
 * Make sure this matches with `TNodeType`
 */
function toTNodeTypeAsString(tNodeType) {
  let text = '';
  tNodeType & 1 /* TNodeType.Text */ && (text += '|Text');
  tNodeType & 2 /* TNodeType.Element */ && (text += '|Element');
  tNodeType & 4 /* TNodeType.Container */ && (text += '|Container');
  tNodeType & 8 /* TNodeType.ElementContainer */ && (text += '|ElementContainer');
  tNodeType & 16 /* TNodeType.Projection */ && (text += '|Projection');
  tNodeType & 32 /* TNodeType.Icu */ && (text += '|IcuContainer');
  tNodeType & 64 /* TNodeType.Placeholder */ && (text += '|Placeholder');
  tNodeType & 128 /* TNodeType.LetDeclaration */ && (text += '|LetDeclaration');
  return text.length > 0 ? text.substring(1) : text;
}
/**
 * Helper function to detect if a given value matches a `TNode` shape.
 *
 * The logic uses the `insertBeforeIndex` and its possible values as
 * a way to differentiate a TNode shape from other types of objects
 * within the `TView.data`. This is not a perfect check, but it can
 * be a reasonable differentiator, since we control the shapes of objects
 * within `TView.data`.
 */
function isTNodeShape(value) {
  return value != null && typeof value === 'object' && (value.insertBeforeIndex === null || typeof value.insertBeforeIndex === 'number' || Array.isArray(value.insertBeforeIndex));
}
function isLetDeclaration(tNode) {
  return !!(tNode.type & 128 /* TNodeType.LetDeclaration */);
}
/**
 * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding.
 *
 * ```
 * <div my-dir [class]="exp"></div>
 * ```
 * and
 * ```
 * @Directive({
 * })
 * class MyDirective {
 *   @Input()
 *   class: string;
 * }
 * ```
 *
 * In the above case it is necessary to write the reconciled styling information into the
 * directive's input.
 *
 * @param tNode
 */
function hasClassInput(tNode) {
  return (tNode.flags & 8 /* TNodeFlags.hasClassInput */) !== 0;
}
/**
 * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding.
 *
 * ```
 * <div my-dir [style]="exp"></div>
 * ```
 * and
 * ```
 * @Directive({
 * })
 * class MyDirective {
 *   @Input()
 *   class: string;
 * }
 * ```
 *
 * In the above case it is necessary to write the reconciled styling information into the
 * directive's input.
 *
 * @param tNode
 */
function hasStyleInput(tNode) {
  return (tNode.flags & 16 /* TNodeFlags.hasStyleInput */) !== 0;
}
function assertTNodeType(tNode, expectedTypes, message) {
  assertDefined(tNode, 'should be called with a TNode');
  if ((tNode.type & expectedTypes) === 0) {
    throwError(message || `Expected [${toTNodeTypeAsString(expectedTypes)}] but got ${toTNodeTypeAsString(tNode.type)}.`);
  }
}
function assertPureTNodeType(type) {
  if (!(type === 2 /* TNodeType.Element */ || type === 1 /* TNodeType.Text */ || type === 4 /* TNodeType.Container */ || type === 8 /* TNodeType.ElementContainer */ || type === 32 /* TNodeType.Icu */ || type === 16 /* TNodeType.Projection */ || type === 64 /* TNodeType.Placeholder */ || type === 128 /* TNodeType.LetDeclaration */)) {
    throwError(`Expected TNodeType to have only a single type selected, but got ${toTNodeTypeAsString(type)}.`);
  }
}

/**
 * Assigns all attribute values to the provided element via the inferred renderer.
 *
 * This function accepts two forms of attribute entries:
 *
 * default: (key, value):
 *  attrs = [key1, value1, key2, value2]
 *
 * namespaced: (NAMESPACE_MARKER, uri, name, value)
 *  attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
 *
 * The `attrs` array can contain a mix of both the default and namespaced entries.
 * The "default" values are set without a marker, but if the function comes across
 * a marker value then it will attempt to set a namespaced value. If the marker is
 * not of a namespaced value then the function will quit and return the index value
 * where it stopped during the iteration of the attrs array.
 *
 * See [AttributeMarker] to understand what the namespace marker value is.
 *
 * Note that this instruction does not support assigning style and class values to
 * an element. See `elementStart` and `elementHostAttrs` to learn how styling values
 * are applied to an element.
 * @param renderer The renderer to be used
 * @param native The element that the attributes will be assigned to
 * @param attrs The attribute array of values that will be assigned to the element
 * @returns the index value that was last accessed in the attributes array
 */
function setUpAttributes(renderer, native, attrs) {
  let i = 0;
  while (i < attrs.length) {
    const value = attrs[i];
    if (typeof value === 'number') {
      // only namespaces are supported. Other value types (such as style/class
      // entries) are not supported in this function.
      if (value !== 0 /* AttributeMarker.NamespaceURI */) {
        break;
      }
      // we just landed on the marker value ... therefore
      // we should skip to the next entry
      i++;
      const namespaceURI = attrs[i++];
      const attrName = attrs[i++];
      const attrVal = attrs[i++];
      ngDevMode && ngDevMode.rendererSetAttribute++;
      renderer.setAttribute(native, attrName, attrVal, namespaceURI);
    } else {
      // attrName is string;
      const attrName = value;
      const attrVal = attrs[++i];
      // Standard attributes
      ngDevMode && ngDevMode.rendererSetAttribute++;
      if (isAnimationProp(attrName)) {
        renderer.setProperty(native, attrName, attrVal);
      } else {
        renderer.setAttribute(native, attrName, attrVal);
      }
      i++;
    }
  }
  // another piece of code may iterate over the same attributes array. Therefore
  // it may be helpful to return the exact spot where the attributes array exited
  // whether by running into an unsupported marker or if all the static values were
  // iterated over.
  return i;
}
/**
 * Test whether the given value is a marker that indicates that the following
 * attribute values in a `TAttributes` array are only the names of attributes,
 * and not name-value pairs.
 * @param marker The attribute marker to test.
 * @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
 */
function isNameOnlyAttributeMarker(marker) {
  return marker === 3 /* AttributeMarker.Bindings */ || marker === 4 /* AttributeMarker.Template */ || marker === 6 /* AttributeMarker.I18n */;
}
function isAnimationProp(name) {
  // Perf note: accessing charCodeAt to check for the first character of a string is faster as
  // compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
  // charCodeAt doesn't allocate memory to return a substring.
  return name.charCodeAt(0) === 64 /* CharCode.AT_SIGN */;
}
/**
 * Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
 *
 * This merge function keeps the order of attrs same.
 *
 * @param dst Location of where the merged `TAttributes` should end up.
 * @param src `TAttributes` which should be appended to `dst`
 */
function mergeHostAttrs(dst, src) {
  if (src === null || src.length === 0) {
    // do nothing
  } else if (dst === null || dst.length === 0) {
    // We have source, but dst is empty, just make a copy.
    dst = src.slice();
  } else {
    let srcMarker = -1 /* AttributeMarker.ImplicitAttributes */;
    for (let i = 0; i < src.length; i++) {
      const item = src[i];
      if (typeof item === 'number') {
        srcMarker = item;
      } else {
        if (srcMarker === 0 /* AttributeMarker.NamespaceURI */) {
          // Case where we need to consume `key1`, `key2`, `value` items.
        } else if (srcMarker === -1 /* AttributeMarker.ImplicitAttributes */ || srcMarker === 2 /* AttributeMarker.Styles */) {
          // Case where we have to consume `key1` and `value` only.
          mergeHostAttribute(dst, srcMarker, item, null, src[++i]);
        } else {
          // Case where we have to consume `key1` only.
          mergeHostAttribute(dst, srcMarker, item, null, null);
        }
      }
    }
  }
  return dst;
}
/**
 * Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
 *
 * @param dst `TAttributes` to append to.
 * @param marker Region where the `key`/`value` should be added.
 * @param key1 Key to add to `TAttributes`
 * @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
 * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
 */
function mergeHostAttribute(dst, marker, key1, key2, value) {
  let i = 0;
  // Assume that new markers will be inserted at the end.
  let markerInsertPosition = dst.length;
  // scan until correct type.
  if (marker === -1 /* AttributeMarker.ImplicitAttributes */) {
    markerInsertPosition = -1;
  } else {
    while (i < dst.length) {
      const dstValue = dst[i++];
      if (typeof dstValue === 'number') {
        if (dstValue === marker) {
          markerInsertPosition = -1;
          break;
        } else if (dstValue > marker) {
          // We need to save this as we want the markers to be inserted in specific order.
          markerInsertPosition = i - 1;
          break;
        }
      }
    }
  }
  // search until you find place of insertion
  while (i < dst.length) {
    const item = dst[i];
    if (typeof item === 'number') {
      // since `i` started as the index after the marker, we did not find it if we are at the next
      // marker
      break;
    } else if (item === key1) {
      // We already have same token
      if (key2 === null) {
        if (value !== null) {
          dst[i + 1] = value;
        }
        return;
      } else if (key2 === dst[i + 1]) {
        dst[i + 2] = value;
        return;
      }
    }
    // Increment counter.
    i++;
    if (key2 !== null) i++;
    if (value !== null) i++;
  }
  // insert at location.
  if (markerInsertPosition !== -1) {
    dst.splice(markerInsertPosition, 0, marker);
    i = markerInsertPosition + 1;
  }
  dst.splice(i++, 0, key1);
  if (key2 !== null) {
    dst.splice(i++, 0, key2);
  }
  if (value !== null) {
    dst.splice(i++, 0, value);
  }
}

// This default value is when checking the hierarchy for a token.
//
// It means both:
// - the token is not provided by the current injector,
// - only the element injectors should be checked (ie do not check module injectors
//
//          mod1
//         /
//       el1   mod2
//         \  /
//         el2
//
// When requesting el2.injector.get(token), we should check in the following order and return the
// first found value:
// - el2.injector.get(token, default)
// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
// - mod2.injector.get(token, default)
const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};

/**
 * Injector that looks up a value using a specific injector, before falling back to the module
 * injector. Used primarily when creating components or embedded views dynamically.
 */
class ChainedInjector {
  injector;
  parentInjector;
  constructor(injector, parentInjector) {
    this.injector = injector;
    this.parentInjector = parentInjector;
  }
  get(token, notFoundValue, flags) {
    flags = convertToBitFlags(flags);
    const value = this.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);
    if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR || notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
      // Return the value from the root element injector when
      // - it provides it
      //   (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
      // - the module injector should not be checked
      //   (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
      return value;
    }
    return this.parentInjector.get(token, notFoundValue, flags);
  }
}

/// Parent Injector Utils ///////////////////////////////////////////////////////////////
function hasParentInjector(parentLocation) {
  return parentLocation !== NO_PARENT_INJECTOR;
}
function getParentInjectorIndex(parentLocation) {
  if (ngDevMode) {
    assertNumber(parentLocation, 'Number expected');
    assertNotEqual(parentLocation, -1, 'Not a valid state.');
    const parentInjectorIndex = parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
    assertGreaterThan(parentInjectorIndex, HEADER_OFFSET, 'Parent injector must be pointing past HEADER_OFFSET.');
  }
  return parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
}
function getParentInjectorViewOffset(parentLocation) {
  return parentLocation >> 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;
}
/**
 * Unwraps a parent injector location number to find the view offset from the current injector,
 * then walks up the declaration view tree until the view is found that contains the parent
 * injector.
 *
 * @param location The location of the parent injector, which contains the view offset
 * @param startView The LView instance from which to start walking up the view tree
 * @returns The LView instance that contains the parent injector
 */
function getParentInjectorView(location, startView) {
  let viewOffset = getParentInjectorViewOffset(location);
  let parentView = startView;
  // For most cases, the parent injector can be found on the host node (e.g. for component
  // or container), but we must keep the loop here to support the rarer case of deeply nested
  // <ng-template> tags or inline views, where the parent injector might live many views
  // above the child injector.
  while (viewOffset > 0) {
    parentView = parentView[DECLARATION_VIEW];
    viewOffset--;
  }
  return parentView;
}
/**
 * Detects whether an injector is an instance of a `ChainedInjector`,
 * created based on the `OutletInjector`.
 */
function isRouterOutletInjector(currentInjector) {
  return currentInjector instanceof ChainedInjector && typeof currentInjector.injector.__ngOutletInjector === 'function';
}

/**
 * Defines if the call to `inject` should include `viewProviders` in its resolution.
 *
 * This is set to true when we try to instantiate a component. This value is reset in
 * `getNodeInjectable` to a value which matches the declaration location of the token about to be
 * instantiated. This is done so that if we are injecting a token which was declared outside of
 * `viewProviders` we don't accidentally pull `viewProviders` in.
 *
 * Example:
 *
 * ```
 * @Injectable()
 * class MyService {
 *   constructor(public value: String) {}
 * }
 *
 * @Component({
 *   providers: [
 *     MyService,
 *     {provide: String, value: 'providers' }
 *   ]
 *   viewProviders: [
 *     {provide: String, value: 'viewProviders'}
 *   ]
 * })
 * class MyComponent {
 *   constructor(myService: MyService, value: String) {
 *     // We expect that Component can see into `viewProviders`.
 *     expect(value).toEqual('viewProviders');
 *     // `MyService` was not declared in `viewProviders` hence it can't see it.
 *     expect(myService.value).toEqual('providers');
 *   }
 * }
 *
 * ```
 */
let includeViewProviders = true;
function setIncludeViewProviders(v) {
  const oldValue = includeViewProviders;
  includeViewProviders = v;
  return oldValue;
}
/**
 * The number of slots in each bloom filter (used by DI). The larger this number, the fewer
 * directives that will share slots, and thus, the fewer false positives when checking for
 * the existence of a directive.
 */
const BLOOM_SIZE = 256;
const BLOOM_MASK = BLOOM_SIZE - 1;
/**
 * The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits,
 * so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash
 * number.
 */
const BLOOM_BUCKET_BITS = 5;
/** Counter used to generate unique IDs for directives. */
let nextNgElementId = 0;
/** Value used when something wasn't found by an injector. */
const NOT_FOUND = {};
/**
 * Registers this directive as present in its node's injector by flipping the directive's
 * corresponding bit in the injector's bloom filter.
 *
 * @param injectorIndex The index of the node injector where this token should be registered
 * @param tView The TView for the injector's bloom filters
 * @param type The directive token to register
 */
function bloomAdd(injectorIndex, tView, type) {
  ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
  let id;
  if (typeof type === 'string') {
    id = type.charCodeAt(0) || 0;
  } else if (type.hasOwnProperty(NG_ELEMENT_ID)) {
    id = type[NG_ELEMENT_ID];
  }
  // Set a unique ID on the directive type, so if something tries to inject the directive,
  // we can easily retrieve the ID and hash it into the bloom bit that should be checked.
  if (id == null) {
    id = type[NG_ELEMENT_ID] = nextNgElementId++;
  }
  // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
  // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
  const bloomHash = id & BLOOM_MASK;
  // Create a mask that targets the specific bit associated with the directive.
  // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  // to bit positions 0 - 31 in a 32 bit integer.
  const mask = 1 << bloomHash;
  // Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`.
  // Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask
  // should be written to.
  tView.data[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask;
}
/**
 * Creates (or gets an existing) injector for a given element or container.
 *
 * @param tNode for which an injector should be retrieved / created.
 * @param lView View where the node is stored
 * @returns Node injector
 */
function getOrCreateNodeInjectorForNode(tNode, lView) {
  const existingInjectorIndex = getInjectorIndex(tNode, lView);
  if (existingInjectorIndex !== -1) {
    return existingInjectorIndex;
  }
  const tView = lView[TVIEW];
  if (tView.firstCreatePass) {
    tNode.injectorIndex = lView.length;
    insertBloom(tView.data, tNode); // foundation for node bloom
    insertBloom(lView, null); // foundation for cumulative bloom
    insertBloom(tView.blueprint, null);
  }
  const parentLoc = getParentInjectorLocation(tNode, lView);
  const injectorIndex = tNode.injectorIndex;
  // If a parent injector can't be found, its location is set to -1.
  // In that case, we don't need to set up a cumulative bloom
  if (hasParentInjector(parentLoc)) {
    const parentIndex = getParentInjectorIndex(parentLoc);
    const parentLView = getParentInjectorView(parentLoc, lView);
    const parentData = parentLView[TVIEW].data;
    // Creates a cumulative bloom filter that merges the parent's bloom filter
    // and its own cumulative bloom (which contains tokens for all ancestors)
    for (let i = 0; i < 8 /* NodeInjectorOffset.BLOOM_SIZE */; i++) {
      lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
    }
  }
  lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */] = parentLoc;
  return injectorIndex;
}
function insertBloom(arr, footer) {
  arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
}
function getInjectorIndex(tNode, lView) {
  if (tNode.injectorIndex === -1 ||
  // If the injector index is the same as its parent's injector index, then the index has been
  // copied down from the parent node. No injector has been created yet on this node.
  tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex ||
  // After the first template pass, the injector index might exist but the parent values
  // might not have been calculated yet for this instance
  lView[tNode.injectorIndex + 8 /* NodeInjectorOffset.PARENT */] === null) {
    return -1;
  } else {
    ngDevMode && assertIndexInRange(lView, tNode.injectorIndex);
    return tNode.injectorIndex;
  }
}
/**
 * Finds the index of the parent injector, with a view offset if applicable. Used to set the
 * parent injector initially.
 *
 * @returns Returns a number that is the combination of the number of LViews that we have to go up
 * to find the LView containing the parent inject AND the index of the injector within that LView.
 */
function getParentInjectorLocation(tNode, lView) {
  if (tNode.parent && tNode.parent.injectorIndex !== -1) {
    // If we have a parent `TNode` and there is an injector associated with it we are done, because
    // the parent injector is within the current `LView`.
    return tNode.parent.injectorIndex; // ViewOffset is 0
  }
  // When parent injector location is computed it may be outside of the current view. (ie it could
  // be pointing to a declared parent location). This variable stores number of declaration parents
  // we need to walk up in order to find the parent injector location.
  let declarationViewOffset = 0;
  let parentTNode = null;
  let lViewCursor = lView;
  // The parent injector is not in the current `LView`. We will have to walk the declared parent
  // `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent
  // `NodeInjector`.
  while (lViewCursor !== null) {
    parentTNode = getTNodeFromLView(lViewCursor);
    if (parentTNode === null) {
      // If we have no parent, than we are done.
      return NO_PARENT_INJECTOR;
    }
    ngDevMode && parentTNode && assertTNodeForLView(parentTNode, lViewCursor[DECLARATION_VIEW]);
    // Every iteration of the loop requires that we go to the declared parent.
    declarationViewOffset++;
    lViewCursor = lViewCursor[DECLARATION_VIEW];
    if (parentTNode.injectorIndex !== -1) {
      // We found a NodeInjector which points to something.
      return parentTNode.injectorIndex | declarationViewOffset << 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;
    }
  }
  return NO_PARENT_INJECTOR;
}
/**
 * Makes a type or an injection token public to the DI system by adding it to an
 * injector's bloom filter.
 *
 * @param di The node injector in which a directive will be added
 * @param token The type or the injection token to be made public
 */
function diPublicInInjector(injectorIndex, tView, token) {
  bloomAdd(injectorIndex, tView, token);
}
/**
 * Inject static attribute value into directive constructor.
 *
 * This method is used with `factory` functions which are generated as part of
 * `defineDirective` or `defineComponent`. The method retrieves the static value
 * of an attribute. (Dynamic attributes are not supported since they are not resolved
 *  at the time of injection and can change over time.)
 *
 * # Example
 * Given:
 * ```
 * @Component(...)
 * class MyComponent {
 *   constructor(@Attribute('title') title: string) { ... }
 * }
 * ```
 * When instantiated with
 * ```
 * <my-component title="Hello"></my-component>
 * ```
 *
 * Then factory method generated is:
 * ```
 * MyComponent.ɵcmp = defineComponent({
 *   factory: () => new MyComponent(injectAttribute('title'))
 *   ...
 * })
 * ```
 *
 * @publicApi
 */
function injectAttributeImpl(tNode, attrNameToInject) {
  ngDevMode && assertTNodeType(tNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  ngDevMode && assertDefined(tNode, 'expecting tNode');
  if (attrNameToInject === 'class') {
    return tNode.classes;
  }
  if (attrNameToInject === 'style') {
    return tNode.styles;
  }
  const attrs = tNode.attrs;
  if (attrs) {
    const attrsLength = attrs.length;
    let i = 0;
    while (i < attrsLength) {
      const value = attrs[i];
      // If we hit a `Bindings` or `Template` marker then we are done.
      if (isNameOnlyAttributeMarker(value)) break;
      // Skip namespaced attributes
      if (value === 0 /* AttributeMarker.NamespaceURI */) {
        // we skip the next two values
        // as namespaced attributes looks like
        // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
        // 'existValue', ...]
        i = i + 2;
      } else if (typeof value === 'number') {
        // Skip to the first value of the marked attribute.
        i++;
        while (i < attrsLength && typeof attrs[i] === 'string') {
          i++;
        }
      } else if (value === attrNameToInject) {
        return attrs[i + 1];
      } else {
        i = i + 2;
      }
    }
  }
  return null;
}
function notFoundValueOrThrow(notFoundValue, token, flags) {
  if (flags & InjectFlags.Optional || notFoundValue !== undefined) {
    return notFoundValue;
  } else {
    throwProviderNotFoundError(token, 'NodeInjector');
  }
}
/**
 * Returns the value associated to the given token from the ModuleInjector or throws exception
 *
 * @param lView The `LView` that contains the `tNode`
 * @param token The token to look for
 * @param flags Injection flags
 * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
 * @returns the value from the injector or throws an exception
 */
function lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue) {
  if (flags & InjectFlags.Optional && notFoundValue === undefined) {
    // This must be set or the NullInjector will throw for optional deps
    notFoundValue = null;
  }
  if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
    const moduleInjector = lView[INJECTOR];
    // switch to `injectInjectorOnly` implementation for module injector, since module injector
    // should not have access to Component/Directive DI scope (that may happen through
    // `directiveInject` implementation)
    const previousInjectImplementation = setInjectImplementation(undefined);
    try {
      if (moduleInjector) {
        return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
      } else {
        return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
      }
    } finally {
      setInjectImplementation(previousInjectImplementation);
    }
  }
  return notFoundValueOrThrow(notFoundValue, token, flags);
}
/**
 * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
 *
 * Look for the injector providing the token by walking up the node injector tree and then
 * the module injector tree.
 *
 * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
 * filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
 *
 * @param tNode The Node where the search for the injector should start
 * @param lView The `LView` that contains the `tNode`
 * @param token The token to look for
 * @param flags Injection flags
 * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
 * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
 */
function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
  if (tNode !== null) {
    // If the view or any of its ancestors have an embedded
    // view injector, we have to look it up there first.
    if (lView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
    // The token must be present on the current node injector when the `Self`
    // flag is set, so the lookup on embedded view injector(s) can be skipped.
    !(flags & InjectFlags.Self)) {
      const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, NOT_FOUND);
      if (embeddedInjectorValue !== NOT_FOUND) {
        return embeddedInjectorValue;
      }
    }
    // Otherwise try the node injector.
    const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND);
    if (value !== NOT_FOUND) {
      return value;
    }
  }
  // Finally, fall back to the module injector.
  return lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
}
/**
 * Returns the value associated to the given token from the node injector.
 *
 * @param tNode The Node where the search for the injector should start
 * @param lView The `LView` that contains the `tNode`
 * @param token The token to look for
 * @param flags Injection flags
 * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
 * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
 */
function lookupTokenUsingNodeInjector(tNode, lView, token, flags, notFoundValue) {
  const bloomHash = bloomHashBitOrFactory(token);
  // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
  // so just call the factory function to create it.
  if (typeof bloomHash === 'function') {
    if (!enterDI(lView, tNode, flags)) {
      // Failed to enter DI, try module injector instead. If a token is injected with the @Host
      // flag, the module injector is not searched for that token in Ivy.
      return flags & InjectFlags.Host ? notFoundValueOrThrow(notFoundValue, token, flags) : lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
    }
    try {
      let value;
      if (ngDevMode) {
        runInInjectorProfilerContext(new NodeInjector(getCurrentTNode(), getLView()), token, () => {
          value = bloomHash(flags);
          if (value != null) {
            emitInstanceCreatedByInjectorEvent(value);
          }
        });
      } else {
        value = bloomHash(flags);
      }
      if (value == null && !(flags & InjectFlags.Optional)) {
        throwProviderNotFoundError(token);
      } else {
        return value;
      }
    } finally {
      leaveDI();
    }
  } else if (typeof bloomHash === 'number') {
    // A reference to the previous injector TView that was found while climbing the element
    // injector tree. This is used to know if viewProviders can be accessed on the current
    // injector.
    let previousTView = null;
    let injectorIndex = getInjectorIndex(tNode, lView);
    let parentLocation = NO_PARENT_INJECTOR;
    let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
    // If we should skip this injector, or if there is no injector on this node, start by
    // searching the parent injector.
    if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
      parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) : lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
      if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) {
        injectorIndex = -1;
      } else {
        previousTView = lView[TVIEW];
        injectorIndex = getParentInjectorIndex(parentLocation);
        lView = getParentInjectorView(parentLocation, lView);
      }
    }
    // Traverse up the injector tree until we find a potential match or until we know there
    // *isn't* a match.
    while (injectorIndex !== -1) {
      ngDevMode && assertNodeInjector(lView, injectorIndex);
      // Check the current injector. If it matches, see if it contains token.
      const tView = lView[TVIEW];
      ngDevMode && assertTNodeForLView(tView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */], lView);
      if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
        // At this point, we have an injector which *may* contain the token, so we step through
        // the providers and directives associated with the injector's corresponding node to get
        // the instance.
        const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
        if (instance !== NOT_FOUND) {
          return instance;
        }
      }
      parentLocation = lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
      if (parentLocation !== NO_PARENT_INJECTOR && shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */] === hostTElementNode) && bloomHasToken(bloomHash, injectorIndex, lView)) {
        // The def wasn't found anywhere on this node, so it was a false positive.
        // Traverse up the tree and continue searching.
        previousTView = tView;
        injectorIndex = getParentInjectorIndex(parentLocation);
        lView = getParentInjectorView(parentLocation, lView);
      } else {
        // If we should not search parent OR If the ancestor bloom filter value does not have the
        // bit corresponding to the directive we can give up on traversing up to find the specific
        // injector.
        injectorIndex = -1;
      }
    }
  }
  return notFoundValue;
}
function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
  const currentTView = lView[TVIEW];
  const tNode = currentTView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  // First, we need to determine if view providers can be accessed by the starting element.
  // There are two possibilities
  const canAccessViewProviders = previousTView == null ?
  // 1) This is the first invocation `previousTView == null` which means that we are at the
  // `TNode` of where injector is starting to look. In such a case the only time we are allowed
  // to look into the ViewProviders is if:
  // - we are on a component
  // - AND the injector set `includeViewProviders` to true (implying that the token can see
  // ViewProviders because it is the Component or a Service which itself was declared in
  // ViewProviders)
  isComponentHost(tNode) && includeViewProviders :
  // 2) `previousTView != null` which means that we are now walking across the parent nodes.
  // In such a case we are only allowed to look into the ViewProviders if:
  // - We just crossed from child View to Parent View `previousTView != currentTView`
  // - AND the parent TNode is an Element.
  // This means that we just came from the Component's View and therefore are allowed to see
  // into the ViewProviders.
  previousTView != currentTView && (tNode.type & 3 /* TNodeType.AnyRNode */) !== 0;
  // This special case happens when there is a @host on the inject and when we are searching
  // on the host element node.
  const isHostSpecialCase = flags & InjectFlags.Host && hostTElementNode === tNode;
  const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
  if (injectableIdx !== null) {
    return getNodeInjectable(lView, currentTView, injectableIdx, tNode);
  } else {
    return NOT_FOUND;
  }
}
/**
 * Searches for the given token among the node's directives and providers.
 *
 * @param tNode TNode on which directives are present.
 * @param tView The tView we are currently processing
 * @param token Provider token or type of a directive to look for.
 * @param canAccessViewProviders Whether view providers should be considered.
 * @param isHostSpecialCase Whether the host special case applies.
 * @returns Index of a found directive or provider, or null when none found.
 */
function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
  const nodeProviderIndexes = tNode.providerIndexes;
  const tInjectables = tView.data;
  const injectablesStart = nodeProviderIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  const directivesStart = tNode.directiveStart;
  const directiveEnd = tNode.directiveEnd;
  const cptViewProvidersCount = nodeProviderIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
  const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;
  // When the host special case applies, only the viewProviders and the component are visible
  const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
  for (let i = startingIndex; i < endIndex; i++) {
    const providerTokenOrDef = tInjectables[i];
    if (i < directivesStart && token === providerTokenOrDef || i >= directivesStart && providerTokenOrDef.type === token) {
      return i;
    }
  }
  if (isHostSpecialCase) {
    const dirDef = tInjectables[directivesStart];
    if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
      return directivesStart;
    }
  }
  return null;
}
/**
 * Retrieve or instantiate the injectable from the `LView` at particular `index`.
 *
 * This function checks to see if the value has already been instantiated and if so returns the
 * cached `injectable`. Otherwise if it detects that the value is still a factory it
 * instantiates the `injectable` and caches the value.
 */
function getNodeInjectable(lView, tView, index, tNode) {
  let value = lView[index];
  const tData = tView.data;
  if (isFactory(value)) {
    const factory = value;
    if (factory.resolving) {
      throwCyclicDependencyError(stringifyForError(tData[index]));
    }
    const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
    factory.resolving = true;
    let prevInjectContext;
    if (ngDevMode) {
      // tData indexes mirror the concrete instances in its corresponding LView.
      // lView[index] here is either the injectable instace itself or a factory,
      // therefore tData[index] is the constructor of that injectable or a
      // definition object that contains the constructor in a `.type` field.
      const token = tData[index].type || tData[index];
      const injector = new NodeInjector(tNode, lView);
      prevInjectContext = setInjectorProfilerContext({
        injector,
        token
      });
    }
    const previousInjectImplementation = factory.injectImpl ? setInjectImplementation(factory.injectImpl) : null;
    const success = enterDI(lView, tNode, InjectFlags.Default);
    ngDevMode && assertEqual(success, true, "Because flags do not contain `SkipSelf' we expect this to always succeed.");
    try {
      value = lView[index] = factory.factory(undefined, tData, lView, tNode);
      ngDevMode && emitInstanceCreatedByInjectorEvent(value);
      // This code path is hit for both directives and providers.
      // For perf reasons, we want to avoid searching for hooks on providers.
      // It does no harm to try (the hooks just won't exist), but the extra
      // checks are unnecessary and this is a hot path. So we check to see
      // if the index of the dependency is in the directive range for this
      // tNode. If it's not, we know it's a provider and skip hook registration.
      if (tView.firstCreatePass && index >= tNode.directiveStart) {
        ngDevMode && assertDirectiveDef(tData[index]);
        registerPreOrderHooks(index, tData[index], tView);
      }
    } finally {
      ngDevMode && setInjectorProfilerContext(prevInjectContext);
      previousInjectImplementation !== null && setInjectImplementation(previousInjectImplementation);
      setIncludeViewProviders(previousIncludeViewProviders);
      factory.resolving = false;
      leaveDI();
    }
  }
  return value;
}
/**
 * Returns the bit in an injector's bloom filter that should be used to determine whether or not
 * the directive might be provided by the injector.
 *
 * When a directive is public, it is added to the bloom filter and given a unique ID that can be
 * retrieved on the Type. When the directive isn't public or the token is not a directive `null`
 * is returned as the node injector can not possibly provide that token.
 *
 * @param token the injection token
 * @returns the matching bit to check in the bloom filter or `null` if the token is not known.
 *   When the returned value is negative then it represents special values such as `Injector`.
 */
function bloomHashBitOrFactory(token) {
  ngDevMode && assertDefined(token, 'token must be defined');
  if (typeof token === 'string') {
    return token.charCodeAt(0) || 0;
  }
  const tokenId =
  // First check with `hasOwnProperty` so we don't get an inherited ID.
  token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;
  // Negative token IDs are used for special objects such as `Injector`
  if (typeof tokenId === 'number') {
    if (tokenId >= 0) {
      return tokenId & BLOOM_MASK;
    } else {
      ngDevMode && assertEqual(tokenId, -1 /* InjectorMarkers.Injector */, 'Expecting to get Special Injector Id');
      return createNodeInjector;
    }
  } else {
    return tokenId;
  }
}
function bloomHasToken(bloomHash, injectorIndex, injectorView) {
  // Create a mask that targets the specific bit associated with the directive we're looking for.
  // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  // to bit positions 0 - 31 in a 32 bit integer.
  const mask = 1 << bloomHash;
  // Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of
  // `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset
  // that should be used.
  const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)];
  // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
  // this injector is a potential match.
  return !!(value & mask);
}
/** Returns true if flags prevent parent injector from being searched for tokens */
function shouldSearchParent(flags, isFirstHostTNode) {
  return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
}
function getNodeInjectorLView(nodeInjector) {
  return nodeInjector._lView;
}
function getNodeInjectorTNode(nodeInjector) {
  return nodeInjector._tNode;
}
class NodeInjector {
  _tNode;
  _lView;
  constructor(_tNode, _lView) {
    this._tNode = _tNode;
    this._lView = _lView;
  }
  get(token, notFoundValue, flags) {
    return getOrCreateInjectable(this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue);
  }
}
/** Creates a `NodeInjector` for the current node. */
function createNodeInjector() {
  return new NodeInjector(getCurrentTNode(), getLView());
}
/**
 * @codeGenApi
 */
function ɵɵgetInheritedFactory(type) {
  return noSideEffects(() => {
    const ownConstructor = type.prototype.constructor;
    const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor);
    const objectPrototype = Object.prototype;
    let parent = Object.getPrototypeOf(type.prototype).constructor;
    // Go up the prototype until we hit `Object`.
    while (parent && parent !== objectPrototype) {
      const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent);
      // If we hit something that has a factory and the factory isn't the same as the type,
      // we've found the inherited factory. Note the check that the factory isn't the type's
      // own factory is redundant in most cases, but if the user has custom decorators on the
      // class, this lookup will start one level down in the prototype chain, causing us to
      // find the own factory first and potentially triggering an infinite loop downstream.
      if (factory && factory !== ownFactory) {
        return factory;
      }
      parent = Object.getPrototypeOf(parent);
    }
    // There is no factory defined. Either this was improper usage of inheritance
    // (no Angular decorator on the superclass) or there is no constructor at all
    // in the inheritance chain. Since the two cases cannot be distinguished, the
    // latter has to be assumed.
    return t => new t();
  });
}
function getFactoryOf(type) {
  if (isForwardRef(type)) {
    return () => {
      const factory = getFactoryOf(resolveForwardRef(type));
      return factory && factory();
    };
  }
  return getFactoryDef(type);
}
/**
 * Returns a value from the closest embedded or node injector.
 *
 * @param tNode The Node where the search for the injector should start
 * @param lView The `LView` that contains the `tNode`
 * @param token The token to look for
 * @param flags Injection flags
 * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
 * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
 */
function lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, notFoundValue) {
  let currentTNode = tNode;
  let currentLView = lView;
  // When an LView with an embedded view injector is inserted, it'll likely be interlaced with
  // nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector).
  // Since the bloom filters for the node injectors have already been constructed and we don't
  // have a way of extracting the records from an injector, the only way to maintain the correct
  // hierarchy when resolving the value is to walk it node-by-node while attempting to resolve
  // the token at each level.
  while (currentTNode !== null && currentLView !== null && currentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ && !(currentLView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {
    ngDevMode && assertTNodeForLView(currentTNode, currentLView);
    // Note that this lookup on the node injector is using the `Self` flag, because
    // we don't want the node injector to look at any parent injectors since we
    // may hit the embedded view injector first.
    const nodeInjectorValue = lookupTokenUsingNodeInjector(currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND);
    if (nodeInjectorValue !== NOT_FOUND) {
      return nodeInjectorValue;
    }
    // Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191
    let parentTNode = currentTNode.parent;
    // `TNode.parent` includes the parent within the current view only. If it doesn't exist,
    // it means that we've hit the view boundary and we need to go up to the next view.
    if (!parentTNode) {
      // Before we go to the next LView, check if the token exists on the current embedded injector.
      const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR];
      if (embeddedViewInjector) {
        const embeddedViewInjectorValue = embeddedViewInjector.get(token, NOT_FOUND, flags);
        if (embeddedViewInjectorValue !== NOT_FOUND) {
          return embeddedViewInjectorValue;
        }
      }
      // Otherwise keep going up the tree.
      parentTNode = getTNodeFromLView(currentLView);
      currentLView = currentLView[DECLARATION_VIEW];
    }
    currentTNode = parentTNode;
  }
  return notFoundValue;
}
/** Gets the TNode associated with an LView inside of the declaration view. */
function getTNodeFromLView(lView) {
  const tView = lView[TVIEW];
  const tViewType = tView.type;
  // The parent pointer differs based on `TView.type`.
  if (tViewType === 2 /* TViewType.Embedded */) {
    ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
    return tView.declTNode;
  } else if (tViewType === 1 /* TViewType.Component */) {
    // Components don't have `TView.declTNode` because each instance of component could be
    // inserted in different location, hence `TView.declTNode` is meaningless.
    return lView[T_HOST];
  }
  return null;
}

/**
 * Facade for the attribute injection from DI.
 *
 * @codeGenApi
 */
function ɵɵinjectAttribute(attrNameToInject) {
  return injectAttributeImpl(getCurrentTNode(), attrNameToInject);
}

/**
 * Attribute decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Attribute = /*#__PURE__*/makeParamDecorator('Attribute', attributeName => ({
  attributeName,
  __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName)
}));
let _reflect = null;
function getReflect() {
  return _reflect = _reflect || new ReflectionCapabilities();
}
function reflectDependencies(type) {
  return convertDependencies(getReflect().parameters(type));
}
function convertDependencies(deps) {
  return deps.map(dep => reflectDependency(dep));
}
function reflectDependency(dep) {
  const meta = {
    token: null,
    attribute: null,
    host: false,
    optional: false,
    self: false,
    skipSelf: false
  };
  if (Array.isArray(dep) && dep.length > 0) {
    for (let j = 0; j < dep.length; j++) {
      const param = dep[j];
      if (param === undefined) {
        // param may be undefined if type of dep is not set by ngtsc
        continue;
      }
      const proto = Object.getPrototypeOf(param);
      if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
        meta.optional = true;
      } else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
        meta.skipSelf = true;
      } else if (param instanceof Self || proto.ngMetadataName === 'Self') {
        meta.self = true;
      } else if (param instanceof Host || proto.ngMetadataName === 'Host') {
        meta.host = true;
      } else if (param instanceof Inject) {
        meta.token = param.token;
      } else if (param instanceof Attribute) {
        if (param.attributeName === undefined) {
          throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Attribute name must be defined.`);
        }
        meta.attribute = param.attributeName;
      } else {
        meta.token = param;
      }
    }
  } else if (dep === undefined || Array.isArray(dep) && dep.length === 0) {
    meta.token = null;
  } else {
    meta.token = dep;
  }
  return meta;
}

/**
 * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
 * injectable def (`ɵprov`) onto the injectable type.
 */
function compileInjectable(type, meta) {
  let ngInjectableDef = null;
  let ngFactoryDef = null;
  // if NG_PROV_DEF is already defined on this class then don't overwrite it
  if (!type.hasOwnProperty(NG_PROV_DEF)) {
    Object.defineProperty(type, NG_PROV_DEF, {
      get: () => {
        if (ngInjectableDef === null) {
          const compiler = getCompilerFacade({
            usage: 0 /* JitCompilerUsage.Decorator */,
            kind: 'injectable',
            type
          });
          ngInjectableDef = compiler.compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta));
        }
        return ngInjectableDef;
      }
    });
  }
  // if NG_FACTORY_DEF is already defined on this class then don't overwrite it
  if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
    Object.defineProperty(type, NG_FACTORY_DEF, {
      get: () => {
        if (ngFactoryDef === null) {
          const compiler = getCompilerFacade({
            usage: 0 /* JitCompilerUsage.Decorator */,
            kind: 'injectable',
            type
          });
          ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
            name: type.name,
            type,
            typeArgumentCount: 0,
            // In JIT mode types are not available nor used.
            deps: reflectDependencies(type),
            target: compiler.FactoryTarget.Injectable
          });
        }
        return ngFactoryDef;
      },
      // Leave this configurable so that the factories from directives or pipes can take precedence.
      configurable: true
    });
  }
}
const USE_VALUE = /*#__PURE__*/getClosureSafeProperty({
  provide: String,
  useValue: getClosureSafeProperty
});
function isUseClassProvider(meta) {
  return meta.useClass !== undefined;
}
function isUseValueProvider(meta) {
  return USE_VALUE in meta;
}
function isUseFactoryProvider(meta) {
  return meta.useFactory !== undefined;
}
function isUseExistingProvider(meta) {
  return meta.useExisting !== undefined;
}
function getInjectableMetadata(type, srcMeta) {
  // Allow the compilation of a class with a `@Injectable()` decorator without parameters
  const meta = srcMeta || {
    providedIn: null
  };
  const compilerMeta = {
    name: type.name,
    type: type,
    typeArgumentCount: 0,
    providedIn: meta.providedIn
  };
  if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
    compilerMeta.deps = convertDependencies(meta.deps);
  }
  // Check to see if the user explicitly provided a `useXxxx` property.
  if (isUseClassProvider(meta)) {
    compilerMeta.useClass = meta.useClass;
  } else if (isUseValueProvider(meta)) {
    compilerMeta.useValue = meta.useValue;
  } else if (isUseFactoryProvider(meta)) {
    compilerMeta.useFactory = meta.useFactory;
  } else if (isUseExistingProvider(meta)) {
    compilerMeta.useExisting = meta.useExisting;
  }
  return compilerMeta;
}

/**
 * Injectable decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Injectable = /*#__PURE__*/makeDecorator('Injectable', undefined, undefined, undefined, (type, meta) => compileInjectable(type, meta));

/**
 * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
 */
function createInjector(defType, parent = null, additionalProviders = null, name) {
  const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
  injector.resolveInjectorInitializers();
  return injector;
}
/**
 * Creates a new injector without eagerly resolving its injector types. Can be used in places
 * where resolving the injector types immediately can lead to an infinite loop. The injector types
 * should be resolved at a later point by calling `_resolveInjectorDefTypes`.
 */
function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {
  const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)];
  name = name || (typeof defType === 'object' ? undefined : stringify(defType));
  return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);
}

/**
 * Concrete injectors implement this interface. Injectors are configured
 * with [providers](guide/di/dependency-injection-providers) that associate
 * dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).
 *
 * @see [DI Providers](guide/di/dependency-injection-providers).
 * @see {@link StaticProvider}
 *
 * @usageNotes
 *
 *  The following example creates a service injector instance.
 *
 * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
 *
 * ### Usage example
 *
 * {@example core/di/ts/injector_spec.ts region='Injector'}
 *
 * `Injector` returns itself when given `Injector` as a token:
 *
 * {@example core/di/ts/injector_spec.ts region='injectInjector'}
 *
 * @publicApi
 */
class Injector {
  static THROW_IF_NOT_FOUND = /*#__PURE__*/(() => THROW_IF_NOT_FOUND)();
  static NULL = /*#__PURE__*/(() => new NullInjector())();
  static create(options, parent) {
    if (Array.isArray(options)) {
      return createInjector({
        name: ''
      }, parent, options, '');
    } else {
      const name = options.name ?? '';
      return createInjector({
        name
      }, options.parent, options.providers, name);
    }
  }
  /** @nocollapse */
  static ɵprov = /*#__PURE__*/(() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
    token: Injector,
    providedIn: 'any',
    factory: () => ɵɵinject(INJECTOR$1)
  }))();
  /**
   * @internal
   * @nocollapse
   */
  static __NG_ELEMENT_ID__ = /*#__PURE__*/(() => -1 /* InjectorMarkers.Injector */)();
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Creates a token that can be used to inject static attributes of the host node.
 *
 * @usageNotes
 * ### Injecting an attribute that is known to exist
 * ```typescript
 * @Directive()
 * class MyDir {
 *   attr: string = inject(new HostAttributeToken('some-attr'));
 * }
 * ```
 *
 * ### Optionally injecting an attribute
 * ```typescript
 * @Directive()
 * class MyDir {
 *   attr: string | null = inject(new HostAttributeToken('some-attr'), {optional: true});
 * }
 * ```
 * @publicApi
 */
class HostAttributeToken {
  attributeName;
  constructor(attributeName) {
    this.attributeName = attributeName;
  }
  /** @internal */
  __NG_ELEMENT_ID__ = () => ɵɵinjectAttribute(this.attributeName);
  toString() {
    return `HostAttributeToken ${this.attributeName}`;
  }
}

/**
 * A token that can be used to inject the tag name of the host node.
 *
 * @usageNotes
 * ### Injecting a tag name that is known to exist
 * ```typescript
 * @Directive()
 * class MyDir {
 *   tagName: string = inject(HOST_TAG_NAME);
 * }
 * ```
 *
 * ### Optionally injecting a tag name
 * ```typescript
 * @Directive()
 * class MyDir {
 *   tagName: string | null = inject(HOST_TAG_NAME, {optional: true});
 * }
 * ```
 * @publicApi
 */
const HOST_TAG_NAME = /*#__PURE__*/new InjectionToken(ngDevMode ? 'HOST_TAG_NAME' : '');
// HOST_TAG_NAME should be resolved at the current node, similar to e.g. ElementRef,
// so we manually specify __NG_ELEMENT_ID__ here, instead of using a factory.
// tslint:disable-next-line:no-toplevel-property-access
HOST_TAG_NAME.__NG_ELEMENT_ID__ = flags => {
  const tNode = getCurrentTNode();
  if (tNode === null) {
    throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'HOST_TAG_NAME can only be injected in directives and components ' + 'during construction time (in a class constructor or as a class field initializer)');
  }
  if (tNode.type & 2 /* TNodeType.Element */) {
    return tNode.value;
  }
  if (flags & InjectFlags.Optional) {
    return null;
  }
  throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `HOST_TAG_NAME was used on ${getDevModeNodeName(tNode)} which doesn't have an underlying element in the DOM. ` + `This is invalid, and so the dependency should be marked as optional.`);
};
function getDevModeNodeName(tNode) {
  if (tNode.type & 8 /* TNodeType.ElementContainer */) {
    return 'an <ng-container>';
  } else if (tNode.type & 4 /* TNodeType.Container */) {
    return 'an <ng-template>';
  } else if (tNode.type & 128 /* TNodeType.LetDeclaration */) {
    return 'an @let declaration';
  } else {
    return 'a node';
  }
}

/**
 * @module
 * @description
 * The `di` module provides dependency injection container services.
 */

/**
 * This file should not be necessary because node resolution should just default to `./di/index`!
 *
 * However it does not seem to work and it breaks:
 *  - //packages/animations/browser/test:test_web_chromium-local
 *  - //packages/compiler-cli/test:extract_i18n
 *  - //packages/compiler-cli/test:ngc
 *  - //packages/compiler-cli/test:perform_watch
 *  - //packages/compiler-cli/test/diagnostics:check_types
 *  - //packages/compiler-cli/test/transformers:test
 *  - //packages/compiler/test:test
 *  - //tools/public_api_guard:core_api
 *
 * Remove this file once the above is solved or wait until `ngc` is deleted and then it should be
 * safe to delete this file.
 */

const SCHEDULE_IN_ROOT_ZONE_DEFAULT = false;

/**
 * `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.
 * The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`
 * is injected in a component or directive, the callbacks run when that component or
 * directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
 *
 * @publicApi
 */
let DestroyRef = /*#__PURE__*/(() => {
  class DestroyRef {
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectDestroyRef)();
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ENV_ID__ = injector => injector;
  }
  return DestroyRef;
})();
class NodeInjectorDestroyRef extends DestroyRef {
  _lView;
  constructor(_lView) {
    super();
    this._lView = _lView;
  }
  onDestroy(callback) {
    storeLViewOnDestroy(this._lView, callback);
    return () => removeLViewOnDestroy(this._lView, callback);
  }
}
function injectDestroyRef() {
  return new NodeInjectorDestroyRef(getLView());
}

/**
 * Injectable that is notified when an `LView` is made aware of changes to application state.
 */
class ChangeDetectionScheduler {}
/** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */
const ZONELESS_ENABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '', {
  providedIn: 'root',
  factory: () => false
});
/** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */
const PROVIDED_ZONELESS = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '', {
  providedIn: 'root',
  factory: () => false
});
const ZONELESS_SCHEDULER_DISABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '');
// TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular.
const SCHEDULE_IN_ROOT_ZONE = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '');

/**
 * Internal implementation of the pending tasks service.
 */
let PendingTasksInternal = /*#__PURE__*/(() => {
  class PendingTasksInternal {
    taskId = 0;
    pendingTasks = (() => new Set())();
    get _hasPendingTasks() {
      return this.hasPendingTasks.value;
    }
    hasPendingTasks = (() => new rxjs__WEBPACK_IMPORTED_MODULE_2__.BehaviorSubject(false))();
    add() {
      if (!this._hasPendingTasks) {
        this.hasPendingTasks.next(true);
      }
      const taskId = this.taskId++;
      this.pendingTasks.add(taskId);
      return taskId;
    }
    has(taskId) {
      return this.pendingTasks.has(taskId);
    }
    remove(taskId) {
      this.pendingTasks.delete(taskId);
      if (this.pendingTasks.size === 0 && this._hasPendingTasks) {
        this.hasPendingTasks.next(false);
      }
    }
    ngOnDestroy() {
      this.pendingTasks.clear();
      if (this._hasPendingTasks) {
        this.hasPendingTasks.next(false);
      }
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: PendingTasksInternal,
      providedIn: 'root',
      factory: () => new PendingTasksInternal()
    }))();
  }
  return PendingTasksInternal;
})();
/**
 * Service that keeps track of pending tasks contributing to the stableness of Angular
 * application. While several existing Angular services (ex.: `HttpClient`) will internally manage
 * tasks influencing stability, this API gives control over stability to library and application
 * developers for specific cases not covered by Angular internals.
 *
 * The concept of stability comes into play in several important scenarios:
 * - SSR process needs to wait for the application stability before serializing and sending rendered
 * HTML;
 * - tests might want to delay assertions until the application becomes stable;
 *
 * @usageNotes
 * ```typescript
 * const pendingTasks = inject(PendingTasks);
 * const taskCleanup = pendingTasks.add();
 * // do work that should block application's stability and then:
 * taskCleanup();
 * ```
 *
 * @publicApi
 * @developerPreview
 */
let PendingTasks = /*#__PURE__*/(() => {
  class PendingTasks {
    internalPendingTasks = (() => inject(PendingTasksInternal))();
    scheduler = (() => inject(ChangeDetectionScheduler))();
    /**
     * Adds a new task that should block application's stability.
     * @returns A cleanup function that removes a task when called.
     */
    add() {
      const taskId = this.internalPendingTasks.add();
      return () => {
        if (!this.internalPendingTasks.has(taskId)) {
          // This pending task has already been cleared.
          return;
        }
        // Notifying the scheduler will hold application stability open until the next tick.
        this.scheduler.notify(12 /* NotificationSource.PendingTaskRemoved */);
        this.internalPendingTasks.remove(taskId);
      };
    }
    /**
     * Runs an asynchronous function and blocks the application's stability until the function completes.
     *
     * ```
     * pendingTasks.run(async () => {
     *   const userData = await fetch('/api/user');
     *   this.userData.set(userData);
     * });
     * ```
     *
     * Application stability is at least delayed until the next tick after the `run` method resolves
     * so it is safe to make additional updates to application state that would require UI synchronization:
     *
     * ```
     * const userData = await pendingTasks.run(() => fetch('/api/user'));
     * this.userData.set(userData);
     * ```
     *
     * @param fn The asynchronous function to execute
     */
    run(fn) {
      var _this = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const removeTask = _this.add();
        try {
          return yield fn();
        } finally {
          removeTask();
        }
      })();
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: PendingTasks,
      providedIn: 'root',
      factory: () => new PendingTasks()
    }))();
  }
  return PendingTasks;
})();
class EventEmitter_ extends rxjs__WEBPACK_IMPORTED_MODULE_3__.Subject {
  __isAsync; // tslint:disable-line
  destroyRef = /*#__PURE__*/(() => undefined)();
  pendingTasks = /*#__PURE__*/(() => undefined)();
  constructor(isAsync = false) {
    super();
    this.__isAsync = isAsync;
    // Attempt to retrieve a `DestroyRef` and `PendingTasks` optionally.
    // For backwards compatibility reasons, this cannot be required.
    if (isInInjectionContext()) {
      // `DestroyRef` is optional because it is not available in all contexts.
      // But it is useful to properly complete the `EventEmitter` if used with `outputToObservable`
      // when the component/directive is destroyed. (See `outputToObservable` for more details.)
      this.destroyRef = inject(DestroyRef, {
        optional: true
      }) ?? undefined;
      this.pendingTasks = inject(PendingTasksInternal, {
        optional: true
      }) ?? undefined;
    }
  }
  emit(value) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      super.next(value);
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
  subscribe(observerOrNext, error, complete) {
    let nextFn = observerOrNext;
    let errorFn = error || (() => null);
    let completeFn = complete;
    if (observerOrNext && typeof observerOrNext === 'object') {
      const observer = observerOrNext;
      nextFn = observer.next?.bind(observer);
      errorFn = observer.error?.bind(observer);
      completeFn = observer.complete?.bind(observer);
    }
    if (this.__isAsync) {
      errorFn = this.wrapInTimeout(errorFn);
      if (nextFn) {
        nextFn = this.wrapInTimeout(nextFn);
      }
      if (completeFn) {
        completeFn = this.wrapInTimeout(completeFn);
      }
    }
    const sink = super.subscribe({
      next: nextFn,
      error: errorFn,
      complete: completeFn
    });
    if (observerOrNext instanceof rxjs__WEBPACK_IMPORTED_MODULE_4__.Subscription) {
      observerOrNext.add(sink);
    }
    return sink;
  }
  wrapInTimeout(fn) {
    return value => {
      const taskId = this.pendingTasks?.add();
      setTimeout(() => {
        fn(value);
        if (taskId !== undefined) {
          this.pendingTasks?.remove(taskId);
        }
      });
    };
  }
}
/**
 * @publicApi
 */
const EventEmitter = EventEmitter_;
function noop(...args) {
  // Do nothing.
}

/**
 * Gets a scheduling function that runs the callback after the first of setTimeout and
 * requestAnimationFrame resolves.
 *
 * - `requestAnimationFrame` ensures that change detection runs ahead of a browser repaint.
 * This ensures that the create and update passes of a change detection always happen
 * in the same frame.
 * - When the browser is resource-starved, `rAF` can execute _before_ a `setTimeout` because
 * rendering is a very high priority process. This means that `setTimeout` cannot guarantee
 * same-frame create and update pass, when `setTimeout` is used to schedule the update phase.
 * - While `rAF` gives us the desirable same-frame updates, it has two limitations that
 * prevent it from being used alone. First, it does not run in background tabs, which would
 * prevent Angular from initializing an application when opened in a new tab (for example).
 * Second, repeated calls to requestAnimationFrame will execute at the refresh rate of the
 * hardware (~16ms for a 60Hz display). This would cause significant slowdown of tests that
 * are written with several updates and asserts in the form of "update; await stable; assert;".
 * - Both `setTimeout` and `rAF` are able to "coalesce" several events from a single user
 * interaction into a single change detection. Importantly, this reduces view tree traversals when
 * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would
 * then be interleaves between each event.
 *
 * By running change detection after the first of `setTimeout` and `rAF` to execute, we get the
 * best of both worlds.
 *
 * @returns a function to cancel the scheduled callback
 */
function scheduleCallbackWithRafRace(callback) {
  let timeoutId;
  let animationFrameId;
  function cleanup() {
    callback = noop;
    try {
      if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') {
        cancelAnimationFrame(animationFrameId);
      }
      if (timeoutId !== undefined) {
        clearTimeout(timeoutId);
      }
    } catch {
      // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched
      // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op.
    }
  }
  timeoutId = setTimeout(() => {
    callback();
    cleanup();
  });
  if (typeof requestAnimationFrame === 'function') {
    animationFrameId = requestAnimationFrame(() => {
      callback();
      cleanup();
    });
  }
  return () => cleanup();
}
function scheduleCallbackWithMicrotask(callback) {
  queueMicrotask(() => callback());
  return () => {
    callback = noop;
  };
}
class AsyncStackTaggingZoneSpec {
  createTask;
  constructor(namePrefix, consoleAsyncStackTaggingImpl = console) {
    this.name = 'asyncStackTagging for ' + namePrefix;
    this.createTask = consoleAsyncStackTaggingImpl?.createTask ?? (() => null);
  }
  // ZoneSpec implementation below.
  name;
  onScheduleTask(delegate, _current, target, task) {
    task.consoleTask = this.createTask(`Zone - ${task.source || task.type}`);
    return delegate.scheduleTask(target, task);
  }
  onInvokeTask(delegate, _currentZone, targetZone, task, applyThis, applyArgs) {
    let ret;
    if (task.consoleTask) {
      ret = task.consoleTask.run(() => delegate.invokeTask(targetZone, task, applyThis, applyArgs));
    } else {
      ret = delegate.invokeTask(targetZone, task, applyThis, applyArgs);
    }
    return ret;
  }
}
const isAngularZoneProperty = 'isAngularZone';
const angularZoneInstanceIdProperty = isAngularZoneProperty + '_ID';
let ngZoneInstanceId = 0;
/**
 * An injectable service for executing work inside or outside of the Angular zone.
 *
 * The most common use of this service is to optimize performance when starting a work consisting of
 * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
 * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
 * can reenter the Angular zone via {@link #run}.
 *
 * <!-- TODO: add/fix links to:
 *   - docs explaining zones and the use of zones in Angular and change-detection
 *   - link to runOutsideAngular/run (throughout this file!)
 *   -->
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * import {Component, NgZone} from '@angular/core';
 * import {NgIf} from '@angular/common';
 *
 * @Component({
 *   selector: 'ng-zone-demo',
 *   template: `
 *     <h2>Demo: NgZone</h2>
 *
 *     <p>Progress: {{progress}}%</p>
 *     <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
 *
 *     <button (click)="processWithinAngularZone()">Process within Angular zone</button>
 *     <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
 *   `,
 * })
 * export class NgZoneDemo {
 *   progress: number = 0;
 *   label: string;
 *
 *   constructor(private _ngZone: NgZone) {}
 *
 *   // Loop inside the Angular zone
 *   // so the UI DOES refresh after each setTimeout cycle
 *   processWithinAngularZone() {
 *     this.label = 'inside';
 *     this.progress = 0;
 *     this._increaseProgress(() => console.log('Inside Done!'));
 *   }
 *
 *   // Loop outside of the Angular zone
 *   // so the UI DOES NOT refresh after each setTimeout cycle
 *   processOutsideOfAngularZone() {
 *     this.label = 'outside';
 *     this.progress = 0;
 *     this._ngZone.runOutsideAngular(() => {
 *       this._increaseProgress(() => {
 *         // reenter the Angular zone and display done
 *         this._ngZone.run(() => { console.log('Outside Done!'); });
 *       });
 *     });
 *   }
 *
 *   _increaseProgress(doneCallback: () => void) {
 *     this.progress += 1;
 *     console.log(`Current progress: ${this.progress}%`);
 *
 *     if (this.progress < 100) {
 *       window.setTimeout(() => this._increaseProgress(doneCallback), 10);
 *     } else {
 *       doneCallback();
 *     }
 *   }
 * }
 * ```
 *
 * @publicApi
 */
class NgZone {
  hasPendingMacrotasks = false;
  hasPendingMicrotasks = false;
  /**
   * Whether there are no outstanding microtasks or macrotasks.
   */
  isStable = true;
  /**
   * Notifies when code enters Angular Zone. This gets fired first on VM Turn.
   */
  onUnstable = /*#__PURE__*/(() => new EventEmitter(false))();
  /**
   * Notifies when there is no more microtasks enqueued in the current VM Turn.
   * This is a hint for Angular to do change detection, which may enqueue more microtasks.
   * For this reason this event can fire multiple times per VM Turn.
   */
  onMicrotaskEmpty = /*#__PURE__*/(() => new EventEmitter(false))();
  /**
   * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
   * implies we are about to relinquish VM turn.
   * This event gets called just once.
   */
  onStable = /*#__PURE__*/(() => new EventEmitter(false))();
  /**
   * Notifies that an error has been delivered.
   */
  onError = /*#__PURE__*/(() => new EventEmitter(false))();
  constructor(options) {
    const {
      enableLongStackTrace = false,
      shouldCoalesceEventChangeDetection = false,
      shouldCoalesceRunChangeDetection = false,
      scheduleInRootZone = SCHEDULE_IN_ROOT_ZONE_DEFAULT
    } = options;
    if (typeof Zone == 'undefined') {
      throw new RuntimeError(908 /* RuntimeErrorCode.MISSING_ZONEJS */, ngDevMode && `In this configuration Angular requires Zone.js`);
    }
    Zone.assertZonePatched();
    const self = this;
    self._nesting = 0;
    self._outer = self._inner = Zone.current;
    // AsyncStackTaggingZoneSpec provides `linked stack traces` to show
    // where the async operation is scheduled. For more details, refer
    // to this article, https://developer.chrome.com/blog/devtools-better-angular-debugging/
    // And we only import this AsyncStackTaggingZoneSpec in development mode,
    // in the production mode, the AsyncStackTaggingZoneSpec will be tree shaken away.
    if (ngDevMode) {
      self._inner = self._inner.fork(new AsyncStackTaggingZoneSpec('Angular'));
    }
    if (Zone['TaskTrackingZoneSpec']) {
      self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']());
    }
    if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
      self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);
    }
    // if shouldCoalesceRunChangeDetection is true, all tasks including event tasks will be
    // coalesced, so shouldCoalesceEventChangeDetection option is not necessary and can be skipped.
    self.shouldCoalesceEventChangeDetection = !shouldCoalesceRunChangeDetection && shouldCoalesceEventChangeDetection;
    self.shouldCoalesceRunChangeDetection = shouldCoalesceRunChangeDetection;
    self.callbackScheduled = false;
    self.scheduleInRootZone = scheduleInRootZone;
    forkInnerZoneWithAngularBehavior(self);
  }
  /**
    This method checks whether the method call happens within an Angular Zone instance.
  */
  static isInAngularZone() {
    // Zone needs to be checked, because this method might be called even when NoopNgZone is used.
    return typeof Zone !== 'undefined' && Zone.current.get(isAngularZoneProperty) === true;
  }
  /**
    Assures that the method is called within the Angular Zone, otherwise throws an error.
  */
  static assertInAngularZone() {
    if (!NgZone.isInAngularZone()) {
      throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to be in Angular Zone, but it is not!');
    }
  }
  /**
    Assures that the method is called outside of the Angular Zone, otherwise throws an error.
  */
  static assertNotInAngularZone() {
    if (NgZone.isInAngularZone()) {
      throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to not be in Angular Zone, but it is!');
    }
  }
  /**
   * Executes the `fn` function synchronously within the Angular zone and returns value returned by
   * the function.
   *
   * Running functions via `run` allows you to reenter Angular zone from a task that was executed
   * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
   *
   * Any future tasks or microtasks scheduled from within this function will continue executing from
   * within the Angular zone.
   *
   * If a synchronous error happens it will be rethrown and not reported via `onError`.
   */
  run(fn, applyThis, applyArgs) {
    return this._inner.run(fn, applyThis, applyArgs);
  }
  /**
   * Executes the `fn` function synchronously within the Angular zone as a task and returns value
   * returned by the function.
   *
   * Running functions via `run` allows you to reenter Angular zone from a task that was executed
   * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
   *
   * Any future tasks or microtasks scheduled from within this function will continue executing from
   * within the Angular zone.
   *
   * If a synchronous error happens it will be rethrown and not reported via `onError`.
   */
  runTask(fn, applyThis, applyArgs, name) {
    const zone = this._inner;
    const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop, noop);
    try {
      return zone.runTask(task, applyThis, applyArgs);
    } finally {
      zone.cancelTask(task);
    }
  }
  /**
   * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
   * rethrown.
   */
  runGuarded(fn, applyThis, applyArgs) {
    return this._inner.runGuarded(fn, applyThis, applyArgs);
  }
  /**
   * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
   * the function.
   *
   * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
   * work that
   * doesn't trigger Angular change-detection or is subject to Angular's error handling.
   *
   * Any future tasks or microtasks scheduled from within this function will continue executing from
   * outside of the Angular zone.
   *
   * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
   */
  runOutsideAngular(fn) {
    return this._outer.run(fn);
  }
}
const EMPTY_PAYLOAD = {};
function checkStable(zone) {
  // TODO: @JiaLiPassion, should check zone.isCheckStableRunning to prevent
  // re-entry. The case is:
  //
  // @Component({...})
  // export class AppComponent {
  // constructor(private ngZone: NgZone) {
  //   this.ngZone.onStable.subscribe(() => {
  //     this.ngZone.run(() => console.log('stable'););
  //   });
  // }
  //
  // The onStable subscriber run another function inside ngZone
  // which causes `checkStable()` re-entry.
  // But this fix causes some issues in g3, so this fix will be
  // launched in another PR.
  if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
    try {
      zone._nesting++;
      zone.onMicrotaskEmpty.emit(null);
    } finally {
      zone._nesting--;
      if (!zone.hasPendingMicrotasks) {
        try {
          zone.runOutsideAngular(() => zone.onStable.emit(null));
        } finally {
          zone.isStable = true;
        }
      }
    }
  }
}
function delayChangeDetectionForEvents(zone) {
  /**
   * We also need to check _nesting here
   * Consider the following case with shouldCoalesceRunChangeDetection = true
   *
   * ngZone.run(() => {});
   * ngZone.run(() => {});
   *
   * We want the two `ngZone.run()` only trigger one change detection
   * when shouldCoalesceRunChangeDetection is true.
   * And because in this case, change detection run in async way(requestAnimationFrame),
   * so we also need to check the _nesting here to prevent multiple
   * change detections.
   */
  if (zone.isCheckStableRunning || zone.callbackScheduled) {
    return;
  }
  zone.callbackScheduled = true;
  function scheduleCheckStable() {
    scheduleCallbackWithRafRace(() => {
      zone.callbackScheduled = false;
      updateMicroTaskStatus(zone);
      zone.isCheckStableRunning = true;
      checkStable(zone);
      zone.isCheckStableRunning = false;
    });
  }
  if (zone.scheduleInRootZone) {
    Zone.root.run(() => {
      scheduleCheckStable();
    });
  } else {
    zone._outer.run(() => {
      scheduleCheckStable();
    });
  }
  updateMicroTaskStatus(zone);
}
function forkInnerZoneWithAngularBehavior(zone) {
  const delayChangeDetectionForEventsDelegate = () => {
    delayChangeDetectionForEvents(zone);
  };
  const instanceId = ngZoneInstanceId++;
  zone._inner = zone._inner.fork({
    name: 'angular',
    properties: {
      [isAngularZoneProperty]: true,
      [angularZoneInstanceIdProperty]: instanceId,
      [angularZoneInstanceIdProperty + instanceId]: true
    },
    onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
      // Prevent triggering change detection when the flag is detected.
      if (shouldBeIgnoredByZone(applyArgs)) {
        return delegate.invokeTask(target, task, applyThis, applyArgs);
      }
      try {
        onEnter(zone);
        return delegate.invokeTask(target, task, applyThis, applyArgs);
      } finally {
        if (zone.shouldCoalesceEventChangeDetection && task.type === 'eventTask' || zone.shouldCoalesceRunChangeDetection) {
          delayChangeDetectionForEventsDelegate();
        }
        onLeave(zone);
      }
    },
    onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
      try {
        onEnter(zone);
        return delegate.invoke(target, callback, applyThis, applyArgs, source);
      } finally {
        if (zone.shouldCoalesceRunChangeDetection &&
        // Do not delay change detection when the task is the scheduler's tick.
        // We need to synchronously trigger the stability logic so that the
        // zone-based scheduler can prevent a duplicate ApplicationRef.tick
        // by first checking if the scheduler tick is running. This does seem a bit roundabout,
        // but we _do_ still want to trigger all the correct events when we exit the zone.run
        // (`onMicrotaskEmpty` and `onStable` _should_ emit; developers can have code which
        // relies on these events happening after change detection runs).
        // Note: `zone.callbackScheduled` is already in delayChangeDetectionForEventsDelegate
        // but is added here as well to prevent reads of applyArgs when not necessary
        !zone.callbackScheduled && !isSchedulerTick(applyArgs)) {
          delayChangeDetectionForEventsDelegate();
        }
        onLeave(zone);
      }
    },
    onHasTask: (delegate, current, target, hasTaskState) => {
      delegate.hasTask(target, hasTaskState);
      if (current === target) {
        // We are only interested in hasTask events which originate from our zone
        // (A child hasTask event is not interesting to us)
        if (hasTaskState.change == 'microTask') {
          zone._hasPendingMicrotasks = hasTaskState.microTask;
          updateMicroTaskStatus(zone);
          checkStable(zone);
        } else if (hasTaskState.change == 'macroTask') {
          zone.hasPendingMacrotasks = hasTaskState.macroTask;
        }
      }
    },
    onHandleError: (delegate, current, target, error) => {
      delegate.handleError(target, error);
      zone.runOutsideAngular(() => zone.onError.emit(error));
      return false;
    }
  });
}
function updateMicroTaskStatus(zone) {
  if (zone._hasPendingMicrotasks || (zone.shouldCoalesceEventChangeDetection || zone.shouldCoalesceRunChangeDetection) && zone.callbackScheduled === true) {
    zone.hasPendingMicrotasks = true;
  } else {
    zone.hasPendingMicrotasks = false;
  }
}
function onEnter(zone) {
  zone._nesting++;
  if (zone.isStable) {
    zone.isStable = false;
    zone.onUnstable.emit(null);
  }
}
function onLeave(zone) {
  zone._nesting--;
  checkStable(zone);
}
/**
 * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
 * to framework to perform rendering.
 */
class NoopNgZone {
  hasPendingMicrotasks = false;
  hasPendingMacrotasks = false;
  isStable = true;
  onUnstable = /*#__PURE__*/(() => new EventEmitter())();
  onMicrotaskEmpty = /*#__PURE__*/(() => new EventEmitter())();
  onStable = /*#__PURE__*/(() => new EventEmitter())();
  onError = /*#__PURE__*/(() => new EventEmitter())();
  run(fn, applyThis, applyArgs) {
    return fn.apply(applyThis, applyArgs);
  }
  runGuarded(fn, applyThis, applyArgs) {
    return fn.apply(applyThis, applyArgs);
  }
  runOutsideAngular(fn) {
    return fn();
  }
  runTask(fn, applyThis, applyArgs, name) {
    return fn.apply(applyThis, applyArgs);
  }
}
function shouldBeIgnoredByZone(applyArgs) {
  return hasApplyArgsData(applyArgs, '__ignore_ng_zone__');
}
function isSchedulerTick(applyArgs) {
  return hasApplyArgsData(applyArgs, '__scheduler_tick__');
}
function hasApplyArgsData(applyArgs, key) {
  if (!Array.isArray(applyArgs)) {
    return false;
  }
  // We should only ever get 1 arg passed through to invokeTask.
  // Short circuit here incase that behavior changes.
  if (applyArgs.length !== 1) {
    return false;
  }
  return applyArgs[0]?.data?.[key] === true;
}
function getNgZone(ngZoneToUse = 'zone.js', options) {
  if (ngZoneToUse === 'noop') {
    return new NoopNgZone();
  }
  if (ngZoneToUse === 'zone.js') {
    return new NgZone(options);
  }
  return ngZoneToUse;
}

// Public API for Zone

/**
 * Provides a hook for centralized exception handling.
 *
 * The default implementation of `ErrorHandler` prints error messages to the `console`. To
 * intercept error handling, write a custom exception handler that replaces this default as
 * appropriate for your app.
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * class MyErrorHandler implements ErrorHandler {
 *   handleError(error) {
 *     // do something with the exception
 *   }
 * }
 *
 * @NgModule({
 *   providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
 * })
 * class MyModule {}
 * ```
 *
 * @publicApi
 */
class ErrorHandler {
  /**
   * @internal
   */
  _console = /*#__PURE__*/(() => console)();
  handleError(error) {
    this._console.error('ERROR', error);
  }
}
/**
 * `InjectionToken` used to configure how to call the `ErrorHandler`.
 *
 * `NgZone` is provided by default today so the default (and only) implementation for this
 * is calling `ErrorHandler.handleError` outside of the Angular zone.
 */
const INTERNAL_APPLICATION_ERROR_HANDLER = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '', {
  providedIn: 'root',
  factory: () => {
    const zone = inject(NgZone);
    const userErrorHandler = inject(ErrorHandler);
    return e => zone.runOutsideAngular(() => userErrorHandler.handleError(e));
  }
});

/**
 * An `OutputEmitterRef` is created by the `output()` function and can be
 * used to emit values to consumers of your directive or component.
 *
 * Consumers of your directive/component can bind to the output and
 * subscribe to changes via the bound event syntax. For example:
 *
 * ```html
 * <my-comp (valueChange)="processNewValue($event)" />
 * ```
 *
 * @publicAPI
 */
class OutputEmitterRef {
  destroyed = false;
  listeners = null;
  errorHandler = /*#__PURE__*/(() => inject(ErrorHandler, {
    optional: true
  }))();
  /** @internal */
  destroyRef = /*#__PURE__*/(() => inject(DestroyRef))();
  constructor() {
    // Clean-up all listeners and mark as destroyed upon destroy.
    this.destroyRef.onDestroy(() => {
      this.destroyed = true;
      this.listeners = null;
    });
  }
  subscribe(callback) {
    if (this.destroyed) {
      throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode && 'Unexpected subscription to destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');
    }
    (this.listeners ??= []).push(callback);
    return {
      unsubscribe: () => {
        const idx = this.listeners?.indexOf(callback);
        if (idx !== undefined && idx !== -1) {
          this.listeners?.splice(idx, 1);
        }
      }
    };
  }
  /** Emits a new value to the output. */
  emit(value) {
    if (this.destroyed) {
      throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode && 'Unexpected emit for destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');
    }
    if (this.listeners === null) {
      return;
    }
    const previousConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      for (const listenerFn of this.listeners) {
        try {
          listenerFn(value);
        } catch (err) {
          this.errorHandler?.handleError(err);
        }
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(previousConsumer);
    }
  }
}
/** Gets the owning `DestroyRef` for the given output. */
function getOutputDestroyRef(ref) {
  return ref.destroyRef;
}

/**
 * The `output` function allows declaration of Angular outputs in
 * directives and components.
 *
 * You can use outputs to emit values to parent directives and component.
 * Parents can subscribe to changes via:
 *
 * - template event bindings. For example, `(myOutput)="doSomething($event)"`
 * - programmatic subscription by using `OutputRef#subscribe`.
 *
 * @usageNotes
 *
 * To use `output()`, import the function from `@angular/core`.
 *
 * ```ts
 * import {output} from '@angular/core';
 * ```
 *
 * Inside your component, introduce a new class member and initialize
 * it with a call to `output`.
 *
 * ```ts
 * @Directive({
 *   ...
 * })
 * export class MyDir {
 *   nameChange = output<string>();    // OutputEmitterRef<string>
 *   onClick    = output();            // OutputEmitterRef<void>
 * }
 * ```
 *
 * You can emit values to consumers of your directive, by using
 * the `emit` method from `OutputEmitterRef`.
 *
 * ```ts
 * updateName(newName: string): void {
 *   this.nameChange.emit(newName);
 * }
 * ```
 * @initializerApiFunction {"showTypesInSignaturePreview": true}
 * @publicAPI
 */
function output(opts) {
  ngDevMode && assertInInjectionContext(output);
  return new OutputEmitterRef();
}
function inputFunction(initialValue, opts) {
  ngDevMode && assertInInjectionContext(input);
  return createInputSignal(initialValue, opts);
}
function inputRequiredFunction(opts) {
  ngDevMode && assertInInjectionContext(input);
  return createInputSignal(REQUIRED_UNSET_VALUE, opts);
}
/**
 * The `input` function allows declaration of Angular inputs in directives
 * and components.
 *
 * There are two variants of inputs that can be declared:
 *
 *   1. **Optional inputs** with an initial value.
 *   2. **Required inputs** that consumers need to set.
 *
 * By default, the `input` function will declare optional inputs that
 * always have an initial value. Required inputs can be declared
 * using the `input.required()` function.
 *
 * Inputs are signals. The values of an input are exposed as a `Signal`.
 * The signal always holds the latest value of the input that is bound
 * from the parent.
 *
 * @usageNotes
 * To use signal-based inputs, import `input` from `@angular/core`.
 *
 * ```
 * import {input} from '@angular/core`;
 * ```
 *
 * Inside your component, introduce a new class member and initialize
 * it with a call to `input` or `input.required`.
 *
 * ```ts
 * @Component({
 *   ...
 * })
 * export class UserProfileComponent {
 *   firstName = input<string>();             // Signal<string|undefined>
 *   lastName  = input.required<string>();    // Signal<string>
 *   age       = input(0)                     // Signal<number>
 * }
 * ```
 *
 * Inside your component template, you can display values of the inputs
 * by calling the signal.
 *
 * ```html
 * <span>{{firstName()}}</span>
 * ```
 *
 * @publicAPI
 * @initializerApiFunction
 */
const input = /*#__PURE__*/(() => {
  // Note: This may be considered a side-effect, but nothing will depend on
  // this assignment, unless this `input` constant export is accessed. It's a
  // self-contained side effect that is local to the user facing`input` export.
  inputFunction.required = inputRequiredFunction;
  return inputFunction;
})();

/**
 * Creates an ElementRef from the most recent node.
 *
 * @returns The ElementRef instance to use
 */
function injectElementRef() {
  return createElementRef(getCurrentTNode(), getLView());
}
/**
 * Creates an ElementRef given a node.
 *
 * @param tNode The node for which you'd like an ElementRef
 * @param lView The view to which the node belongs
 * @returns The ElementRef instance to use
 */
function createElementRef(tNode, lView) {
  return new ElementRef(getNativeByTNode(tNode, lView));
}
/**
 * A wrapper around a native element inside of a View.
 *
 * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
 * element.
 *
 * @security Permitting direct access to the DOM can make your application more vulnerable to
 * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
 * [Security Guide](https://g.co/ng/security).
 *
 * @publicApi
 */
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
// i.e. users have to ask for what they need. With that, we can build better analysis tools
// and could do better codegen in the future.
let ElementRef = /*#__PURE__*/(() => {
  class ElementRef {
    /**
     * <div class="callout is-critical">
     *   <header>Use with caution</header>
     *   <p>
     *    Use this API as the last resort when direct access to DOM is needed. Use templating and
     *    data-binding provided by Angular instead. Alternatively you can take a look at
     *    {@link Renderer2} which provides an API that can be safely used.
     *   </p>
     * </div>
     */
    nativeElement;
    constructor(nativeElement) {
      this.nativeElement = nativeElement;
    }
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectElementRef)();
  }
  return ElementRef;
})();
/**
 * Unwraps `ElementRef` and return the `nativeElement`.
 *
 * @param value value to unwrap
 * @returns `nativeElement` if `ElementRef` otherwise returns value as is.
 */
function unwrapElementRef(value) {
  return value instanceof ElementRef ? value.nativeElement : value;
}
function symbolIterator() {
  // @ts-expect-error accessing a private member
  return this._results[Symbol.iterator]();
}
/**
 * An unmodifiable list of items that Angular keeps up to date when the state
 * of the application changes.
 *
 * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
 * provide.
 *
 * Implements an iterable interface, therefore it can be used in both ES6
 * javascript `for (var i of items)` loops as well as in Angular templates with
 * `*ngFor="let i of myList"`.
 *
 * Changes can be observed by subscribing to the changes `Observable`.
 *
 * NOTE: In the future this class will implement an `Observable` interface.
 *
 * @usageNotes
 * ### Example
 * ```typescript
 * @Component({...})
 * class Container {
 *   @ViewChildren(Item) items:QueryList<Item>;
 * }
 * ```
 *
 * @publicApi
 */
class QueryList {
  _emitDistinctChangesOnly;
  dirty = true;
  _onDirty = /*#__PURE__*/(() => undefined)();
  _results = [];
  _changesDetected = false;
  _changes = /*#__PURE__*/(() => undefined)();
  length = 0;
  first = /*#__PURE__*/(() => undefined)();
  last = /*#__PURE__*/(() => undefined)();
  /**
   * Returns `Observable` of `QueryList` notifying the subscriber of changes.
   */
  get changes() {
    return this._changes ??= new rxjs__WEBPACK_IMPORTED_MODULE_3__.Subject();
  }
  /**
   * @param emitDistinctChangesOnly Whether `QueryList.changes` should fire only when actual change
   *     has occurred. Or if it should fire when query is recomputed. (recomputing could resolve in
   *     the same result)
   */
  constructor(_emitDistinctChangesOnly = false) {
    this._emitDistinctChangesOnly = _emitDistinctChangesOnly;
  }
  /**
   * Returns the QueryList entry at `index`.
   */
  get(index) {
    return this._results[index];
  }
  /**
   * See
   * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
   */
  map(fn) {
    return this._results.map(fn);
  }
  filter(fn) {
    return this._results.filter(fn);
  }
  /**
   * See
   * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
   */
  find(fn) {
    return this._results.find(fn);
  }
  /**
   * See
   * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
   */
  reduce(fn, init) {
    return this._results.reduce(fn, init);
  }
  /**
   * See
   * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
   */
  forEach(fn) {
    this._results.forEach(fn);
  }
  /**
   * See
   * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
   */
  some(fn) {
    return this._results.some(fn);
  }
  /**
   * Returns a copy of the internal results list as an Array.
   */
  toArray() {
    return this._results.slice();
  }
  toString() {
    return this._results.toString();
  }
  /**
   * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
   * on change detection, it will not notify of changes to the queries, unless a new change
   * occurs.
   *
   * @param resultsTree The query results to store
   * @param identityAccessor Optional function for extracting stable object identity from a value
   *    in the array. This function is executed for each element of the query result list while
   *    comparing current query list with the new one (provided as a first argument of the `reset`
   *    function) to detect if the lists are different. If the function is not provided, elements
   *    are compared as is (without any pre-processing).
   */
  reset(resultsTree, identityAccessor) {
    this.dirty = false;
    const newResultFlat = flatten(resultsTree);
    if (this._changesDetected = !arrayEquals(this._results, newResultFlat, identityAccessor)) {
      this._results = newResultFlat;
      this.length = newResultFlat.length;
      this.last = newResultFlat[this.length - 1];
      this.first = newResultFlat[0];
    }
  }
  /**
   * Triggers a change event by emitting on the `changes` {@link EventEmitter}.
   */
  notifyOnChanges() {
    if (this._changes !== undefined && (this._changesDetected || !this._emitDistinctChangesOnly)) this._changes.next(this);
  }
  /** @internal */
  onDirty(cb) {
    this._onDirty = cb;
  }
  /** internal */
  setDirty() {
    this.dirty = true;
    this._onDirty?.();
  }
  /** internal */
  destroy() {
    if (this._changes !== undefined) {
      this._changes.complete();
      this._changes.unsubscribe();
    }
  }
  [Symbol.iterator] = /*#__PURE__*/(() => symbolIterator)();
}

/**
 * The name of an attribute that can be added to the hydration boundary node
 * (component host node) to disable hydration for the content within that boundary.
 */
const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';
/** Lowercase name of the `ngSkipHydration` attribute used for case-insensitive comparisons. */
const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = 'ngskiphydration';
/**
 * Helper function to check if a given TNode has the 'ngSkipHydration' attribute.
 */
function hasSkipHydrationAttrOnTNode(tNode) {
  const attrs = tNode.mergedAttrs;
  if (attrs === null) return false;
  // only ever look at the attribute name and skip the values
  for (let i = 0; i < attrs.length; i += 2) {
    const value = attrs[i];
    // This is a marker, which means that the static attributes section is over,
    // so we can exit early.
    if (typeof value === 'number') return false;
    if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) {
      return true;
    }
  }
  return false;
}
/**
 * Helper function to check if a given RElement has the 'ngSkipHydration' attribute.
 */
function hasSkipHydrationAttrOnRElement(rNode) {
  return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME);
}
/**
 * Checks whether a TNode has a flag to indicate that it's a part of
 * a skip hydration block.
 */
function hasInSkipHydrationBlockFlag(tNode) {
  return (tNode.flags & 128 /* TNodeFlags.inSkipHydrationBlock */) === 128 /* TNodeFlags.inSkipHydrationBlock */;
}
/**
 * Helper function that determines if a given node is within a skip hydration block
 * by navigating up the TNode tree to see if any parent nodes have skip hydration
 * attribute.
 */
function isInSkipHydrationBlock(tNode) {
  if (hasInSkipHydrationBlockFlag(tNode)) {
    return true;
  }
  let currentTNode = tNode.parent;
  while (currentTNode) {
    if (hasInSkipHydrationBlockFlag(tNode) || hasSkipHydrationAttrOnTNode(currentTNode)) {
      return true;
    }
    currentTNode = currentTNode.parent;
  }
  return false;
}
/**
 * Check if an i18n block is in a skip hydration section by looking at a parent TNode
 * to determine if this TNode is in a skip hydration section or the TNode has
 * the `ngSkipHydration` attribute.
 */
function isI18nInSkipHydrationBlock(parentTNode) {
  return hasInSkipHydrationBlockFlag(parentTNode) || hasSkipHydrationAttrOnTNode(parentTNode) || isInSkipHydrationBlock(parentTNode);
}

/**
 * The strategy that the default change detector uses to detect changes.
 * When set, takes effect the next time change detection is triggered.
 *
 * @see [Change detection usage](/api/core/ChangeDetectorRef?tab=usage-notes)
 * @see [Skipping component subtrees](/best-practices/skipping-subtrees)
 *
 * @publicApi
 */
var ChangeDetectionStrategy = /*#__PURE__*/function (ChangeDetectionStrategy) {
  /**
   * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
   * until reactivated by setting the strategy to `Default` (`CheckAlways`).
   * Change detection can still be explicitly invoked.
   * This strategy applies to all child directives and cannot be overridden.
   */
  ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  /**
   * Use the default `CheckAlways` strategy, in which change detection is automatic until
   * explicitly deactivated.
   */
  ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  return ChangeDetectionStrategy;
}(ChangeDetectionStrategy || {});
// Keeps track of the currently-active LViews.
const TRACKED_LVIEWS = /*#__PURE__*/new Map();
// Used for generating unique IDs for LViews.
let uniqueIdCounter = 0;
/** Gets a unique ID that can be assigned to an LView. */
function getUniqueLViewId() {
  return uniqueIdCounter++;
}
/** Starts tracking an LView. */
function registerLView(lView) {
  ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered');
  TRACKED_LVIEWS.set(lView[ID], lView);
}
/** Gets an LView by its unique ID. */
function getLViewById(id) {
  ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number');
  return TRACKED_LVIEWS.get(id) || null;
}
/** Stops tracking an LView. */
function unregisterLView(lView) {
  ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID');
  TRACKED_LVIEWS.delete(lView[ID]);
}
/** Gets the currently-tracked views. */
function getTrackedLViews() {
  return TRACKED_LVIEWS;
}

/**
 * The internal view context which is specific to a given DOM element, directive or
 * component instance. Each value in here (besides the LView and element node details)
 * can be present, null or undefined. If undefined then it implies the value has not been
 * looked up yet, otherwise, if null, then a lookup was executed and nothing was found.
 *
 * Each value will get filled when the respective value is examined within the getContext
 * function. The component, element and each directive instance will share the same instance
 * of the context.
 */
class LContext {
  lViewId;
  nodeIndex;
  native;
  /**
   * The instance of the Component node.
   */
  component;
  /**
   * The list of active directives that exist on this element.
   */
  directives;
  /**
   * The map of local references (local reference name => element or directive instance) that
   * exist on this element.
   */
  localRefs;
  /** Component's parent view data. */
  get lView() {
    return getLViewById(this.lViewId);
  }
  constructor(
  /**
   * ID of the component's parent view data.
   */
  lViewId,
  /**
   * The index instance of the node.
   */
  nodeIndex,
  /**
   * The instance of the DOM node that is attached to the lNode.
   */
  native) {
    this.lViewId = lViewId;
    this.nodeIndex = nodeIndex;
    this.native = native;
  }
}

/**
 * Returns the matching `LContext` data for a given DOM node, directive or component instance.
 *
 * This function will examine the provided DOM element, component, or directive instance\'s
 * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
 * value will be that of the newly created `LContext`.
 *
 * If the monkey-patched value is the `LView` instance then the context value for that
 * target will be created and the monkey-patch reference will be updated. Therefore when this
 * function is called it may mutate the provided element\'s, component\'s or any of the associated
 * directive\'s monkey-patch values.
 *
 * If the monkey-patch value is not detected then the code will walk up the DOM until an element
 * is found which contains a monkey-patch reference. When that occurs then the provided element
 * will be updated with a new context (which is then returned). If the monkey-patch value is not
 * detected for a component/directive instance then it will throw an error (all components and
 * directives should be automatically monkey-patched by ivy).
 *
 * @param target Component, Directive or DOM Node.
 */
function getLContext(target) {
  let mpValue = readPatchedData(target);
  if (mpValue) {
    // only when it's an array is it considered an LView instance
    // ... otherwise it's an already constructed LContext instance
    if (isLView(mpValue)) {
      const lView = mpValue;
      let nodeIndex;
      let component = undefined;
      let directives = undefined;
      if (isComponentInstance(target)) {
        nodeIndex = findViaComponent(lView, target);
        if (nodeIndex == -1) {
          throw new Error('The provided component was not found in the application');
        }
        component = target;
      } else if (isDirectiveInstance(target)) {
        nodeIndex = findViaDirective(lView, target);
        if (nodeIndex == -1) {
          throw new Error('The provided directive was not found in the application');
        }
        directives = getDirectivesAtNodeIndex(nodeIndex, lView);
      } else {
        nodeIndex = findViaNativeElement(lView, target);
        if (nodeIndex == -1) {
          return null;
        }
      }
      // the goal is not to fill the entire context full of data because the lookups
      // are expensive. Instead, only the target data (the element, component, container, ICU
      // expression or directive details) are filled into the context. If called multiple times
      // with different target values then the missing target data will be filled in.
      const native = unwrapRNode(lView[nodeIndex]);
      const existingCtx = readPatchedData(native);
      const context = existingCtx && !Array.isArray(existingCtx) ? existingCtx : createLContext(lView, nodeIndex, native);
      // only when the component has been discovered then update the monkey-patch
      if (component && context.component === undefined) {
        context.component = component;
        attachPatchData(context.component, context);
      }
      // only when the directives have been discovered then update the monkey-patch
      if (directives && context.directives === undefined) {
        context.directives = directives;
        for (let i = 0; i < directives.length; i++) {
          attachPatchData(directives[i], context);
        }
      }
      attachPatchData(context.native, context);
      mpValue = context;
    }
  } else {
    const rElement = target;
    ngDevMode && assertDomNode(rElement);
    // if the context is not found then we need to traverse upwards up the DOM
    // to find the nearest element that has already been monkey patched with data
    let parent = rElement;
    while (parent = parent.parentNode) {
      const parentContext = readPatchedData(parent);
      if (parentContext) {
        const lView = Array.isArray(parentContext) ? parentContext : parentContext.lView;
        // the edge of the app was also reached here through another means
        // (maybe because the DOM was changed manually).
        if (!lView) {
          return null;
        }
        const index = findViaNativeElement(lView, rElement);
        if (index >= 0) {
          const native = unwrapRNode(lView[index]);
          const context = createLContext(lView, index, native);
          attachPatchData(native, context);
          mpValue = context;
          break;
        }
      }
    }
  }
  return mpValue || null;
}
/**
 * Creates an empty instance of a `LContext` context
 */
function createLContext(lView, nodeIndex, native) {
  return new LContext(lView[ID], nodeIndex, native);
}
/**
 * Takes a component instance and returns the view for that component.
 *
 * @param componentInstance
 * @returns The component's view
 */
function getComponentViewByInstance(componentInstance) {
  let patchedData = readPatchedData(componentInstance);
  let lView;
  if (isLView(patchedData)) {
    const contextLView = patchedData;
    const nodeIndex = findViaComponent(contextLView, componentInstance);
    lView = getComponentLViewByIndex(nodeIndex, contextLView);
    const context = createLContext(contextLView, nodeIndex, lView[HOST]);
    context.component = componentInstance;
    attachPatchData(componentInstance, context);
    attachPatchData(context.native, context);
  } else {
    const context = patchedData;
    const contextLView = context.lView;
    ngDevMode && assertLView(contextLView);
    lView = getComponentLViewByIndex(context.nodeIndex, contextLView);
  }
  return lView;
}
/**
 * This property will be monkey-patched on elements, components and directives.
 */
const MONKEY_PATCH_KEY_NAME = '__ngContext__';
function attachLViewId(target, data) {
  target[MONKEY_PATCH_KEY_NAME] = data[ID];
}
/**
 * Returns the monkey-patch value data present on the target (which could be
 * a component, directive or a DOM node).
 */
function readLView(target) {
  const data = readPatchedData(target);
  if (isLView(data)) {
    return data;
  }
  return data ? data.lView : null;
}
/**
 * Assigns the given data to the given target (which could be a component,
 * directive or DOM node instance) using monkey-patching.
 */
function attachPatchData(target, data) {
  ngDevMode && assertDefined(target, 'Target expected');
  // Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this
  // for `LView`, because we have control over when an `LView` is created and destroyed, whereas
  // we can't know when to remove an `LContext`.
  if (isLView(data)) {
    target[MONKEY_PATCH_KEY_NAME] = data[ID];
    registerLView(data);
  } else {
    target[MONKEY_PATCH_KEY_NAME] = data;
  }
}
/**
 * Returns the monkey-patch value data present on the target (which could be
 * a component, directive or a DOM node).
 */
function readPatchedData(target) {
  ngDevMode && assertDefined(target, 'Target expected');
  const data = target[MONKEY_PATCH_KEY_NAME];
  return typeof data === 'number' ? getLViewById(data) : data || null;
}
function readPatchedLView(target) {
  const value = readPatchedData(target);
  if (value) {
    return isLView(value) ? value : value.lView;
  }
  return null;
}
function isComponentInstance(instance) {
  return instance && instance.constructor && instance.constructor.ɵcmp;
}
function isDirectiveInstance(instance) {
  return instance && instance.constructor && instance.constructor.ɵdir;
}
/**
 * Locates the element within the given LView and returns the matching index
 */
function findViaNativeElement(lView, target) {
  const tView = lView[TVIEW];
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    if (unwrapRNode(lView[i]) === target) {
      return i;
    }
  }
  return -1;
}
/**
 * Locates the next tNode (child, sibling or parent).
 */
function traverseNextElement(tNode) {
  if (tNode.child) {
    return tNode.child;
  } else if (tNode.next) {
    return tNode.next;
  } else {
    // Let's take the following template: <div><span>text</span></div><component/>
    // After checking the text node, we need to find the next parent that has a "next" TNode,
    // in this case the parent `div`, so that we can find the component.
    while (tNode.parent && !tNode.parent.next) {
      tNode = tNode.parent;
    }
    return tNode.parent && tNode.parent.next;
  }
}
/**
 * Locates the component within the given LView and returns the matching index
 */
function findViaComponent(lView, componentInstance) {
  const componentIndices = lView[TVIEW].components;
  if (componentIndices) {
    for (let i = 0; i < componentIndices.length; i++) {
      const elementComponentIndex = componentIndices[i];
      const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
      if (componentView[CONTEXT] === componentInstance) {
        return elementComponentIndex;
      }
    }
  } else {
    const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
    const rootComponent = rootComponentView[CONTEXT];
    if (rootComponent === componentInstance) {
      // we are dealing with the root element here therefore we know that the
      // element is the very first element after the HEADER data in the lView
      return HEADER_OFFSET;
    }
  }
  return -1;
}
/**
 * Locates the directive within the given LView and returns the matching index
 */
function findViaDirective(lView, directiveInstance) {
  // if a directive is monkey patched then it will (by default)
  // have a reference to the LView of the current view. The
  // element bound to the directive being search lives somewhere
  // in the view data. We loop through the nodes and check their
  // list of directives for the instance.
  let tNode = lView[TVIEW].firstChild;
  while (tNode) {
    const directiveIndexStart = tNode.directiveStart;
    const directiveIndexEnd = tNode.directiveEnd;
    for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
      if (lView[i] === directiveInstance) {
        return tNode.index;
      }
    }
    tNode = traverseNextElement(tNode);
  }
  return -1;
}
/**
 * Returns a list of directives applied to a node at a specific index. The list includes
 * directives matched by selector and any host directives, but it excludes components.
 * Use `getComponentAtNodeIndex` to find the component applied to a node.
 *
 * @param nodeIndex The node index
 * @param lView The target view data
 */
function getDirectivesAtNodeIndex(nodeIndex, lView) {
  const tNode = lView[TVIEW].data[nodeIndex];
  if (tNode.directiveStart === 0) return EMPTY_ARRAY;
  const results = [];
  for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {
    const directiveInstance = lView[i];
    if (!isComponentInstance(directiveInstance)) {
      results.push(directiveInstance);
    }
  }
  return results;
}
function getComponentAtNodeIndex(nodeIndex, lView) {
  const tNode = lView[TVIEW].data[nodeIndex];
  const {
    directiveStart,
    componentOffset
  } = tNode;
  return componentOffset > -1 ? lView[directiveStart + componentOffset] : null;
}
/**
 * Returns a map of local references (local reference name => element or directive instance) that
 * exist on a given element.
 */
function discoverLocalRefs(lView, nodeIndex) {
  const tNode = lView[TVIEW].data[nodeIndex];
  if (tNode && tNode.localNames) {
    const result = {};
    let localIndex = tNode.index + 1;
    for (let i = 0; i < tNode.localNames.length; i += 2) {
      result[tNode.localNames[i]] = lView[localIndex];
      localIndex++;
    }
    return result;
  }
  return null;
}

/**
 * Retrieve the root view from any component or `LView` by walking the parent `LView` until
 * reaching the root `LView`.
 *
 * @param componentOrLView any component or `LView`
 */
function getRootView(componentOrLView) {
  ngDevMode && assertDefined(componentOrLView, 'component');
  let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
  while (lView && !(lView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {
    lView = getLViewParent(lView);
  }
  ngDevMode && assertLView(lView);
  return lView;
}
/**
 * Returns the context information associated with the application where the target is situated. It
 * does this by walking the parent views until it gets to the root view, then getting the context
 * off of that.
 *
 * @param viewOrComponent the `LView` or component to get the root context for.
 */
function getRootContext(viewOrComponent) {
  const rootView = getRootView(viewOrComponent);
  ngDevMode && assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');
  return rootView[CONTEXT];
}
/**
 * Gets the first `LContainer` in the LView or `null` if none exists.
 */
function getFirstLContainer(lView) {
  return getNearestLContainer(lView[CHILD_HEAD]);
}
/**
 * Gets the next `LContainer` that is a sibling of the given container.
 */
function getNextLContainer(container) {
  return getNearestLContainer(container[NEXT]);
}
function getNearestLContainer(viewOrContainer) {
  while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
    viewOrContainer = viewOrContainer[NEXT];
  }
  return viewOrContainer;
}

/**
 * Retrieves the component instance associated with a given DOM element.
 *
 * @usageNotes
 * Given the following DOM structure:
 *
 * ```html
 * <app-root>
 *   <div>
 *     <child-comp></child-comp>
 *   </div>
 * </app-root>
 * ```
 *
 * Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
 * associated with this DOM element.
 *
 * Calling the function on `<app-root>` will return the `MyApp` instance.
 *
 *
 * @param element DOM element from which the component should be retrieved.
 * @returns Component instance associated with the element or `null` if there
 *    is no component associated with it.
 *
 * @publicApi
 */
function getComponent(element) {
  ngDevMode && assertDomElement(element);
  const context = getLContext(element);
  if (context === null) return null;
  if (context.component === undefined) {
    const lView = context.lView;
    if (lView === null) {
      return null;
    }
    context.component = getComponentAtNodeIndex(context.nodeIndex, lView);
  }
  return context.component;
}
/**
 * If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
 * view that the element is part of. Otherwise retrieves the instance of the component whose view
 * owns the element (in this case, the result is the same as calling `getOwningComponent`).
 *
 * @param element Element for which to get the surrounding component instance.
 * @returns Instance of the component that is around the element or null if the element isn't
 *    inside any component.
 *
 * @publicApi
 */
function getContext(element) {
  assertDomElement(element);
  const context = getLContext(element);
  const lView = context ? context.lView : null;
  return lView === null ? null : lView[CONTEXT];
}
/**
 * Retrieves the component instance whose view contains the DOM element.
 *
 * For example, if `<child-comp>` is used in the template of `<app-comp>`
 * (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
 * would return `<app-comp>`.
 *
 * @param elementOrDir DOM element, component or directive instance
 *    for which to retrieve the root components.
 * @returns Component instance whose view owns the DOM element or null if the element is not
 *    part of a component view.
 *
 * @publicApi
 */
function getOwningComponent(elementOrDir) {
  const context = getLContext(elementOrDir);
  let lView = context ? context.lView : null;
  if (lView === null) return null;
  let parent;
  while (lView[TVIEW].type === 2 /* TViewType.Embedded */ && (parent = getLViewParent(lView))) {
    lView = parent;
  }
  return lView[FLAGS] & 512 /* LViewFlags.IsRoot */ ? null : lView[CONTEXT];
}
/**
 * Retrieves all root components associated with a DOM element, directive or component instance.
 * Root components are those which have been bootstrapped by Angular.
 *
 * @param elementOrDir DOM element, component or directive instance
 *    for which to retrieve the root components.
 * @returns Root components associated with the target object.
 *
 * @publicApi
 */
function getRootComponents(elementOrDir) {
  const lView = readPatchedLView(elementOrDir);
  return lView !== null ? [getRootContext(lView)] : [];
}
/**
 * Retrieves an `Injector` associated with an element, component or directive instance.
 *
 * @param elementOrDir DOM element, component or directive instance for which to
 *    retrieve the injector.
 * @returns Injector associated with the element, component or directive instance.
 *
 * @publicApi
 */
function getInjector(elementOrDir) {
  const context = getLContext(elementOrDir);
  const lView = context ? context.lView : null;
  if (lView === null) return Injector.NULL;
  const tNode = lView[TVIEW].data[context.nodeIndex];
  return new NodeInjector(tNode, lView);
}
/**
 * Retrieve a set of injection tokens at a given DOM node.
 *
 * @param element Element for which the injection tokens should be retrieved.
 */
function getInjectionTokens(element) {
  const context = getLContext(element);
  const lView = context ? context.lView : null;
  if (lView === null) return [];
  const tView = lView[TVIEW];
  const tNode = tView.data[context.nodeIndex];
  const providerTokens = [];
  const startIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  const endIndex = tNode.directiveEnd;
  for (let i = startIndex; i < endIndex; i++) {
    let value = tView.data[i];
    if (isDirectiveDefHack(value)) {
      // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
      // design flaw.  We should always store same type so that we can be monomorphic. The issue
      // is that for Components/Directives we store the def instead the type. The correct behavior
      // is that we should always be storing injectable type in this location.
      value = value.type;
    }
    providerTokens.push(value);
  }
  return providerTokens;
}
/**
 * Retrieves directive instances associated with a given DOM node. Does not include
 * component instances.
 *
 * @usageNotes
 * Given the following DOM structure:
 *
 * ```html
 * <app-root>
 *   <button my-button></button>
 *   <my-comp></my-comp>
 * </app-root>
 * ```
 *
 * Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
 * directive that is associated with the DOM node.
 *
 * Calling `getDirectives` on `<my-comp>` will return an empty array.
 *
 * @param node DOM node for which to get the directives.
 * @returns Array of directives associated with the node.
 *
 * @publicApi
 */
function getDirectives(node) {
  // Skip text nodes because we can't have directives associated with them.
  if (node instanceof Text) {
    return [];
  }
  const context = getLContext(node);
  const lView = context ? context.lView : null;
  if (lView === null) {
    return [];
  }
  const tView = lView[TVIEW];
  const nodeIndex = context.nodeIndex;
  if (!tView?.data[nodeIndex]) {
    return [];
  }
  if (context.directives === undefined) {
    context.directives = getDirectivesAtNodeIndex(nodeIndex, lView);
  }
  // The `directives` in this case are a named array called `LComponentView`. Clone the
  // result so we don't expose an internal data structure in the user's console.
  return context.directives === null ? [] : [...context.directives];
}
/**
 * Returns the debug (partial) metadata for a particular directive or component instance.
 * The function accepts an instance of a directive or component and returns the corresponding
 * metadata.
 *
 * @param directiveOrComponentInstance Instance of a directive or component
 * @returns metadata of the passed directive or component
 *
 * @publicApi
 */
function getDirectiveMetadata$1(directiveOrComponentInstance) {
  const {
    constructor
  } = directiveOrComponentInstance;
  if (!constructor) {
    throw new Error('Unable to find the instance constructor');
  }
  // In case a component inherits from a directive, we may have component and directive metadata
  // To ensure we don't get the metadata of the directive, we want to call `getComponentDef` first.
  const componentDef = getComponentDef(constructor);
  if (componentDef) {
    const inputs = extractInputDebugMetadata(componentDef.inputs);
    return {
      inputs,
      outputs: componentDef.outputs,
      encapsulation: componentDef.encapsulation,
      changeDetection: componentDef.onPush ? ChangeDetectionStrategy.OnPush : ChangeDetectionStrategy.Default
    };
  }
  const directiveDef = getDirectiveDef(constructor);
  if (directiveDef) {
    const inputs = extractInputDebugMetadata(directiveDef.inputs);
    return {
      inputs,
      outputs: directiveDef.outputs
    };
  }
  return null;
}
/**
 * Retrieve map of local references.
 *
 * The references are retrieved as a map of local reference name to element or directive instance.
 *
 * @param target DOM element, component or directive instance for which to retrieve
 *    the local references.
 */
function getLocalRefs(target) {
  const context = getLContext(target);
  if (context === null) return {};
  if (context.localRefs === undefined) {
    const lView = context.lView;
    if (lView === null) {
      return {};
    }
    context.localRefs = discoverLocalRefs(lView, context.nodeIndex);
  }
  return context.localRefs || {};
}
/**
 * Retrieves the host element of a component or directive instance.
 * The host element is the DOM element that matched the selector of the directive.
 *
 * @param componentOrDirective Component or directive instance for which the host
 *     element should be retrieved.
 * @returns Host element of the target.
 *
 * @publicApi
 */
function getHostElement(componentOrDirective) {
  return getLContext(componentOrDirective).native;
}
/**
 * Retrieves the rendered text for a given component.
 *
 * This function retrieves the host element of a component and
 * and then returns the `textContent` for that element. This implies
 * that the text returned will include re-projected content of
 * the component as well.
 *
 * @param component The component to return the content text for.
 */
function getRenderedText(component) {
  const hostElement = getHostElement(component);
  return hostElement.textContent || '';
}
/**
 * Retrieves a list of event listeners associated with a DOM element. The list does include host
 * listeners, but it does not include event listeners defined outside of the Angular context
 * (e.g. through `addEventListener`).
 *
 * @usageNotes
 * Given the following DOM structure:
 *
 * ```html
 * <app-root>
 *   <div (click)="doSomething()"></div>
 * </app-root>
 * ```
 *
 * Calling `getListeners` on `<div>` will return an object that looks as follows:
 *
 * ```ts
 * {
 *   name: 'click',
 *   element: <div>,
 *   callback: () => doSomething(),
 *   useCapture: false
 * }
 * ```
 *
 * @param element Element for which the DOM listeners should be retrieved.
 * @returns Array of event listeners on the DOM element.
 *
 * @publicApi
 */
function getListeners(element) {
  ngDevMode && assertDomElement(element);
  const lContext = getLContext(element);
  const lView = lContext === null ? null : lContext.lView;
  if (lView === null) return [];
  const tView = lView[TVIEW];
  const lCleanup = lView[CLEANUP];
  const tCleanup = tView.cleanup;
  const listeners = [];
  if (tCleanup && lCleanup) {
    for (let i = 0; i < tCleanup.length;) {
      const firstParam = tCleanup[i++];
      const secondParam = tCleanup[i++];
      if (typeof firstParam === 'string') {
        const name = firstParam;
        const listenerElement = unwrapRNode(lView[secondParam]);
        const callback = lCleanup[tCleanup[i++]];
        const useCaptureOrIndx = tCleanup[i++];
        // if useCaptureOrIndx is boolean then report it as is.
        // if useCaptureOrIndx is positive number then it in unsubscribe method
        // if useCaptureOrIndx is negative number then it is a Subscription
        const type = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0 ? 'dom' : 'output';
        const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
        if (element == listenerElement) {
          listeners.push({
            element,
            name,
            callback,
            useCapture,
            type
          });
        }
      }
    }
  }
  listeners.sort(sortListeners);
  return listeners;
}
function sortListeners(a, b) {
  if (a.name == b.name) return 0;
  return a.name < b.name ? -1 : 1;
}
/**
 * This function should not exist because it is megamorphic and only mostly correct.
 *
 * See call site for more info.
 */
function isDirectiveDefHack(obj) {
  return obj.type !== undefined && obj.declaredInputs !== undefined && obj.findHostDirectiveDefs !== undefined;
}
/**
 * Retrieve the component `LView` from component/element.
 *
 * NOTE: `LView` is a private and should not be leaked outside.
 *       Don't export this method to `ng.*` on window.
 *
 * @param target DOM element or component instance for which to retrieve the LView.
 */
function getComponentLView(target) {
  const lContext = getLContext(target);
  const nodeIndx = lContext.nodeIndex;
  const lView = lContext.lView;
  ngDevMode && assertLView(lView);
  const componentLView = lView[nodeIndx];
  ngDevMode && assertLView(componentLView);
  return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value) {
  if (typeof Element !== 'undefined' && !(value instanceof Element)) {
    throw new Error('Expecting instance of DOM Element');
  }
}
/**
 * A directive definition holds additional metadata using bitwise flags to indicate
 * for example whether it is signal based.
 *
 * This information needs to be separate from the `publicName -> minifiedName`
 * mappings for backwards compatibility.
 */
function extractInputDebugMetadata(inputs) {
  const res = {};
  for (const key in inputs) {
    if (!inputs.hasOwnProperty(key)) {
      continue;
    }
    const value = inputs[key];
    if (value === undefined) {
      continue;
    }
    let minifiedName;
    if (Array.isArray(value)) {
      minifiedName = value[0];
      // flags are not used for now.
      // TODO: Consider exposing flag information in discovery.
    } else {
      minifiedName = value;
    }
    res[key] = minifiedName;
  }
  return res;
}

/**
 * Most of the use of `document` in Angular is from within the DI system so it is possible to simply
 * inject the `DOCUMENT` token and are done.
 *
 * Ivy is special because it does not rely upon the DI and must get hold of the document some other
 * way.
 *
 * The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
 * Wherever ivy needs the global document, it calls `getDocument()` instead.
 *
 * When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
 * tell ivy what the global `document` is.
 *
 * Angular does this for us in each of the standard platforms (`Browser` and `Server`)
 * by calling `setDocument()` when providing the `DOCUMENT` token.
 */
let DOCUMENT = undefined;
/**
 * Tell ivy what the `document` is for this platform.
 *
 * It is only necessary to call this if the current platform is not a browser.
 *
 * @param document The object representing the global `document` in this environment.
 */
function setDocument(document) {
  DOCUMENT = document;
}
/**
 * Access the object that represents the `document` for this platform.
 *
 * Ivy calls this whenever it needs to access the `document` object.
 * For example to create the renderer or to do sanitization.
 */
function getDocument() {
  if (DOCUMENT !== undefined) {
    return DOCUMENT;
  } else if (typeof document !== 'undefined') {
    return document;
  }
  throw new RuntimeError(210 /* RuntimeErrorCode.MISSING_DOCUMENT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `The document object is not available in this context. Make sure the DOCUMENT injection token is provided.`);
  // No "document" can be found. This should only happen if we are running ivy outside Angular and
  // the current platform is not a browser. Since this is not a supported scenario at the moment
  // this should not happen in Angular apps.
  // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
  // public API.
}

/**
 * A DI token representing a string ID, used
 * primarily for prefixing application attributes and CSS styles when
 * {@link ViewEncapsulation#Emulated} is being used.
 *
 * The token is needed in cases when multiple applications are bootstrapped on a page
 * (for example, using `bootstrapApplication` calls). In this case, ensure that those applications
 * have different `APP_ID` value setup. For example:
 *
 * ```
 * bootstrapApplication(ComponentA, {
 *   providers: [
 *     { provide: APP_ID, useValue: 'app-a' },
 *     // ... other providers ...
 *   ]
 * });
 *
 * bootstrapApplication(ComponentB, {
 *   providers: [
 *     { provide: APP_ID, useValue: 'app-b' },
 *     // ... other providers ...
 *   ]
 * });
 * ```
 *
 * By default, when there is only one application bootstrapped, you don't need to provide the
 * `APP_ID` token (the `ng` will be used as an app ID).
 *
 * @publicApi
 */
const APP_ID = /*#__PURE__*/new InjectionToken(ngDevMode ? 'AppId' : '', {
  providedIn: 'root',
  factory: () => DEFAULT_APP_ID
});
/** Default value of the `APP_ID` token. */
const DEFAULT_APP_ID = 'ng';
/**
 * A function that is executed when a platform is initialized.
 *
 * @deprecated from v19.0.0, use providePlatformInitializer instead
 *
 * @see {@link providePlatformInitializer}
 *
 * @publicApi
 */
const PLATFORM_INITIALIZER = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Platform Initializer' : '');
/**
 * A token that indicates an opaque platform ID.
 * @publicApi
 */
const PLATFORM_ID = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Platform ID' : '', {
  providedIn: 'platform',
  factory: () => 'unknown' // set a default platform name, when none set explicitly
});
/**
 * A DI token that indicates the root directory of
 * the application
 * @publicApi
 * @deprecated
 */
const PACKAGE_ROOT_URL = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Application Packages Root URL' : '');
// We keep this token here, rather than the animations package, so that modules that only care
// about which animations module is loaded (e.g. the CDK) can retrieve it without having to
// include extra dependencies. See #44970 for more context.
/**
 * A [DI token](api/core/InjectionToken) that indicates which animations
 * module has been loaded.
 * @publicApi
 */
const ANIMATION_MODULE_TYPE = /*#__PURE__*/new InjectionToken(ngDevMode ? 'AnimationModuleType' : '');
// TODO(crisbeto): link to CSP guide here.
/**
 * Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that
 * Angular will apply when inserting inline styles. If not provided, Angular will look up its value
 * from the `ngCspNonce` attribute of the application root node.
 *
 * @publicApi
 */
const CSP_NONCE = /*#__PURE__*/new InjectionToken(ngDevMode ? 'CSP nonce' : '', {
  providedIn: 'root',
  factory: () => {
    // Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on
    // the root node, but because the token value is used in renderers, it has to be available
    // *very* early in the bootstrapping process. This should be a fairly shallow search, because
    // the app won't have been added to the DOM yet. Some approaches that were considered:
    // 1. Find the root node through `ApplicationRef.components[i].location` - normally this would
    // be enough for our purposes, but the token is injected very early so the `components` array
    // isn't populated yet.
    // 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to
    // creating the `LView`. This means that no `LView` will have been entered when this factory is
    // invoked for the root component.
    // 3. Have the token factory return `() => string` which is invoked when a nonce is requested -
    // the slightly later execution does allow us to get an `LView` reference, but the fact that
    // it is a function means that it could be executed at *any* time (including immediately) which
    // may lead to weird bugs.
    // 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the
    // hood - has the same problem as #1 and #2 in that the renderer is used to query for the root
    // node and the nonce value needs to be available when the renderer is created.
    return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null;
  }
});
const IMAGE_CONFIG_DEFAULTS = {
  breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  placeholderResolution: 30,
  disableImageSizeWarning: false,
  disableImageLazyLoadWarning: false
};
/**
 * Injection token that configures the image optimized image functionality.
 * See {@link ImageConfig} for additional information about parameters that
 * can be used.
 *
 * @see {@link NgOptimizedImage}
 * @see {@link ImageConfig}
 * @publicApi
 */
const IMAGE_CONFIG = /*#__PURE__*/new InjectionToken(ngDevMode ? 'ImageConfig' : '', {
  providedIn: 'root',
  factory: () => IMAGE_CONFIG_DEFAULTS
});

/**
 * Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
 *
 * Example:
 *
 * ```
 * const COUNTER_KEY = makeStateKey<number>('counter');
 * let value = 10;
 *
 * transferState.set(COUNTER_KEY, value);
 * ```
 *
 * @publicApi
 */
function makeStateKey(key) {
  return key;
}
function initTransferState() {
  const transferState = new TransferState();
  if (inject(PLATFORM_ID) === 'browser') {
    transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
  }
  return transferState;
}
/**
 * A key value store that is transferred from the application on the server side to the application
 * on the client side.
 *
 * The `TransferState` is available as an injectable token.
 * On the client, just inject this token using DI and use it, it will be lazily initialized.
 * On the server it's already included if `renderApplication` function is used. Otherwise, import
 * the `ServerTransferStateModule` module to make the `TransferState` available.
 *
 * The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
 * boolean, number, string, null and non-class objects will be serialized and deserialized in a
 * non-lossy manner.
 *
 * @publicApi
 */
let TransferState = /*#__PURE__*/(() => {
  class TransferState {
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: TransferState,
      providedIn: 'root',
      factory: initTransferState
    }))();
    /** @internal */
    store = {};
    onSerializeCallbacks = {};
    /**
     * Get the value corresponding to a key. Return `defaultValue` if key is not found.
     */
    get(key, defaultValue) {
      return this.store[key] !== undefined ? this.store[key] : defaultValue;
    }
    /**
     * Set the value corresponding to a key.
     */
    set(key, value) {
      this.store[key] = value;
    }
    /**
     * Remove a key from the store.
     */
    remove(key) {
      delete this.store[key];
    }
    /**
     * Test whether a key exists in the store.
     */
    hasKey(key) {
      return this.store.hasOwnProperty(key);
    }
    /**
     * Indicates whether the state is empty.
     */
    get isEmpty() {
      return Object.keys(this.store).length === 0;
    }
    /**
     * Register a callback to provide the value for a key when `toJson` is called.
     */
    onSerialize(key, callback) {
      this.onSerializeCallbacks[key] = callback;
    }
    /**
     * Serialize the current state of the store to JSON.
     */
    toJson() {
      // Call the onSerialize callbacks and put those values into the store.
      for (const key in this.onSerializeCallbacks) {
        if (this.onSerializeCallbacks.hasOwnProperty(key)) {
          try {
            this.store[key] = this.onSerializeCallbacks[key]();
          } catch (e) {
            console.warn('Exception in onSerialize callback: ', e);
          }
        }
      }
      // Escape script tag to avoid break out of <script> tag in serialized output.
      // Encoding of `<` is the same behaviour as G3 script_builders.
      return JSON.stringify(this.store).replace(/</g, '\\u003C');
    }
  }
  return TransferState;
})();
function retrieveTransferredState(doc, appId) {
  // Locate the script tag with the JSON data transferred from the server.
  // The id of the script tag is set to the Angular appId + 'state'.
  const script = doc.getElementById(appId + '-state');
  if (script?.textContent) {
    try {
      // Avoid using any here as it triggers lint errors in google3 (any is not allowed).
      // Decoding of `<` is done of the box by browsers and node.js, same behaviour as G3
      // script_builders.
      return JSON.parse(script.textContent);
    } catch (e) {
      console.warn('Exception while restoring TransferState for app ' + appId, e);
    }
  }
  return {};
}

/** Encodes that the node lookup should start from the host node of this component. */
const REFERENCE_NODE_HOST = 'h';
/** Encodes that the node lookup should start from the document body node. */
const REFERENCE_NODE_BODY = 'b';
/**
 * Describes navigation steps that the runtime logic need to perform,
 * starting from a given (known) element.
 */
var NodeNavigationStep = /*#__PURE__*/function (NodeNavigationStep) {
  NodeNavigationStep["FirstChild"] = "f";
  NodeNavigationStep["NextSibling"] = "n";
  return NodeNavigationStep;
}(NodeNavigationStep || {});
/**
 * Keys within serialized view data structure to represent various
 * parts. See the `SerializedView` interface below for additional information.
 */
const ELEMENT_CONTAINERS = 'e';
const TEMPLATES = 't';
const CONTAINERS = 'c';
const MULTIPLIER = 'x';
const NUM_ROOT_NODES = 'r';
const TEMPLATE_ID = 'i'; // as it's also an "id"
const NODES = 'n';
const DISCONNECTED_NODES = 'd';
const I18N_DATA = 'l';
const DEFER_BLOCK_ID = 'di';
const DEFER_BLOCK_STATE$1 = 's';
const DEFER_PARENT_BLOCK_ID = 'p';
const DEFER_HYDRATE_TRIGGERS = 't';
const DEFER_PREFETCH_TRIGGERS = 'pt';

/**
 * Internal token that specifies whether DOM reuse logic
 * during hydration is enabled.
 */
const IS_HYDRATION_DOM_REUSE_ENABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_HYDRATION_DOM_REUSE_ENABLED' : '');
// By default (in client rendering mode), we remove all the contents
// of the host element and render an application after that.
const PRESERVE_HOST_CONTENT_DEFAULT = false;
/**
 * Internal token that indicates whether host element content should be
 * retained during the bootstrap.
 */
const PRESERVE_HOST_CONTENT = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'PRESERVE_HOST_CONTENT' : '', {
  providedIn: 'root',
  factory: () => PRESERVE_HOST_CONTENT_DEFAULT
});
/**
 * Internal token that indicates whether hydration support for i18n
 * is enabled.
 */
const IS_I18N_HYDRATION_ENABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_I18N_HYDRATION_ENABLED' : '');
/**
 * Internal token that indicates whether event replay support for SSR
 * is enabled.
 */
const IS_EVENT_REPLAY_ENABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_EVENT_REPLAY_ENABLED' : '');
const EVENT_REPLAY_ENABLED_DEFAULT = false;
/**
 * Internal token that indicates whether incremental hydration support
 * is enabled.
 */
const IS_INCREMENTAL_HYDRATION_ENABLED = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_INCREMENTAL_HYDRATION_ENABLED' : '');
/**
 * A map of DOM elements with `jsaction` attributes grouped by action names.
 */
const JSACTION_BLOCK_ELEMENT_MAP = /*#__PURE__*/new InjectionToken(ngDevMode ? 'JSACTION_BLOCK_ELEMENT_MAP' : '', {
  providedIn: 'root',
  factory: () => new Map()
});
const markedFeatures = /*#__PURE__*/new Set();
// tslint:disable:ban
/**
 * A guarded `performance.mark` for feature marking.
 *
 * This method exists because while all supported browser and node.js version supported by Angular
 * support performance.mark API. This is not the case for other environments such as JSDOM and
 * Cloudflare workers.
 */
function performanceMarkFeature(feature) {
  if (markedFeatures.has(feature)) {
    return;
  }
  markedFeatures.add(feature);
  performance?.mark?.('mark_feature_usage', {
    detail: {
      feature
    }
  });
}

/**
 * Asserts that the current stack frame is not within a reactive context. Useful
 * to disallow certain code from running inside a reactive context (see {@link toSignal}).
 *
 * @param debugFn a reference to the function making the assertion (used for the error message).
 *
 * @publicApi
 */
function assertNotInReactiveContext(debugFn, extraContext) {
  // Taking a `Function` instead of a string name here prevents the un-minified name of the function
  // from being retained in the bundle regardless of minification.
  if ((0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.getActiveConsumer)() !== null) {
    throw new RuntimeError(-602 /* RuntimeErrorCode.ASSERTION_NOT_INSIDE_REACTIVE_CONTEXT */, ngDevMode && `${debugFn.name}() cannot be called from within a reactive context.${extraContext ? ` ${extraContext}` : ''}`);
  }
}

/**
 * The phase to run an `afterRender` or `afterNextRender` callback in.
 *
 * Callbacks in the same phase run in the order they are registered. Phases run in the
 * following order after each render:
 *
 *   1. `AfterRenderPhase.EarlyRead`
 *   2. `AfterRenderPhase.Write`
 *   3. `AfterRenderPhase.MixedReadWrite`
 *   4. `AfterRenderPhase.Read`
 *
 * Angular is unable to verify or enforce that phases are used correctly, and instead
 * relies on each developer to follow the guidelines documented for each value and
 * carefully choose the appropriate one, refactoring their code if necessary. By doing
 * so, Angular is better able to minimize the performance degradation associated with
 * manual DOM access, ensuring the best experience for the end users of your application
 * or library.
 *
 * @deprecated Specify the phase for your callback to run in by passing a spec-object as the first
 *   parameter to `afterRender` or `afterNextRender` instead of a function.
 */
var AfterRenderPhase = /*#__PURE__*/function (AfterRenderPhase) {
  /**
   * Use `AfterRenderPhase.EarlyRead` for callbacks that only need to **read** from the
   * DOM before a subsequent `AfterRenderPhase.Write` callback, for example to perform
   * custom layout that the browser doesn't natively support. Prefer the
   * `AfterRenderPhase.EarlyRead` phase if reading can wait until after the write phase.
   * **Never** write to the DOM in this phase.
   *
   * <div class="alert is-important">
   *
   * Using this value can degrade performance.
   * Instead, prefer using built-in browser functionality when possible.
   *
   * </div>
   */
  AfterRenderPhase[AfterRenderPhase["EarlyRead"] = 0] = "EarlyRead";
  /**
   * Use `AfterRenderPhase.Write` for callbacks that only **write** to the DOM. **Never**
   * read from the DOM in this phase.
   */
  AfterRenderPhase[AfterRenderPhase["Write"] = 1] = "Write";
  /**
   * Use `AfterRenderPhase.MixedReadWrite` for callbacks that read from or write to the
   * DOM, that haven't been refactored to use a different phase. **Never** use this phase if
   * it is possible to divide the work among the other phases instead.
   *
   * <div class="alert is-critical">
   *
   * Using this value can **significantly** degrade performance.
   * Instead, prefer dividing work into the appropriate phase callbacks.
   *
   * </div>
   */
  AfterRenderPhase[AfterRenderPhase["MixedReadWrite"] = 2] = "MixedReadWrite";
  /**
   * Use `AfterRenderPhase.Read` for callbacks that only **read** from the DOM. **Never**
   * write to the DOM in this phase.
   */
  AfterRenderPhase[AfterRenderPhase["Read"] = 3] = "Read";
  return AfterRenderPhase;
}(AfterRenderPhase || {});
let AfterRenderManager = /*#__PURE__*/(() => {
  class AfterRenderManager {
    impl = null;
    execute() {
      this.impl?.execute();
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: AfterRenderManager,
      providedIn: 'root',
      factory: () => new AfterRenderManager()
    }))();
  }
  return AfterRenderManager;
})();
const AFTER_RENDER_PHASES = /* @__PURE__ **/(() => [AfterRenderPhase.EarlyRead, AfterRenderPhase.Write, AfterRenderPhase.MixedReadWrite, AfterRenderPhase.Read])();
let AfterRenderImpl = /*#__PURE__*/(() => {
  class AfterRenderImpl {
    ngZone = (() => inject(NgZone))();
    scheduler = (() => inject(ChangeDetectionScheduler))();
    errorHandler = (() => inject(ErrorHandler, {
      optional: true
    }))();
    /** Current set of active sequences. */
    sequences = (() => new Set())();
    /** Tracks registrations made during the current set of executions. */
    deferredRegistrations = (() => new Set())();
    /** Whether the `AfterRenderManager` is currently executing hooks. */
    executing = false;
    /**
     * Run the sequence of phases of hooks, once through. As a result of executing some hooks, more
     * might be scheduled.
     */
    execute() {
      this.executing = true;
      for (const phase of AFTER_RENDER_PHASES) {
        for (const sequence of this.sequences) {
          if (sequence.erroredOrDestroyed || !sequence.hooks[phase]) {
            continue;
          }
          try {
            sequence.pipelinedValue = this.ngZone.runOutsideAngular(() => sequence.hooks[phase](sequence.pipelinedValue));
          } catch (err) {
            sequence.erroredOrDestroyed = true;
            this.errorHandler?.handleError(err);
          }
        }
      }
      this.executing = false;
      // Cleanup step to reset sequence state and also collect one-shot sequences for removal.
      for (const sequence of this.sequences) {
        sequence.afterRun();
        if (sequence.once) {
          this.sequences.delete(sequence);
          // Destroy the sequence so its on destroy callbacks can be cleaned up
          // immediately, instead of waiting until the injector is destroyed.
          sequence.destroy();
        }
      }
      for (const sequence of this.deferredRegistrations) {
        this.sequences.add(sequence);
      }
      if (this.deferredRegistrations.size > 0) {
        this.scheduler.notify(8 /* NotificationSource.DeferredRenderHook */);
      }
      this.deferredRegistrations.clear();
    }
    register(sequence) {
      if (!this.executing) {
        this.sequences.add(sequence);
        // Trigger an `ApplicationRef.tick()` if one is not already pending/running, because we have a
        // new render hook that needs to run.
        this.scheduler.notify(7 /* NotificationSource.RenderHook */);
      } else {
        this.deferredRegistrations.add(sequence);
      }
    }
    unregister(sequence) {
      if (this.executing && this.sequences.has(sequence)) {
        // We can't remove an `AfterRenderSequence` in the middle of iteration.
        // Instead, mark it as destroyed so it doesn't run any more, and mark it as one-shot so it'll
        // be removed at the end of the current execution.
        sequence.erroredOrDestroyed = true;
        sequence.pipelinedValue = undefined;
        sequence.once = true;
      } else {
        // It's safe to directly remove this sequence.
        this.sequences.delete(sequence);
        this.deferredRegistrations.delete(sequence);
      }
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: AfterRenderImpl,
      providedIn: 'root',
      factory: () => new AfterRenderImpl()
    }))();
  }
  return AfterRenderImpl;
})();
class AfterRenderSequence {
  impl;
  hooks;
  once;
  /**
   * Whether this sequence errored or was destroyed during this execution, and hooks should no
   * longer run for it.
   */
  erroredOrDestroyed = false;
  /**
   * The value returned by the last hook execution (if any), ready to be pipelined into the next
   * one.
   */
  pipelinedValue = /*#__PURE__*/(() => undefined)();
  unregisterOnDestroy;
  constructor(impl, hooks, once, destroyRef) {
    this.impl = impl;
    this.hooks = hooks;
    this.once = once;
    this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  }
  afterRun() {
    this.erroredOrDestroyed = false;
    this.pipelinedValue = undefined;
  }
  destroy() {
    this.impl.unregister(this);
    this.unregisterOnDestroy?.();
  }
}
function afterRender(callbackOrSpec, options) {
  ngDevMode && assertNotInReactiveContext(afterRender, 'Call `afterRender` outside of a reactive context. For example, schedule the render ' + 'callback inside the component constructor`.');
  !options?.injector && assertInInjectionContext(afterRender);
  const injector = options?.injector ?? inject(Injector);
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return NOOP_AFTER_RENDER_REF;
  }
  performanceMarkFeature('NgAfterRender');
  return afterRenderImpl(callbackOrSpec, injector, options, /* once */false);
}
function afterNextRender(callbackOrSpec, options) {
  !options?.injector && assertInInjectionContext(afterNextRender);
  const injector = options?.injector ?? inject(Injector);
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return NOOP_AFTER_RENDER_REF;
  }
  performanceMarkFeature('NgAfterNextRender');
  return afterRenderImpl(callbackOrSpec, injector, options, /* once */true);
}
function getHooks(callbackOrSpec, phase) {
  if (callbackOrSpec instanceof Function) {
    const hooks = [undefined, undefined, undefined, undefined];
    hooks[phase] = callbackOrSpec;
    return hooks;
  } else {
    return [callbackOrSpec.earlyRead, callbackOrSpec.write, callbackOrSpec.mixedReadWrite, callbackOrSpec.read];
  }
}
/**
 * Shared implementation for `afterRender` and `afterNextRender`.
 */
function afterRenderImpl(callbackOrSpec, injector, options, once) {
  const manager = injector.get(AfterRenderManager);
  // Lazily initialize the handler implementation, if necessary. This is so that it can be
  // tree-shaken if `afterRender` and `afterNextRender` aren't used.
  manager.impl ??= injector.get(AfterRenderImpl);
  const hooks = options?.phase ?? AfterRenderPhase.MixedReadWrite;
  const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  const sequence = new AfterRenderSequence(manager.impl, getHooks(callbackOrSpec, hooks), once, destroyRef);
  manager.impl.register(sequence);
  return sequence;
}
/** `AfterRenderRef` that does nothing. */
const NOOP_AFTER_RENDER_REF = {
  destroy() {}
};

/**
 * Describes the state of defer block dependency loading.
 */
var DeferDependenciesLoadingState = /*#__PURE__*/function (DeferDependenciesLoadingState) {
  /** Initial state, dependency loading is not yet triggered */
  DeferDependenciesLoadingState[DeferDependenciesLoadingState["NOT_STARTED"] = 0] = "NOT_STARTED";
  /** Dependency loading is in progress */
  DeferDependenciesLoadingState[DeferDependenciesLoadingState["IN_PROGRESS"] = 1] = "IN_PROGRESS";
  /** Dependency loading has completed successfully */
  DeferDependenciesLoadingState[DeferDependenciesLoadingState["COMPLETE"] = 2] = "COMPLETE";
  /** Dependency loading has failed */
  DeferDependenciesLoadingState[DeferDependenciesLoadingState["FAILED"] = 3] = "FAILED";
  return DeferDependenciesLoadingState;
}(DeferDependenciesLoadingState || {});
/** Slot index where `minimum` parameter value is stored. */
const MINIMUM_SLOT = 0;
/** Slot index where `after` parameter value is stored. */
const LOADING_AFTER_SLOT = 1;
/**
 * Describes the current state of this defer block instance.
 *
 * @publicApi
 */
var DeferBlockState = /*#__PURE__*/function (DeferBlockState) {
  /** The placeholder block content is rendered */
  DeferBlockState[DeferBlockState["Placeholder"] = 0] = "Placeholder";
  /** The loading block content is rendered */
  DeferBlockState[DeferBlockState["Loading"] = 1] = "Loading";
  /** The main content block content is rendered */
  DeferBlockState[DeferBlockState["Complete"] = 2] = "Complete";
  /** The error block content is rendered */
  DeferBlockState[DeferBlockState["Error"] = 3] = "Error";
  return DeferBlockState;
}(DeferBlockState || {});
/**
 * Describes the initial state of this defer block instance.
 *
 * Note: this state is internal only and *must* be represented
 * with a number lower than any value in the `DeferBlockState` enum.
 */
var DeferBlockInternalState = /*#__PURE__*/function (DeferBlockInternalState) {
  /** Initial state. Nothing is rendered yet. */
  DeferBlockInternalState[DeferBlockInternalState["Initial"] = -1] = "Initial";
  return DeferBlockInternalState;
}(DeferBlockInternalState || {});
const NEXT_DEFER_BLOCK_STATE = 0;
// Note: it's *important* to keep the state in this slot, because this slot
// is used by runtime logic to differentiate between LViews, LContainers and
// other types (see `isLView` and `isLContainer` functions). In case of defer
// blocks, this slot would always be a number.
const DEFER_BLOCK_STATE = 1;
const STATE_IS_FROZEN_UNTIL = 2;
const LOADING_AFTER_CLEANUP_FN = 3;
const TRIGGER_CLEANUP_FNS = 4;
const PREFETCH_TRIGGER_CLEANUP_FNS = 5;
const SSR_UNIQUE_ID = 6;
const SSR_BLOCK_STATE = 7;
const ON_COMPLETE_FNS = 8;
const HYDRATE_TRIGGER_CLEANUP_FNS = 9;
/**
 * Options for configuring defer blocks behavior.
 * @publicApi
 */
var DeferBlockBehavior = /*#__PURE__*/function (DeferBlockBehavior) {
  /**
   * Manual triggering mode for defer blocks. Provides control over when defer blocks render
   * and which state they render.
   */
  DeferBlockBehavior[DeferBlockBehavior["Manual"] = 0] = "Manual";
  /**
   * Playthrough mode for defer blocks. This mode behaves like defer blocks would in a browser.
   * This is the default behavior in test environments.
   */
  DeferBlockBehavior[DeferBlockBehavior["Playthrough"] = 1] = "Playthrough";
  return DeferBlockBehavior;
}(DeferBlockBehavior || {});
/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Registers a cleanup function associated with a prefetching trigger
 * or a regular trigger of a defer block.
 */
function storeTriggerCleanupFn(type, lDetails, cleanupFn) {
  const key = getCleanupFnKeyByType(type);
  if (lDetails[key] === null) {
    lDetails[key] = [];
  }
  lDetails[key].push(cleanupFn);
}
/**
 * Invokes registered cleanup functions either for prefetch or for regular triggers.
 */
function invokeTriggerCleanupFns(type, lDetails) {
  const key = getCleanupFnKeyByType(type);
  const cleanupFns = lDetails[key];
  if (cleanupFns !== null) {
    for (const cleanupFn of cleanupFns) {
      cleanupFn();
    }
    lDetails[key] = null;
  }
}
/**
 * Invokes registered cleanup functions for prefetch, hydrate, and regular triggers.
 */
function invokeAllTriggerCleanupFns(lDetails) {
  invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  invokeTriggerCleanupFns(0 /* TriggerType.Regular */, lDetails);
  invokeTriggerCleanupFns(2 /* TriggerType.Hydrate */, lDetails);
}
function getCleanupFnKeyByType(type) {
  let key = TRIGGER_CLEANUP_FNS;
  if (type === 1 /* TriggerType.Prefetch */) {
    key = PREFETCH_TRIGGER_CLEANUP_FNS;
  } else if (type === 2 /* TriggerType.Hydrate */) {
    key = HYDRATE_TRIGGER_CLEANUP_FNS;
  }
  return key;
}

/**
 * Calculates a data slot index for defer block info (either static or
 * instance-specific), given an index of a defer instruction.
 */
function getDeferBlockDataIndex(deferBlockIndex) {
  // Instance state is located at the *next* position
  // after the defer block slot in an LView or TView.data.
  return deferBlockIndex + 1;
}
/** Retrieves a defer block state from an LView, given a TNode that represents a block. */
function getLDeferBlockDetails(lView, tNode) {
  const tView = lView[TVIEW];
  const slotIndex = getDeferBlockDataIndex(tNode.index);
  ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  return lView[slotIndex];
}
/** Stores a defer block instance state in LView. */
function setLDeferBlockDetails(lView, deferBlockIndex, lDetails) {
  const tView = lView[TVIEW];
  const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  lView[slotIndex] = lDetails;
}
/** Retrieves static info about a defer block, given a TView and a TNode that represents a block. */
function getTDeferBlockDetails(tView, tNode) {
  const slotIndex = getDeferBlockDataIndex(tNode.index);
  ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  return tView.data[slotIndex];
}
/** Stores a defer block static info in `TView.data`. */
function setTDeferBlockDetails(tView, deferBlockIndex, deferBlockConfig) {
  const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  tView.data[slotIndex] = deferBlockConfig;
}
function getTemplateIndexForState(newState, hostLView, tNode) {
  const tView = hostLView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  switch (newState) {
    case DeferBlockState.Complete:
      return tDetails.primaryTmplIndex;
    case DeferBlockState.Loading:
      return tDetails.loadingTmplIndex;
    case DeferBlockState.Error:
      return tDetails.errorTmplIndex;
    case DeferBlockState.Placeholder:
      return tDetails.placeholderTmplIndex;
    default:
      ngDevMode && throwError(`Unexpected defer block state: ${newState}`);
      return null;
  }
}
/**
 * Returns a minimum amount of time that a given state should be rendered for,
 * taking into account `minimum` parameter value. If the `minimum` value is
 * not specified - returns `null`.
 */
function getMinimumDurationForState(tDetails, currentState) {
  if (currentState === DeferBlockState.Placeholder) {
    return tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null;
  } else if (currentState === DeferBlockState.Loading) {
    return tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null;
  }
  return null;
}
/** Retrieves the value of the `after` parameter on the @loading block. */
function getLoadingBlockAfter(tDetails) {
  return tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null;
}
/**
 * Adds downloaded dependencies into a directive or a pipe registry,
 * making sure that a dependency doesn't yet exist in the registry.
 */
function addDepsToRegistry(currentDeps, newDeps) {
  if (!currentDeps || currentDeps.length === 0) {
    return newDeps;
  }
  const currentDepSet = new Set(currentDeps);
  for (const dep of newDeps) {
    currentDepSet.add(dep);
  }
  // If `currentDeps` is the same length, there were no new deps and can
  // return the original array.
  return currentDeps.length === currentDepSet.size ? currentDeps : Array.from(currentDepSet);
}
/** Retrieves a TNode that represents main content of a defer block. */
function getPrimaryBlockTNode(tView, tDetails) {
  const adjustedIndex = tDetails.primaryTmplIndex + HEADER_OFFSET;
  return getTNode(tView, adjustedIndex);
}
/**
 * Asserts whether all dependencies for a defer block are loaded.
 * Always run this function (in dev mode) before rendering a defer
 * block in completed state.
 */
function assertDeferredDependenciesLoaded(tDetails) {
  assertEqual(tDetails.loadingState, DeferDependenciesLoadingState.COMPLETE, 'Expecting all deferred dependencies to be loaded.');
}
/**
 * Determines if a given value matches the expected structure of a defer block
 *
 * We can safely rely on the primaryTmplIndex because every defer block requires
 * that a primary template exists. All the other template options are optional.
 */
function isTDeferBlockDetails(value) {
  return value !== null && typeof value === 'object' && typeof value.primaryTmplIndex === 'number';
}
/**
 * Whether a given TNode represents a defer block.
 */
function isDeferBlock(tView, tNode) {
  let tDetails = null;
  const slotIndex = getDeferBlockDataIndex(tNode.index);
  // Check if a slot index is in the reasonable range.
  // Note: we do `-1` on the right border, since defer block details are stored
  // in the `n+1` slot, see `getDeferBlockDataIndex` for more info.
  if (HEADER_OFFSET < slotIndex && slotIndex < tView.bindingStartIndex) {
    tDetails = getTDeferBlockDetails(tView, tNode);
  }
  return !!tDetails && isTDeferBlockDetails(tDetails);
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/** Configuration object used to register passive and capturing events. */
const eventListenerOptions = {
  passive: true,
  capture: true
};
/** Keeps track of the currently-registered `on hover` triggers. */
const hoverTriggers = /*#__PURE__*/new WeakMap();
/** Keeps track of the currently-registered `on interaction` triggers. */
const interactionTriggers = /*#__PURE__*/new WeakMap();
/** Currently-registered `viewport` triggers. */
const viewportTriggers = /*#__PURE__*/new WeakMap();
/** Names of the events considered as interaction events. */
const interactionEventNames = ['click', 'keydown'];
/** Names of the events considered as hover events. */
const hoverEventNames = ['mouseenter', 'mouseover', 'focusin'];
/** `IntersectionObserver` used to observe `viewport` triggers. */
let intersectionObserver = null;
/** Number of elements currently observed with `viewport` triggers. */
let observedViewportElements = 0;
/** Object keeping track of registered callbacks for a deferred block trigger. */
class DeferEventEntry {
  callbacks = /*#__PURE__*/(() => new Set())();
  listener = () => {
    for (const callback of this.callbacks) {
      callback();
    }
  };
}
/**
 * Registers an interaction trigger.
 * @param trigger Element that is the trigger.
 * @param callback Callback to be invoked when the trigger is interacted with.
 */
function onInteraction(trigger, callback) {
  let entry = interactionTriggers.get(trigger);
  // If this is the first entry for this element, add the listeners.
  if (!entry) {
    // Note that managing events centrally like this lends itself well to using global
    // event delegation. It currently does delegation at the element level, rather than the
    // document level, because:
    // 1. Global delegation is the most effective when there are a lot of events being registered
    // at the same time. Deferred blocks are unlikely to be used in such a way.
    // 2. Matching events to their target isn't free. For each `click` and `keydown` event we
    // would have look through all the triggers and check if the target either is the element
    // itself or it's contained within the element. Given that `click` and `keydown` are some
    // of the most common events, this may end up introducing a lot of runtime overhead.
    // 3. We're still registering only two events per element, no matter how many deferred blocks
    // are referencing it.
    entry = new DeferEventEntry();
    interactionTriggers.set(trigger, entry);
    for (const name of interactionEventNames) {
      trigger.addEventListener(name, entry.listener, eventListenerOptions);
    }
  }
  entry.callbacks.add(callback);
  return () => {
    const {
      callbacks,
      listener
    } = entry;
    callbacks.delete(callback);
    if (callbacks.size === 0) {
      interactionTriggers.delete(trigger);
      for (const name of interactionEventNames) {
        trigger.removeEventListener(name, listener, eventListenerOptions);
      }
    }
  };
}
/**
 * Registers a hover trigger.
 * @param trigger Element that is the trigger.
 * @param callback Callback to be invoked when the trigger is hovered over.
 */
function onHover(trigger, callback) {
  let entry = hoverTriggers.get(trigger);
  // If this is the first entry for this element, add the listener.
  if (!entry) {
    entry = new DeferEventEntry();
    hoverTriggers.set(trigger, entry);
    for (const name of hoverEventNames) {
      trigger.addEventListener(name, entry.listener, eventListenerOptions);
    }
  }
  entry.callbacks.add(callback);
  return () => {
    const {
      callbacks,
      listener
    } = entry;
    callbacks.delete(callback);
    if (callbacks.size === 0) {
      for (const name of hoverEventNames) {
        trigger.removeEventListener(name, listener, eventListenerOptions);
      }
      hoverTriggers.delete(trigger);
    }
  };
}
/**
 * Registers a viewport trigger.
 * @param trigger Element that is the trigger.
 * @param callback Callback to be invoked when the trigger comes into the viewport.
 * @param injector Injector that can be used by the trigger to resolve DI tokens.
 */
function onViewport(trigger, callback, injector) {
  const ngZone = injector.get(NgZone);
  let entry = viewportTriggers.get(trigger);
  intersectionObserver = intersectionObserver || ngZone.runOutsideAngular(() => {
    return new IntersectionObserver(entries => {
      for (const current of entries) {
        // Only invoke the callbacks if the specific element is intersecting.
        if (current.isIntersecting && viewportTriggers.has(current.target)) {
          ngZone.run(viewportTriggers.get(current.target).listener);
        }
      }
    });
  });
  if (!entry) {
    entry = new DeferEventEntry();
    ngZone.runOutsideAngular(() => intersectionObserver.observe(trigger));
    viewportTriggers.set(trigger, entry);
    observedViewportElements++;
  }
  entry.callbacks.add(callback);
  return () => {
    // It's possible that a different cleanup callback fully removed this element already.
    if (!viewportTriggers.has(trigger)) {
      return;
    }
    entry.callbacks.delete(callback);
    if (entry.callbacks.size === 0) {
      intersectionObserver?.unobserve(trigger);
      viewportTriggers.delete(trigger);
      observedViewportElements--;
    }
    if (observedViewportElements === 0) {
      intersectionObserver?.disconnect();
      intersectionObserver = null;
    }
  };
}
/**
 * Helper function to get the LView in which a deferred block's trigger is rendered.
 * @param deferredHostLView LView in which the deferred block is defined.
 * @param deferredTNode TNode defining the deferred block.
 * @param walkUpTimes Number of times to go up in the view hierarchy to find the trigger's view.
 *   A negative value means that the trigger is inside the block's placeholder, while an undefined
 *   value means that the trigger is in the same LView as the deferred block.
 */
function getTriggerLView(deferredHostLView, deferredTNode, walkUpTimes) {
  // The trigger is in the same view, we don't need to traverse.
  if (walkUpTimes == null) {
    return deferredHostLView;
  }
  // A positive value or zero means that the trigger is in a parent view.
  if (walkUpTimes >= 0) {
    return walkUpViews(walkUpTimes, deferredHostLView);
  }
  // If the value is negative, it means that the trigger is inside the placeholder.
  const deferredContainer = deferredHostLView[deferredTNode.index];
  ngDevMode && assertLContainer(deferredContainer);
  const triggerLView = deferredContainer[CONTAINER_HEADER_OFFSET] ?? null;
  // We need to null check, because the placeholder might not have been rendered yet.
  if (ngDevMode && triggerLView !== null) {
    const lDetails = getLDeferBlockDetails(deferredHostLView, deferredTNode);
    const renderedState = lDetails[DEFER_BLOCK_STATE];
    assertEqual(renderedState, DeferBlockState.Placeholder, 'Expected a placeholder to be rendered in this defer block.');
    assertLView(triggerLView);
  }
  return triggerLView;
}
/**
 * Gets the element that a deferred block's trigger is pointing to.
 * @param triggerLView LView in which the trigger is defined.
 * @param triggerIndex Index at which the trigger element should've been rendered.
 */
function getTriggerElement(triggerLView, triggerIndex) {
  const element = getNativeByIndex(HEADER_OFFSET + triggerIndex, triggerLView);
  ngDevMode && assertElement(element);
  return element;
}
/**
 * Registers a DOM-node based trigger.
 * @param initialLView LView in which the defer block is rendered.
 * @param tNode TNode representing the defer block.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to go up/down in the view hierarchy to find the trigger.
 * @param registerFn Function that will register the DOM events.
 * @param callback Callback to be invoked when the trigger receives the event that should render
 *     the deferred block.
 * @param type Trigger type to distinguish between regular and prefetch triggers.
 */
function registerDomTrigger(initialLView, tNode, triggerIndex, walkUpTimes, registerFn, callback, type) {
  const injector = initialLView[INJECTOR];
  const zone = injector.get(NgZone);
  function pollDomTrigger() {
    // If the initial view was destroyed, we don't need to do anything.
    if (isDestroyed(initialLView)) {
      return;
    }
    const lDetails = getLDeferBlockDetails(initialLView, tNode);
    const renderedState = lDetails[DEFER_BLOCK_STATE];
    // If the block was loaded before the trigger was resolved, we don't need to do anything.
    if (renderedState !== DeferBlockInternalState.Initial && renderedState !== DeferBlockState.Placeholder) {
      return;
    }
    const triggerLView = getTriggerLView(initialLView, tNode, walkUpTimes);
    // Keep polling until we resolve the trigger's LView.
    if (!triggerLView) {
      afterNextRender({
        read: pollDomTrigger
      }, {
        injector
      });
      return;
    }
    // It's possible that the trigger's view was destroyed before we resolved the trigger element.
    if (isDestroyed(triggerLView)) {
      return;
    }
    const element = getTriggerElement(triggerLView, triggerIndex);
    const cleanup = registerFn(element, () => {
      // `pollDomTrigger` runs outside the zone (because of `afterNextRender`) and registers its
      // listeners outside the zone, so we jump back into the zone prior to running the callback.
      zone.run(() => {
        if (initialLView !== triggerLView) {
          removeLViewOnDestroy(triggerLView, cleanup);
        }
        callback();
      });
    }, injector);
    // The trigger and deferred block might be in different LViews.
    // For the main LView the cleanup would happen as a part of
    // `storeTriggerCleanupFn` logic. For trigger LView we register
    // a cleanup function there to remove event handlers in case an
    // LView gets destroyed before a trigger is invoked.
    if (initialLView !== triggerLView) {
      storeLViewOnDestroy(triggerLView, cleanup);
    }
    storeTriggerCleanupFn(type, lDetails, cleanup);
  }
  // Begin polling for the trigger.
  afterNextRender({
    read: pollDomTrigger
  }, {
    injector
  });
}
const DEFER_BLOCK_SSR_ID_ATTRIBUTE = 'ngb';
function invokeRegisteredDelegationListeners(event) {
  const handlerFns = event.currentTarget?.__jsaction_fns?.get(event.type);
  if (!handlerFns) {
    return;
  }
  for (const handler of handlerFns) {
    handler(event);
  }
}
function setJSActionAttributes(nativeElement, eventTypes, parentDeferBlockId = null) {
  // jsaction attributes specifically should be applied to elements and not comment nodes.
  // Comment nodes also have no setAttribute function. So this avoids errors.
  if (eventTypes.length === 0 || nativeElement.nodeType !== Node.ELEMENT_NODE) {
    return;
  }
  const existingAttr = nativeElement.getAttribute(_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.Attribute.JSACTION);
  // we dedupe cases where hydrate triggers are used as it's possible that
  // someone may have added an event binding to the root node that matches what the
  // hydrate trigger adds.
  const parts = eventTypes.reduce((prev, curr) => {
    // if there is no existing attribute OR it's not in the existing one, we need to add it
    return (existingAttr?.indexOf(curr) ?? -1) === -1 ? prev + curr + ':;' : prev;
  }, '');
  //  This is required to be a module accessor to appease security tests on setAttribute.
  nativeElement.setAttribute(_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.Attribute.JSACTION, `${existingAttr ?? ''}${parts}`);
  const blockName = parentDeferBlockId ?? '';
  if (blockName !== '' && parts.length > 0) {
    nativeElement.setAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE, blockName);
  }
}
const sharedStashFunction = (rEl, eventType, listenerFn) => {
  const el = rEl;
  const eventListenerMap = el.__jsaction_fns ?? new Map();
  const eventListeners = eventListenerMap.get(eventType) ?? [];
  eventListeners.push(listenerFn);
  eventListenerMap.set(eventType, eventListeners);
  el.__jsaction_fns = eventListenerMap;
};
const sharedMapFunction = (rEl, jsActionMap) => {
  let blockName = rEl.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE) ?? '';
  const el = rEl;
  const blockSet = jsActionMap.get(blockName) ?? new Set();
  if (!blockSet.has(el)) {
    blockSet.add(el);
  }
  jsActionMap.set(blockName, blockSet);
};
function removeListenersFromBlocks(blockNames, jsActionMap) {
  if (blockNames.length > 0) {
    let blockList = [];
    for (let blockName of blockNames) {
      if (jsActionMap.has(blockName)) {
        blockList = [...blockList, ...jsActionMap.get(blockName)];
      }
    }
    const replayList = new Set(blockList);
    replayList.forEach(removeListeners);
  }
}
const removeListeners = el => {
  el.removeAttribute(_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.Attribute.JSACTION);
  el.removeAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
  el.__jsaction_fns = undefined;
};
const JSACTION_EVENT_CONTRACT = /*#__PURE__*/new InjectionToken(ngDevMode ? 'EVENT_CONTRACT_DETAILS' : '', {
  providedIn: 'root',
  factory: () => ({})
});
function invokeListeners(event, currentTarget) {
  const handlerFns = currentTarget?.__jsaction_fns?.get(event.type);
  if (!handlerFns) {
    return;
  }
  for (const handler of handlerFns) {
    handler(event);
  }
}

/**
 * An internal injection token to reference `DehydratedBlockRegistry` implementation
 * in a tree-shakable way.
 */
const DEHYDRATED_BLOCK_REGISTRY = /*#__PURE__*/new InjectionToken(ngDevMode ? 'DEHYDRATED_BLOCK_REGISTRY' : '');
/**
 * The DehydratedBlockRegistry is used for incremental hydration purposes. It keeps
 * track of the Defer Blocks that need hydration so we can effectively
 * navigate up to the top dehydrated defer block and fire appropriate cleanup
 * functions post hydration.
 */
let DehydratedBlockRegistry = /*#__PURE__*/(() => {
  class DehydratedBlockRegistry {
    registry = (() => new Map())();
    cleanupFns = (() => new Map())();
    jsActionMap = (() => inject(JSACTION_BLOCK_ELEMENT_MAP))();
    contract = (() => inject(JSACTION_EVENT_CONTRACT))();
    add(blockId, info) {
      this.registry.set(blockId, info);
    }
    get(blockId) {
      return this.registry.get(blockId) ?? null;
    }
    has(blockId) {
      return this.registry.has(blockId);
    }
    cleanup(hydratedBlocks) {
      removeListenersFromBlocks(hydratedBlocks, this.jsActionMap);
      for (let blockId of hydratedBlocks) {
        this.registry.delete(blockId);
        this.jsActionMap.delete(blockId);
        this.invokeTriggerCleanupFns(blockId);
        this.hydrating.delete(blockId);
      }
      if (this.size === 0) {
        this.contract.instance?.cleanUp();
      }
    }
    get size() {
      return this.registry.size;
    }
    // we have to leave the lowest block Id in the registry
    // unless that block has no children
    addCleanupFn(blockId, fn) {
      let cleanupFunctions = [];
      if (this.cleanupFns.has(blockId)) {
        cleanupFunctions = this.cleanupFns.get(blockId);
      }
      cleanupFunctions.push(fn);
      this.cleanupFns.set(blockId, cleanupFunctions);
    }
    invokeTriggerCleanupFns(blockId) {
      const fns = this.cleanupFns.get(blockId) ?? [];
      for (let fn of fns) {
        fn();
      }
      this.cleanupFns.delete(blockId);
    }
    // Blocks that are being hydrated.
    hydrating = (() => new Set())();
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: DehydratedBlockRegistry,
      providedIn: null,
      factory: () => new DehydratedBlockRegistry()
    }))();
  }
  return DehydratedBlockRegistry;
})();
/**
 * The name of the key used in the TransferState collection,
 * where hydration information is located.
 */
const TRANSFER_STATE_TOKEN_ID = '__nghData__';
/**
 * Lookup key used to reference DOM hydration data (ngh) in `TransferState`.
 */
const NGH_DATA_KEY = /*#__PURE__*/makeStateKey(TRANSFER_STATE_TOKEN_ID);
/**
 * The name of the key used in the TransferState collection,
 * where serialized defer block information is located.
 */
const TRANSFER_STATE_DEFER_BLOCKS_INFO = '__nghDeferData__';
/**
 * Lookup key used to retrieve defer block datain `TransferState`.
 */
const NGH_DEFER_BLOCKS_KEY = /*#__PURE__*/makeStateKey(TRANSFER_STATE_DEFER_BLOCKS_INFO);
/**
 * The name of the attribute that would be added to host component
 * nodes and contain a reference to a particular slot in transferred
 * state that contains the necessary hydration info for this component.
 */
const NGH_ATTR_NAME = 'ngh';
/**
 * Marker used in a comment node to ensure hydration content integrity
 */
const SSR_CONTENT_INTEGRITY_MARKER = 'nghm';
/**
 * Reference to a function that reads `ngh` attribute value from a given RNode
 * and retrieves hydration information from the TransferState using that value
 * as an index. Returns `null` by default, when hydration is not enabled.
 *
 * @param rNode Component's host element.
 * @param injector Injector that this component has access to.
 * @param isRootView Specifies whether we trying to read hydration info for the root view.
 */
let _retrieveHydrationInfoImpl = () => null;
function retrieveHydrationInfoImpl(rNode, injector, isRootView = false) {
  let nghAttrValue = rNode.getAttribute(NGH_ATTR_NAME);
  if (nghAttrValue == null) return null;
  // For cases when a root component also acts as an anchor node for a ViewContainerRef
  // (for example, when ViewContainerRef is injected in a root component), there is a need
  // to serialize information about the component itself, as well as an LContainer that
  // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  // (1) hydration info for the root component itself and (2) hydration info for the
  // ViewContainerRef instance (an LContainer). Each piece of information is included into
  // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  // Since we only have 1 root element, we encode both bits of info into a single string:
  // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  // and 25 is the `ngh` for a root view which holds LContainer).
  const [componentViewNgh, rootViewNgh] = nghAttrValue.split('|');
  nghAttrValue = isRootView ? rootViewNgh : componentViewNgh;
  if (!nghAttrValue) return null;
  // We've read one of the ngh ids, keep the remaining one, so that
  // we can set it back on the DOM element.
  const rootNgh = rootViewNgh ? `|${rootViewNgh}` : '';
  const remainingNgh = isRootView ? componentViewNgh : rootNgh;
  let data = {};
  let nghDeferData;
  // An element might have an empty `ngh` attribute value (e.g. `<comp ngh="" />`),
  // which means that no special annotations are required. Do not attempt to read
  // from the TransferState in this case.
  if (nghAttrValue !== '') {
    const transferState = injector.get(TransferState, null, {
      optional: true
    });
    if (transferState !== null) {
      const nghData = transferState.get(NGH_DATA_KEY, []);
      nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
      // The nghAttrValue is always a number referencing an index
      // in the hydration TransferState data.
      data = nghData[Number(nghAttrValue)];
      // If the `ngh` attribute exists and has a non-empty value,
      // the hydration info *must* be present in the TransferState.
      // If there is no data for some reasons, this is an error.
      ngDevMode && assertDefined(data, 'Unable to retrieve hydration info from the TransferState.');
    }
  }
  const dehydratedView = {
    data,
    firstChild: rNode.firstChild ?? null
  };
  if (isRootView) {
    // If there is hydration info present for the root view, it means that there was
    // a ViewContainerRef injected in the root component. The root component host element
    // acted as an anchor node in this scenario. As a result, the DOM nodes that represent
    // embedded views in this ViewContainerRef are located as siblings to the host node,
    // i.e. `<app-root /><#VIEW1><#VIEW2>...<!--container-->`. In this case, the current
    // node becomes the first child of this root view and the next sibling is the first
    // element in the DOM segment.
    dehydratedView.firstChild = rNode;
    // We use `0` here, since this is the slot (right after the HEADER_OFFSET)
    // where a component LView or an LContainer is located in a root LView.
    setSegmentHead(dehydratedView, 0, rNode.nextSibling);
  }
  if (remainingNgh) {
    // If we have only used one of the ngh ids, store the remaining one
    // back on this RNode.
    rNode.setAttribute(NGH_ATTR_NAME, remainingNgh);
  } else {
    // The `ngh` attribute is cleared from the DOM node now
    // that the data has been retrieved for all indices.
    rNode.removeAttribute(NGH_ATTR_NAME);
  }
  // Note: don't check whether this node was claimed for hydration,
  // because this node might've been previously claimed while processing
  // template instructions.
  ngDevMode && markRNodeAsClaimedByHydration(rNode, /* checkIfAlreadyClaimed */false);
  ngDevMode && ngDevMode.hydratedComponents++;
  return dehydratedView;
}
/**
 * Sets the implementation for the `retrieveHydrationInfo` function.
 */
function enableRetrieveHydrationInfoImpl() {
  _retrieveHydrationInfoImpl = retrieveHydrationInfoImpl;
}
/**
 * Retrieves hydration info by reading the value from the `ngh` attribute
 * and accessing a corresponding slot in TransferState storage.
 */
function retrieveHydrationInfo(rNode, injector, isRootView = false) {
  return _retrieveHydrationInfoImpl(rNode, injector, isRootView);
}
/**
 * Retrieves the necessary object from a given ViewRef to serialize:
 *  - an LView for component views
 *  - an LContainer for cases when component acts as a ViewContainerRef anchor
 *  - `null` in case of an embedded view
 */
function getLNodeForHydration(viewRef) {
  // Reading an internal field from `ViewRef` instance.
  let lView = viewRef._lView;
  const tView = lView[TVIEW];
  // A registered ViewRef might represent an instance of an
  // embedded view, in which case we do not need to annotate it.
  if (tView.type === 2 /* TViewType.Embedded */) {
    return null;
  }
  // Check if it's a root view and if so, retrieve component's
  // LView from the first slot after the header.
  if (isRootView(lView)) {
    lView = lView[HEADER_OFFSET];
  }
  return lView;
}
function getTextNodeContent(node) {
  return node.textContent?.replace(/\s/gm, '');
}
/**
 * Restores text nodes and separators into the DOM that were lost during SSR
 * serialization. The hydration process replaces empty text nodes and text
 * nodes that are immediately adjacent to other text nodes with comment nodes
 * that this method filters on to restore those missing nodes that the
 * hydration process is expecting to be present.
 *
 * @param node The app's root HTML Element
 */
function processTextNodeMarkersBeforeHydration(node) {
  const doc = getDocument();
  const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, {
    acceptNode(node) {
      const content = getTextNodeContent(node);
      const isTextNodeMarker = content === "ngetn" /* TextNodeMarker.EmptyNode */ || content === "ngtns" /* TextNodeMarker.Separator */;
      return isTextNodeMarker ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
    }
  });
  let currentNode;
  // We cannot modify the DOM while using the commentIterator,
  // because it throws off the iterator state.
  // So we collect all marker nodes first and then follow up with
  // applying the changes to the DOM: either inserting an empty node
  // or just removing the marker if it was used as a separator.
  const nodes = [];
  while (currentNode = commentNodesIterator.nextNode()) {
    nodes.push(currentNode);
  }
  for (const node of nodes) {
    if (node.textContent === "ngetn" /* TextNodeMarker.EmptyNode */) {
      node.replaceWith(doc.createTextNode(''));
    } else {
      node.remove();
    }
  }
}
/**
 * Internal type that represents a claimed node.
 * Only used in dev mode.
 */
var HydrationStatus = /*#__PURE__*/function (HydrationStatus) {
  HydrationStatus["Hydrated"] = "hydrated";
  HydrationStatus["Skipped"] = "skipped";
  HydrationStatus["Mismatched"] = "mismatched";
  return HydrationStatus;
}(HydrationStatus || {});
const HYDRATION_INFO_KEY = '__ngDebugHydrationInfo__';
function patchHydrationInfo(node, info) {
  node[HYDRATION_INFO_KEY] = info;
}
function readHydrationInfo(node) {
  return node[HYDRATION_INFO_KEY] ?? null;
}
/**
 * Marks a node as "claimed" by hydration process.
 * This is needed to make assessments in tests whether
 * the hydration process handled all nodes.
 */
function markRNodeAsClaimedByHydration(node, checkIfAlreadyClaimed = true) {
  if (!ngDevMode) {
    throw new Error('Calling `markRNodeAsClaimedByHydration` in prod mode ' + 'is not supported and likely a mistake.');
  }
  if (checkIfAlreadyClaimed && isRNodeClaimedForHydration(node)) {
    throw new Error('Trying to claim a node, which was claimed already.');
  }
  patchHydrationInfo(node, {
    status: HydrationStatus.Hydrated
  });
  ngDevMode.hydratedNodes++;
}
function markRNodeAsSkippedByHydration(node) {
  if (!ngDevMode) {
    throw new Error('Calling `markRNodeAsSkippedByHydration` in prod mode ' + 'is not supported and likely a mistake.');
  }
  patchHydrationInfo(node, {
    status: HydrationStatus.Skipped
  });
  ngDevMode.componentsSkippedHydration++;
}
function markRNodeAsHavingHydrationMismatch(node, expectedNodeDetails = null, actualNodeDetails = null) {
  if (!ngDevMode) {
    throw new Error('Calling `markRNodeAsMismatchedByHydration` in prod mode ' + 'is not supported and likely a mistake.');
  }
  // The RNode can be a standard HTMLElement (not an Angular component or directive)
  // The devtools component tree only displays Angular components & directives
  // Therefore we attach the debug info to the closest component/directive
  while (node && !getComponent(node)) {
    node = node?.parentNode;
  }
  if (node) {
    patchHydrationInfo(node, {
      status: HydrationStatus.Mismatched,
      expectedNodeDetails,
      actualNodeDetails
    });
  }
}
function isRNodeClaimedForHydration(node) {
  return readHydrationInfo(node)?.status === HydrationStatus.Hydrated;
}
function setSegmentHead(hydrationInfo, index, node) {
  hydrationInfo.segmentHeads ??= {};
  hydrationInfo.segmentHeads[index] = node;
}
function getSegmentHead(hydrationInfo, index) {
  return hydrationInfo.segmentHeads?.[index] ?? null;
}
function isIncrementalHydrationEnabled(injector) {
  return injector.get(IS_INCREMENTAL_HYDRATION_ENABLED, false, {
    optional: true
  });
}
/** Throws an error if the incremental hydration is not enabled */
function assertIncrementalHydrationIsConfigured(injector) {
  if (!isIncrementalHydrationEnabled(injector)) {
    throw new RuntimeError(508 /* RuntimeErrorCode.MISCONFIGURED_INCREMENTAL_HYDRATION */, 'Angular has detected that some `@defer` blocks use `hydrate` triggers, ' + 'but incremental hydration was not enabled. Please ensure that the `withIncrementalHydration()` ' + 'call is added as an argument for the `provideClientHydration()` function call ' + 'in your application config.');
  }
}
/** Throws an error if the ssrUniqueId on the LDeferBlockDetails is not present  */
function assertSsrIdDefined(ssrUniqueId) {
  assertDefined(ssrUniqueId, 'Internal error: expecting an SSR id for a defer block that should be hydrated, but the id is not present');
}
/**
 * Returns the size of an <ng-container>, using either the information
 * serialized in `ELEMENT_CONTAINERS` (element container size) or by
 * computing the sum of root nodes in all dehydrated views in a given
 * container (in case this `<ng-container>` was also used as a view
 * container host node, e.g. <ng-container *ngIf>).
 */
function getNgContainerSize(hydrationInfo, index) {
  const data = hydrationInfo.data;
  let size = data[ELEMENT_CONTAINERS]?.[index] ?? null;
  // If there is no serialized information available in the `ELEMENT_CONTAINERS` slot,
  // check if we have info about view containers at this location (e.g.
  // `<ng-container *ngIf>`) and use container size as a number of root nodes in this
  // element container.
  if (size === null && data[CONTAINERS]?.[index]) {
    size = calcSerializedContainerSize(hydrationInfo, index);
  }
  return size;
}
function isSerializedElementContainer(hydrationInfo, index) {
  return hydrationInfo.data[ELEMENT_CONTAINERS]?.[index] !== undefined;
}
function getSerializedContainerViews(hydrationInfo, index) {
  return hydrationInfo.data[CONTAINERS]?.[index] ?? null;
}
/**
 * Computes the size of a serialized container (the number of root nodes)
 * by calculating the sum of root nodes in all dehydrated views in this container.
 */
function calcSerializedContainerSize(hydrationInfo, index) {
  const views = getSerializedContainerViews(hydrationInfo, index) ?? [];
  let numNodes = 0;
  for (let view of views) {
    numNodes += view[NUM_ROOT_NODES] * (view[MULTIPLIER] ?? 1);
  }
  return numNodes;
}
/**
 * Attempt to initialize the `disconnectedNodes` field of the given
 * `DehydratedView`. Returns the initialized value.
 */
function initDisconnectedNodes(hydrationInfo) {
  // Check if we are processing disconnected info for the first time.
  if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
    const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
    hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  }
  return hydrationInfo.disconnectedNodes;
}
/**
 * Checks whether a node is annotated as "disconnected", i.e. not present
 * in the DOM at serialization time. We should not attempt hydration for
 * such nodes and instead, use a regular "creation mode".
 */
function isDisconnectedNode$1(hydrationInfo, index) {
  // Check if we are processing disconnected info for the first time.
  if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
    const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
    hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  }
  return !!initDisconnectedNodes(hydrationInfo)?.has(index);
}
/**
 * Helper function to prepare text nodes for serialization by ensuring
 * that seperate logical text blocks in the DOM remain separate after
 * serialization.
 */
function processTextNodeBeforeSerialization(context, node) {
  // Handle cases where text nodes can be lost after DOM serialization:
  //  1. When there is an *empty text node* in DOM: in this case, this
  //     node would not make it into the serialized string and as a result,
  //     this node wouldn't be created in a browser. This would result in
  //     a mismatch during the hydration, where the runtime logic would expect
  //     a text node to be present in live DOM, but no text node would exist.
  //     Example: `<span>{{ name }}</span>` when the `name` is an empty string.
  //     This would result in `<span></span>` string after serialization and
  //     in a browser only the `span` element would be created. To resolve that,
  //     an extra comment node is appended in place of an empty text node and
  //     that special comment node is replaced with an empty text node *before*
  //     hydration.
  //  2. When there are 2 consecutive text nodes present in the DOM.
  //     Example: `<div>Hello <ng-container *ngIf="true">world</ng-container></div>`.
  //     In this scenario, the live DOM would look like this:
  //       <div>#text('Hello ') #text('world') #comment('container')</div>
  //     Serialized string would look like this: `<div>Hello world<!--container--></div>`.
  //     The live DOM in a browser after that would be:
  //       <div>#text('Hello world') #comment('container')</div>
  //     Notice how 2 text nodes are now "merged" into one. This would cause hydration
  //     logic to fail, since it'd expect 2 text nodes being present, not one.
  //     To fix this, we insert a special comment node in between those text nodes, so
  //     serialized representation is: `<div>Hello <!--ngtns-->world<!--container--></div>`.
  //     This forces browser to create 2 text nodes separated by a comment node.
  //     Before running a hydration process, this special comment node is removed, so the
  //     live DOM has exactly the same state as it was before serialization.
  // Collect this node as required special annotation only when its
  // contents is empty. Otherwise, such text node would be present on
  // the client after server-side rendering and no special handling needed.
  const el = node;
  const corruptedTextNodes = context.corruptedTextNodes;
  if (el.textContent === '') {
    corruptedTextNodes.set(el, "ngetn" /* TextNodeMarker.EmptyNode */);
  } else if (el.nextSibling?.nodeType === Node.TEXT_NODE) {
    corruptedTextNodes.set(el, "ngtns" /* TextNodeMarker.Separator */);
  }
}
function convertHydrateTriggersToJsAction(triggers) {
  let actionList = [];
  if (triggers !== null) {
    if (triggers.has(4 /* DeferBlockTrigger.Hover */)) {
      actionList.push(...hoverEventNames);
    }
    if (triggers.has(3 /* DeferBlockTrigger.Interaction */)) {
      actionList.push(...interactionEventNames);
    }
  }
  return actionList;
}
/**
 * Builds a queue of blocks that need to be hydrated, looking up the
 * tree to the topmost defer block that exists in the tree that hasn't
 * been hydrated, but exists in the registry. This queue is in top down
 * heirarchical order as a list of defer block ids.
 * Note: This is utilizing serialized information to navigate up the tree
 */
function getParentBlockHydrationQueue(deferBlockId, injector) {
  const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  const transferState = injector.get(TransferState);
  const deferBlockParents = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  let isTopMostDeferBlock = false;
  let currentBlockId = deferBlockId;
  const deferBlockQueue = [];
  while (!isTopMostDeferBlock && currentBlockId) {
    ngDevMode && assertEqual(deferBlockQueue.indexOf(currentBlockId), -1, 'Internal error: defer block hierarchy has a cycle.');
    deferBlockQueue.unshift(currentBlockId);
    isTopMostDeferBlock = dehydratedBlockRegistry.has(currentBlockId);
    currentBlockId = deferBlockParents[currentBlockId][DEFER_PARENT_BLOCK_ID];
  }
  return deferBlockQueue;
}
function gatherDeferBlocksByJSActionAttribute(doc) {
  const jsactionNodes = doc.body.querySelectorAll('[jsaction]');
  const blockMap = new Set();
  for (let node of jsactionNodes) {
    const attr = node.getAttribute('jsaction');
    const blockId = node.getAttribute('ngb');
    const eventTypes = [...hoverEventNames.join(':;'), ...interactionEventNames.join(':;')].join('|');
    if (attr?.match(eventTypes) && blockId !== null) {
      blockMap.add(node);
    }
  }
  return blockMap;
}
function appendDeferBlocksToJSActionMap(doc, injector) {
  const blockMap = gatherDeferBlocksByJSActionAttribute(doc);
  for (let rNode of blockMap) {
    const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
    sharedMapFunction(rNode, jsActionMap);
  }
}
/**
 * Retrieves defer block hydration information from the TransferState.
 *
 * @param injector Injector that this component has access to.
 */
let _retrieveDeferBlockDataImpl = () => {
  return {};
};
function retrieveDeferBlockDataImpl(injector) {
  const transferState = injector.get(TransferState, null, {
    optional: true
  });
  if (transferState !== null) {
    const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
    ngDevMode && assertDefined(nghDeferData, 'Unable to retrieve defer block info from the TransferState.');
    return nghDeferData;
  }
  return {};
}
/**
 * Sets the implementation for the `retrieveDeferBlockData` function.
 */
function enableRetrieveDeferBlockDataImpl() {
  _retrieveDeferBlockDataImpl = retrieveDeferBlockDataImpl;
}
/**
 * Retrieves defer block data from TransferState storage
 */
function retrieveDeferBlockData(injector) {
  return _retrieveDeferBlockDataImpl(injector);
}
function isTimerTrigger(triggerInfo) {
  return typeof triggerInfo === 'object' && triggerInfo.trigger === 5 /* DeferBlockTrigger.Timer */;
}
function getHydrateTimerTrigger(blockData) {
  const trigger = blockData[DEFER_HYDRATE_TRIGGERS]?.find(t => isTimerTrigger(t));
  return trigger?.delay ?? null;
}
function hasHydrateTrigger(blockData, trigger) {
  return blockData[DEFER_HYDRATE_TRIGGERS]?.includes(trigger) ?? false;
}
/**
 * Creates a summary of the given serialized defer block, which is used later to properly initialize
 * specific triggers.
 */
function createBlockSummary(blockInfo) {
  return {
    data: blockInfo,
    hydrate: {
      idle: hasHydrateTrigger(blockInfo, 0 /* DeferBlockTrigger.Idle */),
      immediate: hasHydrateTrigger(blockInfo, 1 /* DeferBlockTrigger.Immediate */),
      timer: getHydrateTimerTrigger(blockInfo),
      viewport: hasHydrateTrigger(blockInfo, 2 /* DeferBlockTrigger.Viewport */)
    }
  };
}
/**
 * Processes all of the defer block data in the transfer state and creates a map of the summaries
 */
function processBlockData(injector) {
  const blockData = retrieveDeferBlockData(injector);
  let blockDetails = new Map();
  for (let blockId in blockData) {
    blockDetails.set(blockId, createBlockSummary(blockData[blockId]));
  }
  return blockDetails;
}

/**
 * Defines the CSS styles encapsulation policies for the {@link Component} decorator's
 * `encapsulation` option.
 *
 * See {@link Component#encapsulation encapsulation}.
 *
 * @usageNotes
 * ### Example
 *
 * {@example core/ts/metadata/encapsulation.ts region='longform'}
 *
 * @publicApi
 */
var ViewEncapsulation = /*#__PURE__*/function (ViewEncapsulation) {
  // TODO: consider making `ViewEncapsulation` a `const enum` instead. See
  // https://github.com/angular/angular/issues/44119 for additional information.
  /**
   * Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the
   * component's host element and applying the same attribute to all the CSS selectors provided
   * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}.
   *
   * This is the default option.
   */
  ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  /**
   * Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided
   * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable
   * to any HTML element of the application regardless of their host Component.
   */
  ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  /**
   * Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates
   * a ShadowRoot for the component's host element which is then used to encapsulate
   * all the Component's styling.
   */
  ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  return ViewEncapsulation;
}(ViewEncapsulation || {});
/**
 * @fileoverview
 * A module to facilitate use of a Trusted Types policy internally within
 * Angular. It lazily constructs the Trusted Types policy, providing helper
 * utilities for promoting strings to Trusted Types. When Trusted Types are not
 * available, strings are used as a fallback.
 * @security All use of this module is security-sensitive and should go through
 * security review.
 */
/**
 * The Trusted Types policy, or null if Trusted Types are not
 * enabled/supported, or undefined if the policy has not been created yet.
 */
let policy$1;
/**
 * Returns the Trusted Types policy, or null if Trusted Types are not
 * enabled/supported. The first call to this function will create the policy.
 */
function getPolicy$1() {
  if (policy$1 === undefined) {
    policy$1 = null;
    if (_global.trustedTypes) {
      try {
        policy$1 = _global.trustedTypes.createPolicy('angular', {
          createHTML: s => s,
          createScript: s => s,
          createScriptURL: s => s
        });
      } catch {
        // trustedTypes.createPolicy throws if called with a name that is
        // already registered, even in report-only mode. Until the API changes,
        // catch the error not to break the applications functionally. In such
        // cases, the code will fall back to using strings.
      }
    }
  }
  return policy$1;
}
/**
 * Unsafely promote a string to a TrustedHTML, falling back to strings when
 * Trusted Types are not available.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that the
 * provided string will never cause an XSS vulnerability if used in a context
 * that will be interpreted as HTML by a browser, e.g. when assigning to
 * element.innerHTML.
 */
function trustedHTMLFromString(html) {
  return getPolicy$1()?.createHTML(html) || html;
}
/**
 * Unsafely promote a string to a TrustedScript, falling back to strings when
 * Trusted Types are not available.
 * @security In particular, it must be assured that the provided string will
 * never cause an XSS vulnerability if used in a context that will be
 * interpreted and executed as a script by a browser, e.g. when calling eval.
 */
function trustedScriptFromString(script) {
  return getPolicy$1()?.createScript(script) || script;
}
/**
 * Unsafely promote a string to a TrustedScriptURL, falling back to strings
 * when Trusted Types are not available.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that the
 * provided string will never cause an XSS vulnerability if used in a context
 * that will cause a browser to load and execute a resource, e.g. when
 * assigning to script.src.
 */
function trustedScriptURLFromString(url) {
  return getPolicy$1()?.createScriptURL(url) || url;
}
/**
 * Unsafely call the Function constructor with the given string arguments. It
 * is only available in development mode, and should be stripped out of
 * production code.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that it
 * is only called from development code, as use in production code can lead to
 * XSS vulnerabilities.
 */
function newTrustedFunctionForDev(...args) {
  if (typeof ngDevMode === 'undefined') {
    throw new Error('newTrustedFunctionForDev should never be called in production');
  }
  if (!_global.trustedTypes) {
    // In environments that don't support Trusted Types, fall back to the most
    // straightforward implementation:
    return new Function(...args);
  }
  // Chrome currently does not support passing TrustedScript to the Function
  // constructor. The following implements the workaround proposed on the page
  // below, where the Chromium bug is also referenced:
  // https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor
  const fnArgs = args.slice(0, -1).join(',');
  const fnBody = args[args.length - 1];
  const body = `(function anonymous(${fnArgs}
) { ${fnBody}
})`;
  // Using eval directly confuses the compiler and prevents this module from
  // being stripped out of JS binaries even if not used. The global['eval']
  // indirection fixes that.
  const fn = _global['eval'](trustedScriptFromString(body));
  if (fn.bind === undefined) {
    // Workaround for a browser bug that only exists in Chrome 83, where passing
    // a TrustedScript to eval just returns the TrustedScript back without
    // evaluating it. In that case, fall back to the most straightforward
    // implementation:
    return new Function(...args);
  }
  // To completely mimic the behavior of calling "new Function", two more
  // things need to happen:
  // 1. Stringifying the resulting function should return its source code
  fn.toString = () => body;
  // 2. When calling the resulting function, `this` should refer to `global`
  return fn.bind(_global);
  // When Trusted Types support in Function constructors is widely available,
  // the implementation of this function can be simplified to:
  // return new Function(...args.map(a => trustedScriptFromString(a)));
}

/**
 * @fileoverview
 * A module to facilitate use of a Trusted Types policy internally within
 * Angular specifically for bypassSecurityTrust* and custom sanitizers. It
 * lazily constructs the Trusted Types policy, providing helper utilities for
 * promoting strings to Trusted Types. When Trusted Types are not available,
 * strings are used as a fallback.
 * @security All use of this module is security-sensitive and should go through
 * security review.
 */
/**
 * The Trusted Types policy, or null if Trusted Types are not
 * enabled/supported, or undefined if the policy has not been created yet.
 */
let policy;
/**
 * Returns the Trusted Types policy, or null if Trusted Types are not
 * enabled/supported. The first call to this function will create the policy.
 */
function getPolicy() {
  if (policy === undefined) {
    policy = null;
    if (_global.trustedTypes) {
      try {
        policy = _global.trustedTypes.createPolicy('angular#unsafe-bypass', {
          createHTML: s => s,
          createScript: s => s,
          createScriptURL: s => s
        });
      } catch {
        // trustedTypes.createPolicy throws if called with a name that is
        // already registered, even in report-only mode. Until the API changes,
        // catch the error not to break the applications functionally. In such
        // cases, the code will fall back to using strings.
      }
    }
  }
  return policy;
}
/**
 * Unsafely promote a string to a TrustedHTML, falling back to strings when
 * Trusted Types are not available.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that it
 * is only passed strings that come directly from custom sanitizers or the
 * bypassSecurityTrust* functions.
 */
function trustedHTMLFromStringBypass(html) {
  return getPolicy()?.createHTML(html) || html;
}
/**
 * Unsafely promote a string to a TrustedScript, falling back to strings when
 * Trusted Types are not available.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that it
 * is only passed strings that come directly from custom sanitizers or the
 * bypassSecurityTrust* functions.
 */
function trustedScriptFromStringBypass(script) {
  return getPolicy()?.createScript(script) || script;
}
/**
 * Unsafely promote a string to a TrustedScriptURL, falling back to strings
 * when Trusted Types are not available.
 * @security This is a security-sensitive function; any use of this function
 * must go through security review. In particular, it must be assured that it
 * is only passed strings that come directly from custom sanitizers or the
 * bypassSecurityTrust* functions.
 */
function trustedScriptURLFromStringBypass(url) {
  return getPolicy()?.createScriptURL(url) || url;
}
class SafeValueImpl {
  changingThisBreaksApplicationSecurity;
  constructor(changingThisBreaksApplicationSecurity) {
    this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
  }
  toString() {
    return `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` + ` (see ${XSS_SECURITY_URL})`;
  }
}
class SafeHtmlImpl extends SafeValueImpl {
  getTypeName() {
    return "HTML" /* BypassType.Html */;
  }
}
class SafeStyleImpl extends SafeValueImpl {
  getTypeName() {
    return "Style" /* BypassType.Style */;
  }
}
class SafeScriptImpl extends SafeValueImpl {
  getTypeName() {
    return "Script" /* BypassType.Script */;
  }
}
class SafeUrlImpl extends SafeValueImpl {
  getTypeName() {
    return "URL" /* BypassType.Url */;
  }
}
class SafeResourceUrlImpl extends SafeValueImpl {
  getTypeName() {
    return "ResourceURL" /* BypassType.ResourceUrl */;
  }
}
function unwrapSafeValue(value) {
  return value instanceof SafeValueImpl ? value.changingThisBreaksApplicationSecurity : value;
}
function allowSanitizationBypassAndThrow(value, type) {
  const actualType = getSanitizationBypassType(value);
  if (actualType != null && actualType !== type) {
    // Allow ResourceURLs in URL contexts, they are strictly more trusted.
    if (actualType === "ResourceURL" /* BypassType.ResourceUrl */ && type === "URL" /* BypassType.Url */) return true;
    throw new Error(`Required a safe ${type}, got a ${actualType} (see ${XSS_SECURITY_URL})`);
  }
  return actualType === type;
}
function getSanitizationBypassType(value) {
  return value instanceof SafeValueImpl && value.getTypeName() || null;
}
/**
 * Mark `html` string as trusted.
 *
 * This function wraps the trusted string in `String` and brands it in a way which makes it
 * recognizable to {@link htmlSanitizer} to be trusted implicitly.
 *
 * @param trustedHtml `html` string which needs to be implicitly trusted.
 * @returns a `html` which has been branded to be implicitly trusted.
 */
function bypassSanitizationTrustHtml(trustedHtml) {
  return new SafeHtmlImpl(trustedHtml);
}
/**
 * Mark `style` string as trusted.
 *
 * This function wraps the trusted string in `String` and brands it in a way which makes it
 * recognizable to {@link styleSanitizer} to be trusted implicitly.
 *
 * @param trustedStyle `style` string which needs to be implicitly trusted.
 * @returns a `style` hich has been branded to be implicitly trusted.
 */
function bypassSanitizationTrustStyle(trustedStyle) {
  return new SafeStyleImpl(trustedStyle);
}
/**
 * Mark `script` string as trusted.
 *
 * This function wraps the trusted string in `String` and brands it in a way which makes it
 * recognizable to {@link scriptSanitizer} to be trusted implicitly.
 *
 * @param trustedScript `script` string which needs to be implicitly trusted.
 * @returns a `script` which has been branded to be implicitly trusted.
 */
function bypassSanitizationTrustScript(trustedScript) {
  return new SafeScriptImpl(trustedScript);
}
/**
 * Mark `url` string as trusted.
 *
 * This function wraps the trusted string in `String` and brands it in a way which makes it
 * recognizable to {@link urlSanitizer} to be trusted implicitly.
 *
 * @param trustedUrl `url` string which needs to be implicitly trusted.
 * @returns a `url`  which has been branded to be implicitly trusted.
 */
function bypassSanitizationTrustUrl(trustedUrl) {
  return new SafeUrlImpl(trustedUrl);
}
/**
 * Mark `url` string as trusted.
 *
 * This function wraps the trusted string in `String` and brands it in a way which makes it
 * recognizable to {@link resourceUrlSanitizer} to be trusted implicitly.
 *
 * @param trustedResourceUrl `url` string which needs to be implicitly trusted.
 * @returns a `url` which has been branded to be implicitly trusted.
 */
function bypassSanitizationTrustResourceUrl(trustedResourceUrl) {
  return new SafeResourceUrlImpl(trustedResourceUrl);
}

/**
 * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML
 * that needs sanitizing.
 * Depending upon browser support we use one of two strategies for doing this.
 * Default: DOMParser strategy
 * Fallback: InertDocument strategy
 */
function getInertBodyHelper(defaultDoc) {
  const inertDocumentHelper = new InertDocumentHelper(defaultDoc);
  return isDOMParserAvailable() ? new DOMParserHelper(inertDocumentHelper) : inertDocumentHelper;
}
/**
 * Uses DOMParser to create and fill an inert body element.
 * This is the default strategy used in browsers that support it.
 */
class DOMParserHelper {
  inertDocumentHelper;
  constructor(inertDocumentHelper) {
    this.inertDocumentHelper = inertDocumentHelper;
  }
  getInertBodyElement(html) {
    // We add these extra elements to ensure that the rest of the content is parsed as expected
    // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
    // `<head>` tag. Note that the `<body>` tag is closed implicitly to prevent unclosed tags
    // in `html` from consuming the otherwise explicit `</body>` tag.
    html = '<body><remove></remove>' + html;
    try {
      const body = new window.DOMParser().parseFromString(trustedHTMLFromString(html), 'text/html').body;
      if (body === null) {
        // In some browsers (e.g. Mozilla/5.0 iPad AppleWebKit Mobile) the `body` property only
        // becomes available in the following tick of the JS engine. In that case we fall back to
        // the `inertDocumentHelper` instead.
        return this.inertDocumentHelper.getInertBodyElement(html);
      }
      body.firstChild?.remove();
      return body;
    } catch {
      return null;
    }
  }
}
/**
 * Use an HTML5 `template` element to create and fill an inert DOM element.
 * This is the fallback strategy if the browser does not support DOMParser.
 */
class InertDocumentHelper {
  defaultDoc;
  inertDocument;
  constructor(defaultDoc) {
    this.defaultDoc = defaultDoc;
    this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
  }
  getInertBodyElement(html) {
    const templateEl = this.inertDocument.createElement('template');
    templateEl.innerHTML = trustedHTMLFromString(html);
    return templateEl;
  }
}
/**
 * We need to determine whether the DOMParser exists in the global context and
 * supports parsing HTML; HTML parsing support is not as wide as other formats, see
 * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility.
 *
 * @suppress {uselessCode}
 */
function isDOMParserAvailable() {
  try {
    return !!new window.DOMParser().parseFromString(trustedHTMLFromString(''), 'text/html');
  } catch {
    return false;
  }
}

/**
 * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation
 * contexts.
 *
 * This regular expression matches a subset of URLs that will not cause script
 * execution if used in URL context within a HTML document. Specifically, this
 * regular expression matches if:
 * (1) Either a protocol that is not javascript:, and that has valid characters
 *     (alphanumeric or [+-.]).
 * (2) or no protocol.  A protocol must be followed by a colon. The below
 *     allows that by allowing colons only after one of the characters [/?#].
 *     A colon after a hash (#) must be in the fragment.
 *     Otherwise, a colon after a (?) must be in a query.
 *     Otherwise, a colon after a single solidus (/) must be in a path.
 *     Otherwise, a colon after a double solidus (//) must be in the authority
 *     (before port).
 *
 * The pattern disallows &, used in HTML entity declarations before
 * one of the characters in [/?#]. This disallows HTML entities used in the
 * protocol name, which should never happen, e.g. "h&#116;tp" for "http".
 * It also disallows HTML entities in the first path part of a relative path,
 * e.g. "foo&lt;bar/baz".  Our existing escaping functions should not produce
 * that. More importantly, it disallows masking of a colon,
 * e.g. "javascript&#58;...".
 *
 * This regular expression was taken from the Closure sanitization library.
 */
const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:\/?#]*(?:[\/?#]|$))/i;
function _sanitizeUrl(url) {
  url = String(url);
  if (url.match(SAFE_URL_PATTERN)) return url;
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    console.warn(`WARNING: sanitizing unsafe URL value ${url} (see ${XSS_SECURITY_URL})`);
  }
  return 'unsafe:' + url;
}
function tagSet(tags) {
  const res = {};
  for (const t of tags.split(',')) res[t] = true;
  return res;
}
function merge(...sets) {
  const res = {};
  for (const s of sets) {
    for (const v in s) {
      if (s.hasOwnProperty(v)) res[v] = true;
    }
  }
  return res;
}
// Good source of info about elements and attributes
// https://html.spec.whatwg.org/#semantics
// https://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// https://html.spec.whatwg.org/#void-elements
const VOID_ELEMENTS = /*#__PURE__*/tagSet('area,br,col,hr,img,wbr');
// Elements that you can, intentionally, leave open (and which close themselves)
// https://html.spec.whatwg.org/#optional-tags
const OPTIONAL_END_TAG_BLOCK_ELEMENTS = /*#__PURE__*/tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
const OPTIONAL_END_TAG_INLINE_ELEMENTS = /*#__PURE__*/tagSet('rp,rt');
const OPTIONAL_END_TAG_ELEMENTS = /*#__PURE__*/merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
// Safe Block Elements - HTML5
const BLOCK_ELEMENTS = /*#__PURE__*/merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, /*#__PURE__*/tagSet('address,article,' + 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
// Inline Elements - HTML5
const INLINE_ELEMENTS = /*#__PURE__*/merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, /*#__PURE__*/tagSet('a,abbr,acronym,audio,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' + 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
const VALID_ELEMENTS = /*#__PURE__*/merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
// Attributes that have href and hence need to be sanitized
const URI_ATTRS = /*#__PURE__*/tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
const HTML_ATTRS = /*#__PURE__*/tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' + 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' + 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' + 'scope,scrolling,shape,size,sizes,span,srclang,srcset,start,summary,tabindex,target,title,translate,type,usemap,' + 'valign,value,vspace,width');
// Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
const ARIA_ATTRS = /*#__PURE__*/tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' + 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' + 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' + 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' + 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' + 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' + 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
// NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
// issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
// innerHTML is required, SVG attributes should be added here.
// NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
// can be sanitized, but they increase security surface area without a legitimate use case, so they
// are left out here.
const VALID_ATTRS = /*#__PURE__*/merge(URI_ATTRS, HTML_ATTRS, ARIA_ATTRS);
// Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
//
// Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
// `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
// don't want to preserve the content, if the elements themselves are going to be removed.
const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = /*#__PURE__*/tagSet('script,style,template');
/**
 * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
 * attributes.
 */
class SanitizingHtmlSerializer {
  // Explicitly track if something was stripped, to avoid accidentally warning of sanitization just
  // because characters were re-encoded.
  sanitizedSomething = false;
  buf = [];
  sanitizeChildren(el) {
    // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
    // However this code never accesses properties off of `document` before deleting its contents
    // again, so it shouldn't be vulnerable to DOM clobbering.
    let current = el.firstChild;
    let traverseContent = true;
    let parentNodes = [];
    while (current) {
      if (current.nodeType === Node.ELEMENT_NODE) {
        traverseContent = this.startElement(current);
      } else if (current.nodeType === Node.TEXT_NODE) {
        this.chars(current.nodeValue);
      } else {
        // Strip non-element, non-text nodes.
        this.sanitizedSomething = true;
      }
      if (traverseContent && current.firstChild) {
        // Push current node to the parent stack before entering its content.
        parentNodes.push(current);
        current = getFirstChild(current);
        continue;
      }
      while (current) {
        // Leaving the element.
        // Walk up and to the right, closing tags as we go.
        if (current.nodeType === Node.ELEMENT_NODE) {
          this.endElement(current);
        }
        let next = getNextSibling(current);
        if (next) {
          current = next;
          break;
        }
        // There was no next sibling, walk up to the parent node (extract it from the stack).
        current = parentNodes.pop();
      }
    }
    return this.buf.join('');
  }
  /**
   * Sanitizes an opening element tag (if valid) and returns whether the element's contents should
   * be traversed. Element content must always be traversed (even if the element itself is not
   * valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`.
   *
   * @param element The element to sanitize.
   * @return True if the element's contents should be traversed.
   */
  startElement(element) {
    const tagName = getNodeName(element).toLowerCase();
    if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
      this.sanitizedSomething = true;
      return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName);
    }
    this.buf.push('<');
    this.buf.push(tagName);
    const elAttrs = element.attributes;
    for (let i = 0; i < elAttrs.length; i++) {
      const elAttr = elAttrs.item(i);
      const attrName = elAttr.name;
      const lower = attrName.toLowerCase();
      if (!VALID_ATTRS.hasOwnProperty(lower)) {
        this.sanitizedSomething = true;
        continue;
      }
      let value = elAttr.value;
      // TODO(martinprobst): Special case image URIs for data:image/...
      if (URI_ATTRS[lower]) value = _sanitizeUrl(value);
      this.buf.push(' ', attrName, '="', encodeEntities(value), '"');
    }
    this.buf.push('>');
    return true;
  }
  endElement(current) {
    const tagName = getNodeName(current).toLowerCase();
    if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
      this.buf.push('</');
      this.buf.push(tagName);
      this.buf.push('>');
    }
  }
  chars(chars) {
    this.buf.push(encodeEntities(chars));
  }
}
/**
 * Verifies whether a given child node is a descendant of a given parent node.
 * It may not be the case when properties like `.firstChild` are clobbered and
 * accessing `.firstChild` results in an unexpected node returned.
 */
function isClobberedElement(parentNode, childNode) {
  return (parentNode.compareDocumentPosition(childNode) & Node.DOCUMENT_POSITION_CONTAINED_BY) !== Node.DOCUMENT_POSITION_CONTAINED_BY;
}
/**
 * Retrieves next sibling node and makes sure that there is no
 * clobbering of the `nextSibling` property happening.
 */
function getNextSibling(node) {
  const nextSibling = node.nextSibling;
  // Make sure there is no `nextSibling` clobbering: navigating to
  // the next sibling and going back to the previous one should result
  // in the original node.
  if (nextSibling && node !== nextSibling.previousSibling) {
    throw clobberedElementError(nextSibling);
  }
  return nextSibling;
}
/**
 * Retrieves first child node and makes sure that there is no
 * clobbering of the `firstChild` property happening.
 */
function getFirstChild(node) {
  const firstChild = node.firstChild;
  if (firstChild && isClobberedElement(node, firstChild)) {
    throw clobberedElementError(firstChild);
  }
  return firstChild;
}
/** Gets a reasonable nodeName, even for clobbered nodes. */
function getNodeName(node) {
  const nodeName = node.nodeName;
  // If the property is clobbered, assume it is an `HTMLFormElement`.
  return typeof nodeName === 'string' ? nodeName : 'FORM';
}
function clobberedElementError(node) {
  return new Error(`Failed to sanitize html because the element is clobbered: ${node.outerHTML}`);
}
// Regular Expressions for parsing tags and attributes
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// ! to ~ is the ASCII range.
const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
/**
 * Escapes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 */
function encodeEntities(value) {
  return value.replace(/&/g, '&amp;').replace(SURROGATE_PAIR_REGEXP, function (match) {
    const hi = match.charCodeAt(0);
    const low = match.charCodeAt(1);
    return '&#' + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ';';
  }).replace(NON_ALPHANUMERIC_REGEXP, function (match) {
    return '&#' + match.charCodeAt(0) + ';';
  }).replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
let inertBodyHelper;
/**
 * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
 * the DOM in a browser environment.
 */
function _sanitizeHtml(defaultDoc, unsafeHtmlInput) {
  let inertBodyElement = null;
  try {
    inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc);
    // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
    let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
    inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
    // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
    // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
    let mXSSAttempts = 5;
    let parsedHtml = unsafeHtml;
    do {
      if (mXSSAttempts === 0) {
        throw new Error('Failed to sanitize html because the input is unstable');
      }
      mXSSAttempts--;
      unsafeHtml = parsedHtml;
      parsedHtml = inertBodyElement.innerHTML;
      inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
    } while (unsafeHtml !== parsedHtml);
    const sanitizer = new SanitizingHtmlSerializer();
    const safeHtml = sanitizer.sanitizeChildren(getTemplateContent(inertBodyElement) || inertBodyElement);
    if ((typeof ngDevMode === 'undefined' || ngDevMode) && sanitizer.sanitizedSomething) {
      console.warn(`WARNING: sanitizing HTML stripped some content, see ${XSS_SECURITY_URL}`);
    }
    return trustedHTMLFromString(safeHtml);
  } finally {
    // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
    if (inertBodyElement) {
      const parent = getTemplateContent(inertBodyElement) || inertBodyElement;
      while (parent.firstChild) {
        parent.firstChild.remove();
      }
    }
  }
}
function getTemplateContent(el) {
  return 'content' in el /** Microsoft/TypeScript#21517 */ && isTemplateElement(el) ? el.content : null;
}
function isTemplateElement(el) {
  return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE';
}

/**
 * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property
 * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly
 * handled.
 *
 * See DomSanitizer for more details on security in Angular applications.
 *
 * @publicApi
 */
var SecurityContext = /*#__PURE__*/function (SecurityContext) {
  SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  SecurityContext[SecurityContext["URL"] = 4] = "URL";
  SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  return SecurityContext;
}(SecurityContext || {});
/**
 * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
 * dangerous content.
 *
 * This method parses the `html` and locates potentially dangerous content (such as urls and
 * javascript) and removes it.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}.
 *
 * @param unsafeHtml untrusted `html`, typically from the user.
 * @returns `html` string which is safe to display to user, because all of the dangerous javascript
 * and urls have been removed.
 *
 * @codeGenApi
 */
function ɵɵsanitizeHtml(unsafeHtml) {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedHTMLFromStringBypass(sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeHtml, "HTML" /* BypassType.Html */)) {
    return trustedHTMLFromStringBypass(unwrapSafeValue(unsafeHtml));
  }
  return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
}
/**
 * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
 * dangerous content.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}.
 *
 * @param unsafeStyle untrusted `style`, typically from the user.
 * @returns `style` string which is safe to bind to the `style` properties.
 *
 * @codeGenApi
 */
function ɵɵsanitizeStyle(unsafeStyle) {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
  }
  if (allowSanitizationBypassAndThrow(unsafeStyle, "Style" /* BypassType.Style */)) {
    return unwrapSafeValue(unsafeStyle);
  }
  return renderStringify(unsafeStyle);
}
/**
 * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
 * dangerous
 * content.
 *
 * This method parses the `url` and locates potentially dangerous content (such as javascript) and
 * removes it.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}.
 *
 * @param unsafeUrl untrusted `url`, typically from the user.
 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
 * all of the dangerous javascript has been removed.
 *
 * @codeGenApi
 */
function ɵɵsanitizeUrl(unsafeUrl) {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
  }
  if (allowSanitizationBypassAndThrow(unsafeUrl, "URL" /* BypassType.Url */)) {
    return unwrapSafeValue(unsafeUrl);
  }
  return _sanitizeUrl(renderStringify(unsafeUrl));
}
/**
 * A `url` sanitizer which only lets trusted `url`s through.
 *
 * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}.
 *
 * @param unsafeResourceUrl untrusted `url`, typically from the user.
 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
 * only trusted `url`s have been allowed to pass.
 *
 * @codeGenApi
 */
function ɵɵsanitizeResourceUrl(unsafeResourceUrl) {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedScriptURLFromStringBypass(sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeResourceUrl, "ResourceURL" /* BypassType.ResourceUrl */)) {
    return trustedScriptURLFromStringBypass(unwrapSafeValue(unsafeResourceUrl));
  }
  throw new RuntimeError(904 /* RuntimeErrorCode.UNSAFE_VALUE_IN_RESOURCE_URL */, ngDevMode && `unsafe value used in a resource URL context (see ${XSS_SECURITY_URL})`);
}
/**
 * A `script` sanitizer which only lets trusted javascript through.
 *
 * This passes only `script`s marked trusted by calling {@link
 * bypassSanitizationTrustScript}.
 *
 * @param unsafeScript untrusted `script`, typically from the user.
 * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`,
 * because only trusted `scripts` have been allowed to pass.
 *
 * @codeGenApi
 */
function ɵɵsanitizeScript(unsafeScript) {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedScriptFromStringBypass(sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeScript, "Script" /* BypassType.Script */)) {
    return trustedScriptFromStringBypass(unwrapSafeValue(unsafeScript));
  }
  throw new RuntimeError(905 /* RuntimeErrorCode.UNSAFE_VALUE_IN_SCRIPT */, ngDevMode && 'unsafe value used in a script context');
}
/**
 * A template tag function for promoting the associated constant literal to a
 * TrustedHTML. Interpolation is explicitly not allowed.
 *
 * @param html constant template literal containing trusted HTML.
 * @returns TrustedHTML wrapping `html`.
 *
 * @security This is a security-sensitive function and should only be used to
 * convert constant values of attributes and properties found in
 * application-provided Angular templates to TrustedHTML.
 *
 * @codeGenApi
 */
function ɵɵtrustConstantHtml(html) {
  // The following runtime check ensures that the function was called as a
  // template tag (e.g. ɵɵtrustConstantHtml`content`), without any interpolation
  // (e.g. not ɵɵtrustConstantHtml`content ${variable}`). A TemplateStringsArray
  // is an array with a `raw` property that is also an array. The associated
  // template literal has no interpolation if and only if the length of the
  // TemplateStringsArray is 1.
  if (ngDevMode && (!Array.isArray(html) || !Array.isArray(html.raw) || html.length !== 1)) {
    throw new Error(`Unexpected interpolation in trusted HTML constant: ${html.join('?')}`);
  }
  return trustedHTMLFromString(html[0]);
}
/**
 * A template tag function for promoting the associated constant literal to a
 * TrustedScriptURL. Interpolation is explicitly not allowed.
 *
 * @param url constant template literal containing a trusted script URL.
 * @returns TrustedScriptURL wrapping `url`.
 *
 * @security This is a security-sensitive function and should only be used to
 * convert constant values of attributes and properties found in
 * application-provided Angular templates to TrustedScriptURL.
 *
 * @codeGenApi
 */
function ɵɵtrustConstantResourceUrl(url) {
  // The following runtime check ensures that the function was called as a
  // template tag (e.g. ɵɵtrustConstantResourceUrl`content`), without any
  // interpolation (e.g. not ɵɵtrustConstantResourceUrl`content ${variable}`). A
  // TemplateStringsArray is an array with a `raw` property that is also an
  // array. The associated template literal has no interpolation if and only if
  // the length of the TemplateStringsArray is 1.
  if (ngDevMode && (!Array.isArray(url) || !Array.isArray(url.raw) || url.length !== 1)) {
    throw new Error(`Unexpected interpolation in trusted URL constant: ${url.join('?')}`);
  }
  return trustedScriptURLFromString(url[0]);
}
/**
 * Detects which sanitizer to use for URL property, based on tag name and prop name.
 *
 * The rules are based on the RESOURCE_URL context config from
 * `packages/compiler/src/schema/dom_security_schema.ts`.
 * If tag and prop names don't match Resource URL schema, use URL sanitizer.
 */
function getUrlSanitizer(tag, prop) {
  if (prop === 'src' && (tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' || tag === 'script') || prop === 'href' && (tag === 'base' || tag === 'link')) {
    return ɵɵsanitizeResourceUrl;
  }
  return ɵɵsanitizeUrl;
}
/**
 * Sanitizes URL, selecting sanitizer function based on tag and property names.
 *
 * This function is used in case we can't define security context at compile time, when only prop
 * name is available. This happens when we generate host bindings for Directives/Components. The
 * host element is unknown at compile time, so we defer calculation of specific sanitizer to
 * runtime.
 *
 * @param unsafeUrl untrusted `url`, typically from the user.
 * @param tag target element tag name.
 * @param prop name of the property that contains the value.
 * @returns `url` string which is safe to bind.
 *
 * @codeGenApi
 */
function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl, tag, prop) {
  return getUrlSanitizer(tag, prop)(unsafeUrl);
}
function validateAgainstEventProperties(name) {
  if (name.toLowerCase().startsWith('on')) {
    const errorMessage = `Binding to event property '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...` + `\nIf '${name}' is a directive input, make sure the directive is imported by the` + ` current module.`;
    throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  }
}
function validateAgainstEventAttributes(name) {
  if (name.toLowerCase().startsWith('on')) {
    const errorMessage = `Binding to event attribute '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...`;
    throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  }
}
function getSanitizer() {
  const lView = getLView();
  return lView && lView[ENVIRONMENT].sanitizer;
}

/**
 * Disallowed strings in the comment.
 *
 * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
 */
const COMMENT_DISALLOWED = /^>|^->|<!--|-->|--!>|<!-$/g;
/**
 * Delimiter in the disallowed strings which needs to be wrapped with zero with character.
 */
const COMMENT_DELIMITER = /(<|>)/g;
const COMMENT_DELIMITER_ESCAPED = '\u200B$1\u200B';
/**
 * Escape the content of comment strings so that it can be safely inserted into a comment node.
 *
 * The issue is that HTML does not specify any way to escape comment end text inside the comment.
 * Consider: `<!-- The way you close a comment is with ">", and "->" at the beginning or by "-->" or
 * "--!>" at the end. -->`. Above the `"-->"` is meant to be text not an end to the comment. This
 * can be created programmatically through DOM APIs. (`<!--` are also disallowed.)
 *
 * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
 *
 * ```
 * div.innerHTML = div.innerHTML
 * ```
 *
 * One would expect that the above code would be safe to do, but it turns out that because comment
 * text is not escaped, the comment may contain text which will prematurely close the comment
 * opening up the application for XSS attack. (In SSR we programmatically create comment nodes which
 * may contain such text and expect them to be safe.)
 *
 * This function escapes the comment text by looking for comment delimiters (`<` and `>`) and
 * surrounding them with `_>_` where the `_` is a zero width space `\u200B`. The result is that if a
 * comment contains any of the comment start/end delimiters (such as `<!--`, `-->` or `--!>`) the
 * text it will render normally but it will not cause the HTML parser to close/open the comment.
 *
 * @param value text to make safe for comment node by escaping the comment open/close character
 *     sequence.
 */
function escapeCommentText(value) {
  return value.replace(COMMENT_DISALLOWED, text => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED));
}
function normalizeDebugBindingName(name) {
  // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
  name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
  return `ng-reflect-${name}`;
}
const CAMEL_CASE_REGEXP = /([A-Z])/g;
function camelCaseToDashCase(input) {
  return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
}
function normalizeDebugBindingValue(value) {
  try {
    // Limit the size of the value as otherwise the DOM just gets polluted.
    return value != null ? value.toString().slice(0, 30) : value;
  } catch (e) {
    return '[ERROR] Exception while trying to serialize the value';
  }
}

/**
 * Defines a schema that allows an NgModule to contain the following:
 * - Non-Angular elements named with dash case (`-`).
 * - Element properties named with dash case (`-`).
 * Dash case is the naming convention for custom elements.
 *
 * @publicApi
 */
const CUSTOM_ELEMENTS_SCHEMA = {
  name: 'custom-elements'
};
/**
 * Defines a schema that allows any property on any element.
 *
 * This schema allows you to ignore the errors related to any unknown elements or properties in a
 * template. The usage of this schema is generally discouraged because it prevents useful validation
 * and may hide real errors in your template. Consider using the `CUSTOM_ELEMENTS_SCHEMA` instead.
 *
 * @publicApi
 */
const NO_ERRORS_SCHEMA = {
  name: 'no-errors-schema'
};
let shouldThrowErrorOnUnknownElement = false;
/**
 * Sets a strict mode for JIT-compiled components to throw an error on unknown elements,
 * instead of just logging the error.
 * (for AOT-compiled ones this check happens at build time).
 */
function ɵsetUnknownElementStrictMode(shouldThrow) {
  shouldThrowErrorOnUnknownElement = shouldThrow;
}
/**
 * Gets the current value of the strict mode.
 */
function ɵgetUnknownElementStrictMode() {
  return shouldThrowErrorOnUnknownElement;
}
let shouldThrowErrorOnUnknownProperty = false;
/**
 * Sets a strict mode for JIT-compiled components to throw an error on unknown properties,
 * instead of just logging the error.
 * (for AOT-compiled ones this check happens at build time).
 */
function ɵsetUnknownPropertyStrictMode(shouldThrow) {
  shouldThrowErrorOnUnknownProperty = shouldThrow;
}
/**
 * Gets the current value of the strict mode.
 */
function ɵgetUnknownPropertyStrictMode() {
  return shouldThrowErrorOnUnknownProperty;
}
/**
 * Validates that the element is known at runtime and produces
 * an error if it's not the case.
 * This check is relevant for JIT-compiled components (for AOT-compiled
 * ones this check happens at build time).
 *
 * The element is considered known if either:
 * - it's a known HTML element
 * - it's a known custom element
 * - the element matches any directive
 * - the element is allowed by one of the schemas
 *
 * @param element Element to validate
 * @param lView An `LView` that represents a current component that is being rendered
 * @param tagName Name of the tag to check
 * @param schemas Array of schemas
 * @param hasDirectives Boolean indicating that the element matches any directive
 */
function validateElementIsKnown(element, lView, tagName, schemas, hasDirectives) {
  // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  // execute the check below.
  if (schemas === null) return;
  // If the element matches any directive, it's considered as valid.
  if (!hasDirectives && tagName !== null) {
    // The element is unknown if it's an instance of HTMLUnknownElement, or it isn't registered
    // as a custom element. Note that unknown elements with a dash in their name won't be instances
    // of HTMLUnknownElement in browsers that support web components.
    const isUnknown =
    // Note that we can't check for `typeof HTMLUnknownElement === 'function'` because
    // Domino doesn't expose HTMLUnknownElement globally.
    typeof HTMLUnknownElement !== 'undefined' && HTMLUnknownElement && element instanceof HTMLUnknownElement || typeof customElements !== 'undefined' && tagName.indexOf('-') > -1 && !customElements.get(tagName);
    if (isUnknown && !matchingSchemas(schemas, tagName)) {
      const isHostStandalone = isHostComponentStandalone(lView);
      const templateLocation = getTemplateLocationDetails(lView);
      const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
      let message = `'${tagName}' is not a known element${templateLocation}:\n`;
      message += `1. If '${tagName}' is an Angular component, then verify that it is ${isHostStandalone ? "included in the '@Component.imports' of this component" : 'a part of an @NgModule where this component is declared'}.\n`;
      if (tagName && tagName.indexOf('-') > -1) {
        message += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`;
      } else {
        message += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`;
      }
      if (shouldThrowErrorOnUnknownElement) {
        throw new RuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message);
      } else {
        console.error(formatRuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message));
      }
    }
  }
}
/**
 * Validates that the property of the element is known at runtime and returns
 * false if it's not the case.
 * This check is relevant for JIT-compiled components (for AOT-compiled
 * ones this check happens at build time).
 *
 * The property is considered known if either:
 * - it's a known property of the element
 * - the element is allowed by one of the schemas
 * - the property is used for animations
 *
 * @param element Element to validate
 * @param propName Name of the property to check
 * @param tagName Name of the tag hosting the property
 * @param schemas Array of schemas
 */
function isPropertyValid(element, propName, tagName, schemas) {
  // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  // execute the check below.
  if (schemas === null) return true;
  // The property is considered valid if the element matches the schema, it exists on the element,
  // or it is synthetic.
  if (matchingSchemas(schemas, tagName) || propName in element || isAnimationProp(propName)) {
    return true;
  }
  // Note: `typeof Node` returns 'function' in most browsers, but is undefined with domino.
  return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
}
/**
 * Logs or throws an error that a property is not supported on an element.
 *
 * @param propName Name of the invalid property
 * @param tagName Name of the tag hosting the property
 * @param nodeType Type of the node hosting the property
 * @param lView An `LView` that represents a current component
 */
function handleUnknownPropertyError(propName, tagName, nodeType, lView) {
  // Special-case a situation when a structural directive is applied to
  // an `<ng-template>` element, for example: `<ng-template *ngIf="true">`.
  // In this case the compiler generates the `ɵɵtemplate` instruction with
  // the `null` as the tagName. The directive matching logic at runtime relies
  // on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
  // a default value of the `tNode.value` is not feasible at this moment.
  if (!tagName && nodeType === 4 /* TNodeType.Container */) {
    tagName = 'ng-template';
  }
  const isHostStandalone = isHostComponentStandalone(lView);
  const templateLocation = getTemplateLocationDetails(lView);
  let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
  const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
  const importLocation = isHostStandalone ? "included in the '@Component.imports' of this component" : 'a part of an @NgModule where this component is declared';
  if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
    // Most likely this is a control flow directive (such as `*ngIf`) used in
    // a template, but the directive or the `CommonModule` is not imported.
    const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
    message += `\nIf the '${propName}' is an Angular control flow directive, ` + `please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
  } else {
    // May be an Angular component, which is not imported/declared?
    message += `\n1. If '${tagName}' is an Angular component and it has the ` + `'${propName}' input, then verify that it is ${importLocation}.`;
    // May be a Web Component?
    if (tagName && tagName.indexOf('-') > -1) {
      message += `\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` + `to the ${schemas} of this component to suppress this message.`;
      message += `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` + `the ${schemas} of this component.`;
    } else {
      // If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
      message += `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` + `the ${schemas} of this component.`;
    }
  }
  reportUnknownPropertyError(message);
}
function reportUnknownPropertyError(message) {
  if (shouldThrowErrorOnUnknownProperty) {
    throw new RuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message);
  } else {
    console.error(formatRuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message));
  }
}
/**
 * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
 * and must **not** be used in production bundles. The function makes megamorphic reads, which might
 * be too slow for production mode and also it relies on the constructor function being available.
 *
 * Gets a reference to the host component def (where a current component is declared).
 *
 * @param lView An `LView` that represents a current component that is being rendered.
 */
function getDeclarationComponentDef(lView) {
  !ngDevMode && throwError('Must never be called in production mode');
  const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  const context = declarationLView[CONTEXT];
  // Unable to obtain a context.
  if (!context) return null;
  return context.constructor ? getComponentDef(context.constructor) : null;
}
/**
 * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
 * and must **not** be used in production bundles. The function makes megamorphic reads, which might
 * be too slow for production mode.
 *
 * Checks if the current component is declared inside of a standalone component template.
 *
 * @param lView An `LView` that represents a current component that is being rendered.
 */
function isHostComponentStandalone(lView) {
  !ngDevMode && throwError('Must never be called in production mode');
  const componentDef = getDeclarationComponentDef(lView);
  // Treat host component as non-standalone if we can't obtain the def.
  return !!componentDef?.standalone;
}
/**
 * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
 * and must **not** be used in production bundles. The function makes megamorphic reads, which might
 * be too slow for production mode.
 *
 * Constructs a string describing the location of the host component template. The function is used
 * in dev mode to produce error messages.
 *
 * @param lView An `LView` that represents a current component that is being rendered.
 */
function getTemplateLocationDetails(lView) {
  !ngDevMode && throwError('Must never be called in production mode');
  const hostComponentDef = getDeclarationComponentDef(lView);
  const componentClassName = hostComponentDef?.type?.name;
  return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
}
/**
 * The set of known control flow directives and their corresponding imports.
 * We use this set to produce a more precises error message with a note
 * that the `CommonModule` should also be included.
 */
const KNOWN_CONTROL_FLOW_DIRECTIVES = /*#__PURE__*/new Map([['ngIf', 'NgIf'], ['ngFor', 'NgFor'], ['ngSwitchCase', 'NgSwitchCase'], ['ngSwitchDefault', 'NgSwitchDefault']]);
/**
 * Returns true if the tag name is allowed by specified schemas.
 * @param schemas Array of schemas
 * @param tagName Name of the tag
 */
function matchingSchemas(schemas, tagName) {
  if (schemas !== null) {
    for (let i = 0; i < schemas.length; i++) {
      const schema = schemas[i];
      if (schema === NO_ERRORS_SCHEMA || schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1) {
        return true;
      }
    }
  }
  return false;
}

/**
 *
 * @codeGenApi
 */
function ɵɵresolveWindow(element) {
  return element.ownerDocument.defaultView;
}
/**
 *
 * @codeGenApi
 */
function ɵɵresolveDocument(element) {
  return element.ownerDocument;
}
/**
 *
 * @codeGenApi
 */
function ɵɵresolveBody(element) {
  return element.ownerDocument.body;
}
/**
 * The special delimiter we use to separate property names, prefixes, and suffixes
 * in property binding metadata. See storeBindingMetadata().
 *
 * We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
 * because it is a very uncommon character that is unlikely to be part of a user's
 * property names or interpolation strings. If it is in fact used in a property
 * binding, DebugElement.properties will not return the correct value for that
 * binding. However, there should be no runtime effect for real applications.
 *
 * This character is typically rendered as a question mark inside of a diamond.
 * See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
 *
 */
const INTERPOLATION_DELIMITER = `�`;
/**
 * Unwrap a value which might be behind a closure (for forward declaration reasons).
 */
function maybeUnwrapFn(value) {
  if (value instanceof Function) {
    return value();
  } else {
    return value;
  }
}

/**
 * The max length of the string representation of a value in an error message
 */
const VALUE_STRING_LENGTH_LIMIT = 200;
/** Verifies that a given type is a Standalone Component. */
function assertStandaloneComponentType(type) {
  assertComponentDef(type);
  const componentDef = getComponentDef(type);
  if (!componentDef.standalone) {
    throw new RuntimeError(907 /* RuntimeErrorCode.TYPE_IS_NOT_STANDALONE */, `The ${stringifyForError(type)} component is not marked as standalone, ` + `but Angular expects to have a standalone component here. ` + `Please make sure the ${stringifyForError(type)} component has ` + `the \`standalone: true\` flag in the decorator.`);
  }
}
/** Verifies whether a given type is a component */
function assertComponentDef(type) {
  if (!getComponentDef(type)) {
    throw new RuntimeError(906 /* RuntimeErrorCode.MISSING_GENERATED_DEF */, `The ${stringifyForError(type)} is not an Angular component, ` + `make sure it has the \`@Component\` decorator.`);
  }
}
/** Called when there are multiple component selectors that match a given node */
function throwMultipleComponentError(tNode, first, second) {
  throw new RuntimeError(-300 /* RuntimeErrorCode.MULTIPLE_COMPONENTS_MATCH */, `Multiple components match node with tagname ${tNode.value}: ` + `${stringifyForError(first)} and ` + `${stringifyForError(second)}`);
}
/** Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on. */
function throwErrorIfNoChangesMode(creationMode, oldValue, currValue, propName, lView) {
  const hostComponentDef = getDeclarationComponentDef(lView);
  const componentClassName = hostComponentDef?.type?.name;
  const field = propName ? ` for '${propName}'` : '';
  let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${formatValue(oldValue)}'. Current value: '${formatValue(currValue)}'.${componentClassName ? ` Expression location: ${componentClassName} component` : ''}`;
  if (creationMode) {
    msg += ` It seems like the view has been created after its parent and its children have been dirty checked.` + ` Has it been created in a change detection hook?`;
  }
  throw new RuntimeError(-100 /* RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED */, msg);
}
function formatValue(value) {
  let strValue = String(value);
  // JSON.stringify will throw on circular references
  try {
    if (Array.isArray(value) || strValue === '[object Object]') {
      strValue = JSON.stringify(value);
    }
  } catch (error) {}
  return strValue.length > VALUE_STRING_LENGTH_LIMIT ? strValue.substring(0, VALUE_STRING_LENGTH_LIMIT) + '…' : strValue;
}
function constructDetailsForInterpolation(lView, rootIndex, expressionIndex, meta, changedValue) {
  const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER);
  let oldValue = prefix,
    newValue = prefix;
  for (let i = 0; i < chunks.length; i++) {
    const slotIdx = rootIndex + i;
    oldValue += `${lView[slotIdx]}${chunks[i]}`;
    newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`;
  }
  return {
    propName,
    oldValue,
    newValue
  };
}
/**
 * Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError:
 * - property name (for property bindings or interpolations)
 * - old and new values, enriched using information from metadata
 *
 * More information on the metadata storage format can be found in `storePropertyBindingMetadata`
 * function description.
 */
function getExpressionChangedErrorDetails(lView, bindingIndex, oldValue, newValue) {
  const tData = lView[TVIEW].data;
  const metadata = tData[bindingIndex];
  if (typeof metadata === 'string') {
    // metadata for property interpolation
    if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) {
      return constructDetailsForInterpolation(lView, bindingIndex, bindingIndex, metadata, newValue);
    }
    // metadata for property binding
    return {
      propName: metadata,
      oldValue,
      newValue
    };
  }
  // metadata is not available for this expression, check if this expression is a part of the
  // property interpolation by going from the current binding index left and look for a string that
  // contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this:
  // [..., 'id�Prefix � and � suffix', null, null, null, ...]
  if (metadata === null) {
    let idx = bindingIndex - 1;
    while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) {
      idx--;
    }
    const meta = tData[idx];
    if (typeof meta === 'string') {
      const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g'));
      // first interpolation delimiter separates property name from interpolation parts (in case of
      // property interpolations), so we subtract one from total number of found delimiters
      if (matches && matches.length - 1 > bindingIndex - idx) {
        return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue);
      }
    }
  }
  return {
    propName: undefined,
    oldValue,
    newValue
  };
}

/** Flags describing an input for a directive. */
var InputFlags = /*#__PURE__*/function (InputFlags) {
  InputFlags[InputFlags["None"] = 0] = "None";
  InputFlags[InputFlags["SignalBased"] = 1] = "SignalBased";
  InputFlags[InputFlags["HasDecoratorInputTransform"] = 2] = "HasDecoratorInputTransform";
  return InputFlags;
}(InputFlags || {});
/**
 * Flags for renderer-specific style modifiers.
 * @publicApi
 */
var RendererStyleFlags2 = /*#__PURE__*/function (RendererStyleFlags2) {
  // TODO(misko): This needs to be refactored into a separate file so that it can be imported from
  // `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
  // the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
  /**
   * Marks a style as important.
   */
  RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
  /**
   * Marks a style as using dash case naming (this-is-dash-case).
   */
  RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
  return RendererStyleFlags2;
}(RendererStyleFlags2 || {});
let _icuContainerIterate;
/**
 * Iterator which provides ability to visit all of the `TIcuContainerNode` root `RNode`s.
 */
function icuContainerIterate(tIcuContainerNode, lView) {
  return _icuContainerIterate(tIcuContainerNode, lView);
}
/**
 * Ensures that `IcuContainerVisitor`'s implementation is present.
 *
 * This function is invoked when i18n instruction comes across an ICU. The purpose is to allow the
 * bundler to tree shake ICU logic and only load it if ICU instruction is executed.
 */
function ensureIcuContainerVisitorLoaded(loader) {
  if (_icuContainerIterate === undefined) {
    // Do not inline this function. We want to keep `ensureIcuContainerVisitorLoaded` light, so it
    // can be inlined into call-site.
    _icuContainerIterate = loader();
  }
}

/**
 * NOTE: for performance reasons, the possible actions are inlined within the function instead of
 * being passed as an argument.
 */
function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
  // If this slot was allocated for a text node dynamically created by i18n, the text node itself
  // won't be created until i18nApply() in the update block, so this node should be skipped.
  // For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
  // in `i18n_spec.ts`.
  if (lNodeToHandle != null) {
    let lContainer;
    let isComponent = false;
    // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
    // wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
    // it has LContainer so that we can process all of those cases appropriately.
    if (isLContainer(lNodeToHandle)) {
      lContainer = lNodeToHandle;
    } else if (isLView(lNodeToHandle)) {
      isComponent = true;
      ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
      lNodeToHandle = lNodeToHandle[HOST];
    }
    const rNode = unwrapRNode(lNodeToHandle);
    if (action === 0 /* WalkTNodeTreeAction.Create */ && parent !== null) {
      if (beforeNode == null) {
        nativeAppendChild(renderer, parent, rNode);
      } else {
        nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
      }
    } else if (action === 1 /* WalkTNodeTreeAction.Insert */ && parent !== null) {
      nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
    } else if (action === 2 /* WalkTNodeTreeAction.Detach */) {
      nativeRemoveNode(renderer, rNode, isComponent);
    } else if (action === 3 /* WalkTNodeTreeAction.Destroy */) {
      ngDevMode && ngDevMode.rendererDestroyNode++;
      renderer.destroyNode(rNode);
    }
    if (lContainer != null) {
      applyContainer(renderer, action, lContainer, parent, beforeNode);
    }
  }
}
function createTextNode(renderer, value) {
  ngDevMode && ngDevMode.rendererCreateTextNode++;
  ngDevMode && ngDevMode.rendererSetText++;
  return renderer.createText(value);
}
function updateTextNode(renderer, rNode, value) {
  ngDevMode && ngDevMode.rendererSetText++;
  renderer.setValue(rNode, value);
}
function createCommentNode(renderer, value) {
  ngDevMode && ngDevMode.rendererCreateComment++;
  return renderer.createComment(escapeCommentText(value));
}
/**
 * Creates a native element from a tag name, using a renderer.
 * @param renderer A renderer to use
 * @param name the tag name
 * @param namespace Optional namespace for element.
 * @returns the element created
 */
function createElementNode(renderer, name, namespace) {
  ngDevMode && ngDevMode.rendererCreateElement++;
  return renderer.createElement(name, namespace);
}
/**
 * Removes all DOM elements associated with a view.
 *
 * Because some root nodes of the view may be containers, we sometimes need
 * to propagate deeply into the nested containers to remove all elements in the
 * views beneath it.
 *
 * @param tView The `TView' of the `LView` from which elements should be added or removed
 * @param lView The view from which elements should be added or removed
 */
function removeViewFromDOM(tView, lView) {
  detachViewFromDOM(tView, lView);
  lView[HOST] = null;
  lView[T_HOST] = null;
}
/**
 * Adds all DOM elements associated with a view.
 *
 * Because some root nodes of the view may be containers, we sometimes need
 * to propagate deeply into the nested containers to add all elements in the
 * views beneath it.
 *
 * @param tView The `TView' of the `LView` from which elements should be added or removed
 * @param parentTNode The `TNode` where the `LView` should be attached to.
 * @param renderer Current renderer to use for DOM manipulations.
 * @param lView The view from which elements should be added or removed
 * @param parentNativeNode The parent `RElement` where it should be inserted into.
 * @param beforeNode The node before which elements should be added, if insert mode
 */
function addViewToDOM(tView, parentTNode, renderer, lView, parentNativeNode, beforeNode) {
  lView[HOST] = parentNativeNode;
  lView[T_HOST] = parentTNode;
  applyView(tView, lView, renderer, 1 /* WalkTNodeTreeAction.Insert */, parentNativeNode, beforeNode);
}
/**
 * Detach a `LView` from the DOM by detaching its nodes.
 *
 * @param tView The `TView' of the `LView` to be detached
 * @param lView the `LView` to be detached.
 */
function detachViewFromDOM(tView, lView) {
  // When we remove a view from the DOM, we need to rerun afterRender hooks
  // We don't necessarily needs to run change detection. DOM removal only requires
  // change detection if animations are enabled (this notification is handled by animations).
  lView[ENVIRONMENT].changeDetectionScheduler?.notify(10 /* NotificationSource.ViewDetachedFromDOM */);
  applyView(tView, lView, lView[RENDERER], 2 /* WalkTNodeTreeAction.Detach */, null, null);
}
/**
 * Traverses down and up the tree of views and containers to remove listeners and
 * call onDestroy callbacks.
 *
 * Notes:
 *  - Because it's used for onDestroy calls, it needs to be bottom-up.
 *  - Must process containers instead of their views to avoid splicing
 *  when views are destroyed and re-added.
 *  - Using a while loop because it's faster than recursion
 *  - Destroy only called on movement to sibling or movement to parent (laterally or up)
 *
 *  @param rootView The view to destroy
 */
function destroyViewTree(rootView) {
  // If the view has no children, we can clean it up and return early.
  let lViewOrLContainer = rootView[CHILD_HEAD];
  if (!lViewOrLContainer) {
    return cleanUpView(rootView[TVIEW], rootView);
  }
  while (lViewOrLContainer) {
    let next = null;
    if (isLView(lViewOrLContainer)) {
      // If LView, traverse down to child.
      next = lViewOrLContainer[CHILD_HEAD];
    } else {
      ngDevMode && assertLContainer(lViewOrLContainer);
      // If container, traverse down to its first LView.
      const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
      if (firstView) next = firstView;
    }
    if (!next) {
      // Only clean up view when moving to the side or up, as destroy hooks
      // should be called in order from the bottom up.
      while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
        if (isLView(lViewOrLContainer)) {
          cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
        }
        lViewOrLContainer = lViewOrLContainer[PARENT];
      }
      if (lViewOrLContainer === null) lViewOrLContainer = rootView;
      if (isLView(lViewOrLContainer)) {
        cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
      }
      next = lViewOrLContainer && lViewOrLContainer[NEXT];
    }
    lViewOrLContainer = next;
  }
}
/**
 * Inserts a view into a container.
 *
 * This adds the view to the container's array of active views in the correct
 * position. It also adds the view's elements to the DOM if the container isn't a
 * root node of another view (in that case, the view's elements will be added when
 * the container's parent view is added later).
 *
 * @param tView The `TView' of the `LView` to insert
 * @param lView The view to insert
 * @param lContainer The container into which the view should be inserted
 * @param index Which index in the container to insert the child view into
 */
function insertView(tView, lView, lContainer, index) {
  ngDevMode && assertLView(lView);
  ngDevMode && assertLContainer(lContainer);
  const indexInContainer = CONTAINER_HEADER_OFFSET + index;
  const containerLength = lContainer.length;
  if (index > 0) {
    // This is a new view, we need to add it to the children.
    lContainer[indexInContainer - 1][NEXT] = lView;
  }
  if (index < containerLength - CONTAINER_HEADER_OFFSET) {
    lView[NEXT] = lContainer[indexInContainer];
    addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
  } else {
    lContainer.push(lView);
    lView[NEXT] = null;
  }
  lView[PARENT] = lContainer;
  // track views where declaration and insertion points are different
  const declarationLContainer = lView[DECLARATION_LCONTAINER];
  if (declarationLContainer !== null && lContainer !== declarationLContainer) {
    trackMovedView(declarationLContainer, lView);
  }
  // notify query that a new view has been added
  const lQueries = lView[QUERIES];
  if (lQueries !== null) {
    lQueries.insertView(tView);
  }
  updateAncestorTraversalFlagsOnAttach(lView);
  // Sets the attached flag
  lView[FLAGS] |= 128 /* LViewFlags.Attached */;
}
/**
 * Track views created from the declaration container (TemplateRef) and inserted into a
 * different LContainer or attached directly to ApplicationRef.
 */
function trackMovedView(declarationContainer, lView) {
  ngDevMode && assertDefined(lView, 'LView required');
  ngDevMode && assertLContainer(declarationContainer);
  const movedViews = declarationContainer[MOVED_VIEWS];
  const parent = lView[PARENT];
  ngDevMode && assertDefined(parent, 'missing parent');
  if (isLView(parent)) {
    declarationContainer[FLAGS] |= LContainerFlags.HasTransplantedViews;
  } else {
    const insertedComponentLView = parent[PARENT][DECLARATION_COMPONENT_VIEW];
    ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
    const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
    ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
    if (declaredComponentLView !== insertedComponentLView) {
      // At this point the declaration-component is not same as insertion-component; this means that
      // this is a transplanted view. Mark the declared lView as having transplanted views so that
      // those views can participate in CD.
      declarationContainer[FLAGS] |= LContainerFlags.HasTransplantedViews;
    }
  }
  if (movedViews === null) {
    declarationContainer[MOVED_VIEWS] = [lView];
  } else {
    movedViews.push(lView);
  }
}
function detachMovedView(declarationContainer, lView) {
  ngDevMode && assertLContainer(declarationContainer);
  ngDevMode && assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
  const movedViews = declarationContainer[MOVED_VIEWS];
  const declarationViewIndex = movedViews.indexOf(lView);
  movedViews.splice(declarationViewIndex, 1);
}
/**
 * Detaches a view from a container.
 *
 * This method removes the view from the container's array of active views. It also
 * removes the view's elements from the DOM.
 *
 * @param lContainer The container from which to detach a view
 * @param removeIndex The index of the view to detach
 * @returns Detached LView instance.
 */
function detachView(lContainer, removeIndex) {
  if (lContainer.length <= CONTAINER_HEADER_OFFSET) return;
  const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
  const viewToDetach = lContainer[indexInContainer];
  if (viewToDetach) {
    const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
    if (declarationLContainer !== null && declarationLContainer !== lContainer) {
      detachMovedView(declarationLContainer, viewToDetach);
    }
    if (removeIndex > 0) {
      lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT];
    }
    const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
    removeViewFromDOM(viewToDetach[TVIEW], viewToDetach);
    // notify query that a view has been removed
    const lQueries = removedLView[QUERIES];
    if (lQueries !== null) {
      lQueries.detachView(removedLView[TVIEW]);
    }
    viewToDetach[PARENT] = null;
    viewToDetach[NEXT] = null;
    // Unsets the attached flag
    viewToDetach[FLAGS] &= ~128 /* LViewFlags.Attached */;
  }
  return viewToDetach;
}
/**
 * A standalone function which destroys an LView,
 * conducting clean up (e.g. removing listeners, calling onDestroys).
 *
 * @param tView The `TView' of the `LView` to be destroyed
 * @param lView The view to be destroyed.
 */
function destroyLView(tView, lView) {
  if (!(lView[FLAGS] & 256 /* LViewFlags.Destroyed */)) {
    const renderer = lView[RENDERER];
    if (renderer.destroyNode) {
      applyView(tView, lView, renderer, 3 /* WalkTNodeTreeAction.Destroy */, null, null);
    }
    destroyViewTree(lView);
  }
}
/**
 * Calls onDestroys hooks for all directives and pipes in a given view and then removes all
 * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
 * can be propagated to @Output listeners.
 *
 * @param tView `TView` for the `LView` to clean up.
 * @param lView The LView to clean up
 */
function cleanUpView(tView, lView) {
  if (lView[FLAGS] & 256 /* LViewFlags.Destroyed */) {
    return;
  }
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    // Usually the Attached flag is removed when the view is detached from its parent, however
    // if it's a root view, the flag won't be unset hence why we're also removing on destroy.
    lView[FLAGS] &= ~128 /* LViewFlags.Attached */;
    // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
    // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
    // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
    // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
    // really more of an "afterDestroy" hook if you think about it.
    lView[FLAGS] |= 256 /* LViewFlags.Destroyed */;
    lView[REACTIVE_TEMPLATE_CONSUMER] && (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerDestroy)(lView[REACTIVE_TEMPLATE_CONSUMER]);
    executeOnDestroys(tView, lView);
    processCleanups(tView, lView);
    // For component views only, the local renderer is destroyed at clean up time.
    if (lView[TVIEW].type === 1 /* TViewType.Component */) {
      ngDevMode && ngDevMode.rendererDestroy++;
      lView[RENDERER].destroy();
    }
    const declarationContainer = lView[DECLARATION_LCONTAINER];
    // we are dealing with an embedded view that is still inserted into a container
    if (declarationContainer !== null && isLContainer(lView[PARENT])) {
      // and this is a projected view
      if (declarationContainer !== lView[PARENT]) {
        detachMovedView(declarationContainer, lView);
      }
      // For embedded views still attached to a container: remove query result from this view.
      const lQueries = lView[QUERIES];
      if (lQueries !== null) {
        lQueries.detachView(tView);
      }
    }
    // Unregister the view once everything else has been cleaned up.
    unregisterLView(lView);
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
/** Removes listeners and unsubscribes from output subscriptions */
function processCleanups(tView, lView) {
  ngDevMode && assertNotReactive(processCleanups.name);
  const tCleanup = tView.cleanup;
  const lCleanup = lView[CLEANUP];
  if (tCleanup !== null) {
    for (let i = 0; i < tCleanup.length - 1; i += 2) {
      if (typeof tCleanup[i] === 'string') {
        // This is a native DOM listener. It will occupy 4 entries in the TCleanup array (hence i +=
        // 2 at the end of this block).
        const targetIdx = tCleanup[i + 3];
        ngDevMode && assertNumber(targetIdx, 'cleanup target must be a number');
        if (targetIdx >= 0) {
          // Destroy anything whose teardown is a function call (e.g. QueryList, ModelSignal).
          lCleanup[targetIdx]();
        } else {
          // Subscription
          lCleanup[-targetIdx].unsubscribe();
        }
        i += 2;
      } else {
        // This is a cleanup function that is grouped with the index of its context
        const context = lCleanup[tCleanup[i + 1]];
        tCleanup[i].call(context);
      }
    }
  }
  if (lCleanup !== null) {
    lView[CLEANUP] = null;
  }
  const destroyHooks = lView[ON_DESTROY_HOOKS];
  if (destroyHooks !== null) {
    // Reset the ON_DESTROY_HOOKS array before iterating over it to prevent hooks that unregister
    // themselves from mutating the array during iteration.
    lView[ON_DESTROY_HOOKS] = null;
    for (let i = 0; i < destroyHooks.length; i++) {
      const destroyHooksFn = destroyHooks[i];
      ngDevMode && assertFunction(destroyHooksFn, 'Expecting destroy hook to be a function.');
      destroyHooksFn();
    }
  }
  // Destroy effects registered to the view. Many of these will have been processed above.
  const effects = lView[EFFECTS];
  if (effects !== null) {
    lView[EFFECTS] = null;
    for (const effect of effects) {
      effect.destroy();
    }
  }
}
/** Calls onDestroy hooks for this view */
function executeOnDestroys(tView, lView) {
  ngDevMode && assertNotReactive(executeOnDestroys.name);
  let destroyHooks;
  if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
    for (let i = 0; i < destroyHooks.length; i += 2) {
      const context = lView[destroyHooks[i]];
      // Only call the destroy hook if the context has been requested.
      if (!(context instanceof NodeInjectorFactory)) {
        const toCall = destroyHooks[i + 1];
        if (Array.isArray(toCall)) {
          for (let j = 0; j < toCall.length; j += 2) {
            const callContext = context[toCall[j]];
            const hook = toCall[j + 1];
            profiler(4 /* ProfilerEvent.LifecycleHookStart */, callContext, hook);
            try {
              hook.call(callContext);
            } finally {
              profiler(5 /* ProfilerEvent.LifecycleHookEnd */, callContext, hook);
            }
          }
        } else {
          profiler(4 /* ProfilerEvent.LifecycleHookStart */, context, toCall);
          try {
            toCall.call(context);
          } finally {
            profiler(5 /* ProfilerEvent.LifecycleHookEnd */, context, toCall);
          }
        }
      }
    }
  }
}
/**
 * Returns a native element if a node can be inserted into the given parent.
 *
 * There are two reasons why we may not be able to insert a element immediately.
 * - Projection: When creating a child content element of a component, we have to skip the
 *   insertion because the content of a component will be projected.
 *   `<component><content>delayed due to projection</content></component>`
 * - Parent container is disconnected: This can happen when we are inserting a view into
 *   parent container, which itself is disconnected. For example the parent container is part
 *   of a View which has not be inserted or is made for projection but has not been inserted
 *   into destination.
 *
 * @param tView: Current `TView`.
 * @param tNode: `TNode` for which we wish to retrieve render parent.
 * @param lView: Current `LView`.
 */
function getParentRElement(tView, tNode, lView) {
  return getClosestRElement(tView, tNode.parent, lView);
}
/**
 * Get closest `RElement` or `null` if it can't be found.
 *
 * If `TNode` is `TNodeType.Element` => return `RElement` at `LView[tNode.index]` location.
 * If `TNode` is `TNodeType.ElementContainer|IcuContain` => return the parent (recursively).
 * If `TNode` is `null` then return host `RElement`:
 *   - return `null` if projection
 *   - return `null` if parent container is disconnected (we have no parent.)
 *
 * @param tView: Current `TView`.
 * @param tNode: `TNode` for which we wish to retrieve `RElement` (or `null` if host element is
 *     needed).
 * @param lView: Current `LView`.
 * @returns `null` if the `RElement` can't be determined at this time (no parent / projection)
 */
function getClosestRElement(tView, tNode, lView) {
  let parentTNode = tNode;
  // Skip over element and ICU containers as those are represented by a comment node and
  // can't be used as a render parent. Also skip let declarations since they don't have a
  // corresponding DOM node at all.
  while (parentTNode !== null && parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
    tNode = parentTNode;
    parentTNode = tNode.parent;
  }
  // If the parent tNode is null, then we are inserting across views: either into an embedded view
  // or a component view.
  if (parentTNode === null) {
    // We are inserting a root element of the component view into the component host element and
    // it should always be eager.
    return lView[HOST];
  } else {
    ngDevMode && assertTNodeType(parentTNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
    const {
      componentOffset
    } = parentTNode;
    if (componentOffset > -1) {
      ngDevMode && assertTNodeForLView(parentTNode, lView);
      const {
        encapsulation
      } = tView.data[parentTNode.directiveStart + componentOffset];
      // We've got a parent which is an element in the current view. We just need to verify if the
      // parent element is not a component. Component's content nodes are not inserted immediately
      // because they will be projected, and so doing insert at this point would be wasteful.
      // Since the projection would then move it to its final destination. Note that we can't
      // make this assumption when using the Shadow DOM, because the native projection placeholders
      // (<content> or <slot>) have to be in place as elements are being inserted.
      if (encapsulation === ViewEncapsulation.None || encapsulation === ViewEncapsulation.Emulated) {
        return null;
      }
    }
    return getNativeByTNode(parentTNode, lView);
  }
}
/**
 * Inserts a native node before another native node for a given parent.
 * This is a utility function that can be used when native nodes were determined.
 */
function nativeInsertBefore(renderer, parent, child, beforeNode, isMove) {
  ngDevMode && ngDevMode.rendererInsertBefore++;
  renderer.insertBefore(parent, child, beforeNode, isMove);
}
function nativeAppendChild(renderer, parent, child) {
  ngDevMode && ngDevMode.rendererAppendChild++;
  ngDevMode && assertDefined(parent, 'parent node must be defined');
  renderer.appendChild(parent, child);
}
function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode, isMove) {
  if (beforeNode !== null) {
    nativeInsertBefore(renderer, parent, child, beforeNode, isMove);
  } else {
    nativeAppendChild(renderer, parent, child);
  }
}
/**
 * Returns a native parent of a given native node.
 */
function nativeParentNode(renderer, node) {
  return renderer.parentNode(node);
}
/**
 * Returns a native sibling of a given native node.
 */
function nativeNextSibling(renderer, node) {
  return renderer.nextSibling(node);
}
/**
 * Find a node in front of which `currentTNode` should be inserted.
 *
 * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
 * takes `TNode.insertBeforeIndex` into account if i18n code has been invoked.
 *
 * @param parentTNode parent `TNode`
 * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
 * @param lView current `LView`
 */
function getInsertInFrontOfRNode(parentTNode, currentTNode, lView) {
  return _getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView);
}
/**
 * Find a node in front of which `currentTNode` should be inserted. (Does not take i18n into
 * account)
 *
 * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
 * does not take `TNode.insertBeforeIndex` into account.
 *
 * @param parentTNode parent `TNode`
 * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
 * @param lView current `LView`
 */
function getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView) {
  if (parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */)) {
    return getNativeByTNode(parentTNode, lView);
  }
  return null;
}
/**
 * Tree shakable boundary for `getInsertInFrontOfRNodeWithI18n` function.
 *
 * This function will only be set if i18n code runs.
 */
let _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithNoI18n;
/**
 * Tree shakable boundary for `processI18nInsertBefore` function.
 *
 * This function will only be set if i18n code runs.
 */
let _processI18nInsertBefore;
function setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore) {
  _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithI18n;
  _processI18nInsertBefore = processI18nInsertBefore;
}
/**
 * Appends the `child` native node (or a collection of nodes) to the `parent`.
 *
 * @param tView The `TView' to be appended
 * @param lView The current LView
 * @param childRNode The native child (or children) that should be appended
 * @param childTNode The TNode of the child element
 */
function appendChild(tView, lView, childRNode, childTNode) {
  const parentRNode = getParentRElement(tView, childTNode, lView);
  const renderer = lView[RENDERER];
  const parentTNode = childTNode.parent || lView[T_HOST];
  const anchorNode = getInsertInFrontOfRNode(parentTNode, childTNode, lView);
  if (parentRNode != null) {
    if (Array.isArray(childRNode)) {
      for (let i = 0; i < childRNode.length; i++) {
        nativeAppendOrInsertBefore(renderer, parentRNode, childRNode[i], anchorNode, false);
      }
    } else {
      nativeAppendOrInsertBefore(renderer, parentRNode, childRNode, anchorNode, false);
    }
  }
  _processI18nInsertBefore !== undefined && _processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRNode);
}
/**
 * Returns the first native node for a given LView, starting from the provided TNode.
 *
 * Native nodes are returned in the order in which those appear in the native tree (DOM).
 */
function getFirstNativeNode(lView, tNode) {
  if (tNode !== null) {
    ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */ | 16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */);
    const tNodeType = tNode.type;
    if (tNodeType & 3 /* TNodeType.AnyRNode */) {
      return getNativeByTNode(tNode, lView);
    } else if (tNodeType & 4 /* TNodeType.Container */) {
      return getBeforeNodeForView(-1, lView[tNode.index]);
    } else if (tNodeType & 8 /* TNodeType.ElementContainer */) {
      const elIcuContainerChild = tNode.child;
      if (elIcuContainerChild !== null) {
        return getFirstNativeNode(lView, elIcuContainerChild);
      } else {
        const rNodeOrLContainer = lView[tNode.index];
        if (isLContainer(rNodeOrLContainer)) {
          return getBeforeNodeForView(-1, rNodeOrLContainer);
        } else {
          return unwrapRNode(rNodeOrLContainer);
        }
      }
    } else if (tNodeType & 128 /* TNodeType.LetDeclaration */) {
      return getFirstNativeNode(lView, tNode.next);
    } else if (tNodeType & 32 /* TNodeType.Icu */) {
      let nextRNode = icuContainerIterate(tNode, lView);
      let rNode = nextRNode();
      // If the ICU container has no nodes, than we use the ICU anchor as the node.
      return rNode || unwrapRNode(lView[tNode.index]);
    } else {
      const projectionNodes = getProjectionNodes(lView, tNode);
      if (projectionNodes !== null) {
        if (Array.isArray(projectionNodes)) {
          return projectionNodes[0];
        }
        const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
        ngDevMode && assertParentView(parentView);
        return getFirstNativeNode(parentView, projectionNodes);
      } else {
        return getFirstNativeNode(lView, tNode.next);
      }
    }
  }
  return null;
}
function getProjectionNodes(lView, tNode) {
  if (tNode !== null) {
    const componentView = lView[DECLARATION_COMPONENT_VIEW];
    const componentHost = componentView[T_HOST];
    const slotIdx = tNode.projection;
    ngDevMode && assertProjectionSlots(lView);
    return componentHost.projection[slotIdx];
  }
  return null;
}
function getBeforeNodeForView(viewIndexInContainer, lContainer) {
  const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
  if (nextViewIndex < lContainer.length) {
    const lView = lContainer[nextViewIndex];
    const firstTNodeOfView = lView[TVIEW].firstChild;
    if (firstTNodeOfView !== null) {
      return getFirstNativeNode(lView, firstTNodeOfView);
    }
  }
  return lContainer[NATIVE];
}
/**
 * Removes a native node itself using a given renderer. To remove the node we are looking up its
 * parent from the native tree as not all platforms / browsers support the equivalent of
 * node.remove().
 *
 * @param renderer A renderer to be used
 * @param rNode The native node that should be removed
 * @param isHostElement A flag indicating if a node to be removed is a host of a component.
 */
function nativeRemoveNode(renderer, rNode, isHostElement) {
  ngDevMode && ngDevMode.rendererRemoveNode++;
  renderer.removeChild(null, rNode, isHostElement);
}
/**
 * Clears the contents of a given RElement.
 *
 * @param rElement the native RElement to be cleared
 */
function clearElementContents(rElement) {
  rElement.textContent = '';
}
/**
 * Performs the operation of `action` on the node. Typically this involves inserting or removing
 * nodes on the LView or projection boundary.
 */
function applyNodes(renderer, action, tNode, lView, parentRElement, beforeNode, isProjection) {
  while (tNode != null) {
    ngDevMode && assertTNodeForLView(tNode, lView);
    // Let declarations don't have corresponding DOM nodes so we skip over them.
    if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
      tNode = tNode.next;
      continue;
    }
    ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
    const rawSlotValue = lView[tNode.index];
    const tNodeType = tNode.type;
    if (isProjection) {
      if (action === 0 /* WalkTNodeTreeAction.Create */) {
        rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
        tNode.flags |= 2 /* TNodeFlags.isProjected */;
      }
    }
    if ((tNode.flags & 32 /* TNodeFlags.isDetached */) !== 32 /* TNodeFlags.isDetached */) {
      if (tNodeType & 8 /* TNodeType.ElementContainer */) {
        applyNodes(renderer, action, tNode.child, lView, parentRElement, beforeNode, false);
        applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
      } else if (tNodeType & 32 /* TNodeType.Icu */) {
        const nextRNode = icuContainerIterate(tNode, lView);
        let rNode;
        while (rNode = nextRNode()) {
          applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
        }
        applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
      } else if (tNodeType & 16 /* TNodeType.Projection */) {
        applyProjectionRecursive(renderer, action, lView, tNode, parentRElement, beforeNode);
      } else {
        ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
        applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
      }
    }
    tNode = isProjection ? tNode.projectionNext : tNode.next;
  }
}
function applyView(tView, lView, renderer, action, parentRElement, beforeNode) {
  applyNodes(renderer, action, tView.firstChild, lView, parentRElement, beforeNode, false);
}
/**
 * `applyProjection` performs operation on the projection.
 *
 * Inserting a projection requires us to locate the projected nodes from the parent component. The
 * complication is that those nodes themselves could be re-projected from their parent component.
 *
 * @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed
 * @param lView The `LView` which needs to be inserted, detached, destroyed.
 * @param tProjectionNode node to project
 */
function applyProjection(tView, lView, tProjectionNode) {
  const renderer = lView[RENDERER];
  const parentRNode = getParentRElement(tView, tProjectionNode, lView);
  const parentTNode = tProjectionNode.parent || lView[T_HOST];
  let beforeNode = getInsertInFrontOfRNode(parentTNode, tProjectionNode, lView);
  applyProjectionRecursive(renderer, 0 /* WalkTNodeTreeAction.Create */, lView, tProjectionNode, parentRNode, beforeNode);
}
/**
 * `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
 * detach, destroy)
 *
 * Inserting a projection requires us to locate the projected nodes from the parent component. The
 * complication is that those nodes themselves could be re-projected from their parent component.
 *
 * @param renderer Render to use
 * @param action action to perform (insert, detach, destroy)
 * @param lView The LView which needs to be inserted, detached, destroyed.
 * @param tProjectionNode node to project
 * @param parentRElement parent DOM element for insertion/removal.
 * @param beforeNode Before which node the insertions should happen.
 */
function applyProjectionRecursive(renderer, action, lView, tProjectionNode, parentRElement, beforeNode) {
  const componentLView = lView[DECLARATION_COMPONENT_VIEW];
  const componentNode = componentLView[T_HOST];
  ngDevMode && assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
  const nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection];
  if (Array.isArray(nodeToProjectOrRNodes)) {
    // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
    // need to support passing projectable nodes, so we cheat and put them in the TNode
    // of the Host TView. (Yes we put instance info at the T Level). We can get away with it
    // because we know that TView is not shared and therefore it will not be a problem.
    // This should be refactored and cleaned up.
    for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
      const rNode = nodeToProjectOrRNodes[i];
      applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
    }
  } else {
    let nodeToProject = nodeToProjectOrRNodes;
    const projectedComponentLView = componentLView[PARENT];
    // If a parent <ng-content> is located within a skip hydration block,
    // annotate an actual node that is being projected with the same flag too.
    if (hasInSkipHydrationBlockFlag(tProjectionNode)) {
      nodeToProject.flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
    }
    applyNodes(renderer, action, nodeToProject, projectedComponentLView, parentRElement, beforeNode, true);
  }
}
/**
 * `applyContainer` performs an operation on the container and its views as specified by
 * `action` (insert, detach, destroy)
 *
 * Inserting a Container is complicated by the fact that the container may have Views which
 * themselves have containers or projections.
 *
 * @param renderer Renderer to use
 * @param action action to perform (insert, detach, destroy)
 * @param lContainer The LContainer which needs to be inserted, detached, destroyed.
 * @param parentRElement parent DOM element for insertion/removal.
 * @param beforeNode Before which node the insertions should happen.
 */
function applyContainer(renderer, action, lContainer, parentRElement, beforeNode) {
  ngDevMode && assertLContainer(lContainer);
  const anchor = lContainer[NATIVE]; // LContainer has its own before node.
  const native = unwrapRNode(lContainer);
  // An LContainer can be created dynamically on any node by injecting ViewContainerRef.
  // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor
  // node (comment in the DOM) that will be different from the LContainer's host node. In this
  // particular case we need to execute action on 2 nodes:
  // - container's host node (this is done in the executeActionOnElementOrContainer)
  // - container's host node (this is done here)
  if (anchor !== native) {
    // This is very strange to me (Misko). I would expect that the native is same as anchor. I
    // don't see a reason why they should be different, but they are.
    //
    // If they are we need to process the second anchor as well.
    applyToElementOrContainer(action, renderer, parentRElement, anchor, beforeNode);
  }
  for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
    const lView = lContainer[i];
    applyView(lView[TVIEW], lView, renderer, action, parentRElement, anchor);
  }
}
/**
 * Writes class/style to element.
 *
 * @param renderer Renderer to use.
 * @param isClassBased `true` if it should be written to `class` (`false` to write to `style`)
 * @param rNode The Node to write to.
 * @param prop Property to write to. This would be the class/style name.
 * @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
 *        otherwise).
 */
function applyStyling(renderer, isClassBased, rNode, prop, value) {
  if (isClassBased) {
    // We actually want JS true/false here because any truthy value should add the class
    if (!value) {
      ngDevMode && ngDevMode.rendererRemoveClass++;
      renderer.removeClass(rNode, prop);
    } else {
      ngDevMode && ngDevMode.rendererAddClass++;
      renderer.addClass(rNode, prop);
    }
  } else {
    let flags = prop.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase;
    if (value == null /** || value === undefined */) {
      ngDevMode && ngDevMode.rendererRemoveStyle++;
      renderer.removeStyle(rNode, prop, flags);
    } else {
      // A value is important if it ends with `!important`. The style
      // parser strips any semicolons at the end of the value.
      const isImportant = typeof value === 'string' ? value.endsWith('!important') : false;
      if (isImportant) {
        // !important has to be stripped from the value for it to be valid.
        value = value.slice(0, -10);
        flags |= RendererStyleFlags2.Important;
      }
      ngDevMode && ngDevMode.rendererSetStyle++;
      renderer.setStyle(rNode, prop, value, flags);
    }
  }
}
/**
 * Write `cssText` to `RElement`.
 *
 * This function does direct write without any reconciliation. Used for writing initial values, so
 * that static styling values do not pull in the style parser.
 *
 * @param renderer Renderer to use
 * @param element The element which needs to be updated.
 * @param newValue The new class list to write.
 */
function writeDirectStyle(renderer, element, newValue) {
  ngDevMode && assertString(newValue, "'newValue' should be a string");
  renderer.setAttribute(element, 'style', newValue);
  ngDevMode && ngDevMode.rendererSetStyle++;
}
/**
 * Write `className` to `RElement`.
 *
 * This function does direct write without any reconciliation. Used for writing initial values, so
 * that static styling values do not pull in the style parser.
 *
 * @param renderer Renderer to use
 * @param element The element which needs to be updated.
 * @param newValue The new class list to write.
 */
function writeDirectClass(renderer, element, newValue) {
  ngDevMode && assertString(newValue, "'newValue' should be a string");
  if (newValue === '') {
    // There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
    renderer.removeAttribute(element, 'class');
  } else {
    renderer.setAttribute(element, 'class', newValue);
  }
  ngDevMode && ngDevMode.rendererSetClassName++;
}
/** Sets up the static DOM attributes on an `RNode`. */
function setupStaticAttributes(renderer, element, tNode) {
  const {
    mergedAttrs,
    classes,
    styles
  } = tNode;
  if (mergedAttrs !== null) {
    setUpAttributes(renderer, element, mergedAttrs);
  }
  if (classes !== null) {
    writeDirectClass(renderer, element, classes);
  }
  if (styles !== null) {
    writeDirectStyle(renderer, element, styles);
  }
}

/**
 * Returns an index of `classToSearch` in `className` taking token boundaries into account.
 *
 * `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
 *
 * @param className A string containing classes (whitespace separated)
 * @param classToSearch A class name to locate
 * @param startingIndex Starting location of search
 * @returns an index of the located class (or -1 if not found)
 */
function classIndexOf(className, classToSearch, startingIndex) {
  ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
  let end = className.length;
  while (true) {
    const foundIndex = className.indexOf(classToSearch, startingIndex);
    if (foundIndex === -1) return foundIndex;
    if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* CharCode.SPACE */) {
      // Ensure that it has leading whitespace
      const length = classToSearch.length;
      if (foundIndex + length === end || className.charCodeAt(foundIndex + length) <= 32 /* CharCode.SPACE */) {
        // Ensure that it has trailing whitespace
        return foundIndex;
      }
    }
    // False positive, keep searching from where we left off.
    startingIndex = foundIndex + 1;
  }
}
const NG_TEMPLATE_SELECTOR = 'ng-template';
/**
 * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)
 *
 * @param tNode static data of the node to match
 * @param attrs `TAttributes` to search through.
 * @param cssClassToMatch class to match (lowercase)
 * @param isProjectionMode Whether or not class matching should look into the attribute `class` in
 *    addition to the `AttributeMarker.Classes`.
 */
function isCssClassMatching(tNode, attrs, cssClassToMatch, isProjectionMode) {
  ngDevMode && assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');
  let i = 0;
  if (isProjectionMode) {
    for (; i < attrs.length && typeof attrs[i] === 'string'; i += 2) {
      // Search for an implicit `class` attribute and check if its value matches `cssClassToMatch`.
      if (attrs[i] === 'class' && classIndexOf(attrs[i + 1].toLowerCase(), cssClassToMatch, 0) !== -1) {
        return true;
      }
    }
  } else if (isInlineTemplate(tNode)) {
    // Matching directives (i.e. when not matching for projection mode) should not consider the
    // class bindings that are present on inline templates, as those class bindings only target
    // the root node of the template, not the template itself.
    return false;
  }
  // Resume the search for classes after the `Classes` marker.
  i = attrs.indexOf(1 /* AttributeMarker.Classes */, i);
  if (i > -1) {
    // We found the classes section. Start searching for the class.
    let item;
    while (++i < attrs.length && typeof (item = attrs[i]) === 'string') {
      if (item.toLowerCase() === cssClassToMatch) {
        return true;
      }
    }
  }
  return false;
}
/**
 * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).
 *
 * @param tNode current TNode
 */
function isInlineTemplate(tNode) {
  return tNode.type === 4 /* TNodeType.Container */ && tNode.value !== NG_TEMPLATE_SELECTOR;
}
/**
 * Function that checks whether a given tNode matches tag-based selector and has a valid type.
 *
 * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular
 * directive matching mode:
 * - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is
 * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a
 * tag name was extracted from * syntax so we would match the same directive twice);
 * - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing
 * (applicable to TNodeType.Container only).
 */
function hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {
  const tagNameToCompare = tNode.type === 4 /* TNodeType.Container */ && !isProjectionMode ? NG_TEMPLATE_SELECTOR : tNode.value;
  return currentSelector === tagNameToCompare;
}
/**
 * A utility function to match an Ivy node static data against a simple CSS selector
 *
 * @param tNode static data of the node to match
 * @param selector The selector to try matching against the node.
 * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing
 * directive matching.
 * @returns true if node matches the selector.
 */
function isNodeMatchingSelector(tNode, selector, isProjectionMode) {
  ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');
  let mode = 4 /* SelectorFlags.ELEMENT */;
  const nodeAttrs = tNode.attrs;
  // Find the index of first attribute that has no value, only a name.
  const nameOnlyMarkerIdx = nodeAttrs !== null ? getNameOnlyMarkerIndex(nodeAttrs) : 0;
  // When processing ":not" selectors, we skip to the next ":not" if the
  // current one doesn't match
  let skipToNextSelector = false;
  for (let i = 0; i < selector.length; i++) {
    const current = selector[i];
    if (typeof current === 'number') {
      // If we finish processing a :not selector and it hasn't failed, return false
      if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
        return false;
      }
      // If we are skipping to the next :not() and this mode flag is positive,
      // it's a part of the current :not() selector, and we should keep skipping
      if (skipToNextSelector && isPositive(current)) continue;
      skipToNextSelector = false;
      mode = current | mode & 1 /* SelectorFlags.NOT */;
      continue;
    }
    if (skipToNextSelector) continue;
    if (mode & 4 /* SelectorFlags.ELEMENT */) {
      mode = 2 /* SelectorFlags.ATTRIBUTE */ | mode & 1 /* SelectorFlags.NOT */;
      if (current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode) || current === '' && selector.length === 1) {
        if (isPositive(mode)) return false;
        skipToNextSelector = true;
      }
    } else if (mode & 8 /* SelectorFlags.CLASS */) {
      if (nodeAttrs === null || !isCssClassMatching(tNode, nodeAttrs, current, isProjectionMode)) {
        if (isPositive(mode)) return false;
        skipToNextSelector = true;
      }
    } else {
      const selectorAttrValue = selector[++i];
      const attrIndexInNode = findAttrIndexInNode(current, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);
      if (attrIndexInNode === -1) {
        if (isPositive(mode)) return false;
        skipToNextSelector = true;
        continue;
      }
      if (selectorAttrValue !== '') {
        let nodeAttrValue;
        if (attrIndexInNode > nameOnlyMarkerIdx) {
          nodeAttrValue = '';
        } else {
          ngDevMode && assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* AttributeMarker.NamespaceURI */, 'We do not match directives on namespaced attributes');
          // we lowercase the attribute value to be able to match
          // selectors without case-sensitivity
          // (selectors are already in lowercase when generated)
          nodeAttrValue = nodeAttrs[attrIndexInNode + 1].toLowerCase();
        }
        if (mode & 2 /* SelectorFlags.ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {
          if (isPositive(mode)) return false;
          skipToNextSelector = true;
        }
      }
    }
  }
  return isPositive(mode) || skipToNextSelector;
}
function isPositive(mode) {
  return (mode & 1 /* SelectorFlags.NOT */) === 0;
}
/**
 * Examines the attribute's definition array for a node to find the index of the
 * attribute that matches the given `name`.
 *
 * NOTE: This will not match namespaced attributes.
 *
 * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.
 * The following table summarizes which types of attributes we attempt to match:
 *
 * ===========================================================================================================
 * Modes                   | Normal Attributes | Bindings Attributes | Template Attributes | I18n
 * Attributes
 * ===========================================================================================================
 * Inline + Projection     | YES               | YES                 | NO                  | YES
 * -----------------------------------------------------------------------------------------------------------
 * Inline + Directive      | NO                | NO                  | YES                 | NO
 * -----------------------------------------------------------------------------------------------------------
 * Non-inline + Projection | YES               | YES                 | NO                  | YES
 * -----------------------------------------------------------------------------------------------------------
 * Non-inline + Directive  | YES               | YES                 | NO                  | YES
 * ===========================================================================================================
 *
 * @param name the name of the attribute to find
 * @param attrs the attribute array to examine
 * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)
 * rather than a manually expanded template node (e.g `<ng-template>`).
 * @param isProjectionMode true if we are matching against content projection otherwise we are
 * matching against directives.
 */
function findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {
  if (attrs === null) return -1;
  let i = 0;
  if (isProjectionMode || !isInlineTemplate) {
    let bindingsMode = false;
    while (i < attrs.length) {
      const maybeAttrName = attrs[i];
      if (maybeAttrName === name) {
        return i;
      } else if (maybeAttrName === 3 /* AttributeMarker.Bindings */ || maybeAttrName === 6 /* AttributeMarker.I18n */) {
        bindingsMode = true;
      } else if (maybeAttrName === 1 /* AttributeMarker.Classes */ || maybeAttrName === 2 /* AttributeMarker.Styles */) {
        let value = attrs[++i];
        // We should skip classes here because we have a separate mechanism for
        // matching classes in projection mode.
        while (typeof value === 'string') {
          value = attrs[++i];
        }
        continue;
      } else if (maybeAttrName === 4 /* AttributeMarker.Template */) {
        // We do not care about Template attributes in this scenario.
        break;
      } else if (maybeAttrName === 0 /* AttributeMarker.NamespaceURI */) {
        // Skip the whole namespaced attribute and value. This is by design.
        i += 4;
        continue;
      }
      // In binding mode there are only names, rather than name-value pairs.
      i += bindingsMode ? 1 : 2;
    }
    // We did not match the attribute
    return -1;
  } else {
    return matchTemplateAttribute(attrs, name);
  }
}
function isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {
  for (let i = 0; i < selector.length; i++) {
    if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {
      return true;
    }
  }
  return false;
}
function getProjectAsAttrValue(tNode) {
  const nodeAttrs = tNode.attrs;
  if (nodeAttrs != null) {
    const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* AttributeMarker.ProjectAs */);
    // only check for ngProjectAs in attribute names, don't accidentally match attribute's value
    // (attribute names are stored at even indexes)
    if ((ngProjectAsAttrIdx & 1) === 0) {
      return nodeAttrs[ngProjectAsAttrIdx + 1];
    }
  }
  return null;
}
function getNameOnlyMarkerIndex(nodeAttrs) {
  for (let i = 0; i < nodeAttrs.length; i++) {
    const nodeAttr = nodeAttrs[i];
    if (isNameOnlyAttributeMarker(nodeAttr)) {
      return i;
    }
  }
  return nodeAttrs.length;
}
function matchTemplateAttribute(attrs, name) {
  let i = attrs.indexOf(4 /* AttributeMarker.Template */);
  if (i > -1) {
    i++;
    while (i < attrs.length) {
      const attr = attrs[i];
      // Return in case we checked all template attrs and are switching to the next section in the
      // attrs array (that starts with a number that represents an attribute marker).
      if (typeof attr === 'number') return -1;
      if (attr === name) return i;
      i++;
    }
  }
  return -1;
}
/**
 * Checks whether a selector is inside a CssSelectorList
 * @param selector Selector to be checked.
 * @param list List in which to look for the selector.
 */
function isSelectorInSelectorList(selector, list) {
  selectorListLoop: for (let i = 0; i < list.length; i++) {
    const currentSelectorInList = list[i];
    if (selector.length !== currentSelectorInList.length) {
      continue;
    }
    for (let j = 0; j < selector.length; j++) {
      if (selector[j] !== currentSelectorInList[j]) {
        continue selectorListLoop;
      }
    }
    return true;
  }
  return false;
}
function maybeWrapInNotSelector(isNegativeMode, chunk) {
  return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;
}
function stringifyCSSSelector(selector) {
  let result = selector[0];
  let i = 1;
  let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  let currentChunk = '';
  let isNegativeMode = false;
  while (i < selector.length) {
    let valueOrMarker = selector[i];
    if (typeof valueOrMarker === 'string') {
      if (mode & 2 /* SelectorFlags.ATTRIBUTE */) {
        const attrValue = selector[++i];
        currentChunk += '[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']';
      } else if (mode & 8 /* SelectorFlags.CLASS */) {
        currentChunk += '.' + valueOrMarker;
      } else if (mode & 4 /* SelectorFlags.ELEMENT */) {
        currentChunk += ' ' + valueOrMarker;
      }
    } else {
      //
      // Append current chunk to the final result in case we come across SelectorFlag, which
      // indicates that the previous section of a selector is over. We need to accumulate content
      // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.
      // ```
      //  ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']
      // ```
      // should be transformed to `.classA :not(.classB .classC)`.
      //
      // Note: for negative selector part, we accumulate content between flags until we find the
      // next negative flag. This is needed to support a case where `:not()` rule contains more than
      // one chunk, e.g. the following selector:
      // ```
      //  ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']
      // ```
      // should be stringified to `:not(p.foo) :not(.bar)`
      //
      if (currentChunk !== '' && !isPositive(valueOrMarker)) {
        result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
        currentChunk = '';
      }
      mode = valueOrMarker;
      // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
      // mode is maintained for remaining chunks of a selector.
      isNegativeMode = isNegativeMode || !isPositive(mode);
    }
    i++;
  }
  if (currentChunk !== '') {
    result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
  }
  return result;
}
/**
 * Generates string representation of CSS selector in parsed form.
 *
 * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing
 * additional parsing at runtime (for example, for directive matching). However in some cases (for
 * example, while bootstrapping a component), a string version of the selector is required to query
 * for the host element on the page. This function takes the parsed form of a selector and returns
 * its string representation.
 *
 * @param selectorList selector in parsed form
 * @returns string representation of a given selector
 */
function stringifyCSSSelectorList(selectorList) {
  return selectorList.map(stringifyCSSSelector).join(',');
}
/**
 * Extracts attributes and classes information from a given CSS selector.
 *
 * This function is used while creating a component dynamically. In this case, the host element
 * (that is created dynamically) should contain attributes and classes specified in component's CSS
 * selector.
 *
 * @param selector CSS selector in parsed form (in a form of array)
 * @returns object with `attrs` and `classes` fields that contain extracted information
 */
function extractAttrsAndClassesFromSelector(selector) {
  const attrs = [];
  const classes = [];
  let i = 1;
  let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  while (i < selector.length) {
    let valueOrMarker = selector[i];
    if (typeof valueOrMarker === 'string') {
      if (mode === 2 /* SelectorFlags.ATTRIBUTE */) {
        if (valueOrMarker !== '') {
          attrs.push(valueOrMarker, selector[++i]);
        }
      } else if (mode === 8 /* SelectorFlags.CLASS */) {
        classes.push(valueOrMarker);
      }
    } else {
      // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
      // mode is maintained for remaining chunks of a selector. Since attributes and classes are
      // extracted only for "positive" part of the selector, we can stop here.
      if (!isPositive(mode)) break;
      mode = valueOrMarker;
    }
    i++;
  }
  return {
    attrs,
    classes
  };
}

/** A special value which designates that a value has not changed. */
const NO_CHANGE = typeof ngDevMode === 'undefined' || ngDevMode ? {
  __brand__: 'NO_CHANGE'
} : {};

/**
 * Advances to an element for later binding instructions.
 *
 * Used in conjunction with instructions like {@link property} to act on elements with specified
 * indices, for example those created with {@link element} or {@link elementStart}.
 *
 * ```ts
 * (rf: RenderFlags, ctx: any) => {
 *   if (rf & 1) {
 *     text(0, 'Hello');
 *     text(1, 'Goodbye')
 *     element(2, 'div');
 *   }
 *   if (rf & 2) {
 *     advance(2); // Advance twice to the <div>.
 *     property('title', 'test');
 *   }
 *  }
 * ```
 * @param delta Number of elements to advance forwards by.
 *
 * @codeGenApi
 */
function ɵɵadvance(delta = 1) {
  ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward');
  selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, !!ngDevMode && isInCheckNoChangesMode());
}
function selectIndexInternal(tView, lView, index, checkNoChangesMode) {
  ngDevMode && assertIndexInDeclRange(lView[TVIEW], index);
  // Flush the initial hooks for elements in the view that have been added up to this point.
  // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  if (!checkNoChangesMode) {
    const hooksInitPhaseCompleted = (lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
    if (hooksInitPhaseCompleted) {
      const preOrderCheckHooks = tView.preOrderCheckHooks;
      if (preOrderCheckHooks !== null) {
        executeCheckHooks(lView, preOrderCheckHooks, index);
      }
    } else {
      const preOrderHooks = tView.preOrderHooks;
      if (preOrderHooks !== null) {
        executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, index);
      }
    }
  }
  // We must set the selected index *after* running the hooks, because hooks may have side-effects
  // that cause other template functions to run, thus updating the selected index, which is global
  // state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index
  // will be altered by the time we leave the `ɵɵadvance` instruction.
  setSelectedIndex(index);
}
function ɵɵdirectiveInject(token, flags = InjectFlags.Default) {
  const lView = getLView();
  // Fall back to inject() if view hasn't been created. This situation can happen in tests
  // if inject utilities are used before bootstrapping.
  if (lView === null) {
    // Verify that we will not get into infinite loop.
    ngDevMode && assertInjectImplementationNotEqual(ɵɵdirectiveInject);
    return ɵɵinject(token, flags);
  }
  const tNode = getCurrentTNode();
  const value = getOrCreateInjectable(tNode, lView, resolveForwardRef(token), flags);
  ngDevMode && emitInjectEvent(token, value, flags);
  return value;
}
/**
 * Throws an error indicating that a factory function could not be generated by the compiler for a
 * particular class.
 *
 * This instruction allows the actual error message to be optimized away when ngDevMode is turned
 * off, saving bytes of generated code while still providing a good experience in dev mode.
 *
 * The name of the class is not mentioned here, but will be in the generated factory function name
 * and thus in the stack trace.
 *
 * @codeGenApi
 */
function ɵɵinvalidFactory() {
  const msg = ngDevMode ? `This constructor was not compatible with Dependency Injection.` : 'invalid';
  throw new Error(msg);
}
function writeToDirectiveInput(def, instance, publicName, privateName, flags, value) {
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    // If we know we are dealing with a signal input, we cache its reference
    // in a tree-shakable way. The input signal node can then be used for
    // value transform execution or actual value updates without introducing
    // additional megamorphic accesses for accessing the instance field.
    let inputSignalNode = null;
    if ((flags & InputFlags.SignalBased) !== 0) {
      const field = instance[privateName];
      inputSignalNode = field[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
    }
    // If there is a signal node and a transform, run it before potentially
    // delegating to features like `NgOnChanges`.
    if (inputSignalNode !== null && inputSignalNode.transformFn !== undefined) {
      value = inputSignalNode.transformFn(value);
    }
    // If there is a decorator input transform, run it.
    if ((flags & InputFlags.HasDecoratorInputTransform) !== 0) {
      value = def.inputTransforms[privateName].call(instance, value);
    }
    if (def.setInput !== null) {
      def.setInput(instance, inputSignalNode, value, publicName, privateName);
    } else {
      applyValueToInputField(instance, inputSignalNode, privateName, value);
    }
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}

/**
 * Invoke `HostBindingsFunction`s for view.
 *
 * This methods executes `TView.hostBindingOpCodes`. It is used to execute the
 * `HostBindingsFunction`s associated with the current `LView`.
 *
 * @param tView Current `TView`.
 * @param lView Current `LView`.
 */
function processHostBindingOpCodes(tView, lView) {
  const hostBindingOpCodes = tView.hostBindingOpCodes;
  if (hostBindingOpCodes === null) return;
  try {
    for (let i = 0; i < hostBindingOpCodes.length; i++) {
      const opCode = hostBindingOpCodes[i];
      if (opCode < 0) {
        // Negative numbers are element indexes.
        setSelectedIndex(~opCode);
      } else {
        // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex.
        const directiveIdx = opCode;
        const bindingRootIndx = hostBindingOpCodes[++i];
        const hostBindingFn = hostBindingOpCodes[++i];
        setBindingRootForHostBindings(bindingRootIndx, directiveIdx);
        const context = lView[directiveIdx];
        hostBindingFn(2 /* RenderFlags.Update */, context);
      }
    }
  } finally {
    setSelectedIndex(-1);
  }
}
function createLView(parentLView, tView, context, flags, host, tHostNode, environment, renderer, injector, embeddedViewInjector, hydrationInfo) {
  const lView = tView.blueprint.slice();
  lView[HOST] = host;
  lView[FLAGS] = flags | 4 /* LViewFlags.CreationMode */ | 128 /* LViewFlags.Attached */ | 8 /* LViewFlags.FirstLViewPass */ | 64 /* LViewFlags.Dirty */ | 1024 /* LViewFlags.RefreshView */;
  if (embeddedViewInjector !== null || parentLView && parentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */) {
    lView[FLAGS] |= 2048 /* LViewFlags.HasEmbeddedViewInjector */;
  }
  resetPreOrderHookFlags(lView);
  ngDevMode && tView.declTNode && parentLView && assertTNodeForLView(tView.declTNode, parentLView);
  lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
  lView[CONTEXT] = context;
  lView[ENVIRONMENT] = environment || parentLView && parentLView[ENVIRONMENT];
  ngDevMode && assertDefined(lView[ENVIRONMENT], 'LViewEnvironment is required');
  lView[RENDERER] = renderer || parentLView && parentLView[RENDERER];
  ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
  lView[INJECTOR] = injector || parentLView && parentLView[INJECTOR] || null;
  lView[T_HOST] = tHostNode;
  lView[ID] = getUniqueLViewId();
  lView[HYDRATION] = hydrationInfo;
  lView[EMBEDDED_VIEW_INJECTOR] = embeddedViewInjector;
  ngDevMode && assertEqual(tView.type == 2 /* TViewType.Embedded */ ? parentLView !== null : true, true, 'Embedded views must have parentLView');
  lView[DECLARATION_COMPONENT_VIEW] = tView.type == 2 /* TViewType.Embedded */ ? parentLView[DECLARATION_COMPONENT_VIEW] : lView;
  return lView;
}
function getOrCreateTNode(tView, index, type, name, attrs) {
  ngDevMode && index !== 0 &&
  // 0 are bogus nodes and they are OK. See `createContainerRef` in
  // `view_engine_compatibility` for additional context.
  assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  // Keep this function short, so that the VM will inline it.
  ngDevMode && assertPureTNodeType(type);
  let tNode = tView.data[index];
  if (tNode === null) {
    tNode = createTNodeAtIndex(tView, index, type, name, attrs);
    if (isInI18nBlock()) {
      // If we are in i18n block then all elements should be pre declared through `Placeholder`
      // See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
      // If the `TNode` was not pre-declared than it means it was not mentioned which means it was
      // removed, so we mark it as detached.
      tNode.flags |= 32 /* TNodeFlags.isDetached */;
    }
  } else if (tNode.type & 64 /* TNodeType.Placeholder */) {
    tNode.type = type;
    tNode.value = name;
    tNode.attrs = attrs;
    const parent = getCurrentParentTNode();
    tNode.injectorIndex = parent === null ? -1 : parent.injectorIndex;
    ngDevMode && assertTNodeForTView(tNode, tView);
    ngDevMode && assertEqual(index, tNode.index, 'Expecting same index');
  }
  setCurrentTNode(tNode, true);
  return tNode;
}
function createTNodeAtIndex(tView, index, type, name, attrs) {
  const currentTNode = getCurrentTNodePlaceholderOk();
  const isParent = isCurrentTNodeParent();
  const parent = isParent ? currentTNode : currentTNode && currentTNode.parent;
  // Parents cannot cross component boundaries because components will be used in multiple places.
  const tNode = tView.data[index] = createTNode(tView, parent, type, index, name, attrs);
  // Assign a pointer to the first child node of a given view. The first node is not always the one
  // at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has
  // the index 1 or more, so we can't just check node index.
  if (tView.firstChild === null) {
    tView.firstChild = tNode;
  }
  if (currentTNode !== null) {
    if (isParent) {
      // FIXME(misko): This logic looks unnecessarily complicated. Could we simplify?
      if (currentTNode.child == null && tNode.parent !== null) {
        // We are in the same view, which means we are adding content node to the parent view.
        currentTNode.child = tNode;
      }
    } else {
      if (currentTNode.next === null) {
        // In the case of i18n the `currentTNode` may already be linked, in which case we don't want
        // to break the links which i18n created.
        currentTNode.next = tNode;
        tNode.prev = currentTNode;
      }
    }
  }
  return tNode;
}
/**
 * When elements are created dynamically after a view blueprint is created (e.g. through
 * i18nApply()), we need to adjust the blueprint for future
 * template passes.
 *
 * @param tView `TView` associated with `LView`
 * @param lView The `LView` containing the blueprint to adjust
 * @param numSlotsToAlloc The number of slots to alloc in the LView, should be >0
 * @param initialValue Initial value to store in blueprint
 */
function allocExpando(tView, lView, numSlotsToAlloc, initialValue) {
  if (numSlotsToAlloc === 0) return -1;
  if (ngDevMode) {
    assertFirstCreatePass(tView);
    assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!');
    assertEqual(tView.data.length, lView.length, 'Expecting LView to be same size as TView');
    assertEqual(tView.data.length, tView.blueprint.length, 'Expecting Blueprint to be same size as TView');
    assertFirstUpdatePass(tView);
  }
  const allocIdx = lView.length;
  for (let i = 0; i < numSlotsToAlloc; i++) {
    lView.push(initialValue);
    tView.blueprint.push(initialValue);
    tView.data.push(null);
  }
  return allocIdx;
}
function executeTemplate(tView, lView, templateFn, rf, context) {
  const prevSelectedIndex = getSelectedIndex();
  const isUpdatePhase = rf & 2 /* RenderFlags.Update */;
  try {
    setSelectedIndex(-1);
    if (isUpdatePhase && lView.length > HEADER_OFFSET) {
      // When we're updating, inherently select 0 so we don't
      // have to generate that instruction for most update blocks.
      selectIndexInternal(tView, lView, HEADER_OFFSET, !!ngDevMode && isInCheckNoChangesMode());
    }
    const preHookType = isUpdatePhase ? 2 /* ProfilerEvent.TemplateUpdateStart */ : 0 /* ProfilerEvent.TemplateCreateStart */;
    profiler(preHookType, context);
    templateFn(rf, context);
  } finally {
    setSelectedIndex(prevSelectedIndex);
    const postHookType = isUpdatePhase ? 3 /* ProfilerEvent.TemplateUpdateEnd */ : 1 /* ProfilerEvent.TemplateCreateEnd */;
    profiler(postHookType, context);
  }
}
//////////////////////////
//// Element
//////////////////////////
function executeContentQueries(tView, tNode, lView) {
  if (isContentQueryHost(tNode)) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      const start = tNode.directiveStart;
      const end = tNode.directiveEnd;
      for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
        const def = tView.data[directiveIndex];
        if (def.contentQueries) {
          const directiveInstance = lView[directiveIndex];
          ngDevMode && assertDefined(directiveIndex, 'Incorrect reference to a directive defining a content query');
          def.contentQueries(1 /* RenderFlags.Create */, directiveInstance, directiveIndex);
        }
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
}
/**
 * Creates directive instances.
 */
function createDirectivesInstances(tView, lView, tNode) {
  if (!getBindingsEnabled()) return;
  instantiateAllDirectives(tView, lView, tNode, getNativeByTNode(tNode, lView));
  if ((tNode.flags & 64 /* TNodeFlags.hasHostBindings */) === 64 /* TNodeFlags.hasHostBindings */) {
    invokeDirectivesHostBindings(tView, lView, tNode);
  }
}
/**
 * Takes a list of local names and indices and pushes the resolved local variable values
 * to LView in the same order as they are loaded in the template with load().
 */
function saveResolvedLocalsInData(viewData, tNode, localRefExtractor = getNativeByTNode) {
  const localNames = tNode.localNames;
  if (localNames !== null) {
    let localIndex = tNode.index + 1;
    for (let i = 0; i < localNames.length; i += 2) {
      const index = localNames[i + 1];
      const value = index === -1 ? localRefExtractor(tNode, viewData) : viewData[index];
      viewData[localIndex++] = value;
    }
  }
}
/**
 * Gets TView from a template function or creates a new TView
 * if it doesn't already exist.
 *
 * @param def ComponentDef
 * @returns TView
 */
function getOrCreateComponentTView(def) {
  const tView = def.tView;
  // Create a TView if there isn't one, or recreate it if the first create pass didn't
  // complete successfully since we can't know for sure whether it's in a usable shape.
  if (tView === null || tView.incompleteFirstPass) {
    // Declaration node here is null since this function is called when we dynamically create a
    // component and hence there is no declaration.
    const declTNode = null;
    return def.tView = createTView(1 /* TViewType.Component */, declTNode, def.template, def.decls, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas, def.consts, def.id);
  }
  return tView;
}
/**
 * Creates a TView instance
 *
 * @param type Type of `TView`.
 * @param declTNode Declaration location of this `TView`.
 * @param templateFn Template function
 * @param decls The number of nodes, local refs, and pipes in this template
 * @param directives Registry of directives for this view
 * @param pipes Registry of pipes for this view
 * @param viewQuery View queries for this view
 * @param schemas Schemas for this view
 * @param consts Constants for this view
 */
function createTView(type, declTNode, templateFn, decls, vars, directives, pipes, viewQuery, schemas, constsOrFactory, ssrId) {
  ngDevMode && ngDevMode.tView++;
  const bindingStartIndex = HEADER_OFFSET + decls;
  // This length does not yet contain host bindings from child directives because at this point,
  // we don't know which directives are active on this template. As soon as a directive is matched
  // that has a host binding, we will update the blueprint with that def's hostVars count.
  const initialViewLength = bindingStartIndex + vars;
  const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
  const consts = typeof constsOrFactory === 'function' ? constsOrFactory() : constsOrFactory;
  const tView = blueprint[TVIEW] = {
    type: type,
    blueprint: blueprint,
    template: templateFn,
    queries: null,
    viewQuery: viewQuery,
    declTNode: declTNode,
    data: blueprint.slice().fill(null, bindingStartIndex),
    bindingStartIndex: bindingStartIndex,
    expandoStartIndex: initialViewLength,
    hostBindingOpCodes: null,
    firstCreatePass: true,
    firstUpdatePass: true,
    staticViewQueries: false,
    staticContentQueries: false,
    preOrderHooks: null,
    preOrderCheckHooks: null,
    contentHooks: null,
    contentCheckHooks: null,
    viewHooks: null,
    viewCheckHooks: null,
    destroyHooks: null,
    cleanup: null,
    contentQueries: null,
    components: null,
    directiveRegistry: typeof directives === 'function' ? directives() : directives,
    pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
    firstChild: null,
    schemas: schemas,
    consts: consts,
    incompleteFirstPass: false,
    ssrId
  };
  if (ngDevMode) {
    // For performance reasons it is important that the tView retains the same shape during runtime.
    // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
    // prevent class transitions.
    Object.seal(tView);
  }
  return tView;
}
function createViewBlueprint(bindingStartIndex, initialViewLength) {
  const blueprint = [];
  for (let i = 0; i < initialViewLength; i++) {
    blueprint.push(i < bindingStartIndex ? null : NO_CHANGE);
  }
  return blueprint;
}
/**
 * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
 *
 * @param renderer the renderer used to locate the element.
 * @param elementOrSelector Render element or CSS selector to locate the element.
 * @param encapsulation View Encapsulation defined for component that requests host element.
 * @param injector Root view injector instance.
 */
function locateHostElement(renderer, elementOrSelector, encapsulation, injector) {
  // Note: we use default value for the `PRESERVE_HOST_CONTENT` here even though it's a
  // tree-shakable one (providedIn:'root'). This code path can be triggered during dynamic
  // component creation (after calling ViewContainerRef.createComponent) when an injector
  // instance can be provided. The injector instance might be disconnected from the main DI
  // tree, thus the `PRESERVE_HOST_CONTENT` would not be able to instantiate. In this case, the
  // default value will be used.
  const preserveHostContent = injector.get(PRESERVE_HOST_CONTENT, PRESERVE_HOST_CONTENT_DEFAULT);
  // When using native Shadow DOM, do not clear host element to allow native slot
  // projection.
  const preserveContent = preserveHostContent || encapsulation === ViewEncapsulation.ShadowDom;
  const rootElement = renderer.selectRootElement(elementOrSelector, preserveContent);
  applyRootElementTransform(rootElement);
  return rootElement;
}
/**
 * Applies any root element transformations that are needed. If hydration is enabled,
 * this will process corrupted text nodes.
 *
 * @param rootElement the app root HTML Element
 */
function applyRootElementTransform(rootElement) {
  _applyRootElementTransformImpl(rootElement);
}
/**
 * Reference to a function that applies transformations to the root HTML element
 * of an app. When hydration is enabled, this processes any corrupt text nodes
 * so they are properly hydratable on the client.
 *
 * @param rootElement the app root HTML Element
 */
let _applyRootElementTransformImpl = () => null;
/**
 * Processes text node markers before hydration begins. This replaces any special comment
 * nodes that were added prior to serialization are swapped out to restore proper text
 * nodes before hydration.
 *
 * @param rootElement the app root HTML Element
 */
function applyRootElementTransformImpl(rootElement) {
  if (hasSkipHydrationAttrOnRElement(rootElement)) {
    // Handle a situation when the `ngSkipHydration` attribute is applied
    // to the root node of an application. In this case, we should clear
    // the contents and render everything from scratch.
    clearElementContents(rootElement);
  } else {
    processTextNodeMarkersBeforeHydration(rootElement);
  }
}
/**
 * Sets the implementation for the `applyRootElementTransform` function.
 */
function enableApplyRootElementTransformImpl() {
  _applyRootElementTransformImpl = applyRootElementTransformImpl;
}
/**
 * Saves context for this cleanup function in LView.cleanupInstances.
 *
 * On the first template pass, saves in TView:
 * - Cleanup function
 * - Index of context we just saved in LView.cleanupInstances
 */
function storeCleanupWithContext(tView, lView, context, cleanupFn) {
  const lCleanup = getOrCreateLViewCleanup(lView);
  // Historically the `storeCleanupWithContext` was used to register both framework-level and
  // user-defined cleanup callbacks, but over time those two types of cleanups were separated.
  // This dev mode checks assures that user-level cleanup callbacks are _not_ stored in data
  // structures reserved for framework-specific hooks.
  ngDevMode && assertDefined(context, 'Cleanup context is mandatory when registering framework-level destroy hooks');
  lCleanup.push(context);
  if (tView.firstCreatePass) {
    getOrCreateTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1);
  } else {
    // Make sure that no new framework-level cleanup functions are registered after the first
    // template pass is done (and TView data structures are meant to fully constructed).
    if (ngDevMode) {
      Object.freeze(getOrCreateTViewCleanup(tView));
    }
  }
}
function createTNode(tView, tParent, type, index, value, attrs) {
  ngDevMode && index !== 0 &&
  // 0 are bogus nodes and they are OK. See `createContainerRef` in
  // `view_engine_compatibility` for additional context.
  assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  ngDevMode && assertNotSame(attrs, undefined, "'undefined' is not valid value for 'attrs'");
  ngDevMode && ngDevMode.tNode++;
  ngDevMode && tParent && assertTNodeForTView(tParent, tView);
  let injectorIndex = tParent ? tParent.injectorIndex : -1;
  let flags = 0;
  if (isInSkipHydrationBlock$1()) {
    flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
  }
  const tNode = {
    type,
    index,
    insertBeforeIndex: null,
    injectorIndex,
    directiveStart: -1,
    directiveEnd: -1,
    directiveStylingLast: -1,
    componentOffset: -1,
    propertyBindings: null,
    flags,
    providerIndexes: 0,
    value: value,
    attrs: attrs,
    mergedAttrs: null,
    localNames: null,
    initialInputs: undefined,
    inputs: null,
    outputs: null,
    tView: null,
    next: null,
    prev: null,
    projectionNext: null,
    child: null,
    parent: tParent,
    projection: null,
    styles: null,
    stylesWithoutHost: null,
    residualStyles: undefined,
    classes: null,
    classesWithoutHost: null,
    residualClasses: undefined,
    classBindings: 0,
    styleBindings: 0
  };
  if (ngDevMode) {
    // For performance reasons it is important that the tNode retains the same shape during runtime.
    // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
    // prevent class transitions.
    Object.seal(tNode);
  }
  return tNode;
}
function captureNodeBindings(mode, aliasMap, directiveIndex, bindingsResult, hostDirectiveAliasMap) {
  for (let publicName in aliasMap) {
    if (!aliasMap.hasOwnProperty(publicName)) {
      continue;
    }
    const value = aliasMap[publicName];
    if (value === undefined) {
      continue;
    }
    bindingsResult ??= {};
    let internalName;
    let inputFlags = InputFlags.None;
    // For inputs, the value might be an array capturing additional
    // input flags.
    if (Array.isArray(value)) {
      internalName = value[0];
      inputFlags = value[1];
    } else {
      internalName = value;
    }
    // If there are no host directive mappings, we want to remap using the alias map from the
    // definition itself. If there is an alias map, it has two functions:
    // 1. It serves as an allowlist of bindings that are exposed by the host directives. Only the
    // ones inside the host directive map will be exposed on the host.
    // 2. The public name of the property is aliased using the host directive alias map, rather
    // than the alias map from the definition.
    let finalPublicName = publicName;
    if (hostDirectiveAliasMap !== null) {
      // If there is no mapping, it's not part of the allowlist and this input/output
      // is not captured and should be ignored.
      if (!hostDirectiveAliasMap.hasOwnProperty(publicName)) {
        continue;
      }
      finalPublicName = hostDirectiveAliasMap[publicName];
    }
    if (mode === 0 /* CaptureNodeBindingMode.Inputs */) {
      addPropertyBinding(bindingsResult, directiveIndex, finalPublicName, internalName, inputFlags);
    } else {
      addPropertyBinding(bindingsResult, directiveIndex, finalPublicName, internalName);
    }
  }
  return bindingsResult;
}
function addPropertyBinding(bindings, directiveIndex, publicName, internalName, inputFlags) {
  let values;
  if (bindings.hasOwnProperty(publicName)) {
    (values = bindings[publicName]).push(directiveIndex, internalName);
  } else {
    values = bindings[publicName] = [directiveIndex, internalName];
  }
  if (inputFlags !== undefined) {
    values.push(inputFlags);
  }
}
/**
 * Initializes data structures required to work with directive inputs and outputs.
 * Initialization is done for all directives matched on a given TNode.
 */
function initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefinitionMap) {
  ngDevMode && assertFirstCreatePass(tView);
  const start = tNode.directiveStart;
  const end = tNode.directiveEnd;
  const tViewData = tView.data;
  const tNodeAttrs = tNode.attrs;
  const inputsFromAttrs = [];
  let inputsStore = null;
  let outputsStore = null;
  for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
    const directiveDef = tViewData[directiveIndex];
    const aliasData = hostDirectiveDefinitionMap ? hostDirectiveDefinitionMap.get(directiveDef) : null;
    const aliasedInputs = aliasData ? aliasData.inputs : null;
    const aliasedOutputs = aliasData ? aliasData.outputs : null;
    inputsStore = captureNodeBindings(0 /* CaptureNodeBindingMode.Inputs */, directiveDef.inputs, directiveIndex, inputsStore, aliasedInputs);
    outputsStore = captureNodeBindings(1 /* CaptureNodeBindingMode.Outputs */, directiveDef.outputs, directiveIndex, outputsStore, aliasedOutputs);
    // Do not use unbound attributes as inputs to structural directives, since structural
    // directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`).
    // TODO(FW-1930): microsyntax expressions may also contain unbound/static attributes, which
    // should be set for inline templates.
    const initialInputs = inputsStore !== null && tNodeAttrs !== null && !isInlineTemplate(tNode) ? generateInitialInputs(inputsStore, directiveIndex, tNodeAttrs) : null;
    inputsFromAttrs.push(initialInputs);
  }
  if (inputsStore !== null) {
    if (inputsStore.hasOwnProperty('class')) {
      tNode.flags |= 8 /* TNodeFlags.hasClassInput */;
    }
    if (inputsStore.hasOwnProperty('style')) {
      tNode.flags |= 16 /* TNodeFlags.hasStyleInput */;
    }
  }
  tNode.initialInputs = inputsFromAttrs;
  tNode.inputs = inputsStore;
  tNode.outputs = outputsStore;
}
/**
 * Mapping between attributes names that don't correspond to their element property names.
 *
 * Performance note: this function is written as a series of if checks (instead of, say, a property
 * object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of
 * mapping property names. Do NOT change without benchmarking.
 *
 * Note: this mapping has to be kept in sync with the equally named mapping in the template
 * type-checking machinery of ngtsc.
 */
function mapPropName(name) {
  if (name === 'class') return 'className';
  if (name === 'for') return 'htmlFor';
  if (name === 'formaction') return 'formAction';
  if (name === 'innerHtml') return 'innerHTML';
  if (name === 'readonly') return 'readOnly';
  if (name === 'tabindex') return 'tabIndex';
  return name;
}
function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {
  ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  const element = getNativeByTNode(tNode, lView);
  let inputData = tNode.inputs;
  let dataValue;
  if (!nativeOnly && inputData != null && (dataValue = inputData[propName])) {
    setInputsForProperty(tView, lView, dataValue, propName, value);
    if (isComponentHost(tNode)) markDirtyIfOnPush(lView, tNode.index);
    if (ngDevMode) {
      setNgReflectProperties(lView, element, tNode.type, dataValue, value);
    }
  } else if (tNode.type & 3 /* TNodeType.AnyRNode */) {
    propName = mapPropName(propName);
    if (ngDevMode) {
      validateAgainstEventProperties(propName);
      if (!isPropertyValid(element, propName, tNode.value, tView.schemas)) {
        handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
      }
      ngDevMode.rendererSetProperty++;
    }
    // It is assumed that the sanitizer is only added when the compiler determines that the
    // property is risky, so sanitization can be done without further checks.
    value = sanitizer != null ? sanitizer(value, tNode.value || '', propName) : value;
    renderer.setProperty(element, propName, value);
  } else if (tNode.type & 12 /* TNodeType.AnyContainer */) {
    // If the node is a container and the property didn't
    // match any of the inputs or schemas we should throw.
    if (ngDevMode && !matchingSchemas(tView.schemas, tNode.value)) {
      handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
    }
  }
}
/** If node is an OnPush component, marks its LView dirty. */
function markDirtyIfOnPush(lView, viewIndex) {
  ngDevMode && assertLView(lView);
  const childComponentLView = getComponentLViewByIndex(viewIndex, lView);
  if (!(childComponentLView[FLAGS] & 16 /* LViewFlags.CheckAlways */)) {
    childComponentLView[FLAGS] |= 64 /* LViewFlags.Dirty */;
  }
}
function setNgReflectProperty(lView, element, type, attrName, value) {
  const renderer = lView[RENDERER];
  attrName = normalizeDebugBindingName(attrName);
  const debugValue = normalizeDebugBindingValue(value);
  if (type & 3 /* TNodeType.AnyRNode */) {
    if (value == null) {
      renderer.removeAttribute(element, attrName);
    } else {
      renderer.setAttribute(element, attrName, debugValue);
    }
  } else {
    const textContent = escapeCommentText(`bindings=${JSON.stringify({
      [attrName]: debugValue
    }, null, 2)}`);
    renderer.setValue(element, textContent);
  }
}
function setNgReflectProperties(lView, element, type, dataValue, value) {
  if (type & (3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */)) {
    /**
     * dataValue is an array containing runtime input or output names for the directives:
     * i+0: directive instance index
     * i+1: privateName
     *
     * e.g. [0, 'change', 'change-minified']
     * we want to set the reflected property with the privateName: dataValue[i+1]
     */
    for (let i = 0; i < dataValue.length; i += 3) {
      setNgReflectProperty(lView, element, type, dataValue[i + 1], value);
    }
  }
}
/**
 * Resolve the matched directives on a node.
 */
function resolveDirectives(tView, lView, tNode, localRefs) {
  // Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in
  // tsickle.
  ngDevMode && assertFirstCreatePass(tView);
  if (getBindingsEnabled()) {
    const exportsMap = localRefs === null ? null : {
      '': -1
    };
    const matchResult = findDirectiveDefMatches(tView, tNode);
    let directiveDefs;
    let hostDirectiveDefs;
    if (matchResult === null) {
      directiveDefs = hostDirectiveDefs = null;
    } else {
      [directiveDefs, hostDirectiveDefs] = matchResult;
    }
    if (directiveDefs !== null) {
      initializeDirectives(tView, lView, tNode, directiveDefs, exportsMap, hostDirectiveDefs);
    }
    if (exportsMap) cacheMatchingLocalNames(tNode, localRefs, exportsMap);
  }
  // Merge the template attrs last so that they have the highest priority.
  tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
}
/** Initializes the data structures necessary for a list of directives to be instantiated. */
function initializeDirectives(tView, lView, tNode, directives, exportsMap, hostDirectiveDefs) {
  ngDevMode && assertFirstCreatePass(tView);
  // Publishes the directive types to DI so they can be injected. Needs to
  // happen in a separate pass before the TNode flags have been initialized.
  for (let i = 0; i < directives.length; i++) {
    diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, directives[i].type);
  }
  initTNodeFlags(tNode, tView.data.length, directives.length);
  // When the same token is provided by several directives on the same node, some rules apply in
  // the viewEngine:
  // - viewProviders have priority over providers
  // - the last directive in NgModule.declarations has priority over the previous one
  // So to match these rules, the order in which providers are added in the arrays is very
  // important.
  for (let i = 0; i < directives.length; i++) {
    const def = directives[i];
    if (def.providersResolver) def.providersResolver(def);
  }
  let preOrderHooksFound = false;
  let preOrderCheckHooksFound = false;
  let directiveIdx = allocExpando(tView, lView, directives.length, null);
  ngDevMode && assertSame(directiveIdx, tNode.directiveStart, 'TNode.directiveStart should point to just allocated space');
  for (let i = 0; i < directives.length; i++) {
    const def = directives[i];
    // Merge the attrs in the order of matches. This assumes that the first directive is the
    // component itself, so that the component has the least priority.
    tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
    configureViewWithDirective(tView, tNode, lView, directiveIdx, def);
    saveNameToExportMap(directiveIdx, def, exportsMap);
    if (def.contentQueries !== null) tNode.flags |= 4 /* TNodeFlags.hasContentQuery */;
    if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0) tNode.flags |= 64 /* TNodeFlags.hasHostBindings */;
    const lifeCycleHooks = def.type.prototype;
    // Only push a node index into the preOrderHooks array if this is the first
    // pre-order hook found on this node.
    if (!preOrderHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngOnInit || lifeCycleHooks.ngDoCheck)) {
      // We will push the actual hook function into this array later during dir instantiation.
      // We cannot do it now because we must ensure hooks are registered in the same
      // order that directives are created (i.e. injection order).
      (tView.preOrderHooks ??= []).push(tNode.index);
      preOrderHooksFound = true;
    }
    if (!preOrderCheckHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngDoCheck)) {
      (tView.preOrderCheckHooks ??= []).push(tNode.index);
      preOrderCheckHooksFound = true;
    }
    directiveIdx++;
  }
  initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs);
}
/**
 * Add `hostBindings` to the `TView.hostBindingOpCodes`.
 *
 * @param tView `TView` to which the `hostBindings` should be added.
 * @param tNode `TNode` the element which contains the directive
 * @param directiveIdx Directive index in view.
 * @param directiveVarsIdx Where will the directive's vars be stored
 * @param def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add.
 */
function registerHostBindingOpCodes(tView, tNode, directiveIdx, directiveVarsIdx, def) {
  ngDevMode && assertFirstCreatePass(tView);
  const hostBindings = def.hostBindings;
  if (hostBindings) {
    let hostBindingOpCodes = tView.hostBindingOpCodes;
    if (hostBindingOpCodes === null) {
      hostBindingOpCodes = tView.hostBindingOpCodes = [];
    }
    const elementIndx = ~tNode.index;
    if (lastSelectedElementIdx(hostBindingOpCodes) != elementIndx) {
      // Conditionally add select element so that we are more efficient in execution.
      // NOTE: this is strictly not necessary and it trades code size for runtime perf.
      // (We could just always add it.)
      hostBindingOpCodes.push(elementIndx);
    }
    hostBindingOpCodes.push(directiveIdx, directiveVarsIdx, hostBindings);
  }
}
/**
 * Returns the last selected element index in the `HostBindingOpCodes`
 *
 * For perf reasons we don't need to update the selected element index in `HostBindingOpCodes` only
 * if it changes. This method returns the last index (or '0' if not found.)
 *
 * Selected element index are only the ones which are negative.
 */
function lastSelectedElementIdx(hostBindingOpCodes) {
  let i = hostBindingOpCodes.length;
  while (i > 0) {
    const value = hostBindingOpCodes[--i];
    if (typeof value === 'number' && value < 0) {
      return value;
    }
  }
  return 0;
}
/**
 * Instantiate all the directives that were previously resolved on the current node.
 */
function instantiateAllDirectives(tView, lView, tNode, native) {
  const start = tNode.directiveStart;
  const end = tNode.directiveEnd;
  // The component view needs to be created before creating the node injector
  // since it is used to inject some special symbols like `ChangeDetectorRef`.
  if (isComponentHost(tNode)) {
    ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
    addComponentLogic(lView, tNode, tView.data[start + tNode.componentOffset]);
  }
  if (!tView.firstCreatePass) {
    getOrCreateNodeInjectorForNode(tNode, lView);
  }
  attachPatchData(native, lView);
  const initialInputs = tNode.initialInputs;
  for (let i = start; i < end; i++) {
    const def = tView.data[i];
    const directive = getNodeInjectable(lView, tView, i, tNode);
    attachPatchData(directive, lView);
    if (initialInputs !== null) {
      setInputsFromAttrs(lView, i - start, directive, def, tNode, initialInputs);
    }
    if (isComponentDef(def)) {
      const componentView = getComponentLViewByIndex(tNode.index, lView);
      componentView[CONTEXT] = getNodeInjectable(lView, tView, i, tNode);
    }
  }
}
function invokeDirectivesHostBindings(tView, lView, tNode) {
  const start = tNode.directiveStart;
  const end = tNode.directiveEnd;
  const elementIndex = tNode.index;
  const currentDirectiveIndex = getCurrentDirectiveIndex();
  try {
    setSelectedIndex(elementIndex);
    for (let dirIndex = start; dirIndex < end; dirIndex++) {
      const def = tView.data[dirIndex];
      const directive = lView[dirIndex];
      setCurrentDirectiveIndex(dirIndex);
      if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) {
        invokeHostBindingsInCreationMode(def, directive);
      }
    }
  } finally {
    setSelectedIndex(-1);
    setCurrentDirectiveIndex(currentDirectiveIndex);
  }
}
/**
 * Invoke the host bindings in creation mode.
 *
 * @param def `DirectiveDef` which may contain the `hostBindings` function.
 * @param directive Instance of directive.
 */
function invokeHostBindingsInCreationMode(def, directive) {
  if (def.hostBindings !== null) {
    def.hostBindings(1 /* RenderFlags.Create */, directive);
  }
}
/**
 * Matches the current node against all available selectors.
 * If a component is matched (at most one), it is returned in first position in the array.
 */
function findDirectiveDefMatches(tView, tNode) {
  ngDevMode && assertFirstCreatePass(tView);
  ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  const registry = tView.directiveRegistry;
  let matches = null;
  let hostDirectiveDefs = null;
  if (registry) {
    for (let i = 0; i < registry.length; i++) {
      const def = registry[i];
      if (isNodeMatchingSelectorList(tNode, def.selectors, /* isProjectionMode */false)) {
        matches || (matches = []);
        if (isComponentDef(def)) {
          if (ngDevMode) {
            assertTNodeType(tNode, 2 /* TNodeType.Element */, `"${tNode.value}" tags cannot be used as component hosts. ` + `Please use a different tag to activate the ${stringify(def.type)} component.`);
            if (isComponentHost(tNode)) {
              throwMultipleComponentError(tNode, matches.find(isComponentDef).type, def.type);
            }
          }
          // Components are inserted at the front of the matches array so that their lifecycle
          // hooks run before any directive lifecycle hooks. This appears to be for ViewEngine
          // compatibility. This logic doesn't make sense with host directives, because it
          // would allow the host directives to undo any overrides the host may have made.
          // To handle this case, the host directives of components are inserted at the beginning
          // of the array, followed by the component. As such, the insertion order is as follows:
          // 1. Host directives belonging to the selector-matched component.
          // 2. Selector-matched component.
          // 3. Host directives belonging to selector-matched directives.
          // 4. Selector-matched directives.
          if (def.findHostDirectiveDefs !== null) {
            const hostDirectiveMatches = [];
            hostDirectiveDefs = hostDirectiveDefs || new Map();
            def.findHostDirectiveDefs(def, hostDirectiveMatches, hostDirectiveDefs);
            // Add all host directives declared on this component, followed by the component itself.
            // Host directives should execute first so the host has a chance to override changes
            // to the DOM made by them.
            matches.unshift(...hostDirectiveMatches, def);
            // Component is offset starting from the beginning of the host directives array.
            const componentOffset = hostDirectiveMatches.length;
            markAsComponentHost(tView, tNode, componentOffset);
          } else {
            // No host directives on this component, just add the
            // component def to the beginning of the matches.
            matches.unshift(def);
            markAsComponentHost(tView, tNode, 0);
          }
        } else {
          // Append any host directives to the matches first.
          hostDirectiveDefs = hostDirectiveDefs || new Map();
          def.findHostDirectiveDefs?.(def, matches, hostDirectiveDefs);
          matches.push(def);
        }
      }
    }
  }
  ngDevMode && matches !== null && assertNoDuplicateDirectives(matches);
  return matches === null ? null : [matches, hostDirectiveDefs];
}
/**
 * Marks a given TNode as a component's host. This consists of:
 * - setting the component offset on the TNode.
 * - storing index of component's host element so it will be queued for view refresh during CD.
 */
function markAsComponentHost(tView, hostTNode, componentOffset) {
  ngDevMode && assertFirstCreatePass(tView);
  ngDevMode && assertGreaterThan(componentOffset, -1, 'componentOffset must be great than -1');
  hostTNode.componentOffset = componentOffset;
  (tView.components ??= []).push(hostTNode.index);
}
/** Caches local names and their matching directive indices for query and template lookups. */
function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
  if (localRefs) {
    const localNames = tNode.localNames = [];
    // Local names must be stored in tNode in the same order that localRefs are defined
    // in the template to ensure the data is loaded in the same slots as their refs
    // in the template (for template queries).
    for (let i = 0; i < localRefs.length; i += 2) {
      const index = exportsMap[localRefs[i + 1]];
      if (index == null) throw new RuntimeError(-301 /* RuntimeErrorCode.EXPORT_NOT_FOUND */, ngDevMode && `Export of name '${localRefs[i + 1]}' not found!`);
      localNames.push(localRefs[i], index);
    }
  }
}
/**
 * Builds up an export map as directives are created, so local refs can be quickly mapped
 * to their directive instances.
 */
function saveNameToExportMap(directiveIdx, def, exportsMap) {
  if (exportsMap) {
    if (def.exportAs) {
      for (let i = 0; i < def.exportAs.length; i++) {
        exportsMap[def.exportAs[i]] = directiveIdx;
      }
    }
    if (isComponentDef(def)) exportsMap[''] = directiveIdx;
  }
}
/**
 * Initializes the flags on the current node, setting all indices to the initial index,
 * the directive count to 0, and adding the isComponent flag.
 * @param index the initial index
 */
function initTNodeFlags(tNode, index, numberOfDirectives) {
  ngDevMode && assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
  tNode.flags |= 1 /* TNodeFlags.isDirectiveHost */;
  // When the first directive is created on a node, save the index
  tNode.directiveStart = index;
  tNode.directiveEnd = index + numberOfDirectives;
  tNode.providerIndexes = index;
}
/**
 * Setup directive for instantiation.
 *
 * We need to create a `NodeInjectorFactory` which is then inserted in both the `Blueprint` as well
 * as `LView`. `TView` gets the `DirectiveDef`.
 *
 * @param tView `TView`
 * @param tNode `TNode`
 * @param lView `LView`
 * @param directiveIndex Index where the directive will be stored in the Expando.
 * @param def `DirectiveDef`
 */
function configureViewWithDirective(tView, tNode, lView, directiveIndex, def) {
  ngDevMode && assertGreaterThanOrEqual(directiveIndex, HEADER_OFFSET, 'Must be in Expando section');
  tView.data[directiveIndex] = def;
  const directiveFactory = def.factory || (def.factory = getFactoryDef(def.type, true));
  // Even though `directiveFactory` will already be using `ɵɵdirectiveInject` in its generated code,
  // we also want to support `inject()` directly from the directive constructor context so we set
  // `ɵɵdirectiveInject` as the inject implementation here too.
  const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), ɵɵdirectiveInject);
  tView.blueprint[directiveIndex] = nodeInjectorFactory;
  lView[directiveIndex] = nodeInjectorFactory;
  registerHostBindingOpCodes(tView, tNode, directiveIndex, allocExpando(tView, lView, def.hostVars, NO_CHANGE), def);
}
/**
 * Gets the initial set of LView flags based on the component definition that the LView represents.
 * @param def Component definition from which to determine the flags.
 */
function getInitialLViewFlagsFromDef(def) {
  let flags = 16 /* LViewFlags.CheckAlways */;
  if (def.signals) {
    flags = 4096 /* LViewFlags.SignalView */;
  } else if (def.onPush) {
    flags = 64 /* LViewFlags.Dirty */;
  }
  return flags;
}
function addComponentLogic(lView, hostTNode, def) {
  const native = getNativeByTNode(hostTNode, lView);
  const tView = getOrCreateComponentTView(def);
  // Only component views should be added to the view tree directly. Embedded views are
  // accessed through their containers because they may be removed / re-added later.
  const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  const componentView = addToEndOfViewTree(lView, createLView(lView, tView, null, getInitialLViewFlagsFromDef(def), native, hostTNode, null, rendererFactory.createRenderer(native, def), null, null, null));
  // Component view will always be created before any injected LContainers,
  // so this is a regular element, wrap it with the component view
  lView[hostTNode.index] = componentView;
}
function elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace) {
  if (ngDevMode) {
    assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
    validateAgainstEventAttributes(name);
    assertTNodeType(tNode, 2 /* TNodeType.Element */, `Attempted to set attribute \`${name}\` on a container node. ` + `Host bindings are not valid on ng-container or ng-template.`);
  }
  const element = getNativeByTNode(tNode, lView);
  setElementAttribute(lView[RENDERER], element, namespace, tNode.value, name, value, sanitizer);
}
function setElementAttribute(renderer, element, namespace, tagName, name, value, sanitizer) {
  if (value == null) {
    ngDevMode && ngDevMode.rendererRemoveAttribute++;
    renderer.removeAttribute(element, name, namespace);
  } else {
    ngDevMode && ngDevMode.rendererSetAttribute++;
    const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tagName || '', name);
    renderer.setAttribute(element, name, strValue, namespace);
  }
}
/**
 * Sets initial input properties on directive instances from attribute data
 *
 * @param lView Current LView that is being processed.
 * @param directiveIndex Index of the directive in directives array
 * @param instance Instance of the directive on which to set the initial inputs
 * @param def The directive def that contains the list of inputs
 * @param tNode The static data for this node
 */
function setInputsFromAttrs(lView, directiveIndex, instance, def, tNode, initialInputData) {
  const initialInputs = initialInputData[directiveIndex];
  if (initialInputs !== null) {
    for (let i = 0; i < initialInputs.length;) {
      const publicName = initialInputs[i++];
      const privateName = initialInputs[i++];
      const flags = initialInputs[i++];
      const value = initialInputs[i++];
      writeToDirectiveInput(def, instance, publicName, privateName, flags, value);
      if (ngDevMode) {
        const nativeElement = getNativeByTNode(tNode, lView);
        setNgReflectProperty(lView, nativeElement, tNode.type, privateName, value);
      }
    }
  }
}
/**
 * Generates initialInputData for a node and stores it in the template's static storage
 * so subsequent template invocations don't have to recalculate it.
 *
 * initialInputData is an array containing values that need to be set as input properties
 * for directives on this node, but only once on creation. We need this array to support
 * the case where you set an @Input property of a directive using attribute-like syntax.
 * e.g. if you have a `name` @Input, you can set it once like this:
 *
 * <my-component name="Bess"></my-component>
 *
 * @param inputs Input alias map that was generated from the directive def inputs.
 * @param directiveIndex Index of the directive that is currently being processed.
 * @param attrs Static attrs on this node.
 */
function generateInitialInputs(inputs, directiveIndex, attrs) {
  let inputsToStore = null;
  let i = 0;
  while (i < attrs.length) {
    const attrName = attrs[i];
    if (attrName === 0 /* AttributeMarker.NamespaceURI */) {
      // We do not allow inputs on namespaced attributes.
      i += 4;
      continue;
    } else if (attrName === 5 /* AttributeMarker.ProjectAs */) {
      // Skip over the `ngProjectAs` value.
      i += 2;
      continue;
    }
    // If we hit any other attribute markers, we're done anyway. None of those are valid inputs.
    if (typeof attrName === 'number') break;
    if (inputs.hasOwnProperty(attrName)) {
      if (inputsToStore === null) inputsToStore = [];
      // Find the input's public name from the input store. Note that we can be found easier
      // through the directive def, but we want to do it using the inputs store so that it can
      // account for host directive aliases.
      const inputConfig = inputs[attrName];
      for (let j = 0; j < inputConfig.length; j += 3) {
        if (inputConfig[j] === directiveIndex) {
          inputsToStore.push(attrName, inputConfig[j + 1], inputConfig[j + 2], attrs[i + 1]);
          // A directive can't have multiple inputs with the same name so we can break here.
          break;
        }
      }
    }
    i += 2;
  }
  return inputsToStore;
}
//////////////////////////
//// ViewContainer & View
//////////////////////////
/**
 * Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
 *
 * @param hostNative The host element for the LContainer
 * @param hostTNode The host TNode for the LContainer
 * @param currentView The parent view of the LContainer
 * @param native The native comment element
 * @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case
 * @returns LContainer
 */
function createLContainer(hostNative, currentView, native, tNode) {
  ngDevMode && assertLView(currentView);
  const lContainer = [hostNative,
  // host native
  true,
  // Boolean `true` in this position signifies that this is an `LContainer`
  0,
  // flags
  currentView,
  // parent
  null,
  // next
  tNode,
  // t_host
  null,
  // dehydrated views
  native,
  // native,
  null,
  // view refs
  null // moved views
  ];
  ngDevMode && assertEqual(lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.');
  return lContainer;
}
/** Refreshes all content queries declared by directives in a given view */
function refreshContentQueries(tView, lView) {
  const contentQueries = tView.contentQueries;
  if (contentQueries !== null) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      for (let i = 0; i < contentQueries.length; i += 2) {
        const queryStartIdx = contentQueries[i];
        const directiveDefIdx = contentQueries[i + 1];
        if (directiveDefIdx !== -1) {
          const directiveDef = tView.data[directiveDefIdx];
          ngDevMode && assertDefined(directiveDef, 'DirectiveDef not found.');
          ngDevMode && assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
          setCurrentQueryIndex(queryStartIdx);
          directiveDef.contentQueries(2 /* RenderFlags.Update */, lView[directiveDefIdx], directiveDefIdx);
        }
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
}
/**
 * Adds LView or LContainer to the end of the current view tree.
 *
 * This structure will be used to traverse through nested views to remove listeners
 * and call onDestroy callbacks.
 *
 * @param lView The view where LView or LContainer should be added
 * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header
 * @param lViewOrLContainer The LView or LContainer to add to the view tree
 * @returns The state passed in
 */
function addToEndOfViewTree(lView, lViewOrLContainer) {
  // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
  // to the end of the queue, which means if the developer retrieves the LContainers from RNodes out
  // of order, the change detection will run out of order, as the act of retrieving the the
  // LContainer from the RNode is what adds it to the queue.
  if (lView[CHILD_HEAD]) {
    lView[CHILD_TAIL][NEXT] = lViewOrLContainer;
  } else {
    lView[CHILD_HEAD] = lViewOrLContainer;
  }
  lView[CHILD_TAIL] = lViewOrLContainer;
  return lViewOrLContainer;
}
///////////////////////////////
//// Change detection
///////////////////////////////
function executeViewQueryFn(flags, viewQueryFn, component) {
  ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');
  setCurrentQueryIndex(0);
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    viewQueryFn(flags, component);
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
///////////////////////////////
//// Bindings & interpolations
///////////////////////////////
/**
 * Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`.
 *
 * In order to support TestBed's `DebugElement.properties` we need to save, for each binding:
 * - a bound property name;
 * - a static parts of interpolated strings;
 *
 * A given property metadata is saved at the binding's index in the `TView.data` (in other words, a
 * property binding metadata will be stored in `TView.data` at the same index as a bound value in
 * `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the
 * following format:
 * - `propertyName` for bound properties;
 * - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for
 * interpolated properties.
 *
 * @param tData `TData` where meta-data will be saved;
 * @param tNode `TNode` that is a target of the binding;
 * @param propertyName bound property name;
 * @param bindingIndex binding index in `LView`
 * @param interpolationParts static interpolation parts (for property interpolations)
 */
function storePropertyBindingMetadata(tData, tNode, propertyName, bindingIndex, ...interpolationParts) {
  // Binding meta-data are stored only the first time a given property instruction is processed.
  // Since we don't have a concept of the "first update pass" we need to check for presence of the
  // binding meta-data to decide if one should be stored (or if was stored already).
  if (tData[bindingIndex] === null) {
    if (tNode.inputs == null || !tNode.inputs[propertyName]) {
      const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []);
      propBindingIdxs.push(bindingIndex);
      let bindingMetadata = propertyName;
      if (interpolationParts.length > 0) {
        bindingMetadata += INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER);
      }
      tData[bindingIndex] = bindingMetadata;
    }
  }
}
function getOrCreateLViewCleanup(view) {
  // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  return view[CLEANUP] ??= [];
}
function getOrCreateTViewCleanup(tView) {
  return tView.cleanup ??= [];
}
/**
 * There are cases where the sub component's renderer needs to be included
 * instead of the current renderer (see the componentSyntheticHost* instructions).
 */
function loadComponentRenderer(currentDef, tNode, lView) {
  // TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root
  // component (see packages/core/src/render3/component.ts). This is not consistent with the process
  // of creating inner components, when current directive index is available in the state. In order
  // to avoid relying on current def being `null` (thus special-casing root component creation), the
  // process of creating root component should be unified with the process of creating inner
  // components.
  if (currentDef === null || isComponentDef(currentDef)) {
    lView = unwrapLView(lView[tNode.index]);
  }
  return lView[RENDERER];
}
/** Handles an error thrown in an LView. */
function handleError(lView, error) {
  const injector = lView[INJECTOR];
  const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  errorHandler && errorHandler.handleError(error);
}
/**
 * Set the inputs of directives at the current node to corresponding value.
 *
 * @param tView The current TView
 * @param lView the `LView` which contains the directives.
 * @param inputs mapping between the public "input" name and privately-known,
 *        possibly minified, property names to write to.
 * @param value Value to set.
 */
function setInputsForProperty(tView, lView, inputs, publicName, value) {
  for (let i = 0; i < inputs.length;) {
    const index = inputs[i++];
    const privateName = inputs[i++];
    const flags = inputs[i++];
    const instance = lView[index];
    ngDevMode && assertIndexInRange(lView, index);
    const def = tView.data[index];
    writeToDirectiveInput(def, instance, publicName, privateName, flags, value);
  }
}
/**
 * Updates a text binding at a given index in a given LView.
 */
function textBindingInternal(lView, index, value) {
  ngDevMode && assertString(value, 'Value should be a string');
  ngDevMode && assertNotSame(value, NO_CHANGE, 'value should not be NO_CHANGE');
  ngDevMode && assertIndexInRange(lView, index);
  const element = getNativeByIndex(index, lView);
  ngDevMode && assertDefined(element, 'native element should exist');
  updateTextNode(lView[RENDERER], element, value);
}
function renderComponent(hostLView, componentHostIdx) {
  ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
  const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  const componentTView = componentView[TVIEW];
  syncViewWithBlueprint(componentTView, componentView);
  const hostRNode = componentView[HOST];
  // Populate an LView with hydration info retrieved from the DOM via TransferState.
  if (hostRNode !== null && componentView[HYDRATION] === null) {
    componentView[HYDRATION] = retrieveHydrationInfo(hostRNode, componentView[INJECTOR]);
  }
  renderView(componentTView, componentView, componentView[CONTEXT]);
}
/**
 * Syncs an LView instance with its blueprint if they have gotten out of sync.
 *
 * Typically, blueprints and their view instances should always be in sync, so the loop here
 * will be skipped. However, consider this case of two components side-by-side:
 *
 * App template:
 * ```
 * <comp></comp>
 * <comp></comp>
 * ```
 *
 * The following will happen:
 * 1. App template begins processing.
 * 2. First <comp> is matched as a component and its LView is created.
 * 3. Second <comp> is matched as a component and its LView is created.
 * 4. App template completes processing, so it's time to check child templates.
 * 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
 * 6. Second <comp> template is checked. Its blueprint has been updated by the first
 * <comp> template, but its LView was created before this update, so it is out of sync.
 *
 * Note that embedded views inside ngFor loops will never be out of sync because these views
 * are processed as soon as they are created.
 *
 * @param tView The `TView` that contains the blueprint for syncing
 * @param lView The view to sync
 */
function syncViewWithBlueprint(tView, lView) {
  for (let i = lView.length; i < tView.blueprint.length; i++) {
    lView.push(tView.blueprint[i]);
  }
}
/**
 * Processes a view in the creation mode. This includes a number of steps in a specific order:
 * - creating view query functions (if any);
 * - executing a template function in the creation mode;
 * - updating static queries (if any);
 * - creating child components defined in a given view.
 */
function renderView(tView, lView, context) {
  ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
  ngDevMode && assertNotReactive(renderView.name);
  enterView(lView);
  try {
    const viewQuery = tView.viewQuery;
    if (viewQuery !== null) {
      executeViewQueryFn(1 /* RenderFlags.Create */, viewQuery, context);
    }
    // Execute a template associated with this view, if it exists. A template function might not be
    // defined for the root component views.
    const templateFn = tView.template;
    if (templateFn !== null) {
      executeTemplate(tView, lView, templateFn, 1 /* RenderFlags.Create */, context);
    }
    // This needs to be set before children are processed to support recursive components.
    // This must be set to false immediately after the first creation run because in an
    // ngFor loop, all the views will be created together before update mode runs and turns
    // off firstCreatePass. If we don't set it here, instances will perform directive
    // matching, etc again and again.
    if (tView.firstCreatePass) {
      tView.firstCreatePass = false;
    }
    // Mark all queries active in this view as dirty. This is necessary for signal-based queries to
    // have a clear marking point where we can read query results atomically (for a given view).
    lView[QUERIES]?.finishViewCreation(tView);
    // We resolve content queries specifically marked as `static` in creation mode. Dynamic
    // content queries are resolved during change detection (i.e. update mode), after embedded
    // views are refreshed (see block above).
    if (tView.staticContentQueries) {
      refreshContentQueries(tView, lView);
    }
    // We must materialize query results before child components are processed
    // in case a child component has projected a container. The LContainer needs
    // to exist so the embedded views are properly attached by the container.
    if (tView.staticViewQueries) {
      executeViewQueryFn(2 /* RenderFlags.Update */, tView.viewQuery, context);
    }
    // Render child component views.
    const components = tView.components;
    if (components !== null) {
      renderChildComponents(lView, components);
    }
  } catch (error) {
    // If we didn't manage to get past the first template pass due to
    // an error, mark the view as corrupted so we can try to recover.
    if (tView.firstCreatePass) {
      tView.incompleteFirstPass = true;
      tView.firstCreatePass = false;
    }
    throw error;
  } finally {
    lView[FLAGS] &= ~4 /* LViewFlags.CreationMode */;
    leaveView();
  }
}
/** Renders child components in the current view (creation mode). */
function renderChildComponents(hostLView, components) {
  for (let i = 0; i < components.length; i++) {
    renderComponent(hostLView, components[i]);
  }
}
function createAndRenderEmbeddedLView(declarationLView, templateTNode, context, options) {
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    const embeddedTView = templateTNode.tView;
    ngDevMode && assertDefined(embeddedTView, 'TView must be defined for a template node.');
    ngDevMode && assertTNodeForLView(templateTNode, declarationLView);
    // Embedded views follow the change detection strategy of the view they're declared in.
    const isSignalView = declarationLView[FLAGS] & 4096 /* LViewFlags.SignalView */;
    const viewFlags = isSignalView ? 4096 /* LViewFlags.SignalView */ : 16 /* LViewFlags.CheckAlways */;
    const embeddedLView = createLView(declarationLView, embeddedTView, context, viewFlags, null, templateTNode, null, null, options?.injector ?? null, options?.embeddedViewInjector ?? null, options?.dehydratedView ?? null);
    const declarationLContainer = declarationLView[templateTNode.index];
    ngDevMode && assertLContainer(declarationLContainer);
    embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
    const declarationViewLQueries = declarationLView[QUERIES];
    if (declarationViewLQueries !== null) {
      embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
    }
    // execute creation mode of a view
    renderView(embeddedTView, embeddedLView, context);
    return embeddedLView;
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
function getLViewFromLContainer(lContainer, index) {
  const adjustedIndex = CONTAINER_HEADER_OFFSET + index;
  // avoid reading past the array boundaries
  if (adjustedIndex < lContainer.length) {
    const lView = lContainer[adjustedIndex];
    ngDevMode && assertLView(lView);
    return lView;
  }
  return undefined;
}
/**
 * Returns whether an elements that belong to a view should be
 * inserted into the DOM. For client-only cases, DOM elements are
 * always inserted. For hydration cases, we check whether serialized
 * info is available for a view and the view is not in a "skip hydration"
 * block (in which case view contents was re-created, thus needing insertion).
 */
function shouldAddViewToDom(tNode, dehydratedView) {
  return !dehydratedView || dehydratedView.firstChild === null || hasInSkipHydrationBlockFlag(tNode);
}
function addLViewToLContainer(lContainer, lView, index, addToDOM = true) {
  const tView = lView[TVIEW];
  // Insert into the view tree so the new view can be change-detected
  insertView(tView, lView, lContainer, index);
  // Insert elements that belong to this view into the DOM tree
  if (addToDOM) {
    const beforeNode = getBeforeNodeForView(index, lContainer);
    const renderer = lView[RENDERER];
    const parentRNode = nativeParentNode(renderer, lContainer[NATIVE]);
    if (parentRNode !== null) {
      addViewToDOM(tView, lContainer[T_HOST], renderer, lView, parentRNode, beforeNode);
    }
  }
  // When in hydration mode, reset the pointer to the first child in
  // the dehydrated view. This indicates that the view was hydrated and
  // further attaching/detaching should work with this view as normal.
  const hydrationInfo = lView[HYDRATION];
  if (hydrationInfo !== null && hydrationInfo.firstChild !== null) {
    hydrationInfo.firstChild = null;
  }
}
function removeLViewFromLContainer(lContainer, index) {
  const lView = detachView(lContainer, index);
  if (lView !== undefined) {
    destroyLView(lView[TVIEW], lView);
  }
  return lView;
}
function collectNativeNodes(tView, lView, tNode, result, isProjection = false) {
  while (tNode !== null) {
    // Let declarations don't have corresponding DOM nodes so we skip over them.
    if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
      tNode = isProjection ? tNode.projectionNext : tNode.next;
      continue;
    }
    ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
    const lNode = lView[tNode.index];
    if (lNode !== null) {
      result.push(unwrapRNode(lNode));
    }
    // A given lNode can represent either a native node or a LContainer (when it is a host of a
    // ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
    // from the views in this container.
    if (isLContainer(lNode)) {
      collectNativeNodesInLContainer(lNode, result);
    }
    const tNodeType = tNode.type;
    if (tNodeType & 8 /* TNodeType.ElementContainer */) {
      collectNativeNodes(tView, lView, tNode.child, result);
    } else if (tNodeType & 32 /* TNodeType.Icu */) {
      const nextRNode = icuContainerIterate(tNode, lView);
      let rNode;
      while (rNode = nextRNode()) {
        result.push(rNode);
      }
    } else if (tNodeType & 16 /* TNodeType.Projection */) {
      const nodesInSlot = getProjectionNodes(lView, tNode);
      if (Array.isArray(nodesInSlot)) {
        result.push(...nodesInSlot);
      } else {
        const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
        ngDevMode && assertParentView(parentView);
        collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
      }
    }
    tNode = isProjection ? tNode.projectionNext : tNode.next;
  }
  return result;
}
/**
 * Collects all root nodes in all views in a given LContainer.
 */
function collectNativeNodesInLContainer(lContainer, result) {
  for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
    const lViewInAContainer = lContainer[i];
    const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
    if (lViewFirstChildTNode !== null) {
      collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
    }
  }
  // When an LContainer is created, the anchor (comment) node is:
  // - (1) either reused in case of an ElementContainer (<ng-container>)
  // - (2) or a new comment node is created
  // In the first case, the anchor comment node would be added to the final
  // list by the code in the `collectNativeNodes` function
  // (see the `result.push(unwrapRNode(lNode))` line), but the second
  // case requires extra handling: the anchor node needs to be added to the
  // final list manually. See additional information in the `createAnchorNode`
  // function in the `view_container_ref.ts`.
  //
  // In the first case, the same reference would be stored in the `NATIVE`
  // and `HOST` slots in an LContainer. Otherwise, this is the second case and
  // we should add an element to the final list.
  if (lContainer[NATIVE] !== lContainer[HOST]) {
    result.push(lContainer[NATIVE]);
  }
}
let freeConsumers = [];
/**
 * Create a new template consumer pointing at the specified LView.
 * Sometimes, a previously created consumer may be reused, in order to save on allocations. In that
 * case, the LView will be updated.
 */
function getOrBorrowReactiveLViewConsumer(lView) {
  return lView[REACTIVE_TEMPLATE_CONSUMER] ?? borrowReactiveLViewConsumer(lView);
}
function borrowReactiveLViewConsumer(lView) {
  const consumer = freeConsumers.pop() ?? Object.create(REACTIVE_LVIEW_CONSUMER_NODE);
  consumer.lView = lView;
  return consumer;
}
function maybeReturnReactiveLViewConsumer(consumer) {
  if (consumer.lView[REACTIVE_TEMPLATE_CONSUMER] === consumer) {
    // The consumer got committed.
    return;
  }
  consumer.lView = null;
  freeConsumers.push(consumer);
}
const REACTIVE_LVIEW_CONSUMER_NODE = {
  ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.REACTIVE_NODE,
  consumerIsAlwaysLive: true,
  consumerMarkedDirty: node => {
    markAncestorsForTraversal(node.lView);
  },
  consumerOnSignalRead() {
    this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  }
};
/**
 * Creates a temporary consumer for use with `LView`s that should not have consumers.
 * If the LView already has a consumer, returns the existing one instead.
 *
 * This is necessary because some APIs may cause change detection directly on an LView
 * that we do not want to have a consumer (Embedded views today). As a result, there
 * would be no active consumer from running change detection on its host component
 * and any signals in the LView template would be untracked. Instead, we create
 * this temporary consumer that marks the first parent that _should_ have a consumer
 * for refresh. Once change detection runs as part of that refresh, we throw away
 * this consumer because its signals will then be tracked by the parent's consumer.
 */
function getOrCreateTemporaryConsumer(lView) {
  const consumer = lView[REACTIVE_TEMPLATE_CONSUMER] ?? Object.create(TEMPORARY_CONSUMER_NODE);
  consumer.lView = lView;
  return consumer;
}
const TEMPORARY_CONSUMER_NODE = {
  ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.REACTIVE_NODE,
  consumerIsAlwaysLive: true,
  consumerMarkedDirty: node => {
    let parent = getLViewParent(node.lView);
    while (parent && !viewShouldHaveReactiveConsumer(parent[TVIEW])) {
      parent = getLViewParent(parent);
    }
    if (!parent) {
      // If we can't find an appropriate parent that should have a consumer, we
      // don't have a way of appropriately refreshing this LView as part of application synchronization.
      return;
    }
    markViewForRefresh(parent);
  },
  consumerOnSignalRead() {
    this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  }
};
/**
 * Indicates if the view should get its own reactive consumer node.
 *
 * In the current design, all embedded views share a consumer with the component view. This allows
 * us to refresh at the component level rather than at a per-view level. In addition, root views get
 * their own reactive node because root component will have a host view that executes the
 * component's host bindings. This needs to be tracked in a consumer as well.
 *
 * To get a more granular change detection than per-component, all we would just need to update the
 * condition here so that a given view gets a reactive consumer which can become dirty independently
 * from its parent component. For example embedded views for signal components could be created with
 * a new type "SignalEmbeddedView" and the condition here wouldn't even need updating in order to
 * get granular per-view change detection for signal components.
 */
function viewShouldHaveReactiveConsumer(tView) {
  return tView.type !== 2 /* TViewType.Embedded */;
}
function runEffectsInView(view) {
  if (view[EFFECTS] === null) {
    return;
  }
  // Since effects can make other effects dirty, we flush them in a loop until there are no more to
  // flush.
  let tryFlushEffects = true;
  while (tryFlushEffects) {
    let foundDirtyEffect = false;
    for (const effect of view[EFFECTS]) {
      if (!effect.dirty) {
        continue;
      }
      foundDirtyEffect = true;
      // `runEffectsInView` is called during change detection, and therefore runs
      // in the Angular zone if it's available.
      if (effect.zone === null || Zone.current === effect.zone) {
        effect.run();
      } else {
        effect.zone.run(() => effect.run());
      }
    }
    // Check if we need to continue flushing. If we didn't find any dirty effects, then there's
    // no need to loop back. Otherwise, check the view to see if it was marked for traversal
    // again. If so, there's a chance that one of the effects we ran caused another effect to
    // become dirty.
    tryFlushEffects = foundDirtyEffect && !!(view[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */);
  }
}

/**
 * The maximum number of times the change detection traversal will rerun before throwing an error.
 */
const MAXIMUM_REFRESH_RERUNS$1 = 100;
function detectChangesInternal(lView, notifyErrorHandler = true, mode = 0 /* ChangeDetectionMode.Global */) {
  const environment = lView[ENVIRONMENT];
  const rendererFactory = environment.rendererFactory;
  // Check no changes mode is a dev only mode used to verify that bindings have not changed
  // since they were assigned. We do not want to invoke renderer factory functions in that mode
  // to avoid any possible side-effects.
  const checkNoChangesMode = !!ngDevMode && isInCheckNoChangesMode();
  if (!checkNoChangesMode) {
    rendererFactory.begin?.();
  }
  try {
    detectChangesInViewWhileDirty(lView, mode);
  } catch (error) {
    if (notifyErrorHandler) {
      handleError(lView, error);
    }
    throw error;
  } finally {
    if (!checkNoChangesMode) {
      rendererFactory.end?.();
    }
  }
}
function detectChangesInViewWhileDirty(lView, mode) {
  const lastIsRefreshingViewsValue = isRefreshingViews();
  try {
    setIsRefreshingViews(true);
    detectChangesInView(lView, mode);
    // We don't need or want to do any looping when in exhaustive checkNoChanges because we
    // already traverse all the views and nothing should change so we shouldn't have to do
    // another pass to pick up new changes.
    if (ngDevMode && isExhaustiveCheckNoChanges()) {
      return;
    }
    let retries = 0;
    // If after running change detection, this view still needs to be refreshed or there are
    // descendants views that need to be refreshed due to re-dirtying during the change detection
    // run, detect changes on the view again. We run change detection in `Targeted` mode to only
    // refresh views with the `RefreshView` flag.
    while (requiresRefreshOrTraversal(lView)) {
      if (retries === MAXIMUM_REFRESH_RERUNS$1) {
        throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode && 'Infinite change detection while trying to refresh views. ' + 'There may be components which each cause the other to require a refresh, ' + 'causing an infinite loop.');
      }
      retries++;
      // Even if this view is detached, we still detect changes in targeted mode because this was
      // the root of the change detection run.
      detectChangesInView(lView, 1 /* ChangeDetectionMode.Targeted */);
    }
  } finally {
    // restore state to what it was before entering this change detection loop
    setIsRefreshingViews(lastIsRefreshingViewsValue);
  }
}
function checkNoChangesInternal(lView, mode, notifyErrorHandler = true) {
  setIsInCheckNoChangesMode(mode);
  try {
    detectChangesInternal(lView, notifyErrorHandler);
  } finally {
    setIsInCheckNoChangesMode(CheckNoChangesMode.Off);
  }
}
/**
 * Processes a view in update mode. This includes a number of steps in a specific order:
 * - executing a template function in update mode;
 * - executing hooks;
 * - refreshing queries;
 * - setting host bindings;
 * - refreshing child (embedded and component) views.
 */
function refreshView(tView, lView, templateFn, context) {
  ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
  const flags = lView[FLAGS];
  if ((flags & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */) return;
  // Check no changes mode is a dev only mode used to verify that bindings have not changed
  // since they were assigned. We do not want to execute lifecycle hooks in that mode.
  const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  const isInExhaustiveCheckNoChangesPass = ngDevMode && isExhaustiveCheckNoChanges();
  // Start component reactive context
  // - We might already be in a reactive context if this is an embedded view of the host.
  // - We might be descending into a view that needs a consumer.
  enterView(lView);
  let returnConsumerToPool = true;
  let prevConsumer = null;
  let currentConsumer = null;
  if (!isInCheckNoChangesPass) {
    if (viewShouldHaveReactiveConsumer(tView)) {
      currentConsumer = getOrBorrowReactiveLViewConsumer(lView);
      prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerBeforeComputation)(currentConsumer);
    } else if ((0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.getActiveConsumer)() === null) {
      // If the current view should not have a reactive consumer but we don't have an active consumer,
      // we still need to create a temporary consumer to track any signal reads in this template.
      // This is a rare case that can happen with `viewContainerRef.createEmbeddedView(...).detectChanges()`.
      // This temporary consumer marks the first parent that _should_ have a consumer for refresh.
      // Once that refresh happens, the signals will be tracked in the parent consumer and we can destroy
      // the temporary one.
      returnConsumerToPool = false;
      currentConsumer = getOrCreateTemporaryConsumer(lView);
      prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerBeforeComputation)(currentConsumer);
    } else if (lView[REACTIVE_TEMPLATE_CONSUMER]) {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerDestroy)(lView[REACTIVE_TEMPLATE_CONSUMER]);
      lView[REACTIVE_TEMPLATE_CONSUMER] = null;
    }
  }
  try {
    resetPreOrderHookFlags(lView);
    setBindingIndex(tView.bindingStartIndex);
    if (templateFn !== null) {
      executeTemplate(tView, lView, templateFn, 2 /* RenderFlags.Update */, context);
    }
    const hooksInitPhaseCompleted = (flags & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
    // execute pre-order hooks (OnInit, OnChanges, DoCheck)
    // PERF WARNING: do NOT extract this to a separate function without running benchmarks
    if (!isInCheckNoChangesPass) {
      if (hooksInitPhaseCompleted) {
        const preOrderCheckHooks = tView.preOrderCheckHooks;
        if (preOrderCheckHooks !== null) {
          executeCheckHooks(lView, preOrderCheckHooks, null);
        }
      } else {
        const preOrderHooks = tView.preOrderHooks;
        if (preOrderHooks !== null) {
          executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, null);
        }
        incrementInitPhaseFlags(lView, 0 /* InitPhaseState.OnInitHooksToBeRun */);
      }
    }
    // We do not need to mark transplanted views for refresh when doing exhaustive checks
    // because all views will be reached anyways during the traversal.
    if (!isInExhaustiveCheckNoChangesPass) {
      // First mark transplanted views that are declared in this lView as needing a refresh at their
      // insertion points. This is needed to avoid the situation where the template is defined in this
      // `LView` but its declaration appears after the insertion component.
      markTransplantedViewsForRefresh(lView);
    }
    runEffectsInView(lView);
    detectChangesInEmbeddedViews(lView, 0 /* ChangeDetectionMode.Global */);
    // Content query results must be refreshed before content hooks are called.
    if (tView.contentQueries !== null) {
      refreshContentQueries(tView, lView);
    }
    // execute content hooks (AfterContentInit, AfterContentChecked)
    // PERF WARNING: do NOT extract this to a separate function without running benchmarks
    if (!isInCheckNoChangesPass) {
      if (hooksInitPhaseCompleted) {
        const contentCheckHooks = tView.contentCheckHooks;
        if (contentCheckHooks !== null) {
          executeCheckHooks(lView, contentCheckHooks);
        }
      } else {
        const contentHooks = tView.contentHooks;
        if (contentHooks !== null) {
          executeInitAndCheckHooks(lView, contentHooks, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
        }
        incrementInitPhaseFlags(lView, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
      }
    }
    processHostBindingOpCodes(tView, lView);
    // Refresh child component views.
    const components = tView.components;
    if (components !== null) {
      detectChangesInChildComponents(lView, components, 0 /* ChangeDetectionMode.Global */);
    }
    // View queries must execute after refreshing child components because a template in this view
    // could be inserted in a child component. If the view query executes before child component
    // refresh, the template might not yet be inserted.
    const viewQuery = tView.viewQuery;
    if (viewQuery !== null) {
      executeViewQueryFn(2 /* RenderFlags.Update */, viewQuery, context);
    }
    // execute view hooks (AfterViewInit, AfterViewChecked)
    // PERF WARNING: do NOT extract this to a separate function without running benchmarks
    if (!isInCheckNoChangesPass) {
      if (hooksInitPhaseCompleted) {
        const viewCheckHooks = tView.viewCheckHooks;
        if (viewCheckHooks !== null) {
          executeCheckHooks(lView, viewCheckHooks);
        }
      } else {
        const viewHooks = tView.viewHooks;
        if (viewHooks !== null) {
          executeInitAndCheckHooks(lView, viewHooks, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
        }
        incrementInitPhaseFlags(lView, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
      }
    }
    if (tView.firstUpdatePass === true) {
      // We need to make sure that we only flip the flag on successful `refreshView` only
      // Don't do this in `finally` block.
      // If we did this in `finally` block then an exception could block the execution of styling
      // instructions which in turn would be unable to insert themselves into the styling linked
      // list. The result of this would be that if the exception would not be throw on subsequent CD
      // the styling would be unable to process it data and reflect to the DOM.
      tView.firstUpdatePass = false;
    }
    // Schedule any effects that are waiting on the update pass of this view.
    if (lView[EFFECTS_TO_SCHEDULE]) {
      for (const notifyEffect of lView[EFFECTS_TO_SCHEDULE]) {
        notifyEffect();
      }
      // Once they've been run, we can drop the array.
      lView[EFFECTS_TO_SCHEDULE] = null;
    }
    // Do not reset the dirty state when running in check no changes mode. We don't want components
    // to behave differently depending on whether check no changes is enabled or not. For example:
    // Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
    // refresh a `NgClass` binding should work. If we would reset the dirty state in the check
    // no changes cycle, the component would be not be dirty for the next update pass. This would
    // be different in production mode where the component dirty state is not reset.
    if (!isInCheckNoChangesPass) {
      lView[FLAGS] &= ~(64 /* LViewFlags.Dirty */ | 8 /* LViewFlags.FirstLViewPass */);
    }
  } catch (e) {
    if (!isInCheckNoChangesPass) {
      // If refreshing a view causes an error, we need to remark the ancestors as needing traversal
      // because the error might have caused a situation where views below the current location are
      // dirty but will be unreachable because the "has dirty children" flag in the ancestors has been
      // cleared during change detection and we failed to run to completion.
      markAncestorsForTraversal(lView);
    }
    throw e;
  } finally {
    if (currentConsumer !== null) {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerAfterComputation)(currentConsumer, prevConsumer);
      if (returnConsumerToPool) {
        maybeReturnReactiveLViewConsumer(currentConsumer);
      }
    }
    leaveView();
  }
}
/**
 * Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
 * them by executing an associated template function.
 */
function detectChangesInEmbeddedViews(lView, mode) {
  for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
    for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
      const embeddedLView = lContainer[i];
      detectChangesInViewIfAttached(embeddedLView, mode);
    }
  }
}
/**
 * Mark transplanted views as needing to be refreshed at their attachment points.
 *
 * @param lView The `LView` that may have transplanted views.
 */
function markTransplantedViewsForRefresh(lView) {
  for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
    if (!(lContainer[FLAGS] & LContainerFlags.HasTransplantedViews)) continue;
    const movedViews = lContainer[MOVED_VIEWS];
    ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
    for (let i = 0; i < movedViews.length; i++) {
      const movedLView = movedViews[i];
      markViewForRefresh(movedLView);
    }
  }
}
/**
 * Detects changes in a component by entering the component view and processing its bindings,
 * queries, etc. if it is CheckAlways, OnPush and Dirty, etc.
 *
 * @param componentHostIdx  Element index in LView[] (adjusted for HEADER_OFFSET)
 */
function detectChangesInComponent(hostLView, componentHostIdx, mode) {
  ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
  const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  detectChangesInViewIfAttached(componentView, mode);
}
/**
 * Visits a view as part of change detection traversal.
 *
 * If the view is detached, no additional traversal happens.
 */
function detectChangesInViewIfAttached(lView, mode) {
  if (!viewAttachedToChangeDetector(lView)) {
    return;
  }
  detectChangesInView(lView, mode);
}
/**
 * Visits a view as part of change detection traversal.
 *
 * The view is refreshed if:
 * - If the view is CheckAlways or Dirty and ChangeDetectionMode is `Global`
 * - If the view has the `RefreshView` flag
 *
 * The view is not refreshed, but descendants are traversed in `ChangeDetectionMode.Targeted` if the
 * view HasChildViewsToRefresh flag is set.
 */
function detectChangesInView(lView, mode) {
  const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  const tView = lView[TVIEW];
  const flags = lView[FLAGS];
  const consumer = lView[REACTIVE_TEMPLATE_CONSUMER];
  // Refresh CheckAlways views in Global mode.
  let shouldRefreshView = !!(mode === 0 /* ChangeDetectionMode.Global */ && flags & 16 /* LViewFlags.CheckAlways */);
  // Refresh Dirty views in Global mode, as long as we're not in checkNoChanges.
  // CheckNoChanges never worked with `OnPush` components because the `Dirty` flag was
  // cleared before checkNoChanges ran. Because there is now a loop for to check for
  // backwards views, it gives an opportunity for `OnPush` components to be marked `Dirty`
  // before the CheckNoChanges pass. We don't want existing errors that are hidden by the
  // current CheckNoChanges bug to surface when making unrelated changes.
  shouldRefreshView ||= !!(flags & 64 /* LViewFlags.Dirty */ && mode === 0 /* ChangeDetectionMode.Global */ && !isInCheckNoChangesPass);
  // Always refresh views marked for refresh, regardless of mode.
  shouldRefreshView ||= !!(flags & 1024 /* LViewFlags.RefreshView */);
  // Refresh views when they have a dirty reactive consumer, regardless of mode.
  shouldRefreshView ||= !!(consumer?.dirty && (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerPollProducersForChange)(consumer));
  shouldRefreshView ||= !!(ngDevMode && isExhaustiveCheckNoChanges());
  // Mark the Flags and `ReactiveNode` as not dirty before refreshing the component, so that they
  // can be re-dirtied during the refresh process.
  if (consumer) {
    consumer.dirty = false;
  }
  lView[FLAGS] &= ~(8192 /* LViewFlags.HasChildViewsToRefresh */ | 1024 /* LViewFlags.RefreshView */);
  if (shouldRefreshView) {
    refreshView(tView, lView, tView.template, lView[CONTEXT]);
  } else if (flags & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
    runEffectsInView(lView);
    detectChangesInEmbeddedViews(lView, 1 /* ChangeDetectionMode.Targeted */);
    const components = tView.components;
    if (components !== null) {
      detectChangesInChildComponents(lView, components, 1 /* ChangeDetectionMode.Targeted */);
    }
  }
}
/** Refreshes child components in the current view (update mode). */
function detectChangesInChildComponents(hostLView, components, mode) {
  for (let i = 0; i < components.length; i++) {
    detectChangesInComponent(hostLView, components[i], mode);
  }
}

/**
 * Marks current view and all ancestors dirty.
 *
 * Returns the root view because it is found as a byproduct of marking the view tree
 * dirty, and can be used by methods that consume markViewDirty() to easily schedule
 * change detection. Otherwise, such methods would need to traverse up the view tree
 * an additional time to get the root view and schedule a tick on it.
 *
 * @param lView The starting LView to mark dirty
 * @returns the root LView
 */
function markViewDirty(lView, source) {
  const dirtyBitsToUse = isRefreshingViews() ?
  // When we are actively refreshing views, we only use the `Dirty` bit to mark a view
  64 /* LViewFlags.Dirty */ :
  // When we are not actively refreshing a view tree, it is absolutely
  // valid to update state and mark views dirty. We use the `RefreshView` flag in this
  // case to allow synchronously rerunning change detection. This applies today to
  // afterRender hooks as well as animation listeners which execute after detecting
  // changes in a view when the render factory flushes.
  1024 /* LViewFlags.RefreshView */ | 64 /* LViewFlags.Dirty */;
  lView[ENVIRONMENT].changeDetectionScheduler?.notify(source);
  while (lView) {
    lView[FLAGS] |= dirtyBitsToUse;
    const parent = getLViewParent(lView);
    // Stop traversing up as soon as you find a root view that wasn't attached to any container
    if (isRootView(lView) && !parent) {
      return lView;
    }
    // continue otherwise
    lView = parent;
  }
  return null;
}
class ViewRef$1 {
  _lView;
  _cdRefInjectingView;
  notifyErrorHandler;
  _appRef = null;
  _attachedToViewContainer = false;
  get rootNodes() {
    const lView = this._lView;
    const tView = lView[TVIEW];
    return collectNativeNodes(tView, lView, tView.firstChild, []);
  }
  constructor(
  /**
   * This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
   *
   * When ViewRef is created for a dynamic component, this also represents the `LView` for the
   * component.
   *
   * For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
   * view.
   *
   * @internal
   */
  _lView,
  /**
   * This represents the `LView` associated with the point where `ChangeDetectorRef` was
   * requested.
   *
   * This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
   */
  _cdRefInjectingView, notifyErrorHandler = true) {
    this._lView = _lView;
    this._cdRefInjectingView = _cdRefInjectingView;
    this.notifyErrorHandler = notifyErrorHandler;
  }
  get context() {
    return this._lView[CONTEXT];
  }
  /**
   * Reports whether the given view is considered dirty according to the different marking mechanisms.
   */
  get dirty() {
    return !!(this._lView[FLAGS] & (64 /* LViewFlags.Dirty */ | 1024 /* LViewFlags.RefreshView */ | 8192 /* LViewFlags.HasChildViewsToRefresh */)) || !!this._lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty;
  }
  /**
   * @deprecated Replacing the full context object is not supported. Modify the context
   *   directly, or consider using a `Proxy` if you need to replace the full object.
   * // TODO(devversion): Remove this.
   */
  set context(value) {
    if (ngDevMode) {
      // Note: We have a warning message here because the `@deprecated` JSDoc will not be picked
      // up for assignments on the setter. We want to let users know about the deprecated usage.
      console.warn('Angular: Replacing the `context` object of an `EmbeddedViewRef` is deprecated.');
    }
    this._lView[CONTEXT] = value;
  }
  get destroyed() {
    return (this._lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */;
  }
  destroy() {
    if (this._appRef) {
      this._appRef.detachView(this);
    } else if (this._attachedToViewContainer) {
      const parent = this._lView[PARENT];
      if (isLContainer(parent)) {
        const viewRefs = parent[VIEW_REFS];
        const index = viewRefs ? viewRefs.indexOf(this) : -1;
        if (index > -1) {
          ngDevMode && assertEqual(index, parent.indexOf(this._lView) - CONTAINER_HEADER_OFFSET, 'An attached view should be in the same position within its container as its ViewRef in the VIEW_REFS array.');
          detachView(parent, index);
          removeFromArray(viewRefs, index);
        }
      }
      this._attachedToViewContainer = false;
    }
    destroyLView(this._lView[TVIEW], this._lView);
  }
  onDestroy(callback) {
    storeLViewOnDestroy(this._lView, callback);
  }
  /**
   * Marks a view and all of its ancestors dirty.
   *
   * This can be used to ensure an {@link ChangeDetectionStrategy#OnPush} component is
   * checked when it needs to be re-rendered but the two normal triggers haven't marked it
   * dirty (i.e. inputs haven't changed and events haven't fired in the view).
   *
   * <!-- TODO: Add a link to a chapter on OnPush components -->
   *
   * @usageNotes
   * ### Example
   *
   * ```typescript
   * @Component({
   *   selector: 'app-root',
   *   template: `Number of ticks: {{numberOfTicks}}`
   *   changeDetection: ChangeDetectionStrategy.OnPush,
   * })
   * class AppComponent {
   *   numberOfTicks = 0;
   *
   *   constructor(private ref: ChangeDetectorRef) {
   *     setInterval(() => {
   *       this.numberOfTicks++;
   *       // the following is required, otherwise the view will not be updated
   *       this.ref.markForCheck();
   *     }, 1000);
   *   }
   * }
   * ```
   */
  markForCheck() {
    markViewDirty(this._cdRefInjectingView || this._lView, 4 /* NotificationSource.MarkForCheck */);
  }
  markForRefresh() {
    markViewForRefresh(this._cdRefInjectingView || this._lView);
  }
  /**
   * Detaches the view from the change detection tree.
   *
   * Detached views will not be checked during change detection runs until they are
   * re-attached, even if they are dirty. `detach` can be used in combination with
   * {@link ChangeDetectorRef#detectChanges} to implement local change
   * detection checks.
   *
   * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
   * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
   *
   * @usageNotes
   * ### Example
   *
   * The following example defines a component with a large list of readonly data.
   * Imagine the data changes constantly, many times per second. For performance reasons,
   * we want to check and update the list every five seconds. We can do that by detaching
   * the component's change detector and doing a local check every five seconds.
   *
   * ```typescript
   * class DataProvider {
   *   // in a real application the returned data will be different every time
   *   get data() {
   *     return [1,2,3,4,5];
   *   }
   * }
   *
   * @Component({
   *   selector: 'giant-list',
   *   template: `
   *     <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
   *   `,
   * })
   * class GiantList {
   *   constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
   *     ref.detach();
   *     setInterval(() => {
   *       this.ref.detectChanges();
   *     }, 5000);
   *   }
   * }
   *
   * @Component({
   *   selector: 'app',
   *   providers: [DataProvider],
   *   template: `
   *     <giant-list><giant-list>
   *   `,
   * })
   * class App {
   * }
   * ```
   */
  detach() {
    this._lView[FLAGS] &= ~128 /* LViewFlags.Attached */;
  }
  /**
   * Re-attaches a view to the change detection tree.
   *
   * This can be used to re-attach views that were previously detached from the tree
   * using {@link ChangeDetectorRef#detach}. Views are attached to the tree by default.
   *
   * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
   *
   * @usageNotes
   * ### Example
   *
   * The following example creates a component displaying `live` data. The component will detach
   * its change detector from the main change detector tree when the component's live property
   * is set to false.
   *
   * ```typescript
   * class DataProvider {
   *   data = 1;
   *
   *   constructor() {
   *     setInterval(() => {
   *       this.data = this.data * 2;
   *     }, 500);
   *   }
   * }
   *
   * @Component({
   *   selector: 'live-data',
   *   inputs: ['live'],
   *   template: 'Data: {{dataProvider.data}}'
   * })
   * class LiveData {
   *   constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
   *
   *   set live(value) {
   *     if (value) {
   *       this.ref.reattach();
   *     } else {
   *       this.ref.detach();
   *     }
   *   }
   * }
   *
   * @Component({
   *   selector: 'app-root',
   *   providers: [DataProvider],
   *   template: `
   *     Live Update: <input type="checkbox" [(ngModel)]="live">
   *     <live-data [live]="live"><live-data>
   *   `,
   * })
   * class AppComponent {
   *   live = true;
   * }
   * ```
   */
  reattach() {
    updateAncestorTraversalFlagsOnAttach(this._lView);
    this._lView[FLAGS] |= 128 /* LViewFlags.Attached */;
  }
  /**
   * Checks the view and its children.
   *
   * This can also be used in combination with {@link ChangeDetectorRef#detach} to implement
   * local change detection checks.
   *
   * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
   * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
   *
   * @usageNotes
   * ### Example
   *
   * The following example defines a component with a large list of readonly data.
   * Imagine, the data changes constantly, many times per second. For performance reasons,
   * we want to check and update the list every five seconds.
   *
   * We can do that by detaching the component's change detector and doing a local change detection
   * check every five seconds.
   *
   * See {@link ChangeDetectorRef#detach} for more information.
   */
  detectChanges() {
    // Add `RefreshView` flag to ensure this view is refreshed if not already dirty.
    // `RefreshView` flag is used intentionally over `Dirty` because it gets cleared before
    // executing any of the actual refresh code while the `Dirty` flag doesn't get cleared
    // until the end of the refresh. Using `RefreshView` prevents creating a potential difference
    // in the state of the LViewFlags during template execution.
    this._lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
    detectChangesInternal(this._lView, this.notifyErrorHandler);
  }
  /**
   * Checks the change detector and its children, and throws if any changes are detected.
   *
   * This is used in development mode to verify that running change detection doesn't
   * introduce other changes.
   */
  checkNoChanges() {
    if (ngDevMode) {
      checkNoChangesInternal(this._lView, CheckNoChangesMode.OnlyDirtyViews, this.notifyErrorHandler);
    }
  }
  attachToViewContainerRef() {
    if (this._appRef) {
      throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached directly to the ApplicationRef!');
    }
    this._attachedToViewContainer = true;
  }
  detachFromAppRef() {
    this._appRef = null;
    const isRoot = isRootView(this._lView);
    const declarationContainer = this._lView[DECLARATION_LCONTAINER];
    if (declarationContainer !== null && !isRoot) {
      detachMovedView(declarationContainer, this._lView);
    }
    detachViewFromDOM(this._lView[TVIEW], this._lView);
  }
  attachToAppRef(appRef) {
    if (this._attachedToViewContainer) {
      throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached to a ViewContainer!');
    }
    this._appRef = appRef;
    const isRoot = isRootView(this._lView);
    const declarationContainer = this._lView[DECLARATION_LCONTAINER];
    if (declarationContainer !== null && !isRoot) {
      trackMovedView(declarationContainer, this._lView);
    }
    updateAncestorTraversalFlagsOnAttach(this._lView);
  }
}

/**
 * Represents an embedded template that can be used to instantiate embedded views.
 * To instantiate embedded views based on a template, use the `ViewContainerRef`
 * method `createEmbeddedView()`.
 *
 * Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
 * element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
 * is injected into the constructor of the directive,
 * using the `TemplateRef` token.
 *
 * You can also use a `Query` to find a `TemplateRef` associated with
 * a component or a directive.
 *
 * @see {@link ViewContainerRef}
 *
 * @publicApi
 */
let TemplateRef = /*#__PURE__*/(() => {
  class TemplateRef {
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectTemplateRef)();
  }
  return TemplateRef;
})();
const ViewEngineTemplateRef = TemplateRef;
// TODO(alxhub): combine interface and implementation. Currently this is challenging since something
// in g3 depends on them being separate.
const R3TemplateRef = class TemplateRef extends ViewEngineTemplateRef {
  _declarationLView;
  _declarationTContainer;
  elementRef;
  constructor(_declarationLView, _declarationTContainer, elementRef) {
    super();
    this._declarationLView = _declarationLView;
    this._declarationTContainer = _declarationTContainer;
    this.elementRef = elementRef;
  }
  /**
   * Returns an `ssrId` associated with a TView, which was used to
   * create this instance of the `TemplateRef`.
   *
   * @internal
   */
  get ssrId() {
    return this._declarationTContainer.tView?.ssrId || null;
  }
  createEmbeddedView(context, injector) {
    return this.createEmbeddedViewImpl(context, injector);
  }
  /**
   * @internal
   */
  createEmbeddedViewImpl(context, injector, dehydratedView) {
    const embeddedLView = createAndRenderEmbeddedLView(this._declarationLView, this._declarationTContainer, context, {
      embeddedViewInjector: injector,
      dehydratedView
    });
    return new ViewRef$1(embeddedLView);
  }
};
/**
 * Creates a TemplateRef given a node.
 *
 * @returns The TemplateRef instance to use
 */
function injectTemplateRef() {
  return createTemplateRef(getCurrentTNode(), getLView());
}
/**
 * Creates a TemplateRef and stores it on the injector.
 *
 * @param hostTNode The node on which a TemplateRef is requested
 * @param hostLView The `LView` to which the node belongs
 * @returns The TemplateRef instance or null if we can't create a TemplateRef on a given node type
 */
function createTemplateRef(hostTNode, hostLView) {
  if (hostTNode.type & 4 /* TNodeType.Container */) {
    ngDevMode && assertDefined(hostTNode.tView, 'TView must be allocated');
    return new R3TemplateRef(hostLView, hostTNode, createElementRef(hostTNode, hostLView));
  }
  return null;
}
const AT_THIS_LOCATION = '<-- AT THIS LOCATION';
/**
 * Retrieves a user friendly string for a given TNodeType for use in
 * friendly error messages
 *
 * @param tNodeType
 * @returns
 */
function getFriendlyStringFromTNodeType(tNodeType) {
  switch (tNodeType) {
    case 4 /* TNodeType.Container */:
      return 'view container';
    case 2 /* TNodeType.Element */:
      return 'element';
    case 8 /* TNodeType.ElementContainer */:
      return 'ng-container';
    case 32 /* TNodeType.Icu */:
      return 'icu';
    case 64 /* TNodeType.Placeholder */:
      return 'i18n';
    case 16 /* TNodeType.Projection */:
      return 'projection';
    case 1 /* TNodeType.Text */:
      return 'text';
    case 128 /* TNodeType.LetDeclaration */:
      return '@let';
    default:
      // This should not happen as we cover all possible TNode types above.
      return '<unknown>';
  }
}
/**
 * Validates that provided nodes match during the hydration process.
 */
function validateMatchingNode(node, nodeType, tagName, lView, tNode, isViewContainerAnchor = false) {
  if (!node || node.nodeType !== nodeType || node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() !== tagName?.toLowerCase()) {
    const expectedNode = shortRNodeDescription(nodeType, tagName, null);
    let header = `During hydration Angular expected ${expectedNode} but `;
    const hostComponentDef = getDeclarationComponentDef(lView);
    const componentClassName = hostComponentDef?.type?.name;
    const expectedDom = describeExpectedDom(lView, tNode, isViewContainerAnchor);
    const expected = `Angular expected this DOM:\n\n${expectedDom}\n\n`;
    let actual = '';
    const componentHostElement = unwrapRNode(lView[HOST]);
    if (!node) {
      // No node found during hydration.
      header += `the node was not found.\n\n`;
      // Since the node is missing, we use the closest node to attach the error to
      markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom);
    } else {
      const actualNode = shortRNodeDescription(node.nodeType, node.tagName ?? null, node.textContent ?? null);
      header += `found ${actualNode}.\n\n`;
      const actualDom = describeDomFromNode(node);
      actual = `Actual DOM is:\n\n${actualDom}\n\n`;
      // DevTools only report hydration issues on the component level, so we attach extra debug
      // info to a component host element to make it available to DevTools.
      markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom, actualDom);
    }
    const footer = getHydrationErrorFooter(componentClassName);
    const message = header + expected + actual + getHydrationAttributeNote() + footer;
    throw new RuntimeError(-500 /* RuntimeErrorCode.HYDRATION_NODE_MISMATCH */, message);
  }
}
/**
 * Validates that a given node has sibling nodes
 */
function validateSiblingNodeExists(node) {
  validateNodeExists(node);
  if (!node.nextSibling) {
    const header = 'During hydration Angular expected more sibling nodes to be present.\n\n';
    const actual = `Actual DOM is:\n\n${describeDomFromNode(node)}\n\n`;
    const footer = getHydrationErrorFooter();
    const message = header + actual + footer;
    markRNodeAsHavingHydrationMismatch(node, '', actual);
    throw new RuntimeError(-501 /* RuntimeErrorCode.HYDRATION_MISSING_SIBLINGS */, message);
  }
}
/**
 * Validates that a node exists or throws
 */
function validateNodeExists(node, lView = null, tNode = null) {
  if (!node) {
    const header = 'During hydration, Angular expected an element to be present at this location.\n\n';
    let expected = '';
    let footer = '';
    if (lView !== null && tNode !== null) {
      expected = describeExpectedDom(lView, tNode, false);
      footer = getHydrationErrorFooter();
      // Since the node is missing, we use the closest node to attach the error to
      markRNodeAsHavingHydrationMismatch(unwrapRNode(lView[HOST]), expected, '');
    }
    throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, `${header}${expected}\n\n${footer}`);
  }
}
/**
 * Builds the hydration error message when a node is not found
 *
 * @param lView the LView where the node exists
 * @param tNode the TNode
 */
function nodeNotFoundError(lView, tNode) {
  const header = 'During serialization, Angular was unable to find an element in the DOM:\n\n';
  const expected = `${describeExpectedDom(lView, tNode, false)}\n\n`;
  const footer = getHydrationErrorFooter();
  throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + expected + footer);
}
/**
 * Builds a hydration error message when a node is not found at a path location
 *
 * @param host the Host Node
 * @param path the path to the node
 */
function nodeNotFoundAtPathError(host, path) {
  const header = `During hydration Angular was unable to locate a node ` + `using the "${path}" path, starting from the ${describeRNode(host)} node.\n\n`;
  const footer = getHydrationErrorFooter();
  markRNodeAsHavingHydrationMismatch(host);
  throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + footer);
}
/**
 * Builds the hydration error message in the case that dom nodes are created outside of
 * the Angular context and are being used as projected nodes
 *
 * @param lView the LView
 * @param tNode the TNode
 * @returns an error
 */
function unsupportedProjectionOfDomNodes(rNode) {
  const header = 'During serialization, Angular detected DOM nodes ' + 'that were created outside of Angular context and provided as projectable nodes ' + '(likely via `ViewContainerRef.createComponent` or `createComponent` APIs). ' + 'Hydration is not supported for such cases, consider refactoring the code to avoid ' + 'this pattern or using `ngSkipHydration` on the host element of the component.\n\n';
  const actual = `${describeDomFromNode(rNode)}\n\n`;
  const message = header + actual + getHydrationAttributeNote();
  return new RuntimeError(-503 /* RuntimeErrorCode.UNSUPPORTED_PROJECTION_DOM_NODES */, message);
}
/**
 * Builds the hydration error message in the case that ngSkipHydration was used on a
 * node that is not a component host element or host binding
 *
 * @param rNode the HTML Element
 * @returns an error
 */
function invalidSkipHydrationHost(rNode) {
  const header = 'The `ngSkipHydration` flag is applied on a node ' + "that doesn't act as a component host. Hydration can be " + 'skipped only on per-component basis.\n\n';
  const actual = `${describeDomFromNode(rNode)}\n\n`;
  const footer = 'Please move the `ngSkipHydration` attribute to the component host element.\n\n';
  const message = header + actual + footer;
  return new RuntimeError(-504 /* RuntimeErrorCode.INVALID_SKIP_HYDRATION_HOST */, message);
}
// Stringification methods
/**
 * Stringifies a given TNode's attributes
 *
 * @param tNode a provided TNode
 * @returns string
 */
function stringifyTNodeAttrs(tNode) {
  const results = [];
  if (tNode.attrs) {
    for (let i = 0; i < tNode.attrs.length;) {
      const attrName = tNode.attrs[i++];
      // Once we reach the first flag, we know that the list of
      // attributes is over.
      if (typeof attrName == 'number') {
        break;
      }
      const attrValue = tNode.attrs[i++];
      results.push(`${attrName}="${shorten(attrValue)}"`);
    }
  }
  return results.join(' ');
}
/**
 * The list of internal attributes that should be filtered out while
 * producing an error message.
 */
const internalAttrs = /*#__PURE__*/new Set(['ngh', 'ng-version', 'ng-server-context']);
/**
 * Stringifies an HTML Element's attributes
 *
 * @param rNode an HTML Element
 * @returns string
 */
function stringifyRNodeAttrs(rNode) {
  const results = [];
  for (let i = 0; i < rNode.attributes.length; i++) {
    const attr = rNode.attributes[i];
    if (internalAttrs.has(attr.name)) continue;
    results.push(`${attr.name}="${shorten(attr.value)}"`);
  }
  return results.join(' ');
}
// Methods for Describing the DOM
/**
 * Converts a tNode to a helpful readable string value for use in error messages
 *
 * @param tNode a given TNode
 * @param innerContent the content of the node
 * @returns string
 */
function describeTNode(tNode, innerContent = '…') {
  switch (tNode.type) {
    case 1 /* TNodeType.Text */:
      const content = tNode.value ? `(${tNode.value})` : '';
      return `#text${content}`;
    case 2 /* TNodeType.Element */:
      const attrs = stringifyTNodeAttrs(tNode);
      const tag = tNode.value.toLowerCase();
      return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
    case 8 /* TNodeType.ElementContainer */:
      return '<!-- ng-container -->';
    case 4 /* TNodeType.Container */:
      return '<!-- container -->';
    default:
      const typeAsString = getFriendlyStringFromTNodeType(tNode.type);
      return `#node(${typeAsString})`;
  }
}
/**
 * Converts an RNode to a helpful readable string value for use in error messages
 *
 * @param rNode a given RNode
 * @param innerContent the content of the node
 * @returns string
 */
function describeRNode(rNode, innerContent = '…') {
  const node = rNode;
  switch (node.nodeType) {
    case Node.ELEMENT_NODE:
      const tag = node.tagName.toLowerCase();
      const attrs = stringifyRNodeAttrs(node);
      return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
    case Node.TEXT_NODE:
      const content = node.textContent ? shorten(node.textContent) : '';
      return `#text${content ? `(${content})` : ''}`;
    case Node.COMMENT_NODE:
      return `<!-- ${shorten(node.textContent ?? '')} -->`;
    default:
      return `#node(${node.nodeType})`;
  }
}
/**
 * Builds the string containing the expected DOM present given the LView and TNode
 * values for a readable error message
 *
 * @param lView the lView containing the DOM
 * @param tNode the tNode
 * @param isViewContainerAnchor boolean
 * @returns string
 */
function describeExpectedDom(lView, tNode, isViewContainerAnchor) {
  const spacer = '  ';
  let content = '';
  if (tNode.prev) {
    content += spacer + '…\n';
    content += spacer + describeTNode(tNode.prev) + '\n';
  } else if (tNode.type && tNode.type & 12 /* TNodeType.AnyContainer */) {
    content += spacer + '…\n';
  }
  if (isViewContainerAnchor) {
    content += spacer + describeTNode(tNode) + '\n';
    content += spacer + `<!-- container -->  ${AT_THIS_LOCATION}\n`;
  } else {
    content += spacer + describeTNode(tNode) + `  ${AT_THIS_LOCATION}\n`;
  }
  content += spacer + '…\n';
  const parentRNode = tNode.type ? getParentRElement(lView[TVIEW], tNode, lView) : null;
  if (parentRNode) {
    content = describeRNode(parentRNode, '\n' + content);
  }
  return content;
}
/**
 * Builds the string containing the DOM present around a given RNode for a
 * readable error message
 *
 * @param node the RNode
 * @returns string
 */
function describeDomFromNode(node) {
  const spacer = '  ';
  let content = '';
  const currentNode = node;
  if (currentNode.previousSibling) {
    content += spacer + '…\n';
    content += spacer + describeRNode(currentNode.previousSibling) + '\n';
  }
  content += spacer + describeRNode(currentNode) + `  ${AT_THIS_LOCATION}\n`;
  if (node.nextSibling) {
    content += spacer + '…\n';
  }
  if (node.parentNode) {
    content = describeRNode(currentNode.parentNode, '\n' + content);
  }
  return content;
}
/**
 * Shortens the description of a given RNode by its type for readability
 *
 * @param nodeType the type of node
 * @param tagName the node tag name
 * @param textContent the text content in the node
 * @returns string
 */
function shortRNodeDescription(nodeType, tagName, textContent) {
  switch (nodeType) {
    case Node.ELEMENT_NODE:
      return `<${tagName.toLowerCase()}>`;
    case Node.TEXT_NODE:
      const content = textContent ? ` (with the "${shorten(textContent)}" content)` : '';
      return `a text node${content}`;
    case Node.COMMENT_NODE:
      return 'a comment node';
    default:
      return `#node(nodeType=${nodeType})`;
  }
}
/**
 * Builds the footer hydration error message
 *
 * @param componentClassName the name of the component class
 * @returns string
 */
function getHydrationErrorFooter(componentClassName) {
  const componentInfo = componentClassName ? `the "${componentClassName}"` : 'corresponding';
  return `To fix this problem:\n` + `  * check ${componentInfo} component for hydration-related issues\n` + `  * check to see if your template has valid HTML structure\n` + `  * or skip hydration by adding the \`ngSkipHydration\` attribute ` + `to its host node in a template\n\n`;
}
/**
 * An attribute related note for hydration errors
 */
function getHydrationAttributeNote() {
  return 'Note: attributes are only displayed to better represent the DOM' + ' but have no effect on hydration mismatches.\n\n';
}
// Node string utility functions
/**
 * Strips all newlines out of a given string
 *
 * @param input a string to be cleared of new line characters
 * @returns
 */
function stripNewlines(input) {
  return input.replace(/\s+/gm, '');
}
/**
 * Reduces a string down to a maximum length of characters with ellipsis for readability
 *
 * @param input a string input
 * @param maxLength a maximum length in characters
 * @returns string
 */
function shorten(input, maxLength = 50) {
  if (!input) {
    return '';
  }
  input = stripNewlines(input);
  return input.length > maxLength ? `${input.substring(0, maxLength - 1)}…` : input;
}
class _NullComponentFactoryResolver {
  resolveComponentFactory(component) {
    throw Error(`No component factory found for ${stringify(component)}.`);
  }
}
/**
 * A simple registry that maps `Components` to generated `ComponentFactory` classes
 * that can be used to create instances of components.
 * Use to obtain the factory for a given component type,
 * then use the factory's `create()` method to create a component of that type.
 *
 * Note: since v13, dynamic component creation via
 * [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)
 * does **not** require resolving component factory: component class can be used directly.
 *
 * @publicApi
 *
 * @deprecated Angular no longer requires Component factories. Please use other APIs where
 *     Component class can be used directly.
 */
class ComponentFactoryResolver$1 {
  static NULL = /*#__PURE__*/(() => new _NullComponentFactoryResolver())();
}

/**
 * Represents an instance of an `NgModule` created by an `NgModuleFactory`.
 * Provides access to the `NgModule` instance and related objects.
 *
 * @publicApi
 */
class NgModuleRef$1 {}
/**
 * @publicApi
 *
 * @deprecated
 * This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy
 * JIT mode. Angular provides APIs that accept NgModule classes directly (such as
 * [PlatformRef.bootstrapModule](api/core/PlatformRef#bootstrapModule) and
 * [createNgModule](api/core/createNgModule)), consider switching to those APIs instead of
 * using factory-based ones.
 */
class NgModuleFactory$1 {}

/**
 * Represents a component created by a `ComponentFactory`.
 * Provides access to the component instance and related objects,
 * and provides the means of destroying the instance.
 *
 * @publicApi
 */
class ComponentRef$1 {}
/**
 * Base class for a factory that can create a component dynamically.
 * Instantiate a factory for a given type of component with `resolveComponentFactory()`.
 * Use the resulting `ComponentFactory.create()` method to create a component of that type.
 *
 * @publicApi
 *
 * @deprecated Angular no longer requires Component factories. Please use other APIs where
 *     Component class can be used directly.
 */
class ComponentFactory$1 {}

/**
 * Creates and initializes a custom renderer that implements the `Renderer2` base class.
 *
 * @publicApi
 */
class RendererFactory2 {}
/**
 * Extend this base class to implement custom rendering. By default, Angular
 * renders a template into DOM. You can use custom rendering to intercept
 * rendering calls, or to render to something other than DOM.
 *
 * Create your custom renderer using `RendererFactory2`.
 *
 * Use a custom renderer to bypass Angular's templating and
 * make custom UI changes that can't be expressed declaratively.
 * For example if you need to set a property or an attribute whose name is
 * not statically known, use the `setProperty()` or
 * `setAttribute()` method.
 *
 * @publicApi
 */
let Renderer2 = /*#__PURE__*/(() => {
  class Renderer2 {
    /**
     * If null or undefined, the view engine won't call it.
     * This is used as a performance optimization for production mode.
     */
    destroyNode = null;
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = () => injectRenderer2();
  }
  return Renderer2;
})();
/** Injects a Renderer2 for the current component. */
function injectRenderer2() {
  // We need the Renderer to be based on the component that it's being injected into, however since
  // DI happens before we've entered its view, `getLView` will return the parent view instead.
  const lView = getLView();
  const tNode = getCurrentTNode();
  const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
  return (isLView(nodeAtIndex) ? nodeAtIndex : lView)[RENDERER];
}

/**
 * Sanitizer is used by the views to sanitize potentially dangerous values.
 *
 * @publicApi
 */
let Sanitizer = /*#__PURE__*/(() => {
  class Sanitizer {
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: Sanitizer,
      providedIn: 'root',
      factory: () => null
    }))();
  }
  return Sanitizer;
})();
function isModuleWithProviders(value) {
  return value.ngModule !== undefined;
}
function isNgModule(value) {
  return !!getNgModuleDef(value);
}
function isPipe(value) {
  return !!getPipeDef$1(value);
}
function isDirective(value) {
  return !!getDirectiveDef(value);
}
function isComponent(value) {
  return !!getComponentDef(value);
}
function getDependencyTypeForError(type) {
  if (getComponentDef(type)) return 'component';
  if (getDirectiveDef(type)) return 'directive';
  if (getPipeDef$1(type)) return 'pipe';
  return 'type';
}
function verifyStandaloneImport(depType, importingType) {
  if (isForwardRef(depType)) {
    depType = resolveForwardRef(depType);
    if (!depType) {
      throw new Error(`Expected forwardRef function, imported from "${stringifyForError(importingType)}", to return a standalone entity or NgModule but got "${stringifyForError(depType) || depType}".`);
    }
  }
  if (getNgModuleDef(depType) == null) {
    const def = getComponentDef(depType) || getDirectiveDef(depType) || getPipeDef$1(depType);
    if (def != null) {
      // if a component, directive or pipe is imported make sure that it is standalone
      if (!def.standalone) {
        throw new Error(`The "${stringifyForError(depType)}" ${getDependencyTypeForError(depType)}, imported from "${stringifyForError(importingType)}", is not standalone. Did you forget to add the standalone: true flag?`);
      }
    } else {
      // it can be either a module with provider or an unknown (not annotated) type
      if (isModuleWithProviders(depType)) {
        throw new Error(`A module with providers was imported from "${stringifyForError(importingType)}". Modules with providers are not supported in standalone components imports.`);
      } else {
        throw new Error(`The "${stringifyForError(depType)}" type, imported from "${stringifyForError(importingType)}", must be a standalone component / directive / pipe or an NgModule. Did you forget to add the required @Component / @Directive / @Pipe or @NgModule annotation?`);
      }
    }
  }
}

/**
 * Indicates whether to use the runtime dependency tracker for scope calculation in JIT compilation.
 * The value "false" means the old code path based on patching scope info into the types will be
 * used.
 *
 * @deprecated For migration purposes only, to be removed soon.
 */
const USE_RUNTIME_DEPS_TRACKER_FOR_JIT = true;
/**
 * An implementation of DepsTrackerApi which will be used for JIT and local compilation.
 */
class DepsTracker {
  ownerNgModule = /*#__PURE__*/(() => new Map())();
  ngModulesWithSomeUnresolvedDecls = /*#__PURE__*/(() => new Set())();
  ngModulesScopeCache = /*#__PURE__*/(() => new Map())();
  standaloneComponentsScopeCache = /*#__PURE__*/(() => new Map())();
  /**
   * Attempts to resolve ng module's forward ref declarations as much as possible and add them to
   * the `ownerNgModule` map. This method normally should be called after the initial parsing when
   * all the forward refs are resolved (e.g., when trying to render a component)
   */
  resolveNgModulesDecls() {
    if (this.ngModulesWithSomeUnresolvedDecls.size === 0) {
      return;
    }
    for (const moduleType of this.ngModulesWithSomeUnresolvedDecls) {
      const def = getNgModuleDef(moduleType);
      if (def?.declarations) {
        for (const decl of maybeUnwrapFn(def.declarations)) {
          if (isComponent(decl)) {
            this.ownerNgModule.set(decl, moduleType);
          }
        }
      }
    }
    this.ngModulesWithSomeUnresolvedDecls.clear();
  }
  /** @override */
  getComponentDependencies(type, rawImports) {
    this.resolveNgModulesDecls();
    const def = getComponentDef(type);
    if (def === null) {
      throw new Error(`Attempting to get component dependencies for a type that is not a component: ${type}`);
    }
    if (def.standalone) {
      const scope = this.getStandaloneComponentScope(type, rawImports);
      if (scope.compilation.isPoisoned) {
        return {
          dependencies: []
        };
      }
      return {
        dependencies: [...scope.compilation.directives, ...scope.compilation.pipes, ...scope.compilation.ngModules]
      };
    } else {
      if (!this.ownerNgModule.has(type)) {
        // This component is orphan! No need to handle the error since the component rendering
        // pipeline (e.g., view_container_ref) will check for this error based on configs.
        return {
          dependencies: []
        };
      }
      const scope = this.getNgModuleScope(this.ownerNgModule.get(type));
      if (scope.compilation.isPoisoned) {
        return {
          dependencies: []
        };
      }
      return {
        dependencies: [...scope.compilation.directives, ...scope.compilation.pipes]
      };
    }
  }
  /**
   * @override
   * This implementation does not make use of param scopeInfo since it assumes the scope info is
   * already added to the type itself through methods like {@link ɵɵsetNgModuleScope}
   */
  registerNgModule(type, scopeInfo) {
    if (!isNgModule(type)) {
      throw new Error(`Attempting to register a Type which is not NgModule as NgModule: ${type}`);
    }
    // Lazily process the NgModules later when needed.
    this.ngModulesWithSomeUnresolvedDecls.add(type);
  }
  /** @override */
  clearScopeCacheFor(type) {
    this.ngModulesScopeCache.delete(type);
    this.standaloneComponentsScopeCache.delete(type);
  }
  /** @override */
  getNgModuleScope(type) {
    if (this.ngModulesScopeCache.has(type)) {
      return this.ngModulesScopeCache.get(type);
    }
    const scope = this.computeNgModuleScope(type);
    this.ngModulesScopeCache.set(type, scope);
    return scope;
  }
  /** Compute NgModule scope afresh. */
  computeNgModuleScope(type) {
    const def = getNgModuleDef(type, true);
    const scope = {
      exported: {
        directives: new Set(),
        pipes: new Set()
      },
      compilation: {
        directives: new Set(),
        pipes: new Set()
      }
    };
    // Analyzing imports
    for (const imported of maybeUnwrapFn(def.imports)) {
      if (isNgModule(imported)) {
        const importedScope = this.getNgModuleScope(imported);
        // When this module imports another, the imported module's exported directives and pipes
        // are added to the compilation scope of this module.
        addSet(importedScope.exported.directives, scope.compilation.directives);
        addSet(importedScope.exported.pipes, scope.compilation.pipes);
      } else if (isStandalone(imported)) {
        if (isDirective(imported) || isComponent(imported)) {
          scope.compilation.directives.add(imported);
        } else if (isPipe(imported)) {
          scope.compilation.pipes.add(imported);
        } else {
          // The standalone thing is neither a component nor a directive nor a pipe ... (what?)
          throw new RuntimeError(980 /* RuntimeErrorCode.RUNTIME_DEPS_INVALID_IMPORTED_TYPE */, 'The standalone imported type is neither a component nor a directive nor a pipe');
        }
      } else {
        // The import is neither a module nor a module-with-providers nor a standalone thing. This
        // is going to be an error. So we short circuit.
        scope.compilation.isPoisoned = true;
        break;
      }
    }
    // Analyzing declarations
    if (!scope.compilation.isPoisoned) {
      for (const decl of maybeUnwrapFn(def.declarations)) {
        // Cannot declare another NgModule or a standalone thing
        if (isNgModule(decl) || isStandalone(decl)) {
          scope.compilation.isPoisoned = true;
          break;
        }
        if (isPipe(decl)) {
          scope.compilation.pipes.add(decl);
        } else {
          // decl is either a directive or a component. The component may not yet have the ɵcmp due
          // to async compilation.
          scope.compilation.directives.add(decl);
        }
      }
    }
    // Analyzing exports
    for (const exported of maybeUnwrapFn(def.exports)) {
      if (isNgModule(exported)) {
        // When this module exports another, the exported module's exported directives and pipes
        // are added to both the compilation and exported scopes of this module.
        const exportedScope = this.getNgModuleScope(exported);
        // Based on the current logic there is no way to have poisoned exported scope. So no need to
        // check for it.
        addSet(exportedScope.exported.directives, scope.exported.directives);
        addSet(exportedScope.exported.pipes, scope.exported.pipes);
        // Some test toolings which run in JIT mode depend on this behavior that the exported scope
        // should also be present in the compilation scope, even though AoT does not support this
        // and it is also in odds with NgModule metadata definitions. Without this some tests in
        // Google will fail.
        addSet(exportedScope.exported.directives, scope.compilation.directives);
        addSet(exportedScope.exported.pipes, scope.compilation.pipes);
      } else if (isPipe(exported)) {
        scope.exported.pipes.add(exported);
      } else {
        scope.exported.directives.add(exported);
      }
    }
    return scope;
  }
  /** @override */
  getStandaloneComponentScope(type, rawImports) {
    if (this.standaloneComponentsScopeCache.has(type)) {
      return this.standaloneComponentsScopeCache.get(type);
    }
    const ans = this.computeStandaloneComponentScope(type, rawImports);
    this.standaloneComponentsScopeCache.set(type, ans);
    return ans;
  }
  computeStandaloneComponentScope(type, rawImports) {
    const ans = {
      compilation: {
        // Standalone components are always able to self-reference.
        directives: new Set([type]),
        pipes: new Set(),
        ngModules: new Set()
      }
    };
    for (const rawImport of flatten(rawImports ?? [])) {
      const imported = resolveForwardRef(rawImport);
      try {
        verifyStandaloneImport(imported, type);
      } catch (e) {
        // Short-circuit if an import is not valid
        ans.compilation.isPoisoned = true;
        return ans;
      }
      if (isNgModule(imported)) {
        ans.compilation.ngModules.add(imported);
        const importedScope = this.getNgModuleScope(imported);
        // Short-circuit if an imported NgModule has corrupted exported scope.
        if (importedScope.exported.isPoisoned) {
          ans.compilation.isPoisoned = true;
          return ans;
        }
        addSet(importedScope.exported.directives, ans.compilation.directives);
        addSet(importedScope.exported.pipes, ans.compilation.pipes);
      } else if (isPipe(imported)) {
        ans.compilation.pipes.add(imported);
      } else if (isDirective(imported) || isComponent(imported)) {
        ans.compilation.directives.add(imported);
      } else {
        // The imported thing is not module/pipe/directive/component, so we error and short-circuit
        // here
        ans.compilation.isPoisoned = true;
        return ans;
      }
    }
    return ans;
  }
  /** @override */
  isOrphanComponent(cmp) {
    const def = getComponentDef(cmp);
    if (!def || def.standalone) {
      return false;
    }
    this.resolveNgModulesDecls();
    return !this.ownerNgModule.has(cmp);
  }
}
function addSet(sourceSet, targetSet) {
  for (const m of sourceSet) {
    targetSet.add(m);
  }
}
/** The deps tracker to be used in the current Angular app in dev mode. */
const depsTracker = /*#__PURE__*/new DepsTracker();
const TEST_ONLY = {
  DepsTracker
};

/**
 * Compute the static styling (class/style) from `TAttributes`.
 *
 * This function should be called during `firstCreatePass` only.
 *
 * @param tNode The `TNode` into which the styling information should be loaded.
 * @param attrs `TAttributes` containing the styling information.
 * @param writeToHost Where should the resulting static styles be written?
 *   - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
 *   - `true` Write to `TNode.styles` / `TNode.classes`
 */
function computeStaticStyling(tNode, attrs, writeToHost) {
  ngDevMode && assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
  let styles = writeToHost ? tNode.styles : null;
  let classes = writeToHost ? tNode.classes : null;
  let mode = 0;
  if (attrs !== null) {
    for (let i = 0; i < attrs.length; i++) {
      const value = attrs[i];
      if (typeof value === 'number') {
        mode = value;
      } else if (mode == 1 /* AttributeMarker.Classes */) {
        classes = concatStringsWithSpace(classes, value);
      } else if (mode == 2 /* AttributeMarker.Styles */) {
        const style = value;
        const styleValue = attrs[++i];
        styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
      }
    }
  }
  writeToHost ? tNode.styles = styles : tNode.stylesWithoutHost = styles;
  writeToHost ? tNode.classes = classes : tNode.classesWithoutHost = classes;
}
class ComponentFactoryResolver extends ComponentFactoryResolver$1 {
  ngModule;
  /**
   * @param ngModule The NgModuleRef to which all resolved factories are bound.
   */
  constructor(ngModule) {
    super();
    this.ngModule = ngModule;
  }
  resolveComponentFactory(component) {
    ngDevMode && assertComponentType(component);
    const componentDef = getComponentDef(component);
    return new ComponentFactory(componentDef, this.ngModule);
  }
}
function toRefArray(map, isInputMap) {
  const array = [];
  for (const publicName in map) {
    if (!map.hasOwnProperty(publicName)) {
      continue;
    }
    const value = map[publicName];
    if (value === undefined) {
      continue;
    }
    const isArray = Array.isArray(value);
    const propName = isArray ? value[0] : value;
    const flags = isArray ? value[1] : InputFlags.None;
    if (isInputMap) {
      array.push({
        propName: propName,
        templateName: publicName,
        isSignal: (flags & InputFlags.SignalBased) !== 0
      });
    } else {
      array.push({
        propName: propName,
        templateName: publicName
      });
    }
  }
  return array;
}
function getNamespace(elementName) {
  const name = elementName.toLowerCase();
  return name === 'svg' ? SVG_NAMESPACE : name === 'math' ? MATH_ML_NAMESPACE : null;
}
/**
 * ComponentFactory interface implementation.
 */
class ComponentFactory extends ComponentFactory$1 {
  componentDef;
  ngModule;
  selector;
  componentType;
  ngContentSelectors;
  isBoundToModule;
  get inputs() {
    const componentDef = this.componentDef;
    const inputTransforms = componentDef.inputTransforms;
    const refArray = toRefArray(componentDef.inputs, true);
    if (inputTransforms !== null) {
      for (const input of refArray) {
        if (inputTransforms.hasOwnProperty(input.propName)) {
          input.transform = inputTransforms[input.propName];
        }
      }
    }
    return refArray;
  }
  get outputs() {
    return toRefArray(this.componentDef.outputs, false);
  }
  /**
   * @param componentDef The component definition.
   * @param ngModule The NgModuleRef to which the factory is bound.
   */
  constructor(componentDef, ngModule) {
    super();
    this.componentDef = componentDef;
    this.ngModule = ngModule;
    this.componentType = componentDef.type;
    this.selector = stringifyCSSSelectorList(componentDef.selectors);
    this.ngContentSelectors = componentDef.ngContentSelectors ? componentDef.ngContentSelectors : [];
    this.isBoundToModule = !!ngModule;
  }
  create(injector, projectableNodes, rootSelectorOrNode, environmentInjector) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      // Check if the component is orphan
      if (ngDevMode && (typeof ngJitMode === 'undefined' || ngJitMode) && this.componentDef.debugInfo?.forbidOrphanRendering) {
        if (depsTracker.isOrphanComponent(this.componentType)) {
          throw new RuntimeError(981 /* RuntimeErrorCode.RUNTIME_DEPS_ORPHAN_COMPONENT */, `Orphan component found! Trying to render the component ${debugStringifyTypeForError(this.componentType)} without first loading the NgModule that declares it. It is recommended to make this component standalone in order to avoid this error. If this is not possible now, import the component's NgModule in the appropriate NgModule, or the standalone component in which you are trying to render this component. If this is a lazy import, load the NgModule lazily as well and use its module injector.`);
        }
      }
      environmentInjector = environmentInjector || this.ngModule;
      let realEnvironmentInjector = environmentInjector instanceof EnvironmentInjector ? environmentInjector : environmentInjector?.injector;
      if (realEnvironmentInjector && this.componentDef.getStandaloneInjector !== null) {
        realEnvironmentInjector = this.componentDef.getStandaloneInjector(realEnvironmentInjector) || realEnvironmentInjector;
      }
      const rootViewInjector = realEnvironmentInjector ? new ChainedInjector(injector, realEnvironmentInjector) : injector;
      const rendererFactory = rootViewInjector.get(RendererFactory2, null);
      if (rendererFactory === null) {
        throw new RuntimeError(407 /* RuntimeErrorCode.RENDERER_NOT_FOUND */, ngDevMode && 'Angular was not able to inject a renderer (RendererFactory2). ' + 'Likely this is due to a broken DI hierarchy. ' + 'Make sure that any injector used to create this component has a correct parent.');
      }
      const sanitizer = rootViewInjector.get(Sanitizer, null);
      const changeDetectionScheduler = rootViewInjector.get(ChangeDetectionScheduler, null);
      const environment = {
        rendererFactory,
        sanitizer,
        changeDetectionScheduler
      };
      const hostRenderer = rendererFactory.createRenderer(null, this.componentDef);
      // Determine a tag name used for creating host elements when this component is created
      // dynamically. Default to 'div' if this component did not specify any tag name in its
      // selector.
      const elementName = this.componentDef.selectors[0][0] || 'div';
      const hostRNode = rootSelectorOrNode ? locateHostElement(hostRenderer, rootSelectorOrNode, this.componentDef.encapsulation, rootViewInjector) : createElementNode(hostRenderer, elementName, getNamespace(elementName));
      let rootFlags = 512 /* LViewFlags.IsRoot */;
      if (this.componentDef.signals) {
        rootFlags |= 4096 /* LViewFlags.SignalView */;
      } else if (!this.componentDef.onPush) {
        rootFlags |= 16 /* LViewFlags.CheckAlways */;
      }
      let hydrationInfo = null;
      if (hostRNode !== null) {
        hydrationInfo = retrieveHydrationInfo(hostRNode, rootViewInjector, true /* isRootView */);
      }
      // Create the root view. Uses empty TView and ContentTemplate.
      const rootTView = createTView(0 /* TViewType.Root */, null, null, 1, 0, null, null, null, null, null, null);
      const rootLView = createLView(null, rootTView, null, rootFlags, null, null, environment, hostRenderer, rootViewInjector, null, hydrationInfo);
      // rootView is the parent when bootstrapping
      // TODO(misko): it looks like we are entering view here but we don't really need to as
      // `renderView` does that. However as the code is written it is needed because
      // `createRootComponentView` and `createRootComponent` both read global state. Fixing those
      // issues would allow us to drop this.
      enterView(rootLView);
      let component;
      let tElementNode;
      let componentView = null;
      try {
        const rootComponentDef = this.componentDef;
        let rootDirectives;
        let hostDirectiveDefs = null;
        if (rootComponentDef.findHostDirectiveDefs) {
          rootDirectives = [];
          hostDirectiveDefs = new Map();
          rootComponentDef.findHostDirectiveDefs(rootComponentDef, rootDirectives, hostDirectiveDefs);
          rootDirectives.push(rootComponentDef);
          ngDevMode && assertNoDuplicateDirectives(rootDirectives);
        } else {
          rootDirectives = [rootComponentDef];
        }
        const hostTNode = createRootComponentTNode(rootLView, hostRNode);
        componentView = createRootComponentView(hostTNode, hostRNode, rootComponentDef, rootDirectives, rootLView, environment, hostRenderer);
        tElementNode = getTNode(rootTView, HEADER_OFFSET);
        // TODO(crisbeto): in practice `hostRNode` should always be defined, but there are some
        // tests where the renderer is mocked out and `undefined` is returned. We should update the
        // tests so that this check can be removed.
        if (hostRNode) {
          setRootNodeAttributes(hostRenderer, rootComponentDef, hostRNode, rootSelectorOrNode);
        }
        if (projectableNodes !== undefined) {
          projectNodes(tElementNode, this.ngContentSelectors, projectableNodes);
        }
        // TODO: should LifecycleHooksFeature and other host features be generated by the compiler
        // and executed here? Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref
        component = createRootComponent(componentView, rootComponentDef, rootDirectives, hostDirectiveDefs, rootLView, [LifecycleHooksFeature]);
        renderView(rootTView, rootLView, null);
      } catch (e) {
        // Stop tracking the views if creation failed since
        // the consumer won't have a way to dereference them.
        if (componentView !== null) {
          unregisterLView(componentView);
        }
        unregisterLView(rootLView);
        throw e;
      } finally {
        leaveView();
      }
      return new ComponentRef(this.componentType, component, createElementRef(tElementNode, rootLView), rootLView, tElementNode);
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
}
/**
 * Represents an instance of a Component created via a {@link ComponentFactory}.
 *
 * `ComponentRef` provides access to the Component Instance as well other objects related to this
 * Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
 * method.
 *
 */
class ComponentRef extends ComponentRef$1 {
  location;
  _rootLView;
  _tNode;
  instance;
  hostView;
  changeDetectorRef;
  componentType;
  previousInputValues = null;
  constructor(componentType, instance, location, _rootLView, _tNode) {
    super();
    this.location = location;
    this._rootLView = _rootLView;
    this._tNode = _tNode;
    this.instance = instance;
    this.hostView = this.changeDetectorRef = new ViewRef$1(_rootLView, undefined /* _cdRefInjectingView */, false /* notifyErrorHandler */);
    this.componentType = componentType;
  }
  setInput(name, value) {
    const inputData = this._tNode.inputs;
    let dataValue;
    if (inputData !== null && (dataValue = inputData[name])) {
      this.previousInputValues ??= new Map();
      // Do not set the input if it is the same as the last value
      // This behavior matches `bindingUpdated` when binding inputs in templates.
      if (this.previousInputValues.has(name) && Object.is(this.previousInputValues.get(name), value)) {
        return;
      }
      const lView = this._rootLView;
      setInputsForProperty(lView[TVIEW], lView, dataValue, name, value);
      this.previousInputValues.set(name, value);
      const childComponentLView = getComponentLViewByIndex(this._tNode.index, lView);
      markViewDirty(childComponentLView, 1 /* NotificationSource.SetInput */);
    } else {
      if (ngDevMode) {
        const cmpNameForError = stringifyForError(this.componentType);
        let message = `Can't set value of the '${name}' input on the '${cmpNameForError}' component. `;
        message += `Make sure that the '${name}' property is annotated with @Input() or a mapped @Input('${name}') exists.`;
        reportUnknownPropertyError(message);
      }
    }
  }
  get injector() {
    return new NodeInjector(this._tNode, this._rootLView);
  }
  destroy() {
    this.hostView.destroy();
  }
  onDestroy(callback) {
    this.hostView.onDestroy(callback);
  }
}
/** Creates a TNode that can be used to instantiate a root component. */
function createRootComponentTNode(lView, rNode) {
  const tView = lView[TVIEW];
  const index = HEADER_OFFSET;
  ngDevMode && assertIndexInRange(lView, index);
  lView[index] = rNode;
  // '#host' is added here as we don't know the real host DOM name (we don't want to read it) and at
  // the same time we want to communicate the debug `TNode` that this is a special `TNode`
  // representing a host element.
  return getOrCreateTNode(tView, index, 2 /* TNodeType.Element */, '#host', null);
}
/**
 * Creates the root component view and the root component node.
 *
 * @param hostRNode Render host element.
 * @param rootComponentDef ComponentDef
 * @param rootView The parent view where the host node is stored
 * @param rendererFactory Factory to be used for creating child renderers.
 * @param hostRenderer The current renderer
 * @param sanitizer The sanitizer, if provided
 *
 * @returns Component view created
 */
function createRootComponentView(tNode, hostRNode, rootComponentDef, rootDirectives, rootView, environment, hostRenderer) {
  const tView = rootView[TVIEW];
  applyRootComponentStyling(rootDirectives, tNode, hostRNode, hostRenderer);
  // Hydration info is on the host element and needs to be retrieved
  // and passed to the component LView.
  let hydrationInfo = null;
  if (hostRNode !== null) {
    hydrationInfo = retrieveHydrationInfo(hostRNode, rootView[INJECTOR]);
  }
  const viewRenderer = environment.rendererFactory.createRenderer(hostRNode, rootComponentDef);
  const componentView = createLView(rootView, getOrCreateComponentTView(rootComponentDef), null, getInitialLViewFlagsFromDef(rootComponentDef), rootView[tNode.index], tNode, environment, viewRenderer, null, null, hydrationInfo);
  if (tView.firstCreatePass) {
    markAsComponentHost(tView, tNode, rootDirectives.length - 1);
  }
  addToEndOfViewTree(rootView, componentView);
  // Store component view at node index, with node as the HOST
  return rootView[tNode.index] = componentView;
}
/** Sets up the styling information on a root component. */
function applyRootComponentStyling(rootDirectives, tNode, rNode, hostRenderer) {
  for (const def of rootDirectives) {
    tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
  }
  if (tNode.mergedAttrs !== null) {
    computeStaticStyling(tNode, tNode.mergedAttrs, true);
    if (rNode !== null) {
      setupStaticAttributes(hostRenderer, rNode, tNode);
    }
  }
}
/**
 * Creates a root component and sets it up with features and host bindings.Shared by
 * renderComponent() and ViewContainerRef.createComponent().
 */
function createRootComponent(componentView, rootComponentDef, rootDirectives, hostDirectiveDefs, rootLView, hostFeatures) {
  const rootTNode = getCurrentTNode();
  ngDevMode && assertDefined(rootTNode, 'tNode should have been already created');
  const tView = rootLView[TVIEW];
  const native = getNativeByTNode(rootTNode, rootLView);
  initializeDirectives(tView, rootLView, rootTNode, rootDirectives, null, hostDirectiveDefs);
  for (let i = 0; i < rootDirectives.length; i++) {
    const directiveIndex = rootTNode.directiveStart + i;
    const directiveInstance = getNodeInjectable(rootLView, tView, directiveIndex, rootTNode);
    attachPatchData(directiveInstance, rootLView);
  }
  invokeDirectivesHostBindings(tView, rootLView, rootTNode);
  if (native) {
    attachPatchData(native, rootLView);
  }
  // We're guaranteed for the `componentOffset` to be positive here
  // since a root component always matches a component def.
  ngDevMode && assertGreaterThan(rootTNode.componentOffset, -1, 'componentOffset must be great than -1');
  const component = getNodeInjectable(rootLView, tView, rootTNode.directiveStart + rootTNode.componentOffset, rootTNode);
  componentView[CONTEXT] = rootLView[CONTEXT] = component;
  if (hostFeatures !== null) {
    for (const feature of hostFeatures) {
      feature(component, rootComponentDef);
    }
  }
  // We want to generate an empty QueryList for root content queries for backwards
  // compatibility with ViewEngine.
  executeContentQueries(tView, rootTNode, rootLView);
  return component;
}
/** Sets the static attributes on a root component. */
function setRootNodeAttributes(hostRenderer, componentDef, hostRNode, rootSelectorOrNode) {
  if (rootSelectorOrNode) {
    // The placeholder will be replaced with the actual version at build time.
    setUpAttributes(hostRenderer, hostRNode, ['ng-version', '19.0.0']);
  } else {
    // If host element is created as a part of this function call (i.e. `rootSelectorOrNode`
    // is not defined), also apply attributes and classes extracted from component selector.
    // Extract attributes and classes from the first selector only to match VE behavior.
    const {
      attrs,
      classes
    } = extractAttrsAndClassesFromSelector(componentDef.selectors[0]);
    if (attrs) {
      setUpAttributes(hostRenderer, hostRNode, attrs);
    }
    if (classes && classes.length > 0) {
      writeDirectClass(hostRenderer, hostRNode, classes.join(' '));
    }
  }
}
/** Projects the `projectableNodes` that were specified when creating a root component. */
function projectNodes(tNode, ngContentSelectors, projectableNodes) {
  const projection = tNode.projection = [];
  for (let i = 0; i < ngContentSelectors.length; i++) {
    const nodesforSlot = projectableNodes[i];
    // Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
    // case). Here we do normalize passed data structure to be an array of arrays to avoid
    // complex checks down the line.
    // We also normalize the length of the passed in projectable nodes (to match the number of
    // <ng-container> slots defined by a component).
    projection.push(nodesforSlot != null && nodesforSlot.length ? Array.from(nodesforSlot) : null);
  }
}
/**
 * Used to enable lifecycle hooks on the root component.
 *
 * Include this feature when calling `renderComponent` if the root component
 * you are rendering has lifecycle hooks defined. Otherwise, the hooks won't
 * be called properly.
 *
 * Example:
 *
 * ```
 * renderComponent(AppComponent, {hostFeatures: [LifecycleHooksFeature]});
 * ```
 */
function LifecycleHooksFeature() {
  const tNode = getCurrentTNode();
  ngDevMode && assertDefined(tNode, 'TNode is required');
  registerPostOrderHooks(getLView()[TVIEW], tNode);
}

/**
 * Returns a new NgModuleRef instance based on the NgModule class and parent injector provided.
 *
 * @param ngModule NgModule class.
 * @param parentInjector Optional injector instance to use as a parent for the module injector. If
 *     not provided, `NullInjector` will be used instead.
 * @returns NgModuleRef that represents an NgModule instance.
 *
 * @publicApi
 */
function createNgModule(ngModule, parentInjector) {
  return new NgModuleRef(ngModule, parentInjector ?? null, []);
}
/**
 * The `createNgModule` function alias for backwards-compatibility.
 * Please avoid using it directly and use `createNgModule` instead.
 *
 * @deprecated Use `createNgModule` instead.
 */
const createNgModuleRef = createNgModule;
class NgModuleRef extends NgModuleRef$1 {
  ngModuleType;
  _parent;
  // tslint:disable-next-line:require-internal-with-underscore
  _bootstrapComponents = [];
  // tslint:disable-next-line:require-internal-with-underscore
  _r3Injector;
  instance;
  destroyCbs = [];
  // When bootstrapping a module we have a dependency graph that looks like this:
  // ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the
  // module being resolved tries to inject the ComponentFactoryResolver, it'll create a
  // circular dependency which will result in a runtime error, because the injector doesn't
  // exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves
  // and providing it, rather than letting the injector resolve it.
  componentFactoryResolver = /*#__PURE__*/(() => new ComponentFactoryResolver(this))();
  constructor(ngModuleType, _parent, additionalProviders, runInjectorInitializers = true) {
    super();
    this.ngModuleType = ngModuleType;
    this._parent = _parent;
    const ngModuleDef = getNgModuleDef(ngModuleType);
    ngDevMode && assertDefined(ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);
    this._bootstrapComponents = maybeUnwrapFn(ngModuleDef.bootstrap);
    this._r3Injector = createInjectorWithoutInjectorInstances(ngModuleType, _parent, [{
      provide: NgModuleRef$1,
      useValue: this
    }, {
      provide: ComponentFactoryResolver$1,
      useValue: this.componentFactoryResolver
    }, ...additionalProviders], stringify(ngModuleType), new Set(['environment']));
    // We need to resolve the injector types separately from the injector creation, because
    // the module might be trying to use this ref in its constructor for DI which will cause a
    // circular error that will eventually error out, because the injector isn't created yet.
    if (runInjectorInitializers) {
      this.resolveInjectorInitializers();
    }
  }
  resolveInjectorInitializers() {
    this._r3Injector.resolveInjectorInitializers();
    this.instance = this._r3Injector.get(this.ngModuleType);
  }
  get injector() {
    return this._r3Injector;
  }
  destroy() {
    ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
    const injector = this._r3Injector;
    !injector.destroyed && injector.destroy();
    this.destroyCbs.forEach(fn => fn());
    this.destroyCbs = null;
  }
  onDestroy(callback) {
    ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
    this.destroyCbs.push(callback);
  }
}
class NgModuleFactory extends NgModuleFactory$1 {
  moduleType;
  constructor(moduleType) {
    super();
    this.moduleType = moduleType;
  }
  create(parentInjector) {
    return new NgModuleRef(this.moduleType, parentInjector, []);
  }
}
function createNgModuleRefWithProviders(moduleType, parentInjector, additionalProviders) {
  return new NgModuleRef(moduleType, parentInjector, additionalProviders, false);
}
class EnvironmentNgModuleRefAdapter extends NgModuleRef$1 {
  injector;
  componentFactoryResolver = /*#__PURE__*/(() => new ComponentFactoryResolver(this))();
  instance = null;
  constructor(config) {
    super();
    const injector = new R3Injector([...config.providers, {
      provide: NgModuleRef$1,
      useValue: this
    }, {
      provide: ComponentFactoryResolver$1,
      useValue: this.componentFactoryResolver
    }], config.parent || getNullInjector(), config.debugName, new Set(['environment']));
    this.injector = injector;
    if (config.runEnvironmentInitializers) {
      injector.resolveInjectorInitializers();
    }
  }
  destroy() {
    this.injector.destroy();
  }
  onDestroy(callback) {
    this.injector.onDestroy(callback);
  }
}
/**
 * Create a new environment injector.
 *
 * @param providers An array of providers.
 * @param parent A parent environment injector.
 * @param debugName An optional name for this injector instance, which will be used in error
 *     messages.
 *
 * @publicApi
 */
function createEnvironmentInjector(providers, parent, debugName = null) {
  const adapter = new EnvironmentNgModuleRefAdapter({
    providers,
    parent,
    debugName,
    runEnvironmentInitializers: true
  });
  return adapter.injector;
}

/**
 * A service used by the framework to create instances of standalone injectors. Those injectors are
 * created on demand in case of dynamic component instantiation and contain ambient providers
 * collected from the imports graph rooted at a given standalone component.
 */
let StandaloneService = /*#__PURE__*/(() => {
  class StandaloneService {
    _injector;
    cachedInjectors = (() => new Map())();
    constructor(_injector) {
      this._injector = _injector;
    }
    getOrCreateStandaloneInjector(componentDef) {
      if (!componentDef.standalone) {
        return null;
      }
      if (!this.cachedInjectors.has(componentDef)) {
        const providers = internalImportProvidersFrom(false, componentDef.type);
        const standaloneInjector = providers.length > 0 ? createEnvironmentInjector([providers], this._injector, `Standalone[${componentDef.type.name}]`) : null;
        this.cachedInjectors.set(componentDef, standaloneInjector);
      }
      return this.cachedInjectors.get(componentDef);
    }
    ngOnDestroy() {
      try {
        for (const injector of this.cachedInjectors.values()) {
          if (injector !== null) {
            injector.destroy();
          }
        }
      } finally {
        this.cachedInjectors.clear();
      }
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: StandaloneService,
      providedIn: 'environment',
      factory: () => new StandaloneService(ɵɵinject(EnvironmentInjector))
    }))();
  }
  return StandaloneService;
})();
/**
 * Create a component definition object.
 *
 *
 * # Example
 * ```
 * class MyComponent {
 *   // Generated by Angular Template Compiler
 *   // [Symbol] syntax will not be supported by TypeScript until v2.7
 *   static ɵcmp = defineComponent({
 *     ...
 *   });
 * }
 * ```
 * @codeGenApi
 */
function ɵɵdefineComponent(componentDefinition) {
  return noSideEffects(() => {
    // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.
    // See the `initNgDevMode` docstring for more information.
    (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
    const baseDef = getNgDirectiveDef(componentDefinition);
    const def = {
      ...baseDef,
      decls: componentDefinition.decls,
      vars: componentDefinition.vars,
      template: componentDefinition.template,
      consts: componentDefinition.consts || null,
      ngContentSelectors: componentDefinition.ngContentSelectors,
      onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,
      directiveDefs: null,
      // assigned in noSideEffects
      pipeDefs: null,
      // assigned in noSideEffects
      dependencies: baseDef.standalone && componentDefinition.dependencies || null,
      getStandaloneInjector: baseDef.standalone ? parentInjector => {
        return parentInjector.get(StandaloneService).getOrCreateStandaloneInjector(def);
      } : null,
      getExternalStyles: null,
      signals: componentDefinition.signals ?? false,
      data: componentDefinition.data || {},
      encapsulation: componentDefinition.encapsulation || ViewEncapsulation.Emulated,
      styles: componentDefinition.styles || EMPTY_ARRAY,
      _: null,
      schemas: componentDefinition.schemas || null,
      tView: null,
      id: ''
    };
    // TODO: Do we still need/want this ?
    if (baseDef.standalone) {
      performanceMarkFeature('NgStandalone');
    }
    initFeatures(def);
    const dependencies = componentDefinition.dependencies;
    def.directiveDefs = extractDefListOrFactory(dependencies, /* pipeDef */false);
    def.pipeDefs = extractDefListOrFactory(dependencies, /* pipeDef */true);
    def.id = getComponentId(def);
    return def;
  });
}
function extractDirectiveDef(type) {
  return getComponentDef(type) || getDirectiveDef(type);
}
function nonNull(value) {
  return value !== null;
}
/**
 * @codeGenApi
 */
function ɵɵdefineNgModule(def) {
  return noSideEffects(() => {
    const res = {
      type: def.type,
      bootstrap: def.bootstrap || EMPTY_ARRAY,
      declarations: def.declarations || EMPTY_ARRAY,
      imports: def.imports || EMPTY_ARRAY,
      exports: def.exports || EMPTY_ARRAY,
      transitiveCompileScopes: null,
      schemas: def.schemas || null,
      id: def.id || null
    };
    return res;
  });
}
function parseAndConvertBindingsForDefinition(obj, declaredInputs) {
  if (obj == null) return EMPTY_OBJ;
  const newLookup = {};
  for (const minifiedKey in obj) {
    if (obj.hasOwnProperty(minifiedKey)) {
      const value = obj[minifiedKey];
      let publicName;
      let declaredName;
      let inputFlags = InputFlags.None;
      if (Array.isArray(value)) {
        inputFlags = value[0];
        publicName = value[1];
        declaredName = value[2] ?? publicName; // declared name might not be set to save bytes.
      } else {
        publicName = value;
        declaredName = value;
      }
      // For inputs, capture the declared name, or if some flags are set.
      if (declaredInputs) {
        // Perf note: An array is only allocated for the input if there are flags.
        newLookup[publicName] = inputFlags !== InputFlags.None ? [minifiedKey, inputFlags] : minifiedKey;
        declaredInputs[publicName] = declaredName;
      } else {
        newLookup[publicName] = minifiedKey;
      }
    }
  }
  return newLookup;
}
/**
 * Create a directive definition object.
 *
 * # Example
 * ```ts
 * class MyDirective {
 *   // Generated by Angular Template Compiler
 *   // [Symbol] syntax will not be supported by TypeScript until v2.7
 *   static ɵdir = ɵɵdefineDirective({
 *     ...
 *   });
 * }
 * ```
 *
 * @codeGenApi
 */
function ɵɵdefineDirective(directiveDefinition) {
  return noSideEffects(() => {
    const def = getNgDirectiveDef(directiveDefinition);
    initFeatures(def);
    return def;
  });
}
/**
 * Create a pipe definition object.
 *
 * # Example
 * ```
 * class MyPipe implements PipeTransform {
 *   // Generated by Angular Template Compiler
 *   static ɵpipe = definePipe({
 *     ...
 *   });
 * }
 * ```
 * @param pipeDef Pipe definition generated by the compiler
 *
 * @codeGenApi
 */
function ɵɵdefinePipe(pipeDef) {
  return {
    type: pipeDef.type,
    name: pipeDef.name,
    factory: null,
    pure: pipeDef.pure !== false,
    standalone: pipeDef.standalone ?? true,
    onDestroy: pipeDef.type.prototype.ngOnDestroy || null
  };
}
function getNgDirectiveDef(directiveDefinition) {
  const declaredInputs = {};
  return {
    type: directiveDefinition.type,
    providersResolver: null,
    factory: null,
    hostBindings: directiveDefinition.hostBindings || null,
    hostVars: directiveDefinition.hostVars || 0,
    hostAttrs: directiveDefinition.hostAttrs || null,
    contentQueries: directiveDefinition.contentQueries || null,
    declaredInputs: declaredInputs,
    inputTransforms: null,
    inputConfig: directiveDefinition.inputs || EMPTY_OBJ,
    exportAs: directiveDefinition.exportAs || null,
    standalone: directiveDefinition.standalone ?? true,
    signals: directiveDefinition.signals === true,
    selectors: directiveDefinition.selectors || EMPTY_ARRAY,
    viewQuery: directiveDefinition.viewQuery || null,
    features: directiveDefinition.features || null,
    setInput: null,
    findHostDirectiveDefs: null,
    hostDirectives: null,
    inputs: parseAndConvertBindingsForDefinition(directiveDefinition.inputs, declaredInputs),
    outputs: parseAndConvertBindingsForDefinition(directiveDefinition.outputs),
    debugInfo: null
  };
}
function initFeatures(definition) {
  definition.features?.forEach(fn => fn(definition));
}
function extractDefListOrFactory(dependencies, pipeDef) {
  if (!dependencies) {
    return null;
  }
  const defExtractor = pipeDef ? getPipeDef$1 : extractDirectiveDef;
  return () => (typeof dependencies === 'function' ? dependencies() : dependencies).map(dep => defExtractor(dep)).filter(nonNull);
}
/**
 * A map that contains the generated component IDs and type.
 */
const GENERATED_COMP_IDS = /*#__PURE__*/new Map();
/**
 * A method can returns a component ID from the component definition using a variant of DJB2 hash
 * algorithm.
 */
function getComponentId(componentDef) {
  let hash = 0;
  // We cannot rely solely on the component selector as the same selector can be used in different
  // modules.
  //
  // `componentDef.style` is not used, due to it causing inconsistencies. Ex: when server
  // component styles has no sourcemaps and browsers do.
  //
  // Example:
  // https://github.com/angular/components/blob/d9f82c8f95309e77a6d82fd574c65871e91354c2/src/material/core/option/option.ts#L248
  // https://github.com/angular/components/blob/285f46dc2b4c5b127d356cb7c4714b221f03ce50/src/material/legacy-core/option/option.ts#L32
  const hashSelectors = [componentDef.selectors, componentDef.ngContentSelectors, componentDef.hostVars, componentDef.hostAttrs, componentDef.consts, componentDef.vars, componentDef.decls, componentDef.encapsulation, componentDef.standalone, componentDef.signals, componentDef.exportAs, JSON.stringify(componentDef.inputs), JSON.stringify(componentDef.outputs),
  // We cannot use 'componentDef.type.name' as the name of the symbol will change and will not
  // match in the server and browser bundles.
  Object.getOwnPropertyNames(componentDef.type.prototype), !!componentDef.contentQueries, !!componentDef.viewQuery].join('|');
  for (const char of hashSelectors) {
    hash = Math.imul(31, hash) + char.charCodeAt(0) << 0;
  }
  // Force positive number hash.
  // 2147483647 = equivalent of Integer.MAX_VALUE.
  hash += 2147483647 + 1;
  const compId = 'c' + hash;
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (GENERATED_COMP_IDS.has(compId)) {
      const previousCompDefType = GENERATED_COMP_IDS.get(compId);
      if (previousCompDefType !== componentDef.type) {
        console.warn(formatRuntimeError(-912 /* RuntimeErrorCode.COMPONENT_ID_COLLISION */, `Component ID generation collision detected. Components '${previousCompDefType.name}' and '${componentDef.type.name}' with selector '${stringifyCSSSelectorList(componentDef.selectors)}' generated the same component ID. To fix this, you can change the selector of one of those components or add an extra host attribute to force a different ID.`));
      }
    } else {
      GENERATED_COMP_IDS.set(compId, componentDef.type);
    }
  }
  return compId;
}

/**
 * The name of a field that Angular monkey-patches onto a component
 * class to store a function that loads defer-loadable dependencies
 * and applies metadata to a class.
 */
const ASYNC_COMPONENT_METADATA_FN = '__ngAsyncComponentMetadataFn__';
/**
 * If a given component has unresolved async metadata - returns a reference
 * to a function that applies component metadata after resolving defer-loadable
 * dependencies. Otherwise - this function returns `null`.
 */
function getAsyncClassMetadataFn(type) {
  const componentClass = type; // cast to `any`, so that we can read a monkey-patched field
  return componentClass[ASYNC_COMPONENT_METADATA_FN] ?? null;
}
/**
 * Handles the process of applying metadata info to a component class in case
 * component template has defer blocks (thus some dependencies became deferrable).
 *
 * @param type Component class where metadata should be added
 * @param dependencyLoaderFn Function that loads dependencies
 * @param metadataSetterFn Function that forms a scope in which the `setClassMetadata` is invoked
 */
function setClassMetadataAsync(type, dependencyLoaderFn, metadataSetterFn) {
  const componentClass = type; // cast to `any`, so that we can monkey-patch it
  componentClass[ASYNC_COMPONENT_METADATA_FN] = () => Promise.all(dependencyLoaderFn()).then(dependencies => {
    metadataSetterFn(...dependencies);
    // Metadata is now set, reset field value to indicate that this component
    // can by used/compiled synchronously.
    componentClass[ASYNC_COMPONENT_METADATA_FN] = null;
    return dependencies;
  });
  return componentClass[ASYNC_COMPONENT_METADATA_FN];
}
/**
 * Adds decorator, constructor, and property metadata to a given type via static metadata fields
 * on the type.
 *
 * These metadata fields can later be read with Angular's `ReflectionCapabilities` API.
 *
 * Calls to `setClassMetadata` can be guarded by ngDevMode, resulting in the metadata assignments
 * being tree-shaken away during production builds.
 */
function setClassMetadata(type, decorators, ctorParameters, propDecorators) {
  return noSideEffects(() => {
    const clazz = type;
    if (decorators !== null) {
      if (clazz.hasOwnProperty('decorators') && clazz.decorators !== undefined) {
        clazz.decorators.push(...decorators);
      } else {
        clazz.decorators = decorators;
      }
    }
    if (ctorParameters !== null) {
      // Rather than merging, clobber the existing parameters. If other projects exist which
      // use tsickle-style annotations and reflect over them in the same way, this could
      // cause issues, but that is vanishingly unlikely.
      clazz.ctorParameters = ctorParameters;
    }
    if (propDecorators !== null) {
      // The property decorator objects are merged as it is possible different fields have
      // different decorator types. Decorators on individual fields are not merged, as it's
      // also incredibly unlikely that a field will be decorated both with an Angular
      // decorator and a non-Angular decorator that's also been downleveled.
      if (clazz.hasOwnProperty('propDecorators') && clazz.propDecorators !== undefined) {
        clazz.propDecorators = {
          ...clazz.propDecorators,
          ...propDecorators
        };
      } else {
        clazz.propDecorators = propDecorators;
      }
    }
  });
}

/*
 * This file exists to support compilation of @angular/core in Ivy mode.
 *
 * When the Angular compiler processes a compilation unit, it normally writes imports to
 * @angular/core. When compiling the core package itself this strategy isn't usable. Instead, the
 * compiler writes imports to this file.
 *
 * Only a subset of such imports are supported - core is not allowed to declare components or pipes.
 * A check in ngtsc's `R3SymbolsImportRewriter` validates this condition. The rewriter is only used
 * when compiling @angular/core and is responsible for translating an external name (prefixed with
 * ɵ) to the internal symbol name as exported below.
 *
 * The below symbols are used for @Injectable and @NgModule compilation.
 */
/**
 * The existence of this constant (in this particular file) informs the Angular compiler that the
 * current program is actually @angular/core, which needs to be compiled specially.
 */
const ITS_JUST_ANGULAR = true;
let Console = /*#__PURE__*/(() => {
  class Console {
    log(message) {
      // tslint:disable-next-line:no-console
      console.log(message);
    }
    // Note: for reporting errors use `DOM.logError()` as it is platform specific
    warn(message) {
      // tslint:disable-next-line:no-console
      console.warn(message);
    }
    static ɵfac = function Console_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Console)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: Console,
      factory: Console.ɵfac,
      providedIn: 'platform'
    }))();
  }
  return Console;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Console, [{
    type: Injectable,
    args: [{
      providedIn: 'platform'
    }]
  }], null, null);
})();

/**
 * These are the data structures that our framework injector profiler will fill with data in order
 * to support DI debugging APIs.
 *
 * resolverToTokenToDependencies: Maps an injector to a Map of tokens to an Array of
 * dependencies. Injector -> Token -> Dependencies This is used to support the
 * getDependenciesFromInjectable API, which takes in an injector and a token and returns it's
 * dependencies.
 *
 * resolverToProviders: Maps a DI resolver (an Injector or a TNode) to the providers configured
 * within it This is used to support the getInjectorProviders API, which takes in an injector and
 * returns the providers that it was configured with. Note that for the element injector case we
 * use the TNode instead of the LView as the DI resolver. This is because the registration of
 * providers happens only once per type of TNode. If an injector is created with an identical TNode,
 * the providers for that injector will not be reconfigured.
 *
 * standaloneInjectorToComponent: Maps the injector of a standalone component to the standalone
 * component that it is associated with. Used in the getInjectorProviders API, specificially in the
 * discovery of import paths for each provider. This is necessary because the imports array of a
 * standalone component is processed and configured in its standalone injector, but exists within
 * the component's definition. Because getInjectorProviders takes in an injector, if that injector
 * is the injector of a standalone component, we need to be able to discover the place where the
 * imports array is located (the component) in order to flatten the imports array within it to
 * discover all of it's providers.
 *
 *
 * All of these data structures are instantiated with WeakMaps. This will ensure that the presence
 * of any object in the keys of these maps does not prevent the garbage collector from collecting
 * those objects. Because of this property of WeakMaps, these data structures will never be the
 * source of a memory leak.
 *
 * An example of this advantage: When components are destroyed, we don't need to do
 * any additional work to remove that component from our mappings.
 *
 */
class DIDebugData {
  resolverToTokenToDependencies = /*#__PURE__*/(() => new WeakMap())();
  resolverToProviders = /*#__PURE__*/(() => new WeakMap())();
  standaloneInjectorToComponent = /*#__PURE__*/(() => new WeakMap())();
  reset() {
    this.resolverToTokenToDependencies = new WeakMap();
    this.resolverToProviders = new WeakMap();
    this.standaloneInjectorToComponent = new WeakMap();
  }
}
let frameworkDIDebugData = /*#__PURE__*/new DIDebugData();
function getFrameworkDIDebugData() {
  return frameworkDIDebugData;
}
/**
 * Initalize default handling of injector events. This handling parses events
 * as they are emitted and constructs the data structures necessary to support
 * some of debug APIs.
 *
 * See handleInjectEvent, handleCreateEvent and handleProviderConfiguredEvent
 * for descriptions of each handler
 *
 * Supported APIs:
 *               - getDependenciesFromInjectable
 *               - getInjectorProviders
 */
function setupFrameworkInjectorProfiler() {
  frameworkDIDebugData.reset();
  setInjectorProfiler(injectorProfilerEvent => handleInjectorProfilerEvent(injectorProfilerEvent));
}
function handleInjectorProfilerEvent(injectorProfilerEvent) {
  const {
    context,
    type
  } = injectorProfilerEvent;
  if (type === 0 /* InjectorProfilerEventType.Inject */) {
    handleInjectEvent(context, injectorProfilerEvent.service);
  } else if (type === 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */) {
    handleInstanceCreatedByInjectorEvent(context, injectorProfilerEvent.instance);
  } else if (type === 2 /* InjectorProfilerEventType.ProviderConfigured */) {
    handleProviderConfiguredEvent(context, injectorProfilerEvent.providerRecord);
  }
}
/**
 *
 * Stores the injected service in frameworkDIDebugData.resolverToTokenToDependencies
 * based on it's injector and token.
 *
 * @param context InjectorProfilerContext the injection context that this event occurred in.
 * @param data InjectedService the service associated with this inject event.
 *
 */
function handleInjectEvent(context, data) {
  const diResolver = getDIResolver(context.injector);
  if (diResolver === null) {
    throwError('An Inject event must be run within an injection context.');
  }
  const diResolverToInstantiatedToken = frameworkDIDebugData.resolverToTokenToDependencies;
  if (!diResolverToInstantiatedToken.has(diResolver)) {
    diResolverToInstantiatedToken.set(diResolver, new WeakMap());
  }
  // if token is a primitive type, ignore this event. We do this because we cannot keep track of
  // non-primitive tokens in WeakMaps since they are not garbage collectable.
  if (!canBeHeldWeakly(context.token)) {
    return;
  }
  const instantiatedTokenToDependencies = diResolverToInstantiatedToken.get(diResolver);
  if (!instantiatedTokenToDependencies.has(context.token)) {
    instantiatedTokenToDependencies.set(context.token, []);
  }
  const {
    token,
    value,
    flags
  } = data;
  assertDefined(context.token, 'Injector profiler context token is undefined.');
  const dependencies = instantiatedTokenToDependencies.get(context.token);
  assertDefined(dependencies, 'Could not resolve dependencies for token.');
  if (context.injector instanceof NodeInjector) {
    dependencies.push({
      token,
      value,
      flags,
      injectedIn: getNodeInjectorContext(context.injector)
    });
  } else {
    dependencies.push({
      token,
      value,
      flags
    });
  }
}
/**
 *
 * Returns the LView and TNode associated with a NodeInjector. Returns undefined if the injector
 * is not a NodeInjector.
 *
 * @param injector
 * @returns {lView: LView, tNode: TNode}|undefined
 */
function getNodeInjectorContext(injector) {
  if (!(injector instanceof NodeInjector)) {
    throwError('getNodeInjectorContext must be called with a NodeInjector');
  }
  const lView = getNodeInjectorLView(injector);
  const tNode = getNodeInjectorTNode(injector);
  if (tNode === null) {
    return;
  }
  assertTNodeForLView(tNode, lView);
  return {
    lView,
    tNode
  };
}
/**
 *
 * If the created instance is an instance of a standalone component, maps the injector to that
 * standalone component in frameworkDIDebugData.standaloneInjectorToComponent
 *
 * @param context InjectorProfilerContext the injection context that this event occurred in.
 * @param data InjectorCreatedInstance an object containing the instance that was just created
 *
 */
function handleInstanceCreatedByInjectorEvent(context, data) {
  const {
    value
  } = data;
  if (getDIResolver(context.injector) === null) {
    throwError('An InjectorCreatedInstance event must be run within an injection context.');
  }
  // if our value is an instance of a standalone component, map the injector of that standalone
  // component to the component class. Otherwise, this event is a noop.
  let standaloneComponent = undefined;
  if (typeof value === 'object') {
    standaloneComponent = value?.constructor;
  }
  // We want to also cover if `standaloneComponent === null` in addition to `undefined`
  if (standaloneComponent == undefined || !isStandaloneComponent(standaloneComponent)) {
    return;
  }
  const environmentInjector = context.injector.get(EnvironmentInjector, null, {
    optional: true
  });
  // Standalone components should have an environment injector. If one cannot be
  // found we may be in a test case for low level functionality that did not explicitly
  // setup this injector. In those cases, we simply ignore this event.
  if (environmentInjector === null) {
    return;
  }
  const {
    standaloneInjectorToComponent
  } = frameworkDIDebugData;
  // If our injector has already been mapped, as is the case
  // when a standalone component imports another standalone component,
  // we consider the original component (the component doing the importing)
  // as the component connected to our injector.
  if (standaloneInjectorToComponent.has(environmentInjector)) {
    return;
  }
  // If our injector hasn't been mapped, then we map it to the standalone component
  standaloneInjectorToComponent.set(environmentInjector, standaloneComponent);
}
function isStandaloneComponent(value) {
  const def = getComponentDef(value);
  return !!def?.standalone;
}
/**
 *
 * Stores the emitted ProviderRecords from the InjectorProfilerEventType.ProviderConfigured
 * event in frameworkDIDebugData.resolverToProviders
 *
 * @param context InjectorProfilerContext the injection context that this event occurred in.
 * @param data ProviderRecord an object containing the instance that was just created
 *
 */
function handleProviderConfiguredEvent(context, data) {
  const {
    resolverToProviders
  } = frameworkDIDebugData;
  let diResolver;
  if (context?.injector instanceof NodeInjector) {
    diResolver = getNodeInjectorTNode(context.injector);
  } else {
    diResolver = context.injector;
  }
  if (diResolver === null) {
    throwError('A ProviderConfigured event must be run within an injection context.');
  }
  if (!resolverToProviders.has(diResolver)) {
    resolverToProviders.set(diResolver, []);
  }
  resolverToProviders.get(diResolver).push(data);
}
function getDIResolver(injector) {
  let diResolver = null;
  if (injector === undefined) {
    return diResolver;
  }
  // We use the LView as the diResolver for NodeInjectors because they
  // do not persist anywhere in the framework. They are simply wrappers around an LView and a TNode
  // that do persist. Because of this, we rely on the LView of the NodeInjector in order to use
  // as a concrete key to represent this injector. If we get the same LView back later, we know
  // we're looking at the same injector.
  if (injector instanceof NodeInjector) {
    diResolver = getNodeInjectorLView(injector);
  }
  // Other injectors can be used a keys for a map because their instances
  // persist
  else {
    diResolver = injector;
  }
  return diResolver;
}
// inspired by
// https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#sec-canbeheldweakly
function canBeHeldWeakly(value) {
  // we check for value !== null here because typeof null === 'object
  return value !== null && (typeof value === 'object' || typeof value === 'function' || typeof value === 'symbol');
}

/**
 * Checks if the given `value` is a reactive `Signal`.
 */
function isSignal(value) {
  return typeof value === 'function' && value[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] !== undefined;
}

/**
 * Marks a component for check (in case of OnPush components) and synchronously
 * performs change detection on the application this component belongs to.
 *
 * @param component Component to {@link ChangeDetectorRef#markForCheck mark for check}.
 *
 * @publicApi
 */
function applyChanges(component) {
  ngDevMode && assertDefined(component, 'component');
  markViewDirty(getComponentViewByInstance(component), 3 /* NotificationSource.DebugApplyChanges */);
  getRootComponents(component).forEach(rootComponent => detectChanges(rootComponent));
}
/**
 * Synchronously perform change detection on a component (and possibly its sub-components).
 *
 * This function triggers change detection in a synchronous way on a component.
 *
 * @param component The component which the change detection should be performed on.
 */
function detectChanges(component) {
  const view = getComponentViewByInstance(component);
  view[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  detectChangesInternal(view);
}

/**
 * Discovers the dependencies of an injectable instance. Provides DI information about each
 * dependency that the injectable was instantiated with, including where they were provided from.
 *
 * @param injector An injector instance
 * @param token a DI token that was constructed by the given injector instance
 * @returns an object that contains the created instance of token as well as all of the dependencies
 * that it was instantiated with OR undefined if the token was not created within the given
 * injector.
 */
function getDependenciesFromInjectable(injector, token) {
  // First we check to see if the token given maps to an actual instance in the injector given.
  // We use `self: true` because we only want to look at the injector we were given.
  // We use `optional: true` because it's possible that the token we were given was never
  // constructed by the injector we were given.
  const instance = injector.get(token, null, {
    self: true,
    optional: true
  });
  if (instance === null) {
    throw new Error(`Unable to determine instance of ${token} in given injector`);
  }
  const unformattedDependencies = getDependenciesForTokenInInjector(token, injector);
  const resolutionPath = getInjectorResolutionPath(injector);
  const dependencies = unformattedDependencies.map(dep => {
    // injectedIn contains private fields, so we omit it from the response
    const formattedDependency = {
      value: dep.value
    };
    // convert injection flags to booleans
    const flags = dep.flags;
    formattedDependency.flags = {
      optional: (8 /* InternalInjectFlags.Optional */ & flags) === 8 /* InternalInjectFlags.Optional */,
      host: (1 /* InternalInjectFlags.Host */ & flags) === 1 /* InternalInjectFlags.Host */,
      self: (2 /* InternalInjectFlags.Self */ & flags) === 2 /* InternalInjectFlags.Self */,
      skipSelf: (4 /* InternalInjectFlags.SkipSelf */ & flags) === 4 /* InternalInjectFlags.SkipSelf */
    };
    // find the injector that provided the dependency
    for (let i = 0; i < resolutionPath.length; i++) {
      const injectorToCheck = resolutionPath[i];
      // if skipSelf is true we skip the first injector
      if (i === 0 && formattedDependency.flags.skipSelf) {
        continue;
      }
      // host only applies to NodeInjectors
      if (formattedDependency.flags.host && injectorToCheck instanceof EnvironmentInjector) {
        break;
      }
      const instance = injectorToCheck.get(dep.token, null, {
        self: true,
        optional: true
      });
      if (instance !== null) {
        // if host flag is true we double check that we can get the service from the first element
        // in the resolution path by using the host flag. This is done to make sure that we've found
        // the correct providing injector, and not a node injector that is connected to our path via
        // a router outlet.
        if (formattedDependency.flags.host) {
          const firstInjector = resolutionPath[0];
          const lookupFromFirstInjector = firstInjector.get(dep.token, null, {
            ...formattedDependency.flags,
            optional: true
          });
          if (lookupFromFirstInjector !== null) {
            formattedDependency.providedIn = injectorToCheck;
          }
          break;
        }
        formattedDependency.providedIn = injectorToCheck;
        break;
      }
      // if self is true we stop after the first injector
      if (i === 0 && formattedDependency.flags.self) {
        break;
      }
    }
    if (dep.token) formattedDependency.token = dep.token;
    return formattedDependency;
  });
  return {
    instance,
    dependencies
  };
}
function getDependenciesForTokenInInjector(token, injector) {
  const {
    resolverToTokenToDependencies
  } = getFrameworkDIDebugData();
  if (!(injector instanceof NodeInjector)) {
    return resolverToTokenToDependencies.get(injector)?.get?.(token) ?? [];
  }
  const lView = getNodeInjectorLView(injector);
  const tokenDependencyMap = resolverToTokenToDependencies.get(lView);
  const dependencies = tokenDependencyMap?.get(token) ?? [];
  // In the NodeInjector case, all injections for every node are stored in the same lView.
  // We use the injectedIn field of the dependency to filter out the dependencies that
  // do not come from the same node as the instance we're looking at.
  return dependencies.filter(dependency => {
    const dependencyNode = dependency.injectedIn?.tNode;
    if (dependencyNode === undefined) {
      return false;
    }
    const instanceNode = getNodeInjectorTNode(injector);
    assertTNode(dependencyNode);
    assertTNode(instanceNode);
    return dependencyNode === instanceNode;
  });
}
/**
 * Gets the class associated with an injector that contains a provider `imports` array in it's
 * definition
 *
 * For Module Injectors this returns the NgModule constructor.
 *
 * For Standalone injectors this returns the standalone component constructor.
 *
 * @param injector Injector an injector instance
 * @returns the constructor where the `imports` array that configures this injector is located
 */
function getProviderImportsContainer(injector) {
  const {
    standaloneInjectorToComponent
  } = getFrameworkDIDebugData();
  // standalone components configure providers through a component def, so we have to
  // use the standalone component associated with this injector if Injector represents
  // a standalone components EnvironmentInjector
  if (standaloneInjectorToComponent.has(injector)) {
    return standaloneInjectorToComponent.get(injector);
  }
  // Module injectors configure providers through their NgModule def, so we use the
  // injector to lookup its NgModuleRef and through that grab its instance
  const defTypeRef = injector.get(NgModuleRef$1, null, {
    self: true,
    optional: true
  });
  // If we can't find an associated imports container, return null.
  // This could be the case if this function is called with an R3Injector that does not represent
  // a standalone component or NgModule.
  if (defTypeRef === null) {
    return null;
  }
  // In standalone applications, the root environment injector created by bootstrapApplication
  // may have no associated "instance".
  if (defTypeRef.instance === null) {
    return null;
  }
  return defTypeRef.instance.constructor;
}
/**
 * Gets the providers configured on a NodeInjector
 *
 * @param injector A NodeInjector instance
 * @returns ProviderRecord[] an array of objects representing the providers configured on this
 *     injector
 */
function getNodeInjectorProviders(injector) {
  const diResolver = getNodeInjectorTNode(injector);
  const {
    resolverToProviders
  } = getFrameworkDIDebugData();
  return resolverToProviders.get(diResolver) ?? [];
}
/**
 * Gets a mapping of providers configured on an injector to their import paths
 *
 * ModuleA -> imports ModuleB
 * ModuleB -> imports ModuleC
 * ModuleB -> provides MyServiceA
 * ModuleC -> provides MyServiceB
 *
 * getProviderImportPaths(ModuleA)
 * > Map(2) {
 *   MyServiceA => [ModuleA, ModuleB]
 *   MyServiceB => [ModuleA, ModuleB, ModuleC]
 *  }
 *
 * @param providerImportsContainer constructor of class that contains an `imports` array in it's
 *     definition
 * @returns A Map object that maps providers to an array of constructors representing it's import
 *     path
 *
 */
function getProviderImportPaths(providerImportsContainer) {
  const providerToPath = new Map();
  const visitedContainers = new Set();
  const visitor = walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers);
  walkProviderTree(providerImportsContainer, visitor, [], new Set());
  return providerToPath;
}
/**
 *
 * Higher order function that returns a visitor for WalkProviderTree
 *
 * Takes in a Map and Set to keep track of the providers and containers
 * visited, so that we can discover the import paths of these providers
 * during the traversal.
 *
 * This visitor takes advantage of the fact that walkProviderTree performs a
 * postorder traversal of the provider tree for the passed in container. Because postorder
 * traversal recursively processes subtrees from leaf nodes until the traversal reaches the root,
 * we write a visitor that constructs provider import paths in reverse.
 *
 *
 * We use the visitedContainers set defined outside this visitor
 * because we want to run some logic only once for
 * each container in the tree. That logic can be described as:
 *
 *
 * 1. for each discovered_provider and discovered_path in the incomplete provider paths we've
 * already discovered
 * 2. get the first container in discovered_path
 * 3. if that first container is in the imports array of the container we're visiting
 *    Then the container we're visiting is also in the import path of discovered_provider, so we
 *    unshift discovered_path with the container we're currently visiting
 *
 *
 * Example Run:
 * ```
 *                 ┌──────────┐
 *                 │containerA│
 *      ┌─imports-─┤          ├──imports─┐
 *      │          │  provA   │          │
 *      │          │  provB   │          │
 *      │          └──────────┘          │
 *      │                                │
 *     ┌▼─────────┐             ┌────────▼─┐
 *     │containerB│             │containerC│
 *     │          │             │          │
 *     │  provD   │             │  provF   │
 *     │  provE   │             │  provG   │
 *     └──────────┘             └──────────┘
 * ```
 *
 * Each step of the traversal,
 *
 * ```
 * visitor(provD, containerB)
 * providerToPath === Map { provD => [containerB] }
 * visitedContainers === Set { containerB }
 *
 * visitor(provE, containerB)
 * providerToPath === Map { provD => [containerB], provE => [containerB] }
 * visitedContainers === Set { containerB }
 *
 * visitor(provF, containerC)
 * providerToPath === Map { provD => [containerB], provE => [containerB], provF => [containerC] }
 * visitedContainers === Set { containerB, containerC }
 *
 * visitor(provG, containerC)
 * providerToPath === Map {
 *   provD => [containerB], provE => [containerB], provF => [containerC], provG => [containerC]
 * }
 * visitedContainers === Set { containerB, containerC }
 *
 * visitor(provA, containerA)
 * providerToPath === Map {
 *   provD => [containerA, containerB],
 *   provE => [containerA, containerB],
 *   provF => [containerA, containerC],
 *   provG => [containerA, containerC],
 *   provA => [containerA]
 * }
 * visitedContainers === Set { containerB, containerC, containerA }
 *
 * visitor(provB, containerA)
 * providerToPath === Map {
 *   provD => [containerA, containerB],
 *   provE => [containerA, containerB],
 *   provF => [containerA, containerC],
 *   provG => [containerA, containerC],
 *   provA => [containerA]
 *   provB => [containerA]
 * }
 * visitedContainers === Set { containerB, containerC, containerA }
 * ```
 *
 * @param providerToPath Map map of providers to paths that this function fills
 * @param visitedContainers Set a set to keep track of the containers we've already visited
 * @return function(provider SingleProvider, container: Type<unknown> | InjectorType<unknown>) =>
 *     void
 */
function walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers) {
  return (provider, container) => {
    // If the provider is not already in the providerToPath map,
    // add an entry with the provider as the key and an array containing the current container as
    // the value
    if (!providerToPath.has(provider)) {
      providerToPath.set(provider, [container]);
    }
    // This block will run exactly once for each container in the import tree.
    // This is where we run the logic to check the imports array of the current
    // container to see if it's the next container in the path for our currently
    // discovered providers.
    if (!visitedContainers.has(container)) {
      // Iterate through the providers we've already seen
      for (const prov of providerToPath.keys()) {
        const existingImportPath = providerToPath.get(prov);
        let containerDef = getInjectorDef(container);
        if (!containerDef) {
          const ngModule = container.ngModule;
          containerDef = getInjectorDef(ngModule);
        }
        if (!containerDef) {
          return;
        }
        const lastContainerAddedToPath = existingImportPath[0];
        let isNextStepInPath = false;
        deepForEach(containerDef.imports, moduleImport => {
          if (isNextStepInPath) {
            return;
          }
          isNextStepInPath = moduleImport.ngModule === lastContainerAddedToPath || moduleImport === lastContainerAddedToPath;
          if (isNextStepInPath) {
            providerToPath.get(prov)?.unshift(container);
          }
        });
      }
    }
    visitedContainers.add(container);
  };
}
/**
 * Gets the providers configured on an EnvironmentInjector
 *
 * @param injector EnvironmentInjector
 * @returns an array of objects representing the providers of the given injector
 */
function getEnvironmentInjectorProviders(injector) {
  const providerRecordsWithoutImportPaths = getFrameworkDIDebugData().resolverToProviders.get(injector) ?? [];
  // platform injector has no provider imports container so can we skip trying to
  // find import paths
  if (isPlatformInjector(injector)) {
    return providerRecordsWithoutImportPaths;
  }
  const providerImportsContainer = getProviderImportsContainer(injector);
  if (providerImportsContainer === null) {
    // We assume that if an environment injector exists without an associated provider imports
    // container, it was created without such a container. Some examples cases where this could
    // happen:
    // - The root injector of a standalone application
    // - A router injector created by using the providers array in a lazy loaded route
    // - A manually created injector that is attached to the injector tree
    // Since each of these cases has no provider container, there is no concept of import paths,
    // so we can simply return the provider records.
    return providerRecordsWithoutImportPaths;
  }
  const providerToPath = getProviderImportPaths(providerImportsContainer);
  const providerRecords = [];
  for (const providerRecord of providerRecordsWithoutImportPaths) {
    const provider = providerRecord.provider;
    // Ignore these special providers for now until we have a cleaner way of
    // determing when they are provided by the framework vs provided by the user.
    const token = provider.provide;
    if (token === ENVIRONMENT_INITIALIZER || token === INJECTOR_DEF_TYPES) {
      continue;
    }
    let importPath = providerToPath.get(provider) ?? [];
    const def = getComponentDef(providerImportsContainer);
    const isStandaloneComponent = !!def?.standalone;
    // We prepend the component constructor in the standalone case
    // because walkProviderTree does not visit this constructor during it's traversal
    if (isStandaloneComponent) {
      importPath = [providerImportsContainer, ...importPath];
    }
    providerRecords.push({
      ...providerRecord,
      importPath
    });
  }
  return providerRecords;
}
function isPlatformInjector(injector) {
  return injector instanceof R3Injector && injector.scopes.has('platform');
}
/**
 * Gets the providers configured on an injector.
 *
 * @param injector the injector to lookup the providers of
 * @returns ProviderRecord[] an array of objects representing the providers of the given injector
 */
function getInjectorProviders(injector) {
  if (injector instanceof NodeInjector) {
    return getNodeInjectorProviders(injector);
  } else if (injector instanceof EnvironmentInjector) {
    return getEnvironmentInjectorProviders(injector);
  }
  throwError('getInjectorProviders only supports NodeInjector and EnvironmentInjector');
}
/**
 *
 * Given an injector, this function will return
 * an object containing the type and source of the injector.
 *
 * |              | type        | source                                                      |
 * |--------------|-------------|-------------------------------------------------------------|
 * | NodeInjector | element     | DOM element that created this injector                      |
 * | R3Injector   | environment | `injector.source`                                           |
 * | NullInjector | null        | null                                                        |
 *
 * @param injector the Injector to get metadata for
 * @returns an object containing the type and source of the given injector. If the injector metadata
 *     cannot be determined, returns null.
 */
function getInjectorMetadata(injector) {
  if (injector instanceof NodeInjector) {
    const lView = getNodeInjectorLView(injector);
    const tNode = getNodeInjectorTNode(injector);
    assertTNodeForLView(tNode, lView);
    return {
      type: 'element',
      source: getNativeByTNode(tNode, lView)
    };
  }
  if (injector instanceof R3Injector) {
    return {
      type: 'environment',
      source: injector.source ?? null
    };
  }
  if (injector instanceof NullInjector) {
    return {
      type: 'null',
      source: null
    };
  }
  return null;
}
function getInjectorResolutionPath(injector) {
  const resolutionPath = [injector];
  getInjectorResolutionPathHelper(injector, resolutionPath);
  return resolutionPath;
}
function getInjectorResolutionPathHelper(injector, resolutionPath) {
  const parent = getInjectorParent(injector);
  // if getInjectorParent can't find a parent, then we've either reached the end
  // of the path, or we need to move from the Element Injector tree to the
  // module injector tree using the first injector in our path as the connection point.
  if (parent === null) {
    if (injector instanceof NodeInjector) {
      const firstInjector = resolutionPath[0];
      if (firstInjector instanceof NodeInjector) {
        const moduleInjector = getModuleInjectorOfNodeInjector(firstInjector);
        if (moduleInjector === null) {
          throwError('NodeInjector must have some connection to the module injector tree');
        }
        resolutionPath.push(moduleInjector);
        getInjectorResolutionPathHelper(moduleInjector, resolutionPath);
      }
      return resolutionPath;
    }
  } else {
    resolutionPath.push(parent);
    getInjectorResolutionPathHelper(parent, resolutionPath);
  }
  return resolutionPath;
}
/**
 * Gets the parent of an injector.
 *
 * This function is not able to make the jump from the Element Injector Tree to the Module
 * injector tree. This is because the "parent" (the next step in the reoslution path)
 * of a root NodeInjector is dependent on which NodeInjector ancestor initiated
 * the DI lookup. See getInjectorResolutionPath for a function that can make this jump.
 *
 * In the below diagram:
 * ```ts
 * getInjectorParent(NodeInjectorB)
 *  > NodeInjectorA
 * getInjectorParent(NodeInjectorA) // or getInjectorParent(getInjectorParent(NodeInjectorB))
 *  > null // cannot jump to ModuleInjector tree
 * ```
 *
 * ```
 *                ┌───────┐                ┌───────────────────┐
 *    ┌───────────┤ModuleA├───Injector────►│EnvironmentInjector│
 *    │           └───┬───┘                └───────────────────┘
 *    │               │
 *    │           bootstraps
 *    │               │
 *    │               │
 *    │          ┌────▼─────┐                 ┌─────────────┐
 * declares      │ComponentA├────Injector────►│NodeInjectorA│
 *    │          └────┬─────┘                 └─────▲───────┘
 *    │               │                             │
 *    │            renders                        parent
 *    │               │                             │
 *    │          ┌────▼─────┐                 ┌─────┴───────┐
 *    └─────────►│ComponentB├────Injector────►│NodeInjectorB│
 *               └──────────┘                 └─────────────┘
 *```
 *
 * @param injector an Injector to get the parent of
 * @returns Injector the parent of the given injector
 */
function getInjectorParent(injector) {
  if (injector instanceof R3Injector) {
    const parent = injector.parent;
    if (isRouterOutletInjector(parent)) {
      // This is a special case for a `ChainedInjector` instance, which represents
      // a combination of a Router's `OutletInjector` and an EnvironmentInjector,
      // which represents a `@defer` block. Since the `OutletInjector` doesn't store
      // any tokens itself, we point to the parent injector instead. See the
      // `OutletInjector.__ngOutletInjector` field for additional information.
      return parent.parentInjector;
    }
    return parent;
  }
  let tNode;
  let lView;
  if (injector instanceof NodeInjector) {
    tNode = getNodeInjectorTNode(injector);
    lView = getNodeInjectorLView(injector);
  } else if (injector instanceof NullInjector) {
    return null;
  } else if (injector instanceof ChainedInjector) {
    return injector.parentInjector;
  } else {
    throwError('getInjectorParent only support injectors of type R3Injector, NodeInjector, NullInjector');
  }
  const parentLocation = getParentInjectorLocation(tNode, lView);
  if (hasParentInjector(parentLocation)) {
    const parentInjectorIndex = getParentInjectorIndex(parentLocation);
    const parentLView = getParentInjectorView(parentLocation, lView);
    const parentTView = parentLView[TVIEW];
    const parentTNode = parentTView.data[parentInjectorIndex + 8 /* NodeInjectorOffset.TNODE */];
    return new NodeInjector(parentTNode, parentLView);
  } else {
    const chainedInjector = lView[INJECTOR];
    // Case where chainedInjector.injector is an OutletInjector and chainedInjector.injector.parent
    // is a NodeInjector.
    // todo(aleksanderbodurri): ideally nothing in packages/core should deal
    // directly with router concerns. Refactor this so that we can make the jump from
    // NodeInjector -> OutletInjector -> NodeInjector
    // without explicitly relying on types contracts from packages/router
    const injectorParent = chainedInjector.injector?.parent;
    if (injectorParent instanceof NodeInjector) {
      return injectorParent;
    }
  }
  return null;
}
/**
 * Gets the module injector of a NodeInjector.
 *
 * @param injector NodeInjector to get module injector of
 * @returns Injector representing module injector of the given NodeInjector
 */
function getModuleInjectorOfNodeInjector(injector) {
  let lView;
  if (injector instanceof NodeInjector) {
    lView = getNodeInjectorLView(injector);
  } else {
    throwError('getModuleInjectorOfNodeInjector must be called with a NodeInjector');
  }
  const inj = lView[INJECTOR];
  const moduleInjector = inj instanceof ChainedInjector ? inj.parentInjector : inj.parent;
  if (!moduleInjector) {
    throwError('NodeInjector must have some connection to the module injector tree');
  }
  return moduleInjector;
}

/**
 * This file introduces series of globally accessible debug tools
 * to allow for the Angular debugging story to function.
 *
 * To see this in action run the following command:
 *
 *   bazel run //packages/core/test/bundling/todo:devserver
 *
 *  Then load `localhost:5432` and start using the console tools.
 */
/**
 * This value reflects the property on the window where the dev
 * tools are patched (window.ng).
 * */
const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
const globalUtilsFunctions = {
  /**
   * Warning: functions that start with `ɵ` are considered *INTERNAL* and should not be relied upon
   * in application's code. The contract of those functions might be changed in any release and/or a
   * function can be removed completely.
   */
  'ɵgetDependenciesFromInjectable': getDependenciesFromInjectable,
  'ɵgetInjectorProviders': getInjectorProviders,
  'ɵgetInjectorResolutionPath': getInjectorResolutionPath,
  'ɵgetInjectorMetadata': getInjectorMetadata,
  'ɵsetProfiler': setProfiler,
  'getDirectiveMetadata': getDirectiveMetadata$1,
  'getComponent': getComponent,
  'getContext': getContext,
  'getListeners': getListeners,
  'getOwningComponent': getOwningComponent,
  'getHostElement': getHostElement,
  'getInjector': getInjector,
  'getRootComponents': getRootComponents,
  'getDirectives': getDirectives,
  'applyChanges': applyChanges,
  'isSignal': isSignal
};
let _published = false;
/**
 * Publishes a collection of default debug tools onto`window.ng`.
 *
 * These functions are available globally when Angular is in development
 * mode and are automatically stripped away from prod mode is on.
 */
function publishDefaultGlobalUtils$1() {
  if (!_published) {
    _published = true;
    if (typeof window !== 'undefined') {
      // Only configure the injector profiler when running in the browser.
      setupFrameworkInjectorProfiler();
    }
    for (const [methodName, method] of Object.entries(globalUtilsFunctions)) {
      publishGlobalUtil(methodName, method);
    }
  }
}
/**
 * Publishes the given function to `window.ng` so that it can be
 * used from the browser console when an application is not in production.
 */
function publishGlobalUtil(name, fn) {
  publishUtil(name, fn);
}
/**
 * Publishes the given function to `window.ng` from package other than @angular/core
 * So that it can be used from the browser console when an application is not in production.
 */
function publishExternalGlobalUtil(name, fn) {
  publishUtil(name, fn);
}
function publishUtil(name, fn) {
  if (typeof COMPILED === 'undefined' || !COMPILED) {
    // Note: we can't export `ng` when using closure enhanced optimization as:
    // - closure declares globals itself for minified names, which sometimes clobber our `ng` global
    // - we can't declare a closure extern as the namespace `ng` is already used within Google
    //   for typings for AngularJS (via `goog.provide('ng....')`).
    const w = _global;
    ngDevMode && assertDefined(fn, 'function not defined');
    w[GLOBAL_PUBLISH_EXPANDO_KEY] ??= {};
    w[GLOBAL_PUBLISH_EXPANDO_KEY][name] = fn;
  }
}

/**
 * Internal injection token that can used to access an instance of a Testability class.
 *
 * This token acts as a bridge between the core bootstrap code and the `Testability` class. This is
 * needed to ensure that there are no direct references to the `Testability` class, so it can be
 * tree-shaken away (if not referenced). For the environments/setups when the `Testability` class
 * should be available, this token is used to add a provider that references the `Testability`
 * class. Otherwise, only this token is retained in a bundle, but the `Testability` class is not.
 */
const TESTABILITY = /*#__PURE__*/new InjectionToken('');
/**
 * Internal injection token to retrieve Testability getter class instance.
 */
const TESTABILITY_GETTER = /*#__PURE__*/new InjectionToken('');
/**
 * The Testability service provides testing hooks that can be accessed from
 * the browser.
 *
 * Angular applications bootstrapped using an NgModule (via `@NgModule.bootstrap` field) will also
 * instantiate Testability by default (in both development and production modes).
 *
 * For applications bootstrapped using the `bootstrapApplication` function, Testability is not
 * included by default. You can include it into your applications by getting the list of necessary
 * providers using the `provideProtractorTestingSupport()` function and adding them into the
 * `options.providers` array. Example:
 *
 * ```typescript
 * import {provideProtractorTestingSupport} from '@angular/platform-browser';
 *
 * await bootstrapApplication(RootComponent, providers: [provideProtractorTestingSupport()]);
 * ```
 *
 * @publicApi
 */
let Testability = /*#__PURE__*/(() => {
  class Testability {
    _ngZone;
    registry;
    _isZoneStable = true;
    _callbacks = [];
    taskTrackingZone = null;
    constructor(_ngZone, registry, testabilityGetter) {
      this._ngZone = _ngZone;
      this.registry = registry;
      // If there was no Testability logic registered in the global scope
      // before, register the current testability getter as a global one.
      if (!_testabilityGetter) {
        setTestabilityGetter(testabilityGetter);
        testabilityGetter.addToWindow(registry);
      }
      this._watchAngularEvents();
      _ngZone.run(() => {
        this.taskTrackingZone = typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
      });
    }
    _watchAngularEvents() {
      this._ngZone.onUnstable.subscribe({
        next: () => {
          this._isZoneStable = false;
        }
      });
      this._ngZone.runOutsideAngular(() => {
        this._ngZone.onStable.subscribe({
          next: () => {
            NgZone.assertNotInAngularZone();
            queueMicrotask(() => {
              this._isZoneStable = true;
              this._runCallbacksIfReady();
            });
          }
        });
      });
    }
    /**
     * Whether an associated application is stable
     */
    isStable() {
      return this._isZoneStable && !this._ngZone.hasPendingMacrotasks;
    }
    _runCallbacksIfReady() {
      if (this.isStable()) {
        // Schedules the call backs in a new frame so that it is always async.
        queueMicrotask(() => {
          while (this._callbacks.length !== 0) {
            let cb = this._callbacks.pop();
            clearTimeout(cb.timeoutId);
            cb.doneCb();
          }
        });
      } else {
        // Still not stable, send updates.
        let pending = this.getPendingTasks();
        this._callbacks = this._callbacks.filter(cb => {
          if (cb.updateCb && cb.updateCb(pending)) {
            clearTimeout(cb.timeoutId);
            return false;
          }
          return true;
        });
      }
    }
    getPendingTasks() {
      if (!this.taskTrackingZone) {
        return [];
      }
      // Copy the tasks data so that we don't leak tasks.
      return this.taskTrackingZone.macroTasks.map(t => {
        return {
          source: t.source,
          // From TaskTrackingZone:
          // https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
          creationLocation: t.creationLocation,
          data: t.data
        };
      });
    }
    addCallback(cb, timeout, updateCb) {
      let timeoutId = -1;
      if (timeout && timeout > 0) {
        timeoutId = setTimeout(() => {
          this._callbacks = this._callbacks.filter(cb => cb.timeoutId !== timeoutId);
          cb();
        }, timeout);
      }
      this._callbacks.push({
        doneCb: cb,
        timeoutId: timeoutId,
        updateCb: updateCb
      });
    }
    /**
     * Wait for the application to be stable with a timeout. If the timeout is reached before that
     * happens, the callback receives a list of the macro tasks that were pending, otherwise null.
     *
     * @param doneCb The callback to invoke when Angular is stable or the timeout expires
     *    whichever comes first.
     * @param timeout Optional. The maximum time to wait for Angular to become stable. If not
     *    specified, whenStable() will wait forever.
     * @param updateCb Optional. If specified, this callback will be invoked whenever the set of
     *    pending macrotasks changes. If this callback returns true doneCb will not be invoked
     *    and no further updates will be issued.
     */
    whenStable(doneCb, timeout, updateCb) {
      if (updateCb && !this.taskTrackingZone) {
        throw new Error('Task tracking zone is required when passing an update callback to ' + 'whenStable(). Is "zone.js/plugins/task-tracking" loaded?');
      }
      this.addCallback(doneCb, timeout, updateCb);
      this._runCallbacksIfReady();
    }
    /**
     * Registers an application with a testability hook so that it can be tracked.
     * @param token token of application, root element
     *
     * @internal
     */
    registerApplication(token) {
      this.registry.registerApplication(token, this);
    }
    /**
     * Unregisters an application.
     * @param token token of application, root element
     *
     * @internal
     */
    unregisterApplication(token) {
      this.registry.unregisterApplication(token);
    }
    /**
     * Find providers by name
     * @param using The root element to search from
     * @param provider The name of binding variable
     * @param exactMatch Whether using exactMatch
     */
    findProviders(using, provider, exactMatch) {
      // TODO(juliemr): implement.
      return [];
    }
    static ɵfac = function Testability_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Testability)(ɵɵinject(NgZone), ɵɵinject(TestabilityRegistry), ɵɵinject(TESTABILITY_GETTER));
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: Testability,
      factory: Testability.ɵfac
    }))();
  }
  return Testability;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Testability, [{
    type: Injectable
  }], () => [{
    type: NgZone
  }, {
    type: TestabilityRegistry
  }, {
    type: undefined,
    decorators: [{
      type: Inject,
      args: [TESTABILITY_GETTER]
    }]
  }], null);
})();
/**
 * A global registry of {@link Testability} instances for specific elements.
 * @publicApi
 */
let TestabilityRegistry = /*#__PURE__*/(() => {
  class TestabilityRegistry {
    /** @internal */
    _applications = (() => new Map())();
    /**
     * Registers an application with a testability hook so that it can be tracked
     * @param token token of application, root element
     * @param testability Testability hook
     */
    registerApplication(token, testability) {
      this._applications.set(token, testability);
    }
    /**
     * Unregisters an application.
     * @param token token of application, root element
     */
    unregisterApplication(token) {
      this._applications.delete(token);
    }
    /**
     * Unregisters all applications
     */
    unregisterAllApplications() {
      this._applications.clear();
    }
    /**
     * Get a testability hook associated with the application
     * @param elem root element
     */
    getTestability(elem) {
      return this._applications.get(elem) || null;
    }
    /**
     * Get all registered testabilities
     */
    getAllTestabilities() {
      return Array.from(this._applications.values());
    }
    /**
     * Get all registered applications(root elements)
     */
    getAllRootElements() {
      return Array.from(this._applications.keys());
    }
    /**
     * Find testability of a node in the Tree
     * @param elem node
     * @param findInAncestors whether finding testability in ancestors if testability was not found in
     * current node
     */
    findTestabilityInTree(elem, findInAncestors = true) {
      return _testabilityGetter?.findTestabilityInTree(this, elem, findInAncestors) ?? null;
    }
    static ɵfac = function TestabilityRegistry_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || TestabilityRegistry)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: TestabilityRegistry,
      factory: TestabilityRegistry.ɵfac,
      providedIn: 'platform'
    }))();
  }
  return TestabilityRegistry;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(TestabilityRegistry, [{
    type: Injectable,
    args: [{
      providedIn: 'platform'
    }]
  }], null, null);
})();
/**
 * Set the {@link GetTestability} implementation used by the Angular testing framework.
 * @publicApi
 */
function setTestabilityGetter(getter) {
  _testabilityGetter = getter;
}
let _testabilityGetter;

/**
 * Determine if the argument is shaped like a Promise
 */
function isPromise(obj) {
  // allow any Promise/A+ compliant thenable.
  // It's up to the caller to ensure that obj.then conforms to the spec
  return !!obj && typeof obj.then === 'function';
}
/**
 * Determine if the argument is a Subscribable
 */
function isSubscribable(obj) {
  return !!obj && typeof obj.subscribe === 'function';
}

/**
 * A DI token that you can use to provide
 * one or more initialization functions.
 *
 * The provided functions are injected at application startup and executed during
 * app initialization. If any of these functions returns a Promise or an Observable, initialization
 * does not complete until the Promise is resolved or the Observable is completed.
 *
 * You can, for example, create a factory function that loads language data
 * or an external configuration, and provide that function to the `APP_INITIALIZER` token.
 * The function is executed during the application bootstrap process,
 * and the needed data is available on startup.
 *
 * Note that the provided initializer is run in the injection context.
 *
 * @deprecated from v19.0.0, use provideAppInitializer instead
 *
 * @see {@link ApplicationInitStatus}
 * @see {@link provideAppInitializer}
 *
 * @usageNotes
 *
 * The following example illustrates how to configure a multi-provider using `APP_INITIALIZER` token
 * and a function returning a promise.
 * ### Example with NgModule-based application
 * ```
 *  function initializeApp(): Promise<any> {
 *    const http = inject(HttpClient);
 *    return firstValueFrom(
 *      http
 *        .get("https://someUrl.com/api/user")
 *        .pipe(tap(user => { ... }))
 *    );
 *  }
 *
 *  @NgModule({
 *   imports: [BrowserModule],
 *   declarations: [AppComponent],
 *   bootstrap: [AppComponent],
 *   providers: [{
 *     provide: APP_INITIALIZER,
 *     useValue: initializeApp,
 *     multi: true,
 *    }]
 *   })
 *  export class AppModule {}
 * ```
 *
 * ### Example with standalone application
 * ```
 * function initializeApp() {
 *   const http = inject(HttpClient);
 *   return firstValueFrom(
 *     http
 *       .get("https://someUrl.com/api/user")
 *       .pipe(tap(user => { ... }))
 *   );
 * }
 *
 * bootstrapApplication(App, {
 *   providers: [
 *     provideHttpClient(),
 *     {
 *       provide: APP_INITIALIZER,
 *       useValue: initializeApp,
 *       multi: true,
 *     },
 *   ],
 * });

 * ```
 *
 *
 * It's also possible to configure a multi-provider using `APP_INITIALIZER` token and a function
 * returning an observable, see an example below. Note: the `HttpClient` in this example is used for
 * demo purposes to illustrate how the factory function can work with other providers available
 * through DI.
 *
 * ### Example with NgModule-based application
 * ```
 * function initializeApp() {
 *   const http = inject(HttpClient);
 *   return firstValueFrom(
 *     http
 *       .get("https://someUrl.com/api/user")
 *       .pipe(tap(user => { ... }))
 *   );
 * }
 *
 * @NgModule({
 *   imports: [BrowserModule, HttpClientModule],
 *   declarations: [AppComponent],
 *   bootstrap: [AppComponent],
 *   providers: [{
 *     provide: APP_INITIALIZER,
 *     useValue: initializeApp,
 *     multi: true,
 *   }]
 * })
 * export class AppModule {}
 * ```
 *
 * ### Example with standalone application
 * ```
 * function initializeApp() {
 *   const http = inject(HttpClient);
 *   return firstValueFrom(
 *     http
 *       .get("https://someUrl.com/api/user")
 *       .pipe(tap(user => { ... }))
 *   );
 * }
 *
 * bootstrapApplication(App, {
 *   providers: [
 *     provideHttpClient(),
 *     {
 *       provide: APP_INITIALIZER,
 *       useValue: initializeApp,
 *       multi: true,
 *     },
 *   ],
 * });
 * ```
 *
 * @publicApi
 */
const APP_INITIALIZER = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Application Initializer' : '');
/**
 * @description
 * The provided function is injected at application startup and executed during
 * app initialization. If the function returns a Promise or an Observable, initialization
 * does not complete until the Promise is resolved or the Observable is completed.
 *
 * You can, for example, create a function that loads language data
 * or an external configuration, and provide that function using `provideAppInitializer()`.
 * The function is executed during the application bootstrap process,
 * and the needed data is available on startup.
 *
 * Note that the provided initializer is run in the injection context.
 *
 * Previously, this was achieved using the `APP_INITIALIZER` token which is now deprecated.
 *
 * @see {@link APP_INITIALIZER}
 *
 * @usageNotes
 * The following example illustrates how to configure an initialization function using
 * `provideAppInitializer()`
 * ```
 * bootstrapApplication(App, {
 *   providers: [
 *     provideAppInitializer(() => {
 *       const http = inject(HttpClient);
 *       return firstValueFrom(
 *         http
 *           .get("https://someUrl.com/api/user")
 *           .pipe(tap(user => { ... }))
 *       );
 *     }),
 *     provideHttpClient(),
 *   ],
 * });
 * ```
 *
 * @publicApi
 */
function provideAppInitializer(initializerFn) {
  return makeEnvironmentProviders([{
    provide: APP_INITIALIZER,
    multi: true,
    useValue: initializerFn
  }]);
}
/**
 * A class that reflects the state of running {@link APP_INITIALIZER} functions.
 *
 * @publicApi
 */
let ApplicationInitStatus = /*#__PURE__*/(() => {
  class ApplicationInitStatus {
    // Using non null assertion, these fields are defined below
    // within the `new Promise` callback (synchronously).
    resolve;
    reject;
    initialized = false;
    done = false;
    donePromise = (() => new Promise((res, rej) => {
      this.resolve = res;
      this.reject = rej;
    }))();
    appInits = (() => inject(APP_INITIALIZER, {
      optional: true
    }) ?? [])();
    injector = (() => inject(Injector))();
    constructor() {
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) {
        throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_INITIALIZER` token value ' + `(expected an array, but got ${typeof this.appInits}). ` + 'Please check that the `APP_INITIALIZER` token is configured as a ' + '`multi: true` provider.');
      }
    }
    /** @internal */
    runInitializers() {
      if (this.initialized) {
        return;
      }
      const asyncInitPromises = [];
      for (const appInits of this.appInits) {
        const initResult = runInInjectionContext(this.injector, appInits);
        if (isPromise(initResult)) {
          asyncInitPromises.push(initResult);
        } else if (isSubscribable(initResult)) {
          const observableAsPromise = new Promise((resolve, reject) => {
            initResult.subscribe({
              complete: resolve,
              error: reject
            });
          });
          asyncInitPromises.push(observableAsPromise);
        }
      }
      const complete = () => {
        // @ts-expect-error overwriting a readonly
        this.done = true;
        this.resolve();
      };
      Promise.all(asyncInitPromises).then(() => {
        complete();
      }).catch(e => {
        this.reject(e);
      });
      if (asyncInitPromises.length === 0) {
        complete();
      }
      this.initialized = true;
    }
    static ɵfac = function ApplicationInitStatus_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ApplicationInitStatus)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: ApplicationInitStatus,
      factory: ApplicationInitStatus.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ApplicationInitStatus;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationInitStatus, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], () => [], null);
})();

/**
 * A scheduler which manages the execution of effects.
 */
let EffectScheduler = /*#__PURE__*/(() => {
  class EffectScheduler {
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: EffectScheduler,
      providedIn: 'root',
      factory: () => new ZoneAwareEffectScheduler()
    }))();
  }
  return EffectScheduler;
})();
/**
 * A wrapper around `ZoneAwareQueueingScheduler` that schedules flushing via the microtask queue
 * when.
 */
class ZoneAwareEffectScheduler {
  queuedEffectCount = 0;
  queues = /*#__PURE__*/(() => new Map())();
  schedule(handle) {
    this.enqueue(handle);
  }
  enqueue(handle) {
    const zone = handle.zone;
    if (!this.queues.has(zone)) {
      this.queues.set(zone, new Set());
    }
    const queue = this.queues.get(zone);
    if (queue.has(handle)) {
      return;
    }
    this.queuedEffectCount++;
    queue.add(handle);
  }
  /**
   * Run all scheduled effects.
   *
   * Execution order of effects within the same zone is guaranteed to be FIFO, but there is no
   * ordering guarantee between effects scheduled in different zones.
   */
  flush() {
    while (this.queuedEffectCount > 0) {
      for (const [zone, queue] of this.queues) {
        // `zone` here must be defined.
        if (zone === null) {
          this.flushQueue(queue);
        } else {
          zone.run(() => this.flushQueue(queue));
        }
      }
    }
  }
  flushQueue(queue) {
    for (const handle of queue) {
      queue.delete(handle);
      this.queuedEffectCount--;
      // TODO: what happens if this throws an error?
      handle.run();
    }
  }
}

/**
 * A DI token that provides a set of callbacks to
 * be called for every component that is bootstrapped.
 *
 * Each callback must take a `ComponentRef` instance and return nothing.
 *
 * `(componentRef: ComponentRef) => void`
 *
 * @publicApi
 */
const APP_BOOTSTRAP_LISTENER = /*#__PURE__*/new InjectionToken(ngDevMode ? 'appBootstrapListener' : '');
function publishDefaultGlobalUtils() {
  ngDevMode && publishDefaultGlobalUtils$1();
}
/**
 * Sets the error for an invalid write to a signal to be an Angular `RuntimeError`.
 */
function publishSignalConfiguration() {
  (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setThrowInvalidWriteToSignalError)(() => {
    throw new RuntimeError(600 /* RuntimeErrorCode.SIGNAL_WRITE_FROM_ILLEGAL_CONTEXT */, ngDevMode && 'Writing to signals is not allowed in a `computed`.');
  });
}
function isBoundToModule(cf) {
  return cf.isBoundToModule;
}
/**
 * A token for third-party components that can register themselves with NgProbe.
 *
 * @deprecated
 * @publicApi
 */
class NgProbeToken {
  name;
  token;
  constructor(name, token) {
    this.name = name;
    this.token = token;
  }
}
/** Maximum number of times ApplicationRef will refresh all attached views in a single tick. */
const MAXIMUM_REFRESH_RERUNS = 10;
function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
  try {
    const result = callback();
    if (isPromise(result)) {
      return result.catch(e => {
        ngZone.runOutsideAngular(() => errorHandler.handleError(e));
        // rethrow as the exception handler might not do it
        throw e;
      });
    }
    return result;
  } catch (e) {
    ngZone.runOutsideAngular(() => errorHandler.handleError(e));
    // rethrow as the exception handler might not do it
    throw e;
  }
}
function optionsReducer(dst, objs) {
  if (Array.isArray(objs)) {
    return objs.reduce(optionsReducer, dst);
  }
  return {
    ...dst,
    ...objs
  };
}
/**
 * A reference to an Angular application running on a page.
 *
 * @usageNotes
 * {@a is-stable-examples}
 * ### isStable examples and caveats
 *
 * Note two important points about `isStable`, demonstrated in the examples below:
 * - the application will never be stable if you start any kind
 * of recurrent asynchronous task when the application starts
 * (for example for a polling process, started with a `setInterval`, a `setTimeout`
 * or using RxJS operators like `interval`);
 * - the `isStable` Observable runs outside of the Angular zone.
 *
 * Let's imagine that you start a recurrent task
 * (here incrementing a counter, using RxJS `interval`),
 * and at the same time subscribe to `isStable`.
 *
 * ```
 * constructor(appRef: ApplicationRef) {
 *   appRef.isStable.pipe(
 *      filter(stable => stable)
 *   ).subscribe(() => console.log('App is stable now');
 *   interval(1000).subscribe(counter => console.log(counter));
 * }
 * ```
 * In this example, `isStable` will never emit `true`,
 * and the trace "App is stable now" will never get logged.
 *
 * If you want to execute something when the app is stable,
 * you have to wait for the application to be stable
 * before starting your polling process.
 *
 * ```
 * constructor(appRef: ApplicationRef) {
 *   appRef.isStable.pipe(
 *     first(stable => stable),
 *     tap(stable => console.log('App is stable now')),
 *     switchMap(() => interval(1000))
 *   ).subscribe(counter => console.log(counter));
 * }
 * ```
 * In this example, the trace "App is stable now" will be logged
 * and then the counter starts incrementing every second.
 *
 * Note also that this Observable runs outside of the Angular zone,
 * which means that the code in the subscription
 * to this Observable will not trigger the change detection.
 *
 * Let's imagine that instead of logging the counter value,
 * you update a field of your component
 * and display it in its template.
 *
 * ```
 * constructor(appRef: ApplicationRef) {
 *   appRef.isStable.pipe(
 *     first(stable => stable),
 *     switchMap(() => interval(1000))
 *   ).subscribe(counter => this.value = counter);
 * }
 * ```
 * As the `isStable` Observable runs outside the zone,
 * the `value` field will be updated properly,
 * but the template will not be refreshed!
 *
 * You'll have to manually trigger the change detection to update the template.
 *
 * ```
 * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
 *   appRef.isStable.pipe(
 *     first(stable => stable),
 *     switchMap(() => interval(1000))
 *   ).subscribe(counter => {
 *     this.value = counter;
 *     cd.detectChanges();
 *   });
 * }
 * ```
 *
 * Or make the subscription callback run inside the zone.
 *
 * ```
 * constructor(appRef: ApplicationRef, zone: NgZone) {
 *   appRef.isStable.pipe(
 *     first(stable => stable),
 *     switchMap(() => interval(1000))
 *   ).subscribe(counter => zone.run(() => this.value = counter));
 * }
 * ```
 *
 * @publicApi
 */
let ApplicationRef = /*#__PURE__*/(() => {
  class ApplicationRef {
    /** @internal */
    _bootstrapListeners = [];
    /** @internal */
    _runningTick = false;
    _destroyed = false;
    _destroyListeners = [];
    /** @internal */
    _views = [];
    internalErrorHandler = (() => inject(INTERNAL_APPLICATION_ERROR_HANDLER))();
    afterRenderManager = (() => inject(AfterRenderManager))();
    zonelessEnabled = (() => inject(ZONELESS_ENABLED))();
    rootEffectScheduler = (() => inject(EffectScheduler))();
    /**
     * Current dirty state of the application across a number of dimensions (views, afterRender hooks,
     * etc).
     *
     * A flag set here means that `tick()` will attempt to resolve the dirtiness when executed.
     *
     * @internal
     */
    dirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
    /**
     * Like `dirtyFlags` but don't cause `tick()` to loop.
     *
     * @internal
     */
    deferredDirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
    // Needed for ComponentFixture temporarily during migration of autoDetect behavior
    // Eventually the hostView of the fixture should just attach to ApplicationRef.
    externalTestViews = (() => new Set())();
    /** @internal */
    afterTick = (() => new rxjs__WEBPACK_IMPORTED_MODULE_3__.Subject())();
    /** @internal */
    get allViews() {
      return [...this.externalTestViews.keys(), ...this._views];
    }
    /**
     * Indicates whether this instance was destroyed.
     */
    get destroyed() {
      return this._destroyed;
    }
    /**
     * Get a list of component types registered to this application.
     * This list is populated even before the component is created.
     */
    componentTypes = [];
    /**
     * Get a list of components registered to this application.
     */
    components = [];
    /**
     * Returns an Observable that indicates when the application is stable or unstable.
     */
    isStable = (() => inject(PendingTasksInternal).hasPendingTasks.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_6__.map)(pending => !pending)))();
    /**
     * @returns A promise that resolves when the application becomes stable
     */
    whenStable() {
      let subscription;
      return new Promise(resolve => {
        subscription = this.isStable.subscribe({
          next: stable => {
            if (stable) {
              resolve();
            }
          }
        });
      }).finally(() => {
        subscription.unsubscribe();
      });
    }
    _injector = (() => inject(EnvironmentInjector))();
    /**
     * The `EnvironmentInjector` used to create this application.
     */
    get injector() {
      return this._injector;
    }
    /**
     * Bootstrap a component onto the element identified by its selector or, optionally, to a
     * specified element.
     *
     * @usageNotes
     * ### Bootstrap process
     *
     * When bootstrapping a component, Angular mounts it onto a target DOM element
     * and kicks off automatic change detection. The target DOM element can be
     * provided using the `rootSelectorOrNode` argument.
     *
     * If the target DOM element is not provided, Angular tries to find one on a page
     * using the `selector` of the component that is being bootstrapped
     * (first matched element is used).
     *
     * ### Example
     *
     * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`,
     * but it requires us to know the component while writing the application code.
     *
     * Imagine a situation where we have to wait for an API call to decide about the component to
     * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to
     * dynamically bootstrap a component.
     *
     * {@example core/ts/platform/platform.ts region='componentSelector'}
     *
     * Optionally, a component can be mounted onto a DOM element that does not match the
     * selector of the bootstrapped component.
     *
     * In the following example, we are providing a CSS selector to match the target element.
     *
     * {@example core/ts/platform/platform.ts region='cssSelector'}
     *
     * While in this example, we are providing reference to a DOM node.
     *
     * {@example core/ts/platform/platform.ts region='domNode'}
     */
    bootstrap(componentOrFactory, rootSelectorOrNode) {
      (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
      const isComponentFactory = componentOrFactory instanceof ComponentFactory$1;
      const initStatus = this._injector.get(ApplicationInitStatus);
      if (!initStatus.done) {
        const standalone = !isComponentFactory && isStandalone(componentOrFactory);
        const errorMessage = (typeof ngDevMode === 'undefined' || ngDevMode) && 'Cannot bootstrap as there are still asynchronous initializers running.' + (standalone ? '' : ' Bootstrap components in the `ngDoBootstrap` method of the root module.');
        throw new RuntimeError(405 /* RuntimeErrorCode.ASYNC_INITIALIZERS_STILL_RUNNING */, errorMessage);
      }
      let componentFactory;
      if (isComponentFactory) {
        componentFactory = componentOrFactory;
      } else {
        const resolver = this._injector.get(ComponentFactoryResolver$1);
        componentFactory = resolver.resolveComponentFactory(componentOrFactory);
      }
      this.componentTypes.push(componentFactory.componentType);
      // Create a factory associated with the current module if it's not bound to some other
      const ngModule = isBoundToModule(componentFactory) ? undefined : this._injector.get(NgModuleRef$1);
      const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
      const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
      const nativeElement = compRef.location.nativeElement;
      const testability = compRef.injector.get(TESTABILITY, null);
      testability?.registerApplication(nativeElement);
      compRef.onDestroy(() => {
        this.detachView(compRef.hostView);
        remove(this.components, compRef);
        testability?.unregisterApplication(nativeElement);
      });
      this._loadComponent(compRef);
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        const _console = this._injector.get(Console);
        _console.log(`Angular is running in development mode.`);
      }
      return compRef;
    }
    /**
     * Invoke this method to explicitly process change detection and its side-effects.
     *
     * In development mode, `tick()` also performs a second change detection cycle to ensure that no
     * further changes are detected. If additional changes are picked up during this second cycle,
     * bindings in the app have side-effects that cannot be resolved in a single change detection
     * pass.
     * In this case, Angular throws an error, since an Angular application can only have one change
     * detection pass during which all change detection must complete.
     */
    tick() {
      if (!this.zonelessEnabled) {
        this.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
      }
      this._tick();
    }
    /** @internal */
    _tick() {
      (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
      if (this._runningTick) {
        throw new RuntimeError(101 /* RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK */, ngDevMode && 'ApplicationRef.tick is called recursively');
      }
      const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
      try {
        this._runningTick = true;
        this.synchronize();
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          for (let view of this.allViews) {
            view.checkNoChanges();
          }
        }
      } catch (e) {
        // Attention: Don't rethrow as it could cancel subscriptions to Observables!
        this.internalErrorHandler(e);
      } finally {
        this._runningTick = false;
        (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
        this.afterTick.next();
      }
    }
    /**
     * Performs the core work of synchronizing the application state with the UI, resolving any
     * pending dirtiness (potentially in a loop).
     */
    synchronize() {
      let rendererFactory = null;
      if (!this._injector.destroyed) {
        rendererFactory = this._injector.get(RendererFactory2, null, {
          optional: true
        });
      }
      // When beginning synchronization, all deferred dirtiness becomes active dirtiness.
      this.dirtyFlags |= this.deferredDirtyFlags;
      this.deferredDirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
      let runs = 0;
      while (this.dirtyFlags !== 0 /* ApplicationRefDirtyFlags.None */ && runs++ < MAXIMUM_REFRESH_RERUNS) {
        this.synchronizeOnce(rendererFactory);
      }
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && runs >= MAXIMUM_REFRESH_RERUNS) {
        throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode && 'Infinite change detection while refreshing application views. ' + 'Ensure views are not calling `markForCheck` on every template execution or ' + 'that afterRender hooks always mark views for check.');
      }
    }
    /**
     * Perform a single synchronization pass.
     */
    synchronizeOnce(rendererFactory) {
      // If we happened to loop, deferred dirtiness can be processed as active dirtiness again.
      this.dirtyFlags |= this.deferredDirtyFlags;
      this.deferredDirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
      // First, process any dirty root effects.
      if (this.dirtyFlags & 16 /* ApplicationRefDirtyFlags.RootEffects */) {
        this.dirtyFlags &= ~16 /* ApplicationRefDirtyFlags.RootEffects */;
        this.rootEffectScheduler.flush();
      }
      // First check dirty views, if there are any.
      if (this.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
        // Change detection on views starts in targeted mode (only check components if they're
        // marked as dirty) unless global checking is specifically requested via APIs like
        // `ApplicationRef.tick()` and the `NgZone` integration.
        const useGlobalCheck = Boolean(this.dirtyFlags & 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */);
        // Clear the view-related dirty flags.
        this.dirtyFlags &= ~7 /* ApplicationRefDirtyFlags.ViewTreeAny */;
        // Set the AfterRender bit, as we're checking views and will need to run afterRender hooks.
        this.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
        // Check all potentially dirty views.
        for (let {
          _lView,
          notifyErrorHandler
        } of this.allViews) {
          detectChangesInViewIfRequired(_lView, notifyErrorHandler, useGlobalCheck, this.zonelessEnabled);
        }
        // If `markForCheck()` was called during view checking, it will have set the `ViewTreeCheck`
        // flag. We clear the flag here because, for backwards compatibility, `markForCheck()`
        // during view checking doesn't cause the view to be re-checked.
        this.dirtyFlags &= ~4 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
        // Check if any views are still dirty after checking and we need to loop back.
        this.syncDirtyFlagsWithViews();
        if (this.dirtyFlags & (7 /* ApplicationRefDirtyFlags.ViewTreeAny */ | 16 /* ApplicationRefDirtyFlags.RootEffects */)) {
          // If any views or effects are still dirty after checking, loop back before running render
          // hooks.
          return;
        }
      } else {
        // If we skipped refreshing views above, there might still be unflushed animations
        // because we never called `detectChangesInternal` on the views.
        rendererFactory?.begin?.();
        rendererFactory?.end?.();
      }
      // Even if there were no dirty views, afterRender hooks might still be dirty.
      if (this.dirtyFlags & 8 /* ApplicationRefDirtyFlags.AfterRender */) {
        this.dirtyFlags &= ~8 /* ApplicationRefDirtyFlags.AfterRender */;
        this.afterRenderManager.execute();
        // afterRender hooks might influence dirty flags.
      }
      this.syncDirtyFlagsWithViews();
    }
    /**
     * Checks `allViews` for views which require refresh/traversal, and updates `dirtyFlags`
     * accordingly, with two potential behaviors:
     *
     * 1. If any of our views require updating, then this adds the `ViewTreeTraversal` dirty flag.
     *    This _should_ be a no-op, since the scheduler should've added the flag at the same time the
     *    view was marked as needing updating.
     *
     *    TODO(alxhub): figure out if this behavior is still needed for edge cases.
     *
     * 2. If none of our views require updating, then clear the view-related `dirtyFlag`s. This
     *    happens when the scheduler is notified of a view becoming dirty, but the view itself isn't
     *    reachable through traversal from our roots (e.g. it's detached from the CD tree).
     */
    syncDirtyFlagsWithViews() {
      if (this.allViews.some(({
        _lView
      }) => requiresRefreshOrTraversal(_lView))) {
        // If after running all afterRender callbacks new views are dirty, ensure we loop back.
        this.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
        return;
      } else {
        // Even though this flag may be set, none of _our_ views require traversal, and so the
        // `ApplicationRef` doesn't require any repeated checking.
        this.dirtyFlags &= ~7 /* ApplicationRefDirtyFlags.ViewTreeAny */;
      }
    }
    /**
     * Attaches a view so that it will be dirty checked.
     * The view will be automatically detached when it is destroyed.
     * This will throw if the view is already attached to a ViewContainer.
     */
    attachView(viewRef) {
      (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
      const view = viewRef;
      this._views.push(view);
      view.attachToAppRef(this);
    }
    /**
     * Detaches a view from dirty checking again.
     */
    detachView(viewRef) {
      (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
      const view = viewRef;
      remove(this._views, view);
      view.detachFromAppRef();
    }
    _loadComponent(componentRef) {
      this.attachView(componentRef.hostView);
      this.tick();
      this.components.push(componentRef);
      // Get the listeners lazily to prevent DI cycles.
      const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []);
      if (ngDevMode && !Array.isArray(listeners)) {
        throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_BOOTSTRAP_LISTENER` token value ' + `(expected an array, but got ${typeof listeners}). ` + 'Please check that the `APP_BOOTSTRAP_LISTENER` token is configured as a ' + '`multi: true` provider.');
      }
      [...this._bootstrapListeners, ...listeners].forEach(listener => listener(componentRef));
    }
    /** @internal */
    ngOnDestroy() {
      if (this._destroyed) return;
      try {
        // Call all the lifecycle hooks.
        this._destroyListeners.forEach(listener => listener());
        // Destroy all registered views.
        this._views.slice().forEach(view => view.destroy());
      } finally {
        // Indicate that this instance is destroyed.
        this._destroyed = true;
        // Release all references.
        this._views = [];
        this._bootstrapListeners = [];
        this._destroyListeners = [];
      }
    }
    /**
     * Registers a listener to be called when an instance is destroyed.
     *
     * @param callback A callback function to add as a listener.
     * @returns A function which unregisters a listener.
     */
    onDestroy(callback) {
      (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
      this._destroyListeners.push(callback);
      return () => remove(this._destroyListeners, callback);
    }
    /**
     * Destroys an Angular application represented by this `ApplicationRef`. Calling this function
     * will destroy the associated environment injectors as well as all the bootstrapped components
     * with their views.
     */
    destroy() {
      if (this._destroyed) {
        throw new RuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, ngDevMode && 'This instance of the `ApplicationRef` has already been destroyed.');
      }
      const injector = this._injector;
      // Check that this injector instance supports destroy operation.
      if (injector.destroy && !injector.destroyed) {
        // Destroying an underlying injector will trigger the `ngOnDestroy` lifecycle
        // hook, which invokes the remaining cleanup actions.
        injector.destroy();
      }
    }
    /**
     * Returns the number of attached views.
     */
    get viewCount() {
      return this._views.length;
    }
    warnIfDestroyed() {
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && this._destroyed) {
        console.warn(formatRuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, 'This instance of the `ApplicationRef` has already been destroyed.'));
      }
    }
    static ɵfac = function ApplicationRef_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ApplicationRef)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: ApplicationRef,
      factory: ApplicationRef.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ApplicationRef;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationRef, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], null, null);
})();
function remove(list, el) {
  const index = list.indexOf(el);
  if (index > -1) {
    list.splice(index, 1);
  }
}
let whenStableStore;
/**
 * Returns a Promise that resolves when the application becomes stable after this method is called
 * the first time.
 */
function whenStable(applicationRef) {
  whenStableStore ??= new WeakMap();
  const cachedWhenStable = whenStableStore.get(applicationRef);
  if (cachedWhenStable) {
    return cachedWhenStable;
  }
  const whenStablePromise = applicationRef.isStable.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.first)(isStable => isStable)).toPromise().then(() => void 0);
  whenStableStore.set(applicationRef, whenStablePromise);
  // Be a good citizen and clean the store `onDestroy` even though we are using `WeakMap`.
  applicationRef.onDestroy(() => whenStableStore?.delete(applicationRef));
  return whenStablePromise;
}
function detectChangesInViewIfRequired(lView, notifyErrorHandler, isFirstPass, zonelessEnabled) {
  // When re-checking, only check views which actually need it.
  if (!isFirstPass && !requiresRefreshOrTraversal(lView)) {
    return;
  }
  const mode = isFirstPass && !zonelessEnabled ?
  // The first pass is always in Global mode, which includes `CheckAlways` views.
  0 /* ChangeDetectionMode.Global */ :
  // Only refresh views with the `RefreshView` flag or views is a changed signal
  1 /* ChangeDetectionMode.Targeted */;
  detectChangesInternal(lView, notifyErrorHandler, mode);
}

/**
 * Find a node in front of which `currentTNode` should be inserted (takes i18n into account).
 *
 * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
 * takes `TNode.insertBeforeIndex` into account.
 *
 * @param parentTNode parent `TNode`
 * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
 * @param lView current `LView`
 */
function getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView) {
  const tNodeInsertBeforeIndex = currentTNode.insertBeforeIndex;
  const insertBeforeIndex = Array.isArray(tNodeInsertBeforeIndex) ? tNodeInsertBeforeIndex[0] : tNodeInsertBeforeIndex;
  if (insertBeforeIndex === null) {
    return getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView);
  } else {
    ngDevMode && assertIndexInRange(lView, insertBeforeIndex);
    return unwrapRNode(lView[insertBeforeIndex]);
  }
}
/**
 * Process `TNode.insertBeforeIndex` by adding i18n text nodes.
 *
 * See `TNode.insertBeforeIndex`
 */
function processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRElement) {
  const tNodeInsertBeforeIndex = childTNode.insertBeforeIndex;
  if (Array.isArray(tNodeInsertBeforeIndex)) {
    // An array indicates that there are i18n nodes that need to be added as children of this
    // `childRNode`. These i18n nodes were created before this `childRNode` was available and so
    // only now can be added. The first element of the array is the normal index where we should
    // insert the `childRNode`. Additional elements are the extra nodes to be added as children of
    // `childRNode`.
    ngDevMode && assertDomNode(childRNode);
    let i18nParent = childRNode;
    let anchorRNode = null;
    if (!(childTNode.type & 3 /* TNodeType.AnyRNode */)) {
      anchorRNode = i18nParent;
      i18nParent = parentRElement;
    }
    if (i18nParent !== null && childTNode.componentOffset === -1) {
      for (let i = 1; i < tNodeInsertBeforeIndex.length; i++) {
        // No need to `unwrapRNode` because all of the indexes point to i18n text nodes.
        // see `assertDomNode` below.
        const i18nChild = lView[tNodeInsertBeforeIndex[i]];
        nativeInsertBefore(renderer, i18nParent, i18nChild, anchorRNode, false);
      }
    }
  }
}

/**
 * Add `tNode` to `previousTNodes` list and update relevant `TNode`s in `previousTNodes` list
 * `tNode.insertBeforeIndex`.
 *
 * Things to keep in mind:
 * 1. All i18n text nodes are encoded as `TNodeType.Element` and are created eagerly by the
 *    `ɵɵi18nStart` instruction.
 * 2. All `TNodeType.Placeholder` `TNodes` are elements which will be created later by
 *    `ɵɵelementStart` instruction.
 * 3. `ɵɵelementStart` instruction will create `TNode`s in the ascending `TNode.index` order. (So a
 *    smaller index `TNode` is guaranteed to be created before a larger one)
 *
 * We use the above three invariants to determine `TNode.insertBeforeIndex`.
 *
 * In an ideal world `TNode.insertBeforeIndex` would always be `TNode.next.index`. However,
 * this will not work because `TNode.next.index` may be larger than `TNode.index` which means that
 * the next node is not yet created and therefore we can't insert in front of it.
 *
 * Rule1: `TNode.insertBeforeIndex = null` if `TNode.next === null` (Initial condition, as we don't
 *        know if there will be further `TNode`s inserted after.)
 * Rule2: If `previousTNode` is created after the `tNode` being inserted, then
 *        `previousTNode.insertBeforeNode = tNode.index` (So when a new `tNode` is added we check
 *        previous to see if we can update its `insertBeforeTNode`)
 *
 * See `TNode.insertBeforeIndex` for more context.
 *
 * @param previousTNodes A list of previous TNodes so that we can easily traverse `TNode`s in
 *     reverse order. (If `TNode` would have `previous` this would not be necessary.)
 * @param newTNode A TNode to add to the `previousTNodes` list.
 */
function addTNodeAndUpdateInsertBeforeIndex(previousTNodes, newTNode) {
  // Start with Rule1
  ngDevMode && assertEqual(newTNode.insertBeforeIndex, null, 'We expect that insertBeforeIndex is not set');
  previousTNodes.push(newTNode);
  if (previousTNodes.length > 1) {
    for (let i = previousTNodes.length - 2; i >= 0; i--) {
      const existingTNode = previousTNodes[i];
      // Text nodes are created eagerly and so they don't need their `indexBeforeIndex` updated.
      // It is safe to ignore them.
      if (!isI18nText(existingTNode)) {
        if (isNewTNodeCreatedBefore(existingTNode, newTNode) && getInsertBeforeIndex(existingTNode) === null) {
          // If it was created before us in time, (and it does not yet have `insertBeforeIndex`)
          // then add the `insertBeforeIndex`.
          setInsertBeforeIndex(existingTNode, newTNode.index);
        }
      }
    }
  }
}
function isI18nText(tNode) {
  return !(tNode.type & 64 /* TNodeType.Placeholder */);
}
function isNewTNodeCreatedBefore(existingTNode, newTNode) {
  return isI18nText(newTNode) || existingTNode.index > newTNode.index;
}
function getInsertBeforeIndex(tNode) {
  const index = tNode.insertBeforeIndex;
  return Array.isArray(index) ? index[0] : index;
}
function setInsertBeforeIndex(tNode, value) {
  const index = tNode.insertBeforeIndex;
  if (Array.isArray(index)) {
    // Array is stored if we have to insert child nodes. See `TNode.insertBeforeIndex`
    index[0] = value;
  } else {
    setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
    tNode.insertBeforeIndex = value;
  }
}

/**
 * Retrieve `TIcu` at a given `index`.
 *
 * The `TIcu` can be stored either directly (if it is nested ICU) OR
 * it is stored inside tho `TIcuContainer` if it is top level ICU.
 *
 * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
 * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
 * expressed (parent ICU may have selected a case which does not contain it.)
 *
 * @param tView Current `TView`.
 * @param index Index where the value should be read from.
 */
function getTIcu(tView, index) {
  const value = tView.data[index];
  if (value === null || typeof value === 'string') return null;
  if (ngDevMode && !(value.hasOwnProperty('tView') || value.hasOwnProperty('currentCaseLViewIndex'))) {
    throwError("We expect to get 'null'|'TIcu'|'TIcuContainer', but got: " + value);
  }
  // Here the `value.hasOwnProperty('currentCaseLViewIndex')` is a polymorphic read as it can be
  // either TIcu or TIcuContainerNode. This is not ideal, but we still think it is OK because it
  // will be just two cases which fits into the browser inline cache (inline cache can take up to
  // 4)
  const tIcu = value.hasOwnProperty('currentCaseLViewIndex') ? value : value.value;
  ngDevMode && assertTIcu(tIcu);
  return tIcu;
}
/**
 * Store `TIcu` at a give `index`.
 *
 * The `TIcu` can be stored either directly (if it is nested ICU) OR
 * it is stored inside tho `TIcuContainer` if it is top level ICU.
 *
 * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
 * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
 * expressed (parent ICU may have selected a case which does not contain it.)
 *
 * @param tView Current `TView`.
 * @param index Index where the value should be stored at in `Tview.data`
 * @param tIcu The TIcu to store.
 */
function setTIcu(tView, index, tIcu) {
  const tNode = tView.data[index];
  ngDevMode && assertEqual(tNode === null || tNode.hasOwnProperty('tView'), true, "We expect to get 'null'|'TIcuContainer'");
  if (tNode === null) {
    tView.data[index] = tIcu;
  } else {
    ngDevMode && assertTNodeType(tNode, 32 /* TNodeType.Icu */);
    tNode.value = tIcu;
  }
}
/**
 * Set `TNode.insertBeforeIndex` taking the `Array` into account.
 *
 * See `TNode.insertBeforeIndex`
 */
function setTNodeInsertBeforeIndex(tNode, index) {
  ngDevMode && assertTNode(tNode);
  let insertBeforeIndex = tNode.insertBeforeIndex;
  if (insertBeforeIndex === null) {
    setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
    insertBeforeIndex = tNode.insertBeforeIndex = [null /* may be updated to number later */, index];
  } else {
    assertEqual(Array.isArray(insertBeforeIndex), true, 'Expecting array here');
    insertBeforeIndex.push(index);
  }
}
/**
 * Create `TNode.type=TNodeType.Placeholder` node.
 *
 * See `TNodeType.Placeholder` for more information.
 */
function createTNodePlaceholder(tView, previousTNodes, index) {
  const tNode = createTNodeAtIndex(tView, index, 64 /* TNodeType.Placeholder */, null, null);
  addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tNode);
  return tNode;
}
/**
 * Returns current ICU case.
 *
 * ICU cases are stored as index into the `TIcu.cases`.
 * At times it is necessary to communicate that the ICU case just switched and that next ICU update
 * should update all bindings regardless of the mask. In such a case the we store negative numbers
 * for cases which have just been switched. This function removes the negative flag.
 */
function getCurrentICUCaseIndex(tIcu, lView) {
  const currentCase = lView[tIcu.currentCaseLViewIndex];
  return currentCase === null ? currentCase : currentCase < 0 ? ~currentCase : currentCase;
}
function getParentFromIcuCreateOpCode(mergedCode) {
  return mergedCode >>> 17 /* IcuCreateOpCode.SHIFT_PARENT */;
}
function getRefFromIcuCreateOpCode(mergedCode) {
  return (mergedCode & 131070 /* IcuCreateOpCode.MASK_REF */) >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
}
function getInstructionFromIcuCreateOpCode(mergedCode) {
  return mergedCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */;
}
function icuCreateOpCode(opCode, parentIdx, refIdx) {
  ngDevMode && assertGreaterThanOrEqual(parentIdx, 0, 'Missing parent index');
  ngDevMode && assertGreaterThan(refIdx, 0, 'Missing ref index');
  return opCode | parentIdx << 17 /* IcuCreateOpCode.SHIFT_PARENT */ | refIdx << 1 /* IcuCreateOpCode.SHIFT_REF */;
}
// Returns whether the given value corresponds to a root template message,
// or a sub-template.
function isRootTemplateMessage(subTemplateIndex) {
  return subTemplateIndex === -1;
}
function enterIcu(state, tIcu, lView) {
  state.index = 0;
  const currentCase = getCurrentICUCaseIndex(tIcu, lView);
  if (currentCase !== null) {
    ngDevMode && assertNumberInRange(currentCase, 0, tIcu.cases.length - 1);
    state.removes = tIcu.remove[currentCase];
  } else {
    state.removes = EMPTY_ARRAY;
  }
}
function icuContainerIteratorNext(state) {
  if (state.index < state.removes.length) {
    const removeOpCode = state.removes[state.index++];
    ngDevMode && assertNumber(removeOpCode, 'Expecting OpCode number');
    if (removeOpCode > 0) {
      const rNode = state.lView[removeOpCode];
      ngDevMode && assertDomNode(rNode);
      return rNode;
    } else {
      state.stack.push(state.index, state.removes);
      // ICUs are represented by negative indices
      const tIcuIndex = ~removeOpCode;
      const tIcu = state.lView[TVIEW].data[tIcuIndex];
      ngDevMode && assertTIcu(tIcu);
      enterIcu(state, tIcu, state.lView);
      return icuContainerIteratorNext(state);
    }
  } else {
    if (state.stack.length === 0) {
      return null;
    } else {
      state.removes = state.stack.pop();
      state.index = state.stack.pop();
      return icuContainerIteratorNext(state);
    }
  }
}
function loadIcuContainerVisitor() {
  const _state = {
    stack: [],
    index: -1
  };
  /**
   * Retrieves a set of root nodes from `TIcu.remove`. Used by `TNodeType.ICUContainer`
   * to determine which root belong to the ICU.
   *
   * Example of usage.
   * ```
   * const nextRNode = icuContainerIteratorStart(tIcuContainerNode, lView);
   * let rNode: RNode|null;
   * while(rNode = nextRNode()) {
   *   console.log(rNode);
   * }
   * ```
   *
   * @param tIcuContainerNode Current `TIcuContainerNode`
   * @param lView `LView` where the `RNode`s should be looked up.
   */
  function icuContainerIteratorStart(tIcuContainerNode, lView) {
    _state.lView = lView;
    while (_state.stack.length) _state.stack.pop();
    ngDevMode && assertTNodeForLView(tIcuContainerNode, lView);
    enterIcu(_state, tIcuContainerNode.value, lView);
    return icuContainerIteratorNext.bind(null, _state);
  }
  return icuContainerIteratorStart;
}
function createIcuIterator(tIcu, lView) {
  const state = {
    stack: [],
    index: -1,
    lView
  };
  ngDevMode && assertTIcu(tIcu);
  enterIcu(state, tIcu, lView);
  return icuContainerIteratorNext.bind(null, state);
}

/**
 * Regexp that extracts a reference node information from the compressed node location.
 * The reference node is represented as either:
 *  - a number which points to an LView slot
 *  - the `b` char which indicates that the lookup should start from the `document.body`
 *  - the `h` char to start lookup from the component host node (`lView[HOST]`)
 */
const REF_EXTRACTOR_REGEXP = /*#__PURE__*/new RegExp(`^(\\d+)*(${REFERENCE_NODE_BODY}|${REFERENCE_NODE_HOST})*(.*)`);
/**
 * Helper function that takes a reference node location and a set of navigation steps
 * (from the reference node) to a target node and outputs a string that represents
 * a location.
 *
 * For example, given: referenceNode = 'b' (body) and path = ['firstChild', 'firstChild',
 * 'nextSibling'], the function returns: `bf2n`.
 */
function compressNodeLocation(referenceNode, path) {
  const result = [referenceNode];
  for (const segment of path) {
    const lastIdx = result.length - 1;
    if (lastIdx > 0 && result[lastIdx - 1] === segment) {
      // An empty string in a count slot represents 1 occurrence of an instruction.
      const value = result[lastIdx] || 1;
      result[lastIdx] = value + 1;
    } else {
      // Adding a new segment to the path.
      // Using an empty string in a counter field to avoid encoding `1`s
      // into the path, since they are implicit (e.g. `f1n1` vs `fn`), so
      // it's enough to have a single char in this case.
      result.push(segment, '');
    }
  }
  return result.join('');
}
/**
 * Helper function that reverts the `compressNodeLocation` and transforms a given
 * string into an array where at 0th position there is a reference node info and
 * after that it contains information (in pairs) about a navigation step and the
 * number of repetitions.
 *
 * For example, the path like 'bf2n' will be transformed to:
 * ['b', 'firstChild', 2, 'nextSibling', 1].
 *
 * This information is later consumed by the code that navigates the DOM to find
 * a given node by its location.
 */
function decompressNodeLocation(path) {
  const matches = path.match(REF_EXTRACTOR_REGEXP);
  const [_, refNodeId, refNodeName, rest] = matches;
  // If a reference node is represented by an index, transform it to a number.
  const ref = refNodeId ? parseInt(refNodeId, 10) : refNodeName;
  const steps = [];
  // Match all segments in a path.
  for (const [_, step, count] of rest.matchAll(/(f|n)(\d*)/g)) {
    const repeat = parseInt(count, 10) || 1;
    steps.push(step, repeat);
  }
  return [ref, ...steps];
}

/** Whether current TNode is a first node in an <ng-container>. */
function isFirstElementInNgContainer(tNode) {
  return !tNode.prev && tNode.parent?.type === 8 /* TNodeType.ElementContainer */;
}
/** Returns an instruction index (subtracting HEADER_OFFSET). */
function getNoOffsetIndex(tNode) {
  return tNode.index - HEADER_OFFSET;
}
/**
 * Check whether a given node exists, but is disconnected from the DOM.
 */
function isDisconnectedNode(tNode, lView) {
  return !(tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) && !!lView[tNode.index] && isDisconnectedRNode(unwrapRNode(lView[tNode.index]));
}
/**
 * Check whether the given node exists, but is disconnected from the DOM.
 *
 * Note: we leverage the fact that we have this information available in the DOM emulation
 * layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
 * only use internal data structures and state to compute this information.
 */
function isDisconnectedRNode(rNode) {
  return !!rNode && !rNode.isConnected;
}
/**
 * Locate a node in an i18n tree that corresponds to a given instruction index.
 *
 * @param hydrationInfo The hydration annotation data
 * @param noOffsetIndex the instruction index
 * @returns an RNode that corresponds to the instruction index
 */
function locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex) {
  const i18nNodes = hydrationInfo.i18nNodes;
  if (i18nNodes) {
    return i18nNodes.get(noOffsetIndex);
  }
  return undefined;
}
/**
 * Attempt to locate an RNode by a path, if it exists.
 *
 * @param hydrationInfo The hydration annotation data
 * @param lView the current lView
 * @param noOffsetIndex the instruction index
 * @returns an RNode that corresponds to the instruction index or null if no path exists
 */
function tryLocateRNodeByPath(hydrationInfo, lView, noOffsetIndex) {
  const nodes = hydrationInfo.data[NODES];
  const path = nodes?.[noOffsetIndex];
  return path ? locateRNodeByPath(path, lView) : null;
}
/**
 * Locate a node in DOM tree that corresponds to a given TNode.
 *
 * @param hydrationInfo The hydration annotation data
 * @param tView the current tView
 * @param lView the current lView
 * @param tNode the current tNode
 * @returns an RNode that represents a given tNode
 */
function locateNextRNode(hydrationInfo, tView, lView, tNode) {
  const noOffsetIndex = getNoOffsetIndex(tNode);
  let native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  if (native === undefined) {
    const nodes = hydrationInfo.data[NODES];
    if (nodes?.[noOffsetIndex]) {
      // We know the exact location of the node.
      native = locateRNodeByPath(nodes[noOffsetIndex], lView);
    } else if (tView.firstChild === tNode) {
      // We create a first node in this view, so we use a reference
      // to the first child in this DOM segment.
      native = hydrationInfo.firstChild;
    } else {
      // Locate a node based on a previous sibling or a parent node.
      const previousTNodeParent = tNode.prev === null;
      const previousTNode = tNode.prev ?? tNode.parent;
      ngDevMode && assertDefined(previousTNode, 'Unexpected state: current TNode does not have a connection ' + 'to the previous node or a parent node.');
      if (isFirstElementInNgContainer(tNode)) {
        const noOffsetParentIndex = getNoOffsetIndex(tNode.parent);
        native = getSegmentHead(hydrationInfo, noOffsetParentIndex);
      } else {
        let previousRElement = getNativeByTNode(previousTNode, lView);
        if (previousTNodeParent) {
          native = previousRElement.firstChild;
        } else {
          // If the previous node is an element, but it also has container info,
          // this means that we are processing a node like `<div #vcrTarget>`, which is
          // represented in the DOM as `<div></div>...<!--container-->`.
          // In this case, there are nodes *after* this element and we need to skip
          // all of them to reach an element that we are looking for.
          const noOffsetPrevSiblingIndex = getNoOffsetIndex(previousTNode);
          const segmentHead = getSegmentHead(hydrationInfo, noOffsetPrevSiblingIndex);
          if (previousTNode.type === 2 /* TNodeType.Element */ && segmentHead) {
            const numRootNodesToSkip = calcSerializedContainerSize(hydrationInfo, noOffsetPrevSiblingIndex);
            // `+1` stands for an anchor comment node after all the views in this container.
            const nodesToSkip = numRootNodesToSkip + 1;
            // First node after this segment.
            native = siblingAfter(nodesToSkip, segmentHead);
          } else {
            native = previousRElement.nextSibling;
          }
        }
      }
    }
  }
  return native;
}
/**
 * Skips over a specified number of nodes and returns the next sibling node after that.
 */
function siblingAfter(skip, from) {
  let currentNode = from;
  for (let i = 0; i < skip; i++) {
    ngDevMode && validateSiblingNodeExists(currentNode);
    currentNode = currentNode.nextSibling;
  }
  return currentNode;
}
/**
 * Helper function to produce a string representation of the navigation steps
 * (in terms of `nextSibling` and `firstChild` navigations). Used in error
 * messages in dev mode.
 */
function stringifyNavigationInstructions(instructions) {
  const container = [];
  for (let i = 0; i < instructions.length; i += 2) {
    const step = instructions[i];
    const repeat = instructions[i + 1];
    for (let r = 0; r < repeat; r++) {
      container.push(step === NodeNavigationStep.FirstChild ? 'firstChild' : 'nextSibling');
    }
  }
  return container.join('.');
}
/**
 * Helper function that navigates from a starting point node (the `from` node)
 * using provided set of navigation instructions (within `path` argument).
 */
function navigateToNode(from, instructions) {
  let node = from;
  for (let i = 0; i < instructions.length; i += 2) {
    const step = instructions[i];
    const repeat = instructions[i + 1];
    for (let r = 0; r < repeat; r++) {
      if (ngDevMode && !node) {
        throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
      }
      switch (step) {
        case NodeNavigationStep.FirstChild:
          node = node.firstChild;
          break;
        case NodeNavigationStep.NextSibling:
          node = node.nextSibling;
          break;
      }
    }
  }
  if (ngDevMode && !node) {
    throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
  }
  return node;
}
/**
 * Locates an RNode given a set of navigation instructions (which also contains
 * a starting point node info).
 */
function locateRNodeByPath(path, lView) {
  const [referenceNode, ...navigationInstructions] = decompressNodeLocation(path);
  let ref;
  if (referenceNode === REFERENCE_NODE_HOST) {
    ref = lView[DECLARATION_COMPONENT_VIEW][HOST];
  } else if (referenceNode === REFERENCE_NODE_BODY) {
    ref = ɵɵresolveBody(lView[DECLARATION_COMPONENT_VIEW][HOST]);
  } else {
    const parentElementId = Number(referenceNode);
    ref = unwrapRNode(lView[parentElementId + HEADER_OFFSET]);
  }
  return navigateToNode(ref, navigationInstructions);
}
/**
 * Generate a list of DOM navigation operations to get from node `start` to node `finish`.
 *
 * Note: assumes that node `start` occurs before node `finish` in an in-order traversal of the DOM
 * tree. That is, we should be able to get from `start` to `finish` purely by using `.firstChild`
 * and `.nextSibling` operations.
 */
function navigateBetween(start, finish) {
  if (start === finish) {
    return [];
  } else if (start.parentElement == null || finish.parentElement == null) {
    return null;
  } else if (start.parentElement === finish.parentElement) {
    return navigateBetweenSiblings(start, finish);
  } else {
    // `finish` is a child of its parent, so the parent will always have a child.
    const parent = finish.parentElement;
    const parentPath = navigateBetween(start, parent);
    const childPath = navigateBetween(parent.firstChild, finish);
    if (!parentPath || !childPath) return null;
    return [
    // First navigate to `finish`'s parent
    ...parentPath,
    // Then to its first child.
    NodeNavigationStep.FirstChild,
    // And finally from that node to `finish` (maybe a no-op if we're already there).
    ...childPath];
  }
}
/**
 * Calculates a path between 2 sibling nodes (generates a number of `NextSibling` navigations).
 * Returns `null` if no such path exists between the given nodes.
 */
function navigateBetweenSiblings(start, finish) {
  const nav = [];
  let node = null;
  for (node = start; node != null && node !== finish; node = node.nextSibling) {
    nav.push(NodeNavigationStep.NextSibling);
  }
  // If the `node` becomes `null` or `undefined` at the end, that means that we
  // didn't find the `end` node, thus return `null` (which would trigger serialization
  // error to be produced).
  return node == null ? null : nav;
}
/**
 * Calculates a path between 2 nodes in terms of `nextSibling` and `firstChild`
 * navigations:
 * - the `from` node is a known node, used as an starting point for the lookup
 *   (the `fromNodeName` argument is a string representation of the node).
 * - the `to` node is a node that the runtime logic would be looking up,
 *   using the path generated by this function.
 */
function calcPathBetween(from, to, fromNodeName) {
  const path = navigateBetween(from, to);
  return path === null ? null : compressNodeLocation(fromNodeName, path);
}
/**
 * Invoked at serialization time (on the server) when a set of navigation
 * instructions needs to be generated for a TNode.
 */
function calcPathForNode(tNode, lView, excludedParentNodes) {
  let parentTNode = tNode.parent;
  let parentIndex;
  let parentRNode;
  let referenceNodeName;
  // Skip over all parent nodes that are disconnected from the DOM, such nodes
  // can not be used as anchors.
  //
  // This might happen in certain content projection-based use-cases, where
  // a content of an element is projected and used, when a parent element
  // itself remains detached from DOM. In this scenario we try to find a parent
  // element that is attached to DOM and can act as an anchor instead.
  //
  // It can also happen that the parent node should be excluded, for example,
  // because it belongs to an i18n block, which requires paths which aren't
  // relative to other views in an i18n block.
  while (parentTNode !== null && (isDisconnectedNode(parentTNode, lView) || excludedParentNodes?.has(parentTNode.index))) {
    parentTNode = parentTNode.parent;
  }
  if (parentTNode === null || !(parentTNode.type & 3 /* TNodeType.AnyRNode */)) {
    // If there is no parent TNode or a parent TNode does not represent an RNode
    // (i.e. not a DOM node), use component host element as a reference node.
    parentIndex = referenceNodeName = REFERENCE_NODE_HOST;
    parentRNode = lView[DECLARATION_COMPONENT_VIEW][HOST];
  } else {
    // Use parent TNode as a reference node.
    parentIndex = parentTNode.index;
    parentRNode = unwrapRNode(lView[parentIndex]);
    referenceNodeName = renderStringify(parentIndex - HEADER_OFFSET);
  }
  let rNode = unwrapRNode(lView[tNode.index]);
  if (tNode.type & (12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */)) {
    // For <ng-container> nodes, instead of serializing a reference
    // to the anchor comment node, serialize a location of the first
    // DOM element. Paired with the container size (serialized as a part
    // of `ngh.containers`), it should give enough information for runtime
    // to hydrate nodes in this container.
    const firstRNode = getFirstNativeNode(lView, tNode);
    // If container is not empty, use a reference to the first element,
    // otherwise, rNode would point to an anchor comment node.
    if (firstRNode) {
      rNode = firstRNode;
    }
  }
  let path = calcPathBetween(parentRNode, rNode, referenceNodeName);
  if (path === null && parentRNode !== rNode) {
    // Searching for a path between elements within a host node failed.
    // Trying to find a path to an element starting from the `document.body` instead.
    //
    // Important note: this type of reference is relatively unstable, since Angular
    // may not be able to control parts of the page that the runtime logic navigates
    // through. This is mostly needed to cover "portals" use-case (like menus, dialog boxes,
    // etc), where nodes are content-projected (including direct DOM manipulations) outside
    // of the host node. The better solution is to provide APIs to work with "portals",
    // at which point this code path would not be needed.
    const body = parentRNode.ownerDocument.body;
    path = calcPathBetween(body, rNode, REFERENCE_NODE_BODY);
    if (path === null) {
      // If the path is still empty, it's likely that this node is detached and
      // won't be found during hydration.
      throw nodeNotFoundError(lView, tNode);
    }
  }
  return path;
}
/**
 * Retrieves all comments nodes that contain ngh comments referring to a defer block
 */
function gatherDeferBlocksCommentNodes(doc, node) {
  const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, {
    acceptNode
  });
  let currentNode;
  const nodesByBlockId = new Map();
  while (currentNode = commentNodesIterator.nextNode()) {
    // TODO(incremental-hydration: convert this to use string parsing rather than regex
    const regex = new RegExp(/^\s*ngh=(d[0-9]+)/g);
    const result = regex.exec(currentNode?.textContent ?? '');
    if (result && result?.length > 0) {
      nodesByBlockId.set(result[1], currentNode);
    }
  }
  return nodesByBlockId;
}
function acceptNode(node) {
  return node.textContent?.trimStart().startsWith('ngh=') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
let _isI18nHydrationSupportEnabled = false;
let _prepareI18nBlockForHydrationImpl = () => {
  // noop unless `enablePrepareI18nBlockForHydrationImpl` is invoked.
};
function setIsI18nHydrationSupportEnabled(enabled) {
  _isI18nHydrationSupportEnabled = enabled;
}
function isI18nHydrationSupportEnabled() {
  return _isI18nHydrationSupportEnabled;
}
/**
 * Prepares an i18n block and its children, located at the given
 * view and instruction index, for hydration.
 *
 * @param lView lView with the i18n block
 * @param index index of the i18n block in the lView
 * @param parentTNode TNode of the parent of the i18n block
 * @param subTemplateIndex sub-template index, or -1 for the main template
 */
function prepareI18nBlockForHydration(lView, index, parentTNode, subTemplateIndex) {
  _prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex);
}
function enablePrepareI18nBlockForHydrationImpl() {
  _prepareI18nBlockForHydrationImpl = prepareI18nBlockForHydrationImpl;
}
function isI18nHydrationEnabled(injector) {
  injector = injector ?? inject(Injector);
  return injector.get(IS_I18N_HYDRATION_ENABLED, false);
}
/**
 * Collects, if not already cached, all of the indices in the
 * given TView which are children of an i18n block.
 *
 * Since i18n blocks don't introduce a parent TNode, this is necessary
 * in order to determine which indices in a LView are translated.
 */
function getOrComputeI18nChildren(tView, context) {
  let i18nChildren = context.i18nChildren.get(tView);
  if (i18nChildren === undefined) {
    i18nChildren = collectI18nChildren(tView);
    context.i18nChildren.set(tView, i18nChildren);
  }
  return i18nChildren;
}
function collectI18nChildren(tView) {
  const children = new Set();
  function collectI18nViews(node) {
    children.add(node.index);
    switch (node.kind) {
      case 1 /* I18nNodeKind.ELEMENT */:
      case 2 /* I18nNodeKind.PLACEHOLDER */:
        {
          for (const childNode of node.children) {
            collectI18nViews(childNode);
          }
          break;
        }
      case 3 /* I18nNodeKind.ICU */:
        {
          for (const caseNodes of node.cases) {
            for (const caseNode of caseNodes) {
              collectI18nViews(caseNode);
            }
          }
          break;
        }
    }
  }
  // Traverse through the AST of each i18n block in the LView,
  // and collect every instruction index.
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    const tI18n = tView.data[i];
    if (!tI18n || !tI18n.ast) {
      continue;
    }
    for (const node of tI18n.ast) {
      collectI18nViews(node);
    }
  }
  return children.size === 0 ? null : children;
}
/**
 * Attempts to serialize i18n data for an i18n block, located at
 * the given view and instruction index.
 *
 * @param lView lView with the i18n block
 * @param index index of the i18n block in the lView
 * @param context the hydration context
 * @returns the i18n data, or null if there is no relevant data
 */
function trySerializeI18nBlock(lView, index, context) {
  if (!context.isI18nHydrationEnabled) {
    return null;
  }
  const tView = lView[TVIEW];
  const tI18n = tView.data[index];
  if (!tI18n || !tI18n.ast) {
    return null;
  }
  const parentTNode = tView.data[tI18n.parentTNodeIndex];
  if (parentTNode && isI18nInSkipHydrationBlock(parentTNode)) {
    return null;
  }
  const serializedI18nBlock = {
    caseQueue: [],
    disconnectedNodes: new Set(),
    disjointNodes: new Set()
  };
  serializeI18nBlock(lView, serializedI18nBlock, context, tI18n.ast);
  return serializedI18nBlock.caseQueue.length === 0 && serializedI18nBlock.disconnectedNodes.size === 0 && serializedI18nBlock.disjointNodes.size === 0 ? null : serializedI18nBlock;
}
function serializeI18nBlock(lView, serializedI18nBlock, context, nodes) {
  let prevRNode = null;
  for (const node of nodes) {
    const nextRNode = serializeI18nNode(lView, serializedI18nBlock, context, node);
    if (nextRNode) {
      if (isDisjointNode(prevRNode, nextRNode)) {
        serializedI18nBlock.disjointNodes.add(node.index - HEADER_OFFSET);
      }
      prevRNode = nextRNode;
    }
  }
  return prevRNode;
}
/**
 * Helper to determine whether the given nodes are "disjoint".
 *
 * The i18n hydration process walks through the DOM and i18n nodes
 * at the same time. It expects the sibling DOM node of the previous
 * i18n node to be the first node of the next i18n node.
 *
 * In cases of content projection, this won't always be the case. So
 * when we detect that, we mark the node as "disjoint", ensuring that
 * we will serialize the path to the node. This way, when we hydrate the
 * i18n node, we will be able to find the correct place to start.
 */
function isDisjointNode(prevNode, nextNode) {
  return prevNode && prevNode.nextSibling !== nextNode;
}
/**
 * Process the given i18n node for serialization.
 * Returns the first RNode for the i18n node to begin hydration.
 */
function serializeI18nNode(lView, serializedI18nBlock, context, node) {
  const maybeRNode = unwrapRNode(lView[node.index]);
  if (!maybeRNode || isDisconnectedRNode(maybeRNode)) {
    serializedI18nBlock.disconnectedNodes.add(node.index - HEADER_OFFSET);
    return null;
  }
  const rNode = maybeRNode;
  switch (node.kind) {
    case 0 /* I18nNodeKind.TEXT */:
      {
        processTextNodeBeforeSerialization(context, rNode);
        break;
      }
    case 1 /* I18nNodeKind.ELEMENT */:
    case 2 /* I18nNodeKind.PLACEHOLDER */:
      {
        serializeI18nBlock(lView, serializedI18nBlock, context, node.children);
        break;
      }
    case 3 /* I18nNodeKind.ICU */:
      {
        const currentCase = lView[node.currentCaseLViewIndex];
        if (currentCase != null) {
          // i18n uses a negative value to signal a change to a new case, so we
          // need to invert it to get the proper value.
          const caseIdx = currentCase < 0 ? ~currentCase : currentCase;
          serializedI18nBlock.caseQueue.push(caseIdx);
          serializeI18nBlock(lView, serializedI18nBlock, context, node.cases[caseIdx]);
        }
        break;
      }
  }
  return getFirstNativeNodeForI18nNode(lView, node);
}
/**
 * Helper function to get the first native node to begin hydrating
 * the given i18n node.
 */
function getFirstNativeNodeForI18nNode(lView, node) {
  const tView = lView[TVIEW];
  const maybeTNode = tView.data[node.index];
  if (isTNodeShape(maybeTNode)) {
    // If the node is backed by an actual TNode, we can simply delegate.
    return getFirstNativeNode(lView, maybeTNode);
  } else if (node.kind === 3 /* I18nNodeKind.ICU */) {
    // A nested ICU container won't have an actual TNode. In that case, we can use
    // an iterator to find the first child.
    const icuIterator = createIcuIterator(maybeTNode, lView);
    let rNode = icuIterator();
    // If the ICU container has no nodes, then we use the ICU anchor as the node.
    return rNode ?? unwrapRNode(lView[node.index]);
  } else {
    // Otherwise, the node is a text or trivial element in an ICU container,
    // and we can just use the RNode directly.
    return unwrapRNode(lView[node.index]) ?? null;
  }
}
function setCurrentNode(state, node) {
  state.currentNode = node;
}
/**
 * Marks the current RNode as the hydration root for the given
 * AST node.
 */
function appendI18nNodeToCollection(context, state, astNode) {
  const noOffsetIndex = astNode.index - HEADER_OFFSET;
  const {
    disconnectedNodes
  } = context;
  const currentNode = state.currentNode;
  if (state.isConnected) {
    context.i18nNodes.set(noOffsetIndex, currentNode);
    // We expect the node to be connected, so ensure that it
    // is not in the set, regardless of whether we found it,
    // so that the downstream error handling can provide the
    // proper context.
    disconnectedNodes.delete(noOffsetIndex);
  } else {
    disconnectedNodes.add(noOffsetIndex);
  }
  return currentNode;
}
/**
 * Skip over some sibling nodes during hydration.
 *
 * Note: we use this instead of `siblingAfter` as it's expected that
 * sometimes we might encounter null nodes. In those cases, we want to
 * defer to downstream error handling to provide proper context.
 */
function skipSiblingNodes(state, skip) {
  let currentNode = state.currentNode;
  for (let i = 0; i < skip; i++) {
    if (!currentNode) {
      break;
    }
    currentNode = currentNode?.nextSibling ?? null;
  }
  return currentNode;
}
/**
 * Fork the given state into a new state for hydrating children.
 */
function forkHydrationState(state, nextNode) {
  return {
    currentNode: nextNode,
    isConnected: state.isConnected
  };
}
function prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex) {
  const hydrationInfo = lView[HYDRATION];
  if (!hydrationInfo) {
    return;
  }
  if (!isI18nHydrationSupportEnabled() || parentTNode && (isI18nInSkipHydrationBlock(parentTNode) || isDisconnectedNode$1(hydrationInfo, parentTNode.index - HEADER_OFFSET))) {
    return;
  }
  const tView = lView[TVIEW];
  const tI18n = tView.data[index];
  ngDevMode && assertDefined(tI18n, 'Expected i18n data to be present in a given TView slot during hydration');
  function findHydrationRoot() {
    if (isRootTemplateMessage(subTemplateIndex)) {
      // This is the root of an i18n block. In this case, our hydration root will
      // depend on where our parent TNode (i.e. the block with i18n applied) is
      // in the DOM.
      ngDevMode && assertDefined(parentTNode, 'Expected parent TNode while hydrating i18n root');
      const rootNode = locateNextRNode(hydrationInfo, tView, lView, parentTNode);
      // If this i18n block is attached to an <ng-container>, then we want to begin
      // hydrating directly with the RNode. Otherwise, for a TNode with a physical DOM
      // element, we want to recurse into the first child and begin there.
      return parentTNode.type & 8 /* TNodeType.ElementContainer */ ? rootNode : rootNode.firstChild;
    }
    // This is a nested template in an i18n block. In this case, the entire view
    // is translated, and part of a dehydrated view in a container. This means that
    // we can simply begin hydration with the first dehydrated child.
    return hydrationInfo?.firstChild;
  }
  const currentNode = findHydrationRoot();
  ngDevMode && assertDefined(currentNode, 'Expected root i18n node during hydration');
  const disconnectedNodes = initDisconnectedNodes(hydrationInfo) ?? new Set();
  const i18nNodes = hydrationInfo.i18nNodes ??= new Map();
  const caseQueue = hydrationInfo.data[I18N_DATA]?.[index - HEADER_OFFSET] ?? [];
  const dehydratedIcuData = hydrationInfo.dehydratedIcuData ??= new Map();
  collectI18nNodesFromDom({
    hydrationInfo,
    lView,
    i18nNodes,
    disconnectedNodes,
    caseQueue,
    dehydratedIcuData
  }, {
    currentNode,
    isConnected: true
  }, tI18n.ast);
  // Nodes from inactive ICU cases should be considered disconnected. We track them above
  // because they aren't (and shouldn't be) serialized. Since we may mutate or create a
  // new set, we need to be sure to write the expected value back to the DehydratedView.
  hydrationInfo.disconnectedNodes = disconnectedNodes.size === 0 ? null : disconnectedNodes;
}
function collectI18nNodesFromDom(context, state, nodeOrNodes) {
  if (Array.isArray(nodeOrNodes)) {
    let nextState = state;
    for (const node of nodeOrNodes) {
      // Whenever a node doesn't directly follow the previous RNode, it
      // is given a path. We need to resume collecting nodes from that location
      // until and unless we find another disjoint node.
      const targetNode = tryLocateRNodeByPath(context.hydrationInfo, context.lView, node.index - HEADER_OFFSET);
      if (targetNode) {
        nextState = forkHydrationState(state, targetNode);
      }
      collectI18nNodesFromDom(context, nextState, node);
    }
  } else {
    if (context.disconnectedNodes.has(nodeOrNodes.index - HEADER_OFFSET)) {
      // i18n nodes can be considered disconnected if e.g. they were projected.
      // In that case, we have to make sure to skip over them.
      return;
    }
    switch (nodeOrNodes.kind) {
      case 0 /* I18nNodeKind.TEXT */:
        {
          // Claim a text node for hydration
          const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
          setCurrentNode(state, currentNode?.nextSibling ?? null);
          break;
        }
      case 1 /* I18nNodeKind.ELEMENT */:
        {
          // Recurse into the current element's children...
          collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
          // And claim the parent element itself.
          const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
          setCurrentNode(state, currentNode?.nextSibling ?? null);
          break;
        }
      case 2 /* I18nNodeKind.PLACEHOLDER */:
        {
          const noOffsetIndex = nodeOrNodes.index - HEADER_OFFSET;
          const {
            hydrationInfo
          } = context;
          const containerSize = getNgContainerSize(hydrationInfo, noOffsetIndex);
          switch (nodeOrNodes.type) {
            case 0 /* I18nPlaceholderType.ELEMENT */:
              {
                // Hydration expects to find the head of the element.
                const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
                // A TNode for the node may not yet if we're hydrating during the first pass,
                // so use the serialized data to determine if this is an <ng-container>.
                if (isSerializedElementContainer(hydrationInfo, noOffsetIndex)) {
                  // An <ng-container> doesn't have a physical DOM node, so we need to
                  // continue hydrating from siblings.
                  collectI18nNodesFromDom(context, state, nodeOrNodes.children);
                  // Skip over the anchor element. It will be claimed by the
                  // downstream container hydration.
                  const nextNode = skipSiblingNodes(state, 1);
                  setCurrentNode(state, nextNode);
                } else {
                  // Non-container elements represent an actual node in the DOM, so we
                  // need to continue hydration with the children, and claim the node.
                  collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
                  setCurrentNode(state, currentNode?.nextSibling ?? null);
                  // Elements can also be the anchor of a view container, so there may
                  // be elements after this node that we need to skip.
                  if (containerSize !== null) {
                    // `+1` stands for an anchor node after all of the views in the container.
                    const nextNode = skipSiblingNodes(state, containerSize + 1);
                    setCurrentNode(state, nextNode);
                  }
                }
                break;
              }
            case 1 /* I18nPlaceholderType.SUBTEMPLATE */:
              {
                ngDevMode && assertNotEqual(containerSize, null, 'Expected a container size while hydrating i18n subtemplate');
                // Hydration expects to find the head of the template.
                appendI18nNodeToCollection(context, state, nodeOrNodes);
                // Skip over all of the template children, as well as the anchor
                // node, since the template itself will handle them instead.
                const nextNode = skipSiblingNodes(state, containerSize + 1);
                setCurrentNode(state, nextNode);
                break;
              }
          }
          break;
        }
      case 3 /* I18nNodeKind.ICU */:
        {
          // If the current node is connected, we need to pop the next case from the
          // queue, so that the active case is also considered connected.
          const selectedCase = state.isConnected ? context.caseQueue.shift() : null;
          const childState = {
            currentNode: null,
            isConnected: false
          };
          // We traverse through each case, even if it's not active,
          // so that we correctly populate disconnected nodes.
          for (let i = 0; i < nodeOrNodes.cases.length; i++) {
            collectI18nNodesFromDom(context, i === selectedCase ? state : childState, nodeOrNodes.cases[i]);
          }
          if (selectedCase !== null) {
            // ICUs represent a branching state, and the selected case could be different
            // than what it was on the server. In that case, we need to be able to clean
            // up the nodes from the original case. To do that, we store the selected case.
            context.dehydratedIcuData.set(nodeOrNodes.index, {
              case: selectedCase,
              node: nodeOrNodes
            });
          }
          // Hydration expects to find the ICU anchor element.
          const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
          setCurrentNode(state, currentNode?.nextSibling ?? null);
          break;
        }
    }
  }
}
let _claimDehydratedIcuCaseImpl = () => {
  // noop unless `enableClaimDehydratedIcuCaseImpl` is invoked
};
/**
 * Mark the case for the ICU node at the given index in the view as claimed,
 * allowing its nodes to be hydrated and not cleaned up.
 */
function claimDehydratedIcuCase(lView, icuIndex, caseIndex) {
  _claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex);
}
function enableClaimDehydratedIcuCaseImpl() {
  _claimDehydratedIcuCaseImpl = claimDehydratedIcuCaseImpl;
}
function claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex) {
  const dehydratedIcuDataMap = lView[HYDRATION]?.dehydratedIcuData;
  if (dehydratedIcuDataMap) {
    const dehydratedIcuData = dehydratedIcuDataMap.get(icuIndex);
    if (dehydratedIcuData?.case === caseIndex) {
      // If the case we're attempting to claim matches the dehydrated one,
      // we remove it from the map to mark it as "claimed."
      dehydratedIcuDataMap.delete(icuIndex);
    }
  }
}
/**
 * Clean up all i18n hydration data associated with the given view.
 */
function cleanupI18nHydrationData(lView) {
  const hydrationInfo = lView[HYDRATION];
  if (hydrationInfo) {
    const {
      i18nNodes,
      dehydratedIcuData: dehydratedIcuDataMap
    } = hydrationInfo;
    if (i18nNodes && dehydratedIcuDataMap) {
      const renderer = lView[RENDERER];
      for (const dehydratedIcuData of dehydratedIcuDataMap.values()) {
        cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData);
      }
    }
    hydrationInfo.i18nNodes = undefined;
    hydrationInfo.dehydratedIcuData = undefined;
  }
}
function cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData) {
  for (const node of dehydratedIcuData.node.cases[dehydratedIcuData.case]) {
    const rNode = i18nNodes.get(node.index - HEADER_OFFSET);
    if (rNode) {
      nativeRemoveNode(renderer, rNode, false);
    }
  }
}

/**
 * Removes all dehydrated views from a given LContainer:
 * both in internal data structure, as well as removing
 * corresponding DOM nodes that belong to that dehydrated view.
 */
function removeDehydratedViews(lContainer) {
  const views = lContainer[DEHYDRATED_VIEWS] ?? [];
  const parentLView = lContainer[PARENT];
  const renderer = parentLView[RENDERER];
  const retainedViews = [];
  for (const view of views) {
    // Do not clean up contents of `@defer` blocks.
    // The cleanup for this content would happen once a given block
    // is triggered and hydrated.
    if (view.data[DEFER_BLOCK_ID] !== undefined) {
      retainedViews.push(view);
    } else {
      removeDehydratedView(view, renderer);
      ngDevMode && ngDevMode.dehydratedViewsRemoved++;
    }
  }
  // Reset the value to an array to indicate that no
  // further processing of dehydrated views is needed for
  // this view container (i.e. do not trigger the lookup process
  // once again in case a `ViewContainerRef` is created later).
  lContainer[DEHYDRATED_VIEWS] = retainedViews;
}
/**
 * Helper function to remove all nodes from a dehydrated view.
 */
function removeDehydratedView(dehydratedView, renderer) {
  let nodesRemoved = 0;
  let currentRNode = dehydratedView.firstChild;
  if (currentRNode) {
    const numNodes = dehydratedView.data[NUM_ROOT_NODES];
    while (nodesRemoved < numNodes) {
      ngDevMode && validateSiblingNodeExists(currentRNode);
      const nextSibling = currentRNode.nextSibling;
      nativeRemoveNode(renderer, currentRNode, false);
      currentRNode = nextSibling;
      nodesRemoved++;
    }
  }
}
/**
 * Walks over all views within this LContainer invokes dehydrated views
 * cleanup function for each one.
 */
function cleanupLContainer(lContainer) {
  removeDehydratedViews(lContainer);
  // The host could be an LView if this container is on a component node.
  // In this case, descend into host LView for further cleanup. See also
  // LContainer[HOST] docs for additional information.
  const hostLView = lContainer[HOST];
  if (isLView(hostLView)) {
    cleanupLView(hostLView);
  }
  for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
    cleanupLView(lContainer[i]);
  }
}
/**
 * Walks over `LContainer`s and components registered within
 * this LView and invokes dehydrated views cleanup function for each one.
 */
function cleanupLView(lView) {
  cleanupI18nHydrationData(lView);
  const tView = lView[TVIEW];
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    if (isLContainer(lView[i])) {
      const lContainer = lView[i];
      cleanupLContainer(lContainer);
    } else if (isLView(lView[i])) {
      // This is a component, enter the `cleanupLView` recursively.
      cleanupLView(lView[i]);
    }
  }
}
/**
 * Walks over all views registered within the ApplicationRef and removes
 * all dehydrated views from all `LContainer`s along the way.
 */
function cleanupDehydratedViews(appRef) {
  const viewRefs = appRef._views;
  for (const viewRef of viewRefs) {
    const lNode = getLNodeForHydration(viewRef);
    // An `lView` might be `null` if a `ViewRef` represents
    // an embedded view (not a component view).
    if (lNode !== null && lNode[HOST] !== null) {
      if (isLView(lNode)) {
        cleanupLView(lNode);
      } else {
        // Cleanup in all views within this view container
        cleanupLContainer(lNode);
      }
      ngDevMode && ngDevMode.dehydratedViewsCleanupRuns++;
    }
  }
}
/**
 * post hydration cleanup handling for defer blocks that were incrementally
 * hydrated. This removes all the jsaction attributes, timers, observers,
 * dehydrated views and containers
 */
function cleanupDeferBlock(_x, _x2, _x3) {
  return _cleanupDeferBlock.apply(this, arguments);
}
/**
 * Given a current DOM node and a serialized information about the views
 * in a container, walks over the DOM structure, collecting the list of
 * dehydrated views.
 */
function _cleanupDeferBlock() {
  _cleanupDeferBlock = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (deferBlock, hydratedBlocks, injector) {
    if (deferBlock !== null) {
      // hydratedBlocks is a set, and needs to be converted to an array
      // for removing listeners
      const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
      registry.cleanup([...hydratedBlocks]);
      cleanupLContainer(deferBlock.lContainer);
      cleanupDehydratedViews(injector.get(ApplicationRef));
    }
    // we need to wait for app stability here so we don't continue before
    // the hydration process has finished, which could result in problems
    return whenStable(injector.get(ApplicationRef));
  });
  return _cleanupDeferBlock.apply(this, arguments);
}
function locateDehydratedViewsInContainer(currentRNode, serializedViews) {
  const dehydratedViews = [];
  for (const serializedView of serializedViews) {
    // Repeats a view multiple times as needed, based on the serialized information
    // (for example, for *ngFor-produced views).
    for (let i = 0; i < (serializedView[MULTIPLIER] ?? 1); i++) {
      const view = {
        data: serializedView,
        firstChild: null
      };
      if (serializedView[NUM_ROOT_NODES] > 0) {
        // Keep reference to the first node in this view,
        // so it can be accessed while invoking template instructions.
        view.firstChild = currentRNode;
        // Move over to the next node after this view, which can
        // either be a first node of the next view or an anchor comment
        // node after the last view in a container.
        currentRNode = siblingAfter(serializedView[NUM_ROOT_NODES], currentRNode);
      }
      dehydratedViews.push(view);
    }
  }
  return [currentRNode, dehydratedViews];
}
/**
 * Reference to a function that searches for a matching dehydrated views
 * stored on a given lContainer.
 * Returns `null` by default, when hydration is not enabled.
 */
let _findMatchingDehydratedViewImpl = () => null;
/**
 * Retrieves the next dehydrated view from the LContainer and verifies that
 * it matches a given template id (from the TView that was used to create this
 * instance of a view). If the id doesn't match, that means that we are in an
 * unexpected state and can not complete the reconciliation process. Thus,
 * all dehydrated views from this LContainer are removed (including corresponding
 * DOM nodes) and the rendering is performed as if there were no dehydrated views
 * in this container.
 */
function findMatchingDehydratedViewImpl(lContainer, template) {
  const views = lContainer[DEHYDRATED_VIEWS];
  if (!template || views === null || views.length === 0) {
    return null;
  }
  const view = views[0];
  // Verify whether the first dehydrated view in the container matches
  // the template id passed to this function (that originated from a TView
  // that was used to create an instance of an embedded or component views.
  if (view.data[TEMPLATE_ID] === template) {
    // If the template id matches - extract the first view and return it.
    return views.shift();
  } else {
    // Otherwise, we are at the state when reconciliation can not be completed,
    // thus we remove all dehydrated views within this container (remove them
    // from internal data structures as well as delete associated elements from
    // the DOM tree).
    removeDehydratedViews(lContainer);
    return null;
  }
}
function enableFindMatchingDehydratedViewImpl() {
  _findMatchingDehydratedViewImpl = findMatchingDehydratedViewImpl;
}
function findMatchingDehydratedView(lContainer, template) {
  return _findMatchingDehydratedViewImpl(lContainer, template);
}

/**
 * Represents a container where one or more views can be attached to a component.
 *
 * Can contain *host views* (created by instantiating a
 * component with the `createComponent()` method), and *embedded views*
 * (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
 *
 * A view container instance can contain other view containers,
 * creating a view hierarchy.
 *
 * @usageNotes
 *
 * The example below demonstrates how the `createComponent` function can be used
 * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
 * so that it gets included into change detection cycles.
 *
 * Note: the example uses standalone components, but the function can also be used for
 * non-standalone components (declared in an NgModule) as well.
 *
 * ```typescript
 * @Component({
 *   standalone: true,
 *   selector: 'dynamic',
 *   template: `<span>This is a content of a dynamic component.</span>`,
 * })
 * class DynamicComponent {
 *   vcr = inject(ViewContainerRef);
 * }
 *
 * @Component({
 *   standalone: true,
 *   selector: 'app',
 *   template: `<main>Hi! This is the main content.</main>`,
 * })
 * class AppComponent {
 *   vcr = inject(ViewContainerRef);
 *
 *   ngAfterViewInit() {
 *     const compRef = this.vcr.createComponent(DynamicComponent);
 *     compRef.changeDetectorRef.detectChanges();
 *   }
 * }
 * ```
 *
 * @see {@link ComponentRef}
 * @see {@link EmbeddedViewRef}
 *
 * @publicApi
 */
let ViewContainerRef = /*#__PURE__*/(() => {
  class ViewContainerRef {
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectViewContainerRef)();
  }
  return ViewContainerRef;
})();
/**
 * Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
 * already exists, retrieves the existing ViewContainerRef.
 *
 * @returns The ViewContainerRef instance to use
 */
function injectViewContainerRef() {
  const previousTNode = getCurrentTNode();
  return createContainerRef(previousTNode, getLView());
}
const VE_ViewContainerRef = ViewContainerRef;
// TODO(alxhub): cleaning up this indirection triggers a subtle bug in Closure in g3. Once the fix
// for that lands, this can be cleaned up.
const R3ViewContainerRef = class ViewContainerRef extends VE_ViewContainerRef {
  _lContainer;
  _hostTNode;
  _hostLView;
  constructor(_lContainer, _hostTNode, _hostLView) {
    super();
    this._lContainer = _lContainer;
    this._hostTNode = _hostTNode;
    this._hostLView = _hostLView;
  }
  get element() {
    return createElementRef(this._hostTNode, this._hostLView);
  }
  get injector() {
    return new NodeInjector(this._hostTNode, this._hostLView);
  }
  /** @deprecated No replacement */
  get parentInjector() {
    const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostLView);
    if (hasParentInjector(parentLocation)) {
      const parentView = getParentInjectorView(parentLocation, this._hostLView);
      const injectorIndex = getParentInjectorIndex(parentLocation);
      ngDevMode && assertNodeInjector(parentView, injectorIndex);
      const parentTNode = parentView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
      return new NodeInjector(parentTNode, parentView);
    } else {
      return new NodeInjector(null, this._hostLView);
    }
  }
  clear() {
    while (this.length > 0) {
      this.remove(this.length - 1);
    }
  }
  get(index) {
    const viewRefs = getViewRefs(this._lContainer);
    return viewRefs !== null && viewRefs[index] || null;
  }
  get length() {
    return this._lContainer.length - CONTAINER_HEADER_OFFSET;
  }
  createEmbeddedView(templateRef, context, indexOrOptions) {
    let index;
    let injector;
    if (typeof indexOrOptions === 'number') {
      index = indexOrOptions;
    } else if (indexOrOptions != null) {
      index = indexOrOptions.index;
      injector = indexOrOptions.injector;
    }
    const dehydratedView = findMatchingDehydratedView(this._lContainer, templateRef.ssrId);
    const viewRef = templateRef.createEmbeddedViewImpl(context || {}, injector, dehydratedView);
    this.insertImpl(viewRef, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
    return viewRef;
  }
  createComponent(componentFactoryOrType, indexOrOptions, injector, projectableNodes, environmentInjector) {
    const isComponentFactory = componentFactoryOrType && !isType(componentFactoryOrType);
    let index;
    // This function supports 2 signatures and we need to handle options correctly for both:
    //   1. When first argument is a Component type. This signature also requires extra
    //      options to be provided as object (more ergonomic option).
    //   2. First argument is a Component factory. In this case extra options are represented as
    //      positional arguments. This signature is less ergonomic and will be deprecated.
    if (isComponentFactory) {
      if (ngDevMode) {
        assertEqual(typeof indexOrOptions !== 'object', true, 'It looks like Component factory was provided as the first argument ' + 'and an options object as the second argument. This combination of arguments ' + 'is incompatible. You can either change the first argument to provide Component ' + 'type or change the second argument to be a number (representing an index at ' + "which to insert the new component's host view into this container)");
      }
      index = indexOrOptions;
    } else {
      if (ngDevMode) {
        assertDefined(getComponentDef(componentFactoryOrType), `Provided Component class doesn't contain Component definition. ` + `Please check whether provided class has @Component decorator.`);
        assertEqual(typeof indexOrOptions !== 'number', true, 'It looks like Component type was provided as the first argument ' + "and a number (representing an index at which to insert the new component's " + 'host view into this container as the second argument. This combination of arguments ' + 'is incompatible. Please use an object as the second argument instead.');
      }
      const options = indexOrOptions || {};
      if (ngDevMode && options.environmentInjector && options.ngModuleRef) {
        throwError(`Cannot pass both environmentInjector and ngModuleRef options to createComponent().`);
      }
      index = options.index;
      injector = options.injector;
      projectableNodes = options.projectableNodes;
      environmentInjector = options.environmentInjector || options.ngModuleRef;
    }
    const componentFactory = isComponentFactory ? componentFactoryOrType : new ComponentFactory(getComponentDef(componentFactoryOrType));
    const contextInjector = injector || this.parentInjector;
    // If an `NgModuleRef` is not provided explicitly, try retrieving it from the DI tree.
    if (!environmentInjector && componentFactory.ngModule == null) {
      // For the `ComponentFactory` case, entering this logic is very unlikely, since we expect that
      // an instance of a `ComponentFactory`, resolved via `ComponentFactoryResolver` would have an
      // `ngModule` field. This is possible in some test scenarios and potentially in some JIT-based
      // use-cases. For the `ComponentFactory` case we preserve backwards-compatibility and try
      // using a provided injector first, then fall back to the parent injector of this
      // `ViewContainerRef` instance.
      //
      // For the factory-less case, it's critical to establish a connection with the module
      // injector tree (by retrieving an instance of an `NgModuleRef` and accessing its injector),
      // so that a component can use DI tokens provided in MgModules. For this reason, we can not
      // rely on the provided injector, since it might be detached from the DI tree (for example, if
      // it was created via `Injector.create` without specifying a parent injector, or if an
      // injector is retrieved from an `NgModuleRef` created via `createNgModule` using an
      // NgModule outside of a module tree). Instead, we always use `ViewContainerRef`'s parent
      // injector, which is normally connected to the DI tree, which includes module injector
      // subtree.
      const _injector = isComponentFactory ? contextInjector : this.parentInjector;
      // DO NOT REFACTOR. The code here used to have a `injector.get(NgModuleRef, null) ||
      // undefined` expression which seems to cause internal google apps to fail. This is documented
      // in the following internal bug issue: go/b/142967802
      const result = _injector.get(EnvironmentInjector, null);
      if (result) {
        environmentInjector = result;
      }
    }
    const componentDef = getComponentDef(componentFactory.componentType ?? {});
    const dehydratedView = findMatchingDehydratedView(this._lContainer, componentDef?.id ?? null);
    const rNode = dehydratedView?.firstChild ?? null;
    const componentRef = componentFactory.create(contextInjector, projectableNodes, rNode, environmentInjector);
    this.insertImpl(componentRef.hostView, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
    return componentRef;
  }
  insert(viewRef, index) {
    return this.insertImpl(viewRef, index, true);
  }
  insertImpl(viewRef, index, addToDOM) {
    const lView = viewRef._lView;
    if (ngDevMode && viewRef.destroyed) {
      throw new Error('Cannot insert a destroyed View in a ViewContainer!');
    }
    if (viewAttachedToContainer(lView)) {
      // If view is already attached, detach it first so we clean up references appropriately.
      const prevIdx = this.indexOf(viewRef);
      // A view might be attached either to this or a different container. The `prevIdx` for
      // those cases will be:
      // equal to -1 for views attached to this ViewContainerRef
      // >= 0 for views attached to a different ViewContainerRef
      if (prevIdx !== -1) {
        this.detach(prevIdx);
      } else {
        const prevLContainer = lView[PARENT];
        ngDevMode && assertEqual(isLContainer(prevLContainer), true, 'An attached view should have its PARENT point to a container.');
        // We need to re-create a R3ViewContainerRef instance since those are not stored on
        // LView (nor anywhere else).
        const prevVCRef = new R3ViewContainerRef(prevLContainer, prevLContainer[T_HOST], prevLContainer[PARENT]);
        prevVCRef.detach(prevVCRef.indexOf(viewRef));
      }
    }
    // Logical operation of adding `LView` to `LContainer`
    const adjustedIdx = this._adjustIndex(index);
    const lContainer = this._lContainer;
    addLViewToLContainer(lContainer, lView, adjustedIdx, addToDOM);
    viewRef.attachToViewContainerRef();
    addToArray(getOrCreateViewRefs(lContainer), adjustedIdx, viewRef);
    return viewRef;
  }
  move(viewRef, newIndex) {
    if (ngDevMode && viewRef.destroyed) {
      throw new Error('Cannot move a destroyed View in a ViewContainer!');
    }
    return this.insert(viewRef, newIndex);
  }
  indexOf(viewRef) {
    const viewRefsArr = getViewRefs(this._lContainer);
    return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
  }
  remove(index) {
    const adjustedIdx = this._adjustIndex(index, -1);
    const detachedView = detachView(this._lContainer, adjustedIdx);
    if (detachedView) {
      // Before destroying the view, remove it from the container's array of `ViewRef`s.
      // This ensures the view container length is updated before calling
      // `destroyLView`, which could recursively call view container methods that
      // rely on an accurate container length.
      // (e.g. a method on this view container being called by a child directive's OnDestroy
      // lifecycle hook)
      removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx);
      destroyLView(detachedView[TVIEW], detachedView);
    }
  }
  detach(index) {
    const adjustedIdx = this._adjustIndex(index, -1);
    const view = detachView(this._lContainer, adjustedIdx);
    const wasDetached = view && removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx) != null;
    return wasDetached ? new ViewRef$1(view) : null;
  }
  _adjustIndex(index, shift = 0) {
    if (index == null) {
      return this.length + shift;
    }
    if (ngDevMode) {
      assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
      // +1 because it's legal to insert at the end.
      assertLessThan(index, this.length + 1 + shift, 'index');
    }
    return index;
  }
};
function getViewRefs(lContainer) {
  return lContainer[VIEW_REFS];
}
function getOrCreateViewRefs(lContainer) {
  return lContainer[VIEW_REFS] || (lContainer[VIEW_REFS] = []);
}
/**
 * Creates a ViewContainerRef and stores it on the injector.
 *
 * @param hostTNode The node that is requesting a ViewContainerRef
 * @param hostLView The view to which the node belongs
 * @returns The ViewContainerRef instance to use
 */
function createContainerRef(hostTNode, hostLView) {
  ngDevMode && assertTNodeType(hostTNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  let lContainer;
  const slotValue = hostLView[hostTNode.index];
  if (isLContainer(slotValue)) {
    // If the host is a container, we don't need to create a new LContainer
    lContainer = slotValue;
  } else {
    // An LContainer anchor can not be `null`, but we set it here temporarily
    // and update to the actual value later in this function (see
    // `_locateOrCreateAnchorNode`).
    lContainer = createLContainer(slotValue, hostLView, null, hostTNode);
    hostLView[hostTNode.index] = lContainer;
    addToEndOfViewTree(hostLView, lContainer);
  }
  _locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  return new R3ViewContainerRef(lContainer, hostTNode, hostLView);
}
/**
 * Creates and inserts a comment node that acts as an anchor for a view container.
 *
 * If the host is a regular element, we have to insert a comment node manually which will
 * be used as an anchor when inserting elements. In this specific case we use low-level DOM
 * manipulation to insert it.
 */
function insertAnchorNode(hostLView, hostTNode) {
  const renderer = hostLView[RENDERER];
  ngDevMode && ngDevMode.rendererCreateComment++;
  const commentNode = renderer.createComment(ngDevMode ? 'container' : '');
  const hostNative = getNativeByTNode(hostTNode, hostLView);
  const parentOfHostNative = nativeParentNode(renderer, hostNative);
  nativeInsertBefore(renderer, parentOfHostNative, commentNode, nativeNextSibling(renderer, hostNative), false);
  return commentNode;
}
let _locateOrCreateAnchorNode = createAnchorNode;
let _populateDehydratedViewsInLContainer = () => false; // noop by default
/**
 * Looks up dehydrated views that belong to a given LContainer and populates
 * this information into the `LContainer[DEHYDRATED_VIEWS]` slot. When running
 * in client-only mode, this function is a noop.
 *
 * @param lContainer LContainer that should be populated.
 * @param tNode Corresponding TNode.
 * @param hostLView LView that hosts LContainer.
 * @returns a boolean flag that indicates whether a populating operation
 *   was successful. The operation might be unsuccessful in case is has completed
 *   previously, we are rendering in client-only mode or this content is located
 *   in a skip hydration section.
 */
function populateDehydratedViewsInLContainer(lContainer, tNode, hostLView) {
  return _populateDehydratedViewsInLContainer(lContainer, tNode, hostLView);
}
/**
 * Regular creation mode: an anchor is created and
 * assigned to the `lContainer[NATIVE]` slot.
 */
function createAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  // We already have a native element (anchor) set, return.
  if (lContainer[NATIVE]) return;
  let commentNode;
  // If the host is an element container, the native host element is guaranteed to be a
  // comment and we can reuse that comment as anchor element for the new LContainer.
  // The comment node in question is already part of the DOM structure so we don't need to append
  // it again.
  if (hostTNode.type & 8 /* TNodeType.ElementContainer */) {
    commentNode = unwrapRNode(slotValue);
  } else {
    commentNode = insertAnchorNode(hostLView, hostTNode);
  }
  lContainer[NATIVE] = commentNode;
}
/**
 * Hydration logic that looks up all dehydrated views in this container
 * and puts them into `lContainer[DEHYDRATED_VIEWS]` slot.
 *
 * @returns a boolean flag that indicates whether a populating operation
 *   was successful. The operation might be unsuccessful in case is has completed
 *   previously, we are rendering in client-only mode or this content is located
 *   in a skip hydration section.
 */
function populateDehydratedViewsInLContainerImpl(lContainer, tNode, hostLView) {
  // We already have a native element (anchor) set and the process
  // of finding dehydrated views happened (so the `lContainer[DEHYDRATED_VIEWS]`
  // is not null), exit early.
  if (lContainer[NATIVE] && lContainer[DEHYDRATED_VIEWS]) {
    return true;
  }
  const hydrationInfo = hostLView[HYDRATION];
  const noOffsetIndex = tNode.index - HEADER_OFFSET;
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock(tNode) || isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  // Regular creation mode.
  if (isNodeCreationMode) {
    return false;
  }
  // Hydration mode, looking up an anchor node and dehydrated views in DOM.
  const currentRNode = getSegmentHead(hydrationInfo, noOffsetIndex);
  const serializedViews = hydrationInfo.data[CONTAINERS]?.[noOffsetIndex];
  ngDevMode && assertDefined(serializedViews, 'Unexpected state: no hydration info available for a given TNode, ' + 'which represents a view container.');
  const [commentNode, dehydratedViews] = locateDehydratedViewsInContainer(currentRNode, serializedViews);
  if (ngDevMode) {
    validateMatchingNode(commentNode, Node.COMMENT_NODE, null, hostLView, tNode, true);
    // Do not throw in case this node is already claimed (thus `false` as a second
    // argument). If this container is created based on an `<ng-template>`, the comment
    // node would be already claimed from the `template` instruction. If an element acts
    // as an anchor (e.g. <div #vcRef>), a separate comment node would be created/located,
    // so we need to claim it here.
    markRNodeAsClaimedByHydration(commentNode, false);
  }
  lContainer[NATIVE] = commentNode;
  lContainer[DEHYDRATED_VIEWS] = dehydratedViews;
  return true;
}
function locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  if (!_populateDehydratedViewsInLContainer(lContainer, hostTNode, hostLView)) {
    // Populating dehydrated views operation returned `false`, which indicates
    // that the logic was running in client-only mode, this an anchor comment
    // node should be created for this container.
    createAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  }
}
function enableLocateOrCreateContainerRefImpl() {
  _locateOrCreateAnchorNode = locateOrCreateAnchorNode;
  _populateDehydratedViewsInLContainer = populateDehydratedViewsInLContainerImpl;
}
class LQuery_ {
  queryList;
  matches = null;
  constructor(queryList) {
    this.queryList = queryList;
  }
  clone() {
    return new LQuery_(this.queryList);
  }
  setDirty() {
    this.queryList.setDirty();
  }
}
class LQueries_ {
  queries;
  constructor(queries = []) {
    this.queries = queries;
  }
  createEmbeddedView(tView) {
    const tQueries = tView.queries;
    if (tQueries !== null) {
      const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
      const viewLQueries = [];
      // An embedded view has queries propagated from a declaration view at the beginning of the
      // TQueries collection and up until a first content query declared in the embedded view. Only
      // propagated LQueries are created at this point (LQuery corresponding to declared content
      // queries will be instantiated from the content query instructions for each directive).
      for (let i = 0; i < noOfInheritedQueries; i++) {
        const tQuery = tQueries.getByIndex(i);
        const parentLQuery = this.queries[tQuery.indexInDeclarationView];
        viewLQueries.push(parentLQuery.clone());
      }
      return new LQueries_(viewLQueries);
    }
    return null;
  }
  insertView(tView) {
    this.dirtyQueriesWithMatches(tView);
  }
  detachView(tView) {
    this.dirtyQueriesWithMatches(tView);
  }
  finishViewCreation(tView) {
    this.dirtyQueriesWithMatches(tView);
  }
  dirtyQueriesWithMatches(tView) {
    for (let i = 0; i < this.queries.length; i++) {
      if (getTQuery(tView, i).matches !== null) {
        this.queries[i].setDirty();
      }
    }
  }
}
class TQueryMetadata_ {
  flags;
  read;
  predicate;
  constructor(predicate, flags, read = null) {
    this.flags = flags;
    this.read = read;
    // Compiler might not be able to pre-optimize and split multiple selectors.
    if (typeof predicate === 'string') {
      this.predicate = splitQueryMultiSelectors(predicate);
    } else {
      this.predicate = predicate;
    }
  }
}
class TQueries_ {
  queries;
  constructor(queries = []) {
    this.queries = queries;
  }
  elementStart(tView, tNode) {
    ngDevMode && assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
    for (let i = 0; i < this.queries.length; i++) {
      this.queries[i].elementStart(tView, tNode);
    }
  }
  elementEnd(tNode) {
    for (let i = 0; i < this.queries.length; i++) {
      this.queries[i].elementEnd(tNode);
    }
  }
  embeddedTView(tNode) {
    let queriesForTemplateRef = null;
    for (let i = 0; i < this.length; i++) {
      const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
      const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
      if (tqueryClone) {
        tqueryClone.indexInDeclarationView = i;
        if (queriesForTemplateRef !== null) {
          queriesForTemplateRef.push(tqueryClone);
        } else {
          queriesForTemplateRef = [tqueryClone];
        }
      }
    }
    return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
  }
  template(tView, tNode) {
    ngDevMode && assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
    for (let i = 0; i < this.queries.length; i++) {
      this.queries[i].template(tView, tNode);
    }
  }
  getByIndex(index) {
    ngDevMode && assertIndexInRange(this.queries, index);
    return this.queries[index];
  }
  get length() {
    return this.queries.length;
  }
  track(tquery) {
    this.queries.push(tquery);
  }
}
class TQuery_ {
  metadata;
  matches = null;
  indexInDeclarationView = /*#__PURE__*/(() => -1)();
  crossesNgTemplate = false;
  /**
   * A node index on which a query was declared (-1 for view queries and ones inherited from the
   * declaration template). We use this index (alongside with _appliesToNextNode flag) to know
   * when to apply content queries to elements in a template.
   */
  _declarationNodeIndex;
  /**
   * A flag indicating if a given query still applies to nodes it is crossing. We use this flag
   * (alongside with _declarationNodeIndex) to know when to stop applying content queries to
   * elements in a template.
   */
  _appliesToNextNode = true;
  constructor(metadata, nodeIndex = -1) {
    this.metadata = metadata;
    this._declarationNodeIndex = nodeIndex;
  }
  elementStart(tView, tNode) {
    if (this.isApplyingToNode(tNode)) {
      this.matchTNode(tView, tNode);
    }
  }
  elementEnd(tNode) {
    if (this._declarationNodeIndex === tNode.index) {
      this._appliesToNextNode = false;
    }
  }
  template(tView, tNode) {
    this.elementStart(tView, tNode);
  }
  embeddedTView(tNode, childQueryIndex) {
    if (this.isApplyingToNode(tNode)) {
      this.crossesNgTemplate = true;
      // A marker indicating a `<ng-template>` element (a placeholder for query results from
      // embedded views created based on this `<ng-template>`).
      this.addMatch(-tNode.index, childQueryIndex);
      return new TQuery_(this.metadata);
    }
    return null;
  }
  isApplyingToNode(tNode) {
    if (this._appliesToNextNode && (this.metadata.flags & 1 /* QueryFlags.descendants */) !== 1 /* QueryFlags.descendants */) {
      const declarationNodeIdx = this._declarationNodeIndex;
      let parent = tNode.parent;
      // Determine if a given TNode is a "direct" child of a node on which a content query was
      // declared (only direct children of query's host node can match with the descendants: false
      // option). There are 3 main use-case / conditions to consider here:
      // - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
      // host node;
      // - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
      // here <i #target> parent node is null;
      // - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
      // to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
      // up past the query's host node!).
      while (parent !== null && parent.type & 8 /* TNodeType.ElementContainer */ && parent.index !== declarationNodeIdx) {
        parent = parent.parent;
      }
      return declarationNodeIdx === (parent !== null ? parent.index : -1);
    }
    return this._appliesToNextNode;
  }
  matchTNode(tView, tNode) {
    const predicate = this.metadata.predicate;
    if (Array.isArray(predicate)) {
      for (let i = 0; i < predicate.length; i++) {
        const name = predicate[i];
        this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name));
        // Also try matching the name to a provider since strings can be used as DI tokens too.
        this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false));
      }
    } else {
      if (predicate === TemplateRef) {
        if (tNode.type & 4 /* TNodeType.Container */) {
          this.matchTNodeWithReadOption(tView, tNode, -1);
        }
      } else {
        this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false));
      }
    }
  }
  matchTNodeWithReadOption(tView, tNode, nodeMatchIdx) {
    if (nodeMatchIdx !== null) {
      const read = this.metadata.read;
      if (read !== null) {
        if (read === ElementRef || read === ViewContainerRef || read === TemplateRef && tNode.type & 4 /* TNodeType.Container */) {
          this.addMatch(tNode.index, -2);
        } else {
          const directiveOrProviderIdx = locateDirectiveOrProvider(tNode, tView, read, false, false);
          if (directiveOrProviderIdx !== null) {
            this.addMatch(tNode.index, directiveOrProviderIdx);
          }
        }
      } else {
        this.addMatch(tNode.index, nodeMatchIdx);
      }
    }
  }
  addMatch(tNodeIdx, matchIdx) {
    if (this.matches === null) {
      this.matches = [tNodeIdx, matchIdx];
    } else {
      this.matches.push(tNodeIdx, matchIdx);
    }
  }
}
/**
 * Iterates over local names for a given node and returns directive index
 * (or -1 if a local name points to an element).
 *
 * @param tNode static data of a node to check
 * @param selector selector to match
 * @returns directive index, -1 or null if a selector didn't match any of the local names
 */
function getIdxOfMatchingSelector(tNode, selector) {
  const localNames = tNode.localNames;
  if (localNames !== null) {
    for (let i = 0; i < localNames.length; i += 2) {
      if (localNames[i] === selector) {
        return localNames[i + 1];
      }
    }
  }
  return null;
}
function createResultByTNodeType(tNode, currentView) {
  if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
    return createElementRef(tNode, currentView);
  } else if (tNode.type & 4 /* TNodeType.Container */) {
    return createTemplateRef(tNode, currentView);
  }
  return null;
}
function createResultForNode(lView, tNode, matchingIdx, read) {
  if (matchingIdx === -1) {
    // if read token and / or strategy is not specified, detect it using appropriate tNode type
    return createResultByTNodeType(tNode, lView);
  } else if (matchingIdx === -2) {
    // read a special token from a node injector
    return createSpecialToken(lView, tNode, read);
  } else {
    // read a token
    return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode);
  }
}
function createSpecialToken(lView, tNode, read) {
  if (read === ElementRef) {
    return createElementRef(tNode, lView);
  } else if (read === TemplateRef) {
    return createTemplateRef(tNode, lView);
  } else if (read === ViewContainerRef) {
    ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
    return createContainerRef(tNode, lView);
  } else {
    ngDevMode && throwError(`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`);
  }
}
/**
 * A helper function that creates query results for a given view. This function is meant to do the
 * processing once and only once for a given view instance (a set of results for a given view
 * doesn't change).
 */
function materializeViewResults(tView, lView, tQuery, queryIndex) {
  const lQuery = lView[QUERIES].queries[queryIndex];
  if (lQuery.matches === null) {
    const tViewData = tView.data;
    const tQueryMatches = tQuery.matches;
    const result = [];
    for (let i = 0; tQueryMatches !== null && i < tQueryMatches.length; i += 2) {
      const matchedNodeIdx = tQueryMatches[i];
      if (matchedNodeIdx < 0) {
        // we at the <ng-template> marker which might have results in views created based on this
        // <ng-template> - those results will be in separate views though, so here we just leave
        // null as a placeholder
        result.push(null);
      } else {
        ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx);
        const tNode = tViewData[matchedNodeIdx];
        result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
      }
    }
    lQuery.matches = result;
  }
  return lQuery.matches;
}
/**
 * A helper function that collects (already materialized) query results from a tree of views,
 * starting with a provided LView.
 */
function collectQueryResults(tView, lView, queryIndex, result) {
  const tQuery = tView.queries.getByIndex(queryIndex);
  const tQueryMatches = tQuery.matches;
  if (tQueryMatches !== null) {
    const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex);
    for (let i = 0; i < tQueryMatches.length; i += 2) {
      const tNodeIdx = tQueryMatches[i];
      if (tNodeIdx > 0) {
        result.push(lViewResults[i / 2]);
      } else {
        const childQueryIndex = tQueryMatches[i + 1];
        const declarationLContainer = lView[-tNodeIdx];
        ngDevMode && assertLContainer(declarationLContainer);
        // collect matches for views inserted in this container
        for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
          const embeddedLView = declarationLContainer[i];
          if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
            collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
          }
        }
        // collect matches for views created from this declaration container and inserted into
        // different containers
        if (declarationLContainer[MOVED_VIEWS] !== null) {
          const embeddedLViews = declarationLContainer[MOVED_VIEWS];
          for (let i = 0; i < embeddedLViews.length; i++) {
            const embeddedLView = embeddedLViews[i];
            collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
          }
        }
      }
    }
  }
  return result;
}
function loadQueryInternal(lView, queryIndex) {
  ngDevMode && assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
  ngDevMode && assertIndexInRange(lView[QUERIES].queries, queryIndex);
  return lView[QUERIES].queries[queryIndex].queryList;
}
/**
 * Creates a new instance of LQuery and returns its index in the collection of LQuery objects.
 *
 * @returns index in the collection of LQuery objects
 */
function createLQuery(tView, lView, flags) {
  const queryList = new QueryList((flags & 4 /* QueryFlags.emitDistinctChangesOnly */) === 4 /* QueryFlags.emitDistinctChangesOnly */);
  storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
  const lQueries = (lView[QUERIES] ??= new LQueries_()).queries;
  return lQueries.push(new LQuery_(queryList)) - 1;
}
function createViewQuery(predicate, flags, read) {
  ngDevMode && assertNumber(flags, 'Expecting flags');
  const tView = getTView();
  if (tView.firstCreatePass) {
    createTQuery(tView, new TQueryMetadata_(predicate, flags, read), -1);
    if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
      tView.staticViewQueries = true;
    }
  }
  return createLQuery(tView, getLView(), flags);
}
function createContentQuery(directiveIndex, predicate, flags, read) {
  ngDevMode && assertNumber(flags, 'Expecting flags');
  const tView = getTView();
  if (tView.firstCreatePass) {
    const tNode = getCurrentTNode();
    createTQuery(tView, new TQueryMetadata_(predicate, flags, read), tNode.index);
    saveContentQueryAndDirectiveIndex(tView, directiveIndex);
    if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
      tView.staticContentQueries = true;
    }
  }
  return createLQuery(tView, getLView(), flags);
}
/** Splits multiple selectors in the locator. */
function splitQueryMultiSelectors(locator) {
  return locator.split(',').map(s => s.trim());
}
function createTQuery(tView, metadata, nodeIndex) {
  if (tView.queries === null) tView.queries = new TQueries_();
  tView.queries.track(new TQuery_(metadata, nodeIndex));
}
function saveContentQueryAndDirectiveIndex(tView, directiveIndex) {
  const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
  const lastSavedDirectiveIndex = tViewContentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1;
  if (directiveIndex !== lastSavedDirectiveIndex) {
    tViewContentQueries.push(tView.queries.length - 1, directiveIndex);
  }
}
function getTQuery(tView, index) {
  ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
  return tView.queries.getByIndex(index);
}
/**
 * A helper function collecting results from all the views where a given query was active.
 * @param lView
 * @param queryIndex
 */
function getQueryResults(lView, queryIndex) {
  const tView = lView[TVIEW];
  const tQuery = getTQuery(tView, queryIndex);
  return tQuery.crossesNgTemplate ? collectQueryResults(tView, lView, queryIndex, []) : materializeViewResults(tView, lView, tQuery, queryIndex);
}

/** Symbol used distinguish `WritableSignal` from other non-writable signals and functions. */
const ɵWRITABLE_SIGNAL = /* @__PURE__ */Symbol('WRITABLE_SIGNAL');
/**
 * Utility function used during template type checking to extract the value from a `WritableSignal`.
 * @codeGenApi
 */
function ɵunwrapWritableSignal(value) {
  // Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`,
  // because the latter incorrectly unwraps non-signal getter functions.
  return null;
}
/**
 * Create a `Signal` that can be set or updated directly.
 */
function signal(initialValue, options) {
  performanceMarkFeature('NgSignals');
  const signalFn = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.createSignal)(initialValue);
  const node = signalFn[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
  if (options?.equal) {
    node.equal = options.equal;
  }
  signalFn.set = newValue => (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalSetFn)(node, newValue);
  signalFn.update = updateFn => (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalUpdateFn)(node, updateFn);
  signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn);
  if (ngDevMode) {
    signalFn.toString = () => `[Signal: ${signalFn()}]`;
    node.debugName = options?.debugName;
  }
  return signalFn;
}
function signalAsReadonlyFn() {
  const node = this[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
  if (node.readonlyFn === undefined) {
    const readonlyFn = () => this();
    readonlyFn[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
    node.readonlyFn = readonlyFn;
  }
  return node.readonlyFn;
}
/**
 * Checks if the given `value` is a writeable signal.
 */
function isWritableSignal(value) {
  return isSignal(value) && typeof value.set === 'function';
}

/**
 * A signal factory function in charge of creating a new computed signal capturing query
 * results. This centralized creation function is used by all types of queries (child / children,
 * required / optional).
 *
 * @param firstOnly indicates if all or only the first result should be returned
 * @param required indicates if at least one result is required
 * @returns a read-only signal with query results
 */
function createQuerySignalFn(firstOnly, required, opts) {
  let node;
  const signalFn = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.createComputed)(() => {
    // A dedicated signal that increments its value every time a query changes its dirty status. By
    // using this signal we can implement a query as computed and avoid creation of a specialized
    // reactive node type. Please note that a query gets marked dirty under the following
    // circumstances:
    // - a view (where a query is active) finished its first creation pass;
    // - a new view is inserted / deleted and it impacts query results.
    node._dirtyCounter();
    const value = refreshSignalQuery(node, firstOnly);
    if (required && value === undefined) {
      throw new RuntimeError(-951 /* RuntimeErrorCode.REQUIRED_QUERY_NO_VALUE */, ngDevMode && 'Child query result is required but no value is available.');
    }
    return value;
  });
  node = signalFn[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
  node._dirtyCounter = signal(0);
  node._flatValue = undefined;
  if (ngDevMode) {
    signalFn.toString = () => `[Query Signal]`;
    node.debugName = opts?.debugName;
  }
  return signalFn;
}
function createSingleResultOptionalQuerySignalFn(opts) {
  return createQuerySignalFn(/* firstOnly */true, /* required */false, opts);
}
function createSingleResultRequiredQuerySignalFn(opts) {
  return createQuerySignalFn(/* firstOnly */true, /* required */true, opts);
}
function createMultiResultQuerySignalFn(opts) {
  return createQuerySignalFn(/* firstOnly */false, /* required */false, opts);
}
function bindQueryToSignal(target, queryIndex) {
  const node = target[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
  node._lView = getLView();
  node._queryIndex = queryIndex;
  node._queryList = loadQueryInternal(node._lView, queryIndex);
  node._queryList.onDirty(() => node._dirtyCounter.update(v => v + 1));
}
function refreshSignalQuery(node, firstOnly) {
  const lView = node._lView;
  const queryIndex = node._queryIndex;
  // There are 2 conditions under which we want to return "empty" results instead of the ones
  // collected by a query:
  //
  // 1) a given query wasn't created yet (this is a period of time between the directive creation
  // and execution of the query creation function) - in this case a query doesn't exist yet and we
  // don't have any results to return.
  //
  // 2) we are in the process of constructing a view (the first
  // creation pass didn't finish) and a query might have partial results, but we don't want to
  // return those - instead we do delay results collection until all nodes had a chance of matching
  // and we can present consistent, "atomic" (on a view level) results.
  if (lView === undefined || queryIndex === undefined || lView[FLAGS] & 4 /* LViewFlags.CreationMode */) {
    return firstOnly ? undefined : EMPTY_ARRAY;
  }
  const queryList = loadQueryInternal(lView, queryIndex);
  const results = getQueryResults(lView, queryIndex);
  queryList.reset(results, unwrapElementRef);
  if (firstOnly) {
    return queryList.first;
  } else {
    // TODO: remove access to the private _changesDetected field by abstracting / removing usage of
    // QueryList in the signal-based queries (perf follow-up)
    const resultChanged = queryList._changesDetected;
    if (resultChanged || node._flatValue === undefined) {
      return node._flatValue = queryList.toArray();
    }
    return node._flatValue;
  }
}
function viewChildFn(locator, opts) {
  ngDevMode && assertInInjectionContext(viewChild);
  return createSingleResultOptionalQuerySignalFn(opts);
}
function viewChildRequiredFn(locator, opts) {
  ngDevMode && assertInInjectionContext(viewChild);
  return createSingleResultRequiredQuerySignalFn(opts);
}
/**
 * Initializes a view child query.
 *
 * Consider using `viewChild.required` for queries that should always match.
 *
 * @usageNotes
 * Create a child query in your component by declaring a
 * class field and initializing it with the `viewChild()` function.
 *
 * ```ts
 * @Component({template: '<div #el></div><my-component #cmp />'})
 * export class TestComponent {
 *   divEl = viewChild<ElementRef>('el');                   // Signal<ElementRef|undefined>
 *   divElRequired = viewChild.required<ElementRef>('el');  // Signal<ElementRef>
 *   cmp = viewChild(MyComponent);                          // Signal<MyComponent|undefined>
 *   cmpRequired = viewChild.required(MyComponent);         // Signal<MyComponent>
 * }
 * ```
 *
 * @publicAPI
 * @initializerApiFunction
 */
const viewChild = /*#__PURE__*/(() => {
  // Note: This may be considered a side-effect, but nothing will depend on
  // this assignment, unless this `viewChild` constant export is accessed. It's a
  // self-contained side effect that is local to the user facing `viewChild` export.
  viewChildFn.required = viewChildRequiredFn;
  return viewChildFn;
})();
/**
 * Initializes a view children query.
 *
 * Query results are represented as a signal of a read-only collection containing all matched
 * elements.
 *
 * @usageNotes
 * Create a children query in your component by declaring a
 * class field and initializing it with the `viewChildren()` function.
 *
 * ```ts
 * @Component({...})
 * export class TestComponent {
 *   divEls = viewChildren<ElementRef>('el');   // Signal<ReadonlyArray<ElementRef>>
 * }
 * ```
 *
 * @initializerApiFunction
 * @publicAPI
 */
function viewChildren(locator, opts) {
  ngDevMode && assertInInjectionContext(viewChildren);
  return createMultiResultQuerySignalFn(opts);
}
function contentChildFn(locator, opts) {
  ngDevMode && assertInInjectionContext(contentChild);
  return createSingleResultOptionalQuerySignalFn(opts);
}
function contentChildRequiredFn(locator, opts) {
  ngDevMode && assertInInjectionContext(contentChildren);
  return createSingleResultRequiredQuerySignalFn(opts);
}
/**
 * Initializes a content child query. Consider using `contentChild.required` for queries that should
 * always match.
 *
 * @usageNotes
 * Create a child query in your component by declaring a
 * class field and initializing it with the `contentChild()` function.
 *
 * ```ts
 * @Component({...})
 * export class TestComponent {
 *   headerEl = contentChild<ElementRef>('h');                    // Signal<ElementRef|undefined>
 *   headerElElRequired = contentChild.required<ElementRef>('h'); // Signal<ElementRef>
 *   header = contentChild(MyHeader);                             // Signal<MyHeader|undefined>
 *   headerRequired = contentChild.required(MyHeader);            // Signal<MyHeader>
 * }
 * ```
 *
 * @initializerApiFunction
 * @publicAPI
 */
const contentChild = /*#__PURE__*/(() => {
  // Note: This may be considered a side-effect, but nothing will depend on
  // this assignment, unless this `viewChild` constant export is accessed. It's a
  // self-contained side effect that is local to the user facing `viewChild` export.
  contentChildFn.required = contentChildRequiredFn;
  return contentChildFn;
})();
/**
 * Initializes a content children query.
 *
 * Query results are represented as a signal of a read-only collection containing all matched
 * elements.
 *
 * @usageNotes
 * Create a children query in your component by declaring a
 * class field and initializing it with the `contentChildren()` function.
 *
 * ```ts
 * @Component({...})
 * export class TestComponent {
 *   headerEl = contentChildren<ElementRef>('h');   // Signal<ReadonlyArray<ElementRef>>
 * }
 * ```
 *
 * @initializerApiFunction
 * @publicAPI
 */
function contentChildren(locator, opts) {
  return createMultiResultQuerySignalFn(opts);
}

/**
 * Creates a model signal.
 *
 * @param initialValue The initial value.
 *   Can be set to {@link REQUIRED_UNSET_VALUE} for required model signals.
 * @param options Additional options for the model.
 */
function createModelSignal(initialValue, opts) {
  const node = Object.create(INPUT_SIGNAL_NODE);
  const emitterRef = new OutputEmitterRef();
  node.value = initialValue;
  function getter() {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerAccessed)(node);
    assertModelSet(node.value);
    return node.value;
  }
  getter[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
  getter.asReadonly = signalAsReadonlyFn.bind(getter);
  // TODO: Should we throw an error when updating a destroyed model?
  getter.set = newValue => {
    if (!node.equal(node.value, newValue)) {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalSetFn)(node, newValue);
      emitterRef.emit(newValue);
    }
  };
  getter.update = updateFn => {
    assertModelSet(node.value);
    getter.set(updateFn(node.value));
  };
  getter.subscribe = emitterRef.subscribe.bind(emitterRef);
  getter.destroyRef = emitterRef.destroyRef;
  if (ngDevMode) {
    getter.toString = () => `[Model Signal: ${getter()}]`;
    node.debugName = opts?.debugName;
  }
  return getter;
}
/** Asserts that a model's value is set. */
function assertModelSet(value) {
  if (value === REQUIRED_UNSET_VALUE) {
    throw new RuntimeError(952 /* RuntimeErrorCode.REQUIRED_MODEL_NO_VALUE */, ngDevMode && 'Model is required but no value is available yet.');
  }
}
function modelFunction(initialValue, opts) {
  ngDevMode && assertInInjectionContext(model);
  return createModelSignal(initialValue, opts);
}
function modelRequiredFunction(opts) {
  ngDevMode && assertInInjectionContext(model);
  return createModelSignal(REQUIRED_UNSET_VALUE, opts);
}
/**
 * `model` declares a writeable signal that is exposed as an input/output
 * pair on the containing directive.
 *
 * The input name is taken either from the class member or from the `alias` option.
 * The output name is generated by taking the input name and appending `Change`.
 *
 * @usageNotes
 *
 * To use `model()`, import the function from `@angular/core`.
 *
 * ```
 * import {model} from '@angular/core`;
 * ```
 *
 * Inside your component, introduce a new class member and initialize
 * it with a call to `model` or `model.required`.
 *
 * ```ts
 * @Directive({
 *   ...
 * })
 * export class MyDir {
 *   firstName = model<string>();            // ModelSignal<string|undefined>
 *   lastName  = model.required<string>();   // ModelSignal<string>
 *   age       = model(0);                   // ModelSignal<number>
 * }
 * ```
 *
 * Inside your component template, you can display the value of a `model`
 * by calling the signal.
 *
 * ```html
 * <span>{{firstName()}}</span>
 * ```
 *
 * Updating the `model` is equivalent to updating a writable signal.
 *
 * ```ts
 * updateName(newFirstName: string): void {
 *   this.firstName.set(newFirstName);
 * }
 * ```
 *
 * @publicAPI
 * @initializerApiFunction
 */
const model = /*#__PURE__*/(() => {
  // Note: This may be considered a side-effect, but nothing will depend on
  // this assignment, unless this `model` constant export is accessed. It's a
  // self-contained side effect that is local to the user facing `model` export.
  modelFunction.required = modelRequiredFunction;
  return modelFunction;
})();

// Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
// explicitly set.
const emitDistinctChangesOnlyDefaultValue = true;
/**
 * Base class for query metadata.
 *
 * @see {@link ContentChildren}
 * @see {@link ContentChild}
 * @see {@link ViewChildren}
 * @see {@link ViewChild}
 *
 * @publicApi
 */
class Query {}
/**
 * ContentChildren decorator and metadata.
 *
 *
 * @Annotation
 * @publicApi
 */
const ContentChildren = /*#__PURE__*/makePropDecorator('ContentChildren', (selector, opts = {}) => ({
  selector,
  first: false,
  isViewQuery: false,
  descendants: false,
  emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  ...opts
}), Query);
/**
 * ContentChild decorator and metadata.
 *
 *
 * @Annotation
 *
 * @publicApi
 */
const ContentChild = /*#__PURE__*/makePropDecorator('ContentChild', (selector, opts = {}) => ({
  selector,
  first: true,
  isViewQuery: false,
  descendants: true,
  ...opts
}), Query);
/**
 * ViewChildren decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const ViewChildren = /*#__PURE__*/makePropDecorator('ViewChildren', (selector, opts = {}) => ({
  selector,
  first: false,
  isViewQuery: true,
  descendants: true,
  emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  ...opts
}), Query);
/**
 * ViewChild decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const ViewChild = /*#__PURE__*/makePropDecorator('ViewChild', (selector, opts) => ({
  selector,
  first: true,
  isViewQuery: true,
  descendants: true,
  ...opts
}), Query);

/**
 * Used to resolve resource URLs on `@Component` when used with JIT compilation.
 *
 * Example:
 * ```
 * @Component({
 *   selector: 'my-comp',
 *   templateUrl: 'my-comp.html', // This requires asynchronous resolution
 * })
 * class MyComponent{
 * }
 *
 * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
 * // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
 *
 * // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
 * // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
 *
 * // Use browser's `fetch()` function as the default resource resolution strategy.
 * resolveComponentResources(fetch).then(() => {
 *   // After resolution all URLs have been converted into `template` strings.
 *   renderComponent(MyComponent);
 * });
 *
 * ```
 *
 * NOTE: In AOT the resolution happens during compilation, and so there should be no need
 * to call this method outside JIT mode.
 *
 * @param resourceResolver a function which is responsible for returning a `Promise` to the
 * contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
 */
function resolveComponentResources(resourceResolver) {
  // Store all promises which are fetching the resources.
  const componentResolved = [];
  // Cache so that we don't fetch the same resource more than once.
  const urlMap = new Map();
  function cachedResourceResolve(url) {
    let promise = urlMap.get(url);
    if (!promise) {
      const resp = resourceResolver(url);
      urlMap.set(url, promise = resp.then(unwrapResponse));
    }
    return promise;
  }
  componentResourceResolutionQueue.forEach((component, type) => {
    const promises = [];
    if (component.templateUrl) {
      promises.push(cachedResourceResolve(component.templateUrl).then(template => {
        component.template = template;
      }));
    }
    const styles = typeof component.styles === 'string' ? [component.styles] : component.styles || [];
    component.styles = styles;
    if (component.styleUrl && component.styleUrls?.length) {
      throw new Error('@Component cannot define both `styleUrl` and `styleUrls`. ' + 'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple');
    } else if (component.styleUrls?.length) {
      const styleOffset = component.styles.length;
      const styleUrls = component.styleUrls;
      component.styleUrls.forEach((styleUrl, index) => {
        styles.push(''); // pre-allocate array.
        promises.push(cachedResourceResolve(styleUrl).then(style => {
          styles[styleOffset + index] = style;
          styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
          if (styleUrls.length == 0) {
            component.styleUrls = undefined;
          }
        }));
      });
    } else if (component.styleUrl) {
      promises.push(cachedResourceResolve(component.styleUrl).then(style => {
        styles.push(style);
        component.styleUrl = undefined;
      }));
    }
    const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type));
    componentResolved.push(fullyResolved);
  });
  clearResolutionOfComponentResourcesQueue();
  return Promise.all(componentResolved).then(() => undefined);
}
let componentResourceResolutionQueue = /*#__PURE__*/new Map();
// Track when existing ɵcmp for a Type is waiting on resources.
const componentDefPendingResolution = /*#__PURE__*/new Set();
function maybeQueueResolutionOfComponentResources(type, metadata) {
  if (componentNeedsResolution(metadata)) {
    componentResourceResolutionQueue.set(type, metadata);
    componentDefPendingResolution.add(type);
  }
}
function isComponentDefPendingResolution(type) {
  return componentDefPendingResolution.has(type);
}
function componentNeedsResolution(component) {
  return !!(component.templateUrl && !component.hasOwnProperty('template') || component.styleUrls && component.styleUrls.length || component.styleUrl);
}
function clearResolutionOfComponentResourcesQueue() {
  const old = componentResourceResolutionQueue;
  componentResourceResolutionQueue = new Map();
  return old;
}
function restoreComponentResolutionQueue(queue) {
  componentDefPendingResolution.clear();
  queue.forEach((_, type) => componentDefPendingResolution.add(type));
  componentResourceResolutionQueue = queue;
}
function isComponentResourceResolutionQueueEmpty() {
  return componentResourceResolutionQueue.size === 0;
}
function unwrapResponse(response) {
  return typeof response == 'string' ? response : response.text();
}
function componentDefResolved(type) {
  componentDefPendingResolution.delete(type);
}

/**
 * Map of module-id to the corresponding NgModule.
 */
const modules = /*#__PURE__*/new Map();
/**
 * Whether to check for duplicate NgModule registrations.
 *
 * This can be disabled for testing.
 */
let checkForDuplicateNgModules = true;
function assertSameOrNotExisting(id, type, incoming) {
  if (type && type !== incoming && checkForDuplicateNgModules) {
    throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
  }
}
/**
 * Adds the given NgModule type to Angular's NgModule registry.
 *
 * This is generated as a side-effect of NgModule compilation. Note that the `id` is passed in
 * explicitly and not read from the NgModule definition. This is for two reasons: it avoids a
 * megamorphic read, and in JIT there's a chicken-and-egg problem where the NgModule may not be
 * fully resolved when it's registered.
 *
 * @codeGenApi
 */
function registerNgModuleType(ngModuleType, id) {
  const existing = modules.get(id) || null;
  assertSameOrNotExisting(id, existing, ngModuleType);
  modules.set(id, ngModuleType);
}
function clearModulesForTest() {
  modules.clear();
}
function getRegisteredNgModuleType(id) {
  return modules.get(id);
}
/**
 * Control whether the NgModule registration system enforces that each NgModule type registered has
 * a unique id.
 *
 * This is useful for testing as the NgModule registry cannot be properly reset between tests with
 * Angular's current API.
 */
function setAllowDuplicateNgModuleIdsForTest(allowDuplicates) {
  checkForDuplicateNgModules = !allowDuplicates;
}

/**
 * Validation function invoked at runtime for each binding that might potentially
 * represent a security-sensitive attribute of an <iframe>.
 * See `IFRAME_SECURITY_SENSITIVE_ATTRS` in the
 * `packages/compiler/src/schema/dom_security_schema.ts` script for the full list
 * of such attributes.
 *
 * @codeGenApi
 */
function ɵɵvalidateIframeAttribute(attrValue, tagName, attrName) {
  const lView = getLView();
  const tNode = getSelectedTNode();
  const element = getNativeByTNode(tNode, lView);
  // Restrict any dynamic bindings of security-sensitive attributes/properties
  // on an <iframe> for security reasons.
  if (tNode.type === 2 /* TNodeType.Element */ && tagName.toLowerCase() === 'iframe') {
    const iframe = element;
    // Unset previously applied `src` and `srcdoc` if we come across a situation when
    // a security-sensitive attribute is set later via an attribute/property binding.
    iframe.src = '';
    iframe.srcdoc = trustedHTMLFromString('');
    // Also remove the <iframe> from the document.
    nativeRemoveNode(lView[RENDERER], iframe);
    const errorMessage = ngDevMode && `Angular has detected that the \`${attrName}\` was applied ` + `as a binding to an <iframe>${getTemplateLocationDetails(lView)}. ` + `For security reasons, the \`${attrName}\` can be set on an <iframe> ` + `as a static attribute only. \n` + `To fix this, switch the \`${attrName}\` binding to a static attribute ` + `in a template or in host bindings section.`;
    throw new RuntimeError(-910 /* RuntimeErrorCode.UNSAFE_IFRAME_ATTRS */, errorMessage);
  }
  return attrValue;
}
function getSuperType(type) {
  return Object.getPrototypeOf(type.prototype).constructor;
}
/**
 * Merges the definition from a super class to a sub class.
 * @param definition The definition that is a SubClass of another directive of component
 *
 * @codeGenApi
 */
function ɵɵInheritDefinitionFeature(definition) {
  let superType = getSuperType(definition.type);
  let shouldInheritFields = true;
  const inheritanceChain = [definition];
  while (superType) {
    let superDef = undefined;
    if (isComponentDef(definition)) {
      // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
      superDef = superType.ɵcmp || superType.ɵdir;
    } else {
      if (superType.ɵcmp) {
        throw new RuntimeError(903 /* RuntimeErrorCode.INVALID_INHERITANCE */, ngDevMode && `Directives cannot inherit Components. Directive ${stringifyForError(definition.type)} is attempting to extend component ${stringifyForError(superType)}`);
      }
      // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
      superDef = superType.ɵdir;
    }
    if (superDef) {
      if (shouldInheritFields) {
        inheritanceChain.push(superDef);
        // Some fields in the definition may be empty, if there were no values to put in them that
        // would've justified object creation. Unwrap them if necessary.
        const writeableDef = definition;
        writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
        writeableDef.inputTransforms = maybeUnwrapEmpty(definition.inputTransforms);
        writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
        writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
        // Merge hostBindings
        const superHostBindings = superDef.hostBindings;
        superHostBindings && inheritHostBindings(definition, superHostBindings);
        // Merge queries
        const superViewQuery = superDef.viewQuery;
        const superContentQueries = superDef.contentQueries;
        superViewQuery && inheritViewQuery(definition, superViewQuery);
        superContentQueries && inheritContentQueries(definition, superContentQueries);
        // Merge inputs and outputs
        mergeInputsWithTransforms(definition, superDef);
        fillProperties(definition.outputs, superDef.outputs);
        // Merge animations metadata.
        // If `superDef` is a Component, the `data` field is present (defaults to an empty object).
        if (isComponentDef(superDef) && superDef.data.animation) {
          // If super def is a Component, the `definition` is also a Component, since Directives can
          // not inherit Components (we throw an error above and cannot reach this code).
          const defData = definition.data;
          defData.animation = (defData.animation || []).concat(superDef.data.animation);
        }
      }
      // Run parent features
      const features = superDef.features;
      if (features) {
        for (let i = 0; i < features.length; i++) {
          const feature = features[i];
          if (feature && feature.ngInherit) {
            feature(definition);
          }
          // If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
          // def already has all the necessary information inherited from its super class(es), so we
          // can stop merging fields from super classes. However we need to iterate through the
          // prototype chain to look for classes that might contain other "features" (like
          // NgOnChanges), which we should invoke for the original `definition`. We set the
          // `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
          // logic and only invoking functions from the "features" list.
          if (feature === ɵɵInheritDefinitionFeature) {
            shouldInheritFields = false;
          }
        }
      }
    }
    superType = Object.getPrototypeOf(superType);
  }
  mergeHostAttrsAcrossInheritance(inheritanceChain);
}
function mergeInputsWithTransforms(target, source) {
  for (const key in source.inputs) {
    if (!source.inputs.hasOwnProperty(key)) {
      continue;
    }
    if (target.inputs.hasOwnProperty(key)) {
      continue;
    }
    const value = source.inputs[key];
    if (value === undefined) {
      continue;
    }
    target.inputs[key] = value;
    target.declaredInputs[key] = source.declaredInputs[key];
    // If the input is inherited, and we have a transform for it, we also inherit it.
    // Note that transforms should not be inherited if the input has its own metadata
    // in the `source` directive itself already (i.e. the input is re-declared/overridden).
    if (source.inputTransforms !== null) {
      // Note: transforms are stored with their minified names.
      // Perf: only access the minified name when there are source transforms.
      const minifiedName = Array.isArray(value) ? value[0] : value;
      if (!source.inputTransforms.hasOwnProperty(minifiedName)) {
        continue;
      }
      target.inputTransforms ??= {};
      target.inputTransforms[minifiedName] = source.inputTransforms[minifiedName];
    }
  }
}
/**
 * Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
 *
 * @param inheritanceChain A list of `WritableDefs` starting at the top most type and listing
 * sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
 * type.
 */
function mergeHostAttrsAcrossInheritance(inheritanceChain) {
  let hostVars = 0;
  let hostAttrs = null;
  // We process the inheritance order from the base to the leaves here.
  for (let i = inheritanceChain.length - 1; i >= 0; i--) {
    const def = inheritanceChain[i];
    // For each `hostVars`, we need to add the superclass amount.
    def.hostVars = hostVars += def.hostVars;
    // for each `hostAttrs` we need to merge it with superclass.
    def.hostAttrs = mergeHostAttrs(def.hostAttrs, hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs));
  }
}
function maybeUnwrapEmpty(value) {
  if (value === EMPTY_OBJ) {
    return {};
  } else if (value === EMPTY_ARRAY) {
    return [];
  } else {
    return value;
  }
}
function inheritViewQuery(definition, superViewQuery) {
  const prevViewQuery = definition.viewQuery;
  if (prevViewQuery) {
    definition.viewQuery = (rf, ctx) => {
      superViewQuery(rf, ctx);
      prevViewQuery(rf, ctx);
    };
  } else {
    definition.viewQuery = superViewQuery;
  }
}
function inheritContentQueries(definition, superContentQueries) {
  const prevContentQueries = definition.contentQueries;
  if (prevContentQueries) {
    definition.contentQueries = (rf, ctx, directiveIndex) => {
      superContentQueries(rf, ctx, directiveIndex);
      prevContentQueries(rf, ctx, directiveIndex);
    };
  } else {
    definition.contentQueries = superContentQueries;
  }
}
function inheritHostBindings(definition, superHostBindings) {
  const prevHostBindings = definition.hostBindings;
  if (prevHostBindings) {
    definition.hostBindings = (rf, ctx) => {
      superHostBindings(rf, ctx);
      prevHostBindings(rf, ctx);
    };
  } else {
    definition.hostBindings = superHostBindings;
  }
}

/**
 * Fields which exist on either directive or component definitions, and need to be copied from
 * parent to child classes by the `ɵɵCopyDefinitionFeature`.
 */
const COPY_DIRECTIVE_FIELDS = [
// The child class should use the providers of its parent.
'providersResolver'
// Not listed here are any fields which are handled by the `ɵɵInheritDefinitionFeature`, such
// as inputs, outputs, and host binding functions.
];
/**
 * Fields which exist only on component definitions, and need to be copied from parent to child
 * classes by the `ɵɵCopyDefinitionFeature`.
 *
 * The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
 * since those should go in `COPY_DIRECTIVE_FIELDS` above.
 */
const COPY_COMPONENT_FIELDS = [
// The child class should use the template function of its parent, including all template
// semantics.
'template', 'decls', 'consts', 'vars', 'onPush', 'ngContentSelectors',
// The child class should use the CSS styles of its parent, including all styling semantics.
'styles', 'encapsulation',
// The child class should be checked by the runtime in the same way as its parent.
'schemas'];
/**
 * Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
 * definition.
 *
 * This exists primarily to support ngcc migration of an existing View Engine pattern, where an
 * entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
 * generates a skeleton definition on the child class, and applies this feature.
 *
 * The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
 * including things like the component template function.
 *
 * @param definition The definition of a child class which inherits from a parent class with its
 * own definition.
 *
 * @codeGenApi
 */
function ɵɵCopyDefinitionFeature(definition) {
  let superType = getSuperType(definition.type);
  let superDef = undefined;
  if (isComponentDef(definition)) {
    // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
    superDef = superType.ɵcmp;
  } else {
    // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
    superDef = superType.ɵdir;
  }
  // Needed because `definition` fields are readonly.
  const defAny = definition;
  // Copy over any fields that apply to either directives or components.
  for (const field of COPY_DIRECTIVE_FIELDS) {
    defAny[field] = superDef[field];
  }
  if (isComponentDef(superDef)) {
    // Copy over any component-specific fields.
    for (const field of COPY_COMPONENT_FIELDS) {
      defAny[field] = superDef[field];
    }
  }
}

/**
 * This feature adds the host directives behavior to a directive definition by patching a
 * function onto it. The expectation is that the runtime will invoke the function during
 * directive matching.
 *
 * For example:
 * ```ts
 * class ComponentWithHostDirective {
 *   static ɵcmp = defineComponent({
 *    type: ComponentWithHostDirective,
 *    features: [ɵɵHostDirectivesFeature([
 *      SimpleHostDirective,
 *      {directive: AdvancedHostDirective, inputs: ['foo: alias'], outputs: ['bar']},
 *    ])]
 *  });
 * }
 * ```
 *
 * @codeGenApi
 */
function ɵɵHostDirectivesFeature(rawHostDirectives) {
  const feature = definition => {
    const isEager = Array.isArray(rawHostDirectives);
    if (definition.hostDirectives === null) {
      definition.findHostDirectiveDefs = findHostDirectiveDefs;
      definition.hostDirectives = isEager ? rawHostDirectives.map(createHostDirectiveDef) : [rawHostDirectives];
    } else if (isEager) {
      definition.hostDirectives.unshift(...rawHostDirectives.map(createHostDirectiveDef));
    } else {
      definition.hostDirectives.unshift(rawHostDirectives);
    }
  };
  feature.ngInherit = true;
  return feature;
}
function findHostDirectiveDefs(currentDef, matchedDefs, hostDirectiveDefs) {
  if (currentDef.hostDirectives !== null) {
    for (const configOrFn of currentDef.hostDirectives) {
      if (typeof configOrFn === 'function') {
        const resolved = configOrFn();
        for (const config of resolved) {
          trackHostDirectiveDef(createHostDirectiveDef(config), matchedDefs, hostDirectiveDefs);
        }
      } else {
        trackHostDirectiveDef(configOrFn, matchedDefs, hostDirectiveDefs);
      }
    }
  }
}
/** Tracks a single host directive during directive matching. */
function trackHostDirectiveDef(def, matchedDefs, hostDirectiveDefs) {
  const hostDirectiveDef = getDirectiveDef(def.directive);
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    validateHostDirective(def, hostDirectiveDef);
  }
  // We need to patch the `declaredInputs` so that
  // `ngOnChanges` can map the properties correctly.
  patchDeclaredInputs(hostDirectiveDef.declaredInputs, def.inputs);
  // Host directives execute before the host so that its host bindings can be overwritten.
  findHostDirectiveDefs(hostDirectiveDef, matchedDefs, hostDirectiveDefs);
  hostDirectiveDefs.set(hostDirectiveDef, def);
  matchedDefs.push(hostDirectiveDef);
}
/** Creates a `HostDirectiveDef` from a used-defined host directive configuration. */
function createHostDirectiveDef(config) {
  return typeof config === 'function' ? {
    directive: resolveForwardRef(config),
    inputs: EMPTY_OBJ,
    outputs: EMPTY_OBJ
  } : {
    directive: resolveForwardRef(config.directive),
    inputs: bindingArrayToMap(config.inputs),
    outputs: bindingArrayToMap(config.outputs)
  };
}
/**
 * Converts an array in the form of `['publicName', 'alias', 'otherPublicName', 'otherAlias']` into
 * a map in the form of `{publicName: 'alias', otherPublicName: 'otherAlias'}`.
 */
function bindingArrayToMap(bindings) {
  if (bindings === undefined || bindings.length === 0) {
    return EMPTY_OBJ;
  }
  const result = {};
  for (let i = 0; i < bindings.length; i += 2) {
    result[bindings[i]] = bindings[i + 1];
  }
  return result;
}
/**
 * `ngOnChanges` has some leftover legacy ViewEngine behavior where the keys inside the
 * `SimpleChanges` event refer to the *declared* name of the input, not its public name or its
 * minified name. E.g. in `@Input('alias') foo: string`, the name in the `SimpleChanges` object
 * will always be `foo`, and not `alias` or the minified name of `foo` in apps using property
 * minification.
 *
 * This is achieved through the `DirectiveDef.declaredInputs` map that is constructed when the
 * definition is declared. When a property is written to the directive instance, the
 * `NgOnChangesFeature` will try to remap the property name being written to using the
 * `declaredInputs`.
 *
 * Since the host directive input remapping happens during directive matching, `declaredInputs`
 * won't contain the new alias that the input is available under. This function addresses the
 * issue by patching the host directive aliases to the `declaredInputs`. There is *not* a risk of
 * this patching accidentally introducing new inputs to the host directive, because `declaredInputs`
 * is used *only* by the `NgOnChangesFeature` when determining what name is used in the
 * `SimpleChanges` object which won't be reached if an input doesn't exist.
 */
function patchDeclaredInputs(declaredInputs, exposedInputs) {
  for (const publicName in exposedInputs) {
    if (exposedInputs.hasOwnProperty(publicName)) {
      const remappedPublicName = exposedInputs[publicName];
      const privateName = declaredInputs[publicName];
      // We *technically* shouldn't be able to hit this case because we can't have multiple
      // inputs on the same property and we have validations against conflicting aliases in
      // `validateMappings`. If we somehow did, it would lead to `ngOnChanges` being invoked
      // with the wrong name so we have a non-user-friendly assertion here just in case.
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && declaredInputs.hasOwnProperty(remappedPublicName)) {
        assertEqual(declaredInputs[remappedPublicName], declaredInputs[publicName], `Conflicting host directive input alias ${publicName}.`);
      }
      declaredInputs[remappedPublicName] = privateName;
    }
  }
}
/**
 * Verifies that the host directive has been configured correctly.
 * @param hostDirectiveConfig Host directive configuration object.
 * @param directiveDef Directive definition of the host directive.
 */
function validateHostDirective(hostDirectiveConfig, directiveDef) {
  const type = hostDirectiveConfig.directive;
  if (directiveDef === null) {
    if (getComponentDef(type) !== null) {
      throw new RuntimeError(310 /* RuntimeErrorCode.HOST_DIRECTIVE_COMPONENT */, `Host directive ${type.name} cannot be a component.`);
    }
    throw new RuntimeError(307 /* RuntimeErrorCode.HOST_DIRECTIVE_UNRESOLVABLE */, `Could not resolve metadata for host directive ${type.name}. ` + `Make sure that the ${type.name} class is annotated with an @Directive decorator.`);
  }
  if (!directiveDef.standalone) {
    throw new RuntimeError(308 /* RuntimeErrorCode.HOST_DIRECTIVE_NOT_STANDALONE */, `Host directive ${directiveDef.type.name} must be standalone.`);
  }
  validateMappings('input', directiveDef, hostDirectiveConfig.inputs);
  validateMappings('output', directiveDef, hostDirectiveConfig.outputs);
}
/**
 * Checks that the host directive inputs/outputs configuration is valid.
 * @param bindingType Kind of binding that is being validated. Used in the error message.
 * @param def Definition of the host directive that is being validated against.
 * @param hostDirectiveBindings Host directive mapping object that shold be validated.
 */
function validateMappings(bindingType, def, hostDirectiveBindings) {
  const className = def.type.name;
  const bindings = bindingType === 'input' ? def.inputs : def.outputs;
  for (const publicName in hostDirectiveBindings) {
    if (hostDirectiveBindings.hasOwnProperty(publicName)) {
      if (!bindings.hasOwnProperty(publicName)) {
        throw new RuntimeError(311 /* RuntimeErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING */, `Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`);
      }
      const remappedPublicName = hostDirectiveBindings[publicName];
      if (bindings.hasOwnProperty(remappedPublicName) && remappedPublicName !== publicName) {
        throw new RuntimeError(312 /* RuntimeErrorCode.HOST_DIRECTIVE_CONFLICTING_ALIAS */, `Cannot alias ${bindingType} ${publicName} of host directive ${className} to ${remappedPublicName}, because it already has a different ${bindingType} with the same public name.`);
      }
    }
  }
}

/**
 * Decorates the directive definition with support for input transform functions.
 *
 * If the directive uses inheritance, the feature should be included before the
 * `InheritDefinitionFeature` to ensure that the `inputTransforms` field is populated.
 *
 * @codeGenApi
 */
function ɵɵInputTransformsFeature(definition) {
  const inputs = definition.inputConfig;
  const inputTransforms = {};
  for (const minifiedKey in inputs) {
    if (inputs.hasOwnProperty(minifiedKey)) {
      // Note: the private names are used for the keys, rather than the public ones, because public
      // names can be re-aliased in host directives which would invalidate the lookup.
      const value = inputs[minifiedKey];
      if (Array.isArray(value) && value[3]) {
        inputTransforms[minifiedKey] = value[3];
      }
    }
  }
  definition.inputTransforms = inputTransforms;
}
function isIterable(obj) {
  return obj !== null && typeof obj === 'object' && obj[Symbol.iterator] !== undefined;
}
function isListLikeIterable(obj) {
  if (!isJsObject(obj)) return false;
  return Array.isArray(obj) || !(obj instanceof Map) &&
  // JS Map are iterables but return entries as [k, v]
  Symbol.iterator in obj; // JS Iterable have a Symbol.iterator prop
}
function areIterablesEqual(a, b, comparator) {
  const iterator1 = a[Symbol.iterator]();
  const iterator2 = b[Symbol.iterator]();
  while (true) {
    const item1 = iterator1.next();
    const item2 = iterator2.next();
    if (item1.done && item2.done) return true;
    if (item1.done || item2.done) return false;
    if (!comparator(item1.value, item2.value)) return false;
  }
}
function iterateListLike(obj, fn) {
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      fn(obj[i]);
    }
  } else {
    const iterator = obj[Symbol.iterator]();
    let item;
    while (!(item = iterator.next()).done) {
      fn(item.value);
    }
  }
}
function isJsObject(o) {
  return o !== null && (typeof o === 'function' || typeof o === 'object');
}
function devModeEqual(a, b) {
  const isListLikeIterableA = isListLikeIterable(a);
  const isListLikeIterableB = isListLikeIterable(b);
  if (isListLikeIterableA && isListLikeIterableB) {
    return areIterablesEqual(a, b, devModeEqual);
  } else {
    const isAObject = a && (typeof a === 'object' || typeof a === 'function');
    const isBObject = b && (typeof b === 'object' || typeof b === 'function');
    if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
      return true;
    } else {
      return Object.is(a, b);
    }
  }
}

// TODO(misko): consider inlining
/** Updates binding and returns the value. */
function updateBinding(lView, bindingIndex, value) {
  return lView[bindingIndex] = value;
}
/** Gets the current binding value. */
function getBinding(lView, bindingIndex) {
  ngDevMode && assertIndexInRange(lView, bindingIndex);
  ngDevMode && assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.');
  return lView[bindingIndex];
}
/**
 * Updates binding if changed, then returns whether it was updated.
 *
 * This function also checks the `CheckNoChangesMode` and throws if changes are made.
 * Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE
 * behavior.
 *
 * @param lView current `LView`
 * @param bindingIndex The binding in the `LView` to check
 * @param value New value to check against `lView[bindingIndex]`
 * @returns `true` if the bindings has changed. (Throws if binding has changed during
 *          `CheckNoChangesMode`)
 */
function bindingUpdated(lView, bindingIndex, value) {
  ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  ngDevMode && assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`);
  const oldValue = lView[bindingIndex];
  if (Object.is(oldValue, value)) {
    return false;
  } else {
    if (ngDevMode && isInCheckNoChangesMode()) {
      // View engine didn't report undefined values as changed on the first checkNoChanges pass
      // (before the change detection was run).
      const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined;
      if (!devModeEqual(oldValueToCompare, value)) {
        const details = getExpressionChangedErrorDetails(lView, bindingIndex, oldValueToCompare, value);
        throwErrorIfNoChangesMode(oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName, lView);
      }
      // There was a change, but the `devModeEqual` decided that the change is exempt from an error.
      // For this reason we exit as if no change. The early exit is needed to prevent the changed
      // value to be written into `LView` (If we would write the new value that we would not see it
      // as change on next CD.)
      return false;
    }
    lView[bindingIndex] = value;
    return true;
  }
}
/** Updates 2 bindings if changed, then returns whether either was updated. */
function bindingUpdated2(lView, bindingIndex, exp1, exp2) {
  const different = bindingUpdated(lView, bindingIndex, exp1);
  return bindingUpdated(lView, bindingIndex + 1, exp2) || different;
}
/** Updates 3 bindings if changed, then returns whether any was updated. */
function bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) {
  const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  return bindingUpdated(lView, bindingIndex + 2, exp3) || different;
}
/** Updates 4 bindings if changed, then returns whether any was updated. */
function bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) {
  const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different;
}

/**
 * Checks whether a TNode is considered detached, i.e. not present in the
 * translated i18n template. We should not attempt hydration for such nodes
 * and instead, use a regular "creation mode".
 */
function isDetachedByI18n(tNode) {
  return (tNode.flags & 32 /* TNodeFlags.isDetached */) === 32 /* TNodeFlags.isDetached */;
}
function templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrs, localRefsIndex) {
  ngDevMode && assertFirstCreatePass(tView);
  ngDevMode && ngDevMode.firstCreatePass++;
  const tViewConsts = tView.consts;
  // TODO(pk): refactor getOrCreateTNode to have the "create" only version
  const tNode = getOrCreateTNode(tView, index, 4 /* TNodeType.Container */, tagName || null, attrs || null);
  resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
  registerPostOrderHooks(tView, tNode);
  const embeddedTView = tNode.tView = createTView(2 /* TViewType.Embedded */, tNode, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts, null /* ssrId */);
  if (tView.queries !== null) {
    tView.queries.template(tView, tNode);
    embeddedTView.queries = tView.queries.embeddedTView(tNode);
  }
  return tNode;
}
/**
 * Creates an LContainer for an embedded view.
 *
 * @param declarationLView LView in which the template was declared.
 * @param declarationTView TView in which the template wa declared.
 * @param index The index of the container in the data array
 * @param templateFn Inline template
 * @param decls The number of nodes, local refs, and pipes for this template
 * @param vars The number of bindings for this template
 * @param tagName The name of the container element, if applicable
 * @param attrsIndex Index of template attributes in the `consts` array.
 * @param localRefs Index of the local references in the `consts` array.
 * @param localRefExtractor A function which extracts local-refs values from the template.
 *        Defaults to the current element associated with the local-ref.
 */
function declareTemplate(declarationLView, declarationTView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor) {
  const adjustedIndex = index + HEADER_OFFSET;
  const tNode = declarationTView.firstCreatePass ? templateFirstCreatePass(adjustedIndex, declarationTView, declarationLView, templateFn, decls, vars, tagName, attrs, localRefsIndex) : declarationTView.data[adjustedIndex];
  setCurrentTNode(tNode, false);
  const comment = _locateOrCreateContainerAnchor(declarationTView, declarationLView, tNode, index);
  if (wasLastNodeCreated()) {
    appendChild(declarationTView, declarationLView, comment, tNode);
  }
  attachPatchData(comment, declarationLView);
  const lContainer = createLContainer(comment, declarationLView, comment, tNode);
  declarationLView[adjustedIndex] = lContainer;
  addToEndOfViewTree(declarationLView, lContainer);
  // If hydration is enabled, looks up dehydrated views in the DOM
  // using hydration annotation info and stores those views on LContainer.
  // In client-only mode, this function is a noop.
  populateDehydratedViewsInLContainer(lContainer, tNode, declarationLView);
  if (isDirectiveHost(tNode)) {
    createDirectivesInstances(declarationTView, declarationLView, tNode);
  }
  if (localRefsIndex != null) {
    saveResolvedLocalsInData(declarationLView, tNode, localRefExtractor);
  }
  return tNode;
}
/**
 * Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
 *
 * <ng-template #foo>
 *    <div></div>
 * </ng-template>
 *
 * @param index The index of the container in the data array
 * @param templateFn Inline template
 * @param decls The number of nodes, local refs, and pipes for this template
 * @param vars The number of bindings for this template
 * @param tagName The name of the container element, if applicable
 * @param attrsIndex Index of template attributes in the `consts` array.
 * @param localRefs Index of the local references in the `consts` array.
 * @param localRefExtractor A function which extracts local-refs values from the template.
 *        Defaults to the current element associated with the local-ref.
 *
 * @codeGenApi
 */
function ɵɵtemplate(index, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex, localRefExtractor) {
  const lView = getLView();
  const tView = getTView();
  const attrs = getConstant(tView.consts, attrsIndex);
  declareTemplate(lView, tView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor);
  return ɵɵtemplate;
}
let _locateOrCreateContainerAnchor = createContainerAnchorImpl;
/**
 * Regular creation mode for LContainers and their anchor (comment) nodes.
 */
function createContainerAnchorImpl(tView, lView, tNode, index) {
  lastNodeWasCreated(true);
  return lView[RENDERER].createComment(ngDevMode ? 'container' : '');
}
/**
 * Enables hydration code path (to lookup existing elements in DOM)
 * in addition to the regular creation mode for LContainers and their
 * anchor (comment) nodes.
 */
function locateOrCreateContainerAnchorImpl(tView, lView, tNode, index) {
  const hydrationInfo = lView[HYDRATION];
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1() || isDetachedByI18n(tNode) || isDisconnectedNode$1(hydrationInfo, index);
  lastNodeWasCreated(isNodeCreationMode);
  // Regular creation mode.
  if (isNodeCreationMode) {
    return createContainerAnchorImpl(tView, lView, tNode, index);
  }
  const ssrId = hydrationInfo.data[TEMPLATES]?.[index] ?? null;
  // Apply `ssrId` value to the underlying TView if it was not previously set.
  //
  // There might be situations when the same component is present in a template
  // multiple times and some instances are opted-out of using hydration via
  // `ngSkipHydration` attribute. In this scenario, at the time a TView is created,
  // the `ssrId` might be `null` (if the first component is opted-out of hydration).
  // The code below makes sure that the `ssrId` is applied to the TView if it's still
  // `null` and verifies we never try to override it with a different value.
  if (ssrId !== null && tNode.tView !== null) {
    if (tNode.tView.ssrId === null) {
      tNode.tView.ssrId = ssrId;
    } else {
      ngDevMode && assertEqual(tNode.tView.ssrId, ssrId, 'Unexpected value of the `ssrId` for this TView');
    }
  }
  // Hydration mode, looking up existing elements in DOM.
  const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  setSegmentHead(hydrationInfo, index, currentRNode);
  const viewContainerSize = calcSerializedContainerSize(hydrationInfo, index);
  const comment = siblingAfter(viewContainerSize, currentRNode);
  if (ngDevMode) {
    validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
    markRNodeAsClaimedByHydration(comment);
  }
  return comment;
}
function enableLocateOrCreateContainerAnchorImpl() {
  _locateOrCreateContainerAnchor = locateOrCreateContainerAnchorImpl;
}

/**
 * Helper function to schedule a callback to be invoked when a browser becomes idle.
 *
 * @param callback A function to be invoked when a browser becomes idle.
 * @param injector injector for the app
 */
function onIdle(callback, injector) {
  const scheduler = injector.get(IdleScheduler);
  const cleanupFn = () => scheduler.remove(callback);
  scheduler.add(callback);
  return cleanupFn;
}
/**
 * Use shims for the `requestIdleCallback` and `cancelIdleCallback` functions for
 * environments where those functions are not available (e.g. Node.js and Safari).
 *
 * Note: we wrap the `requestIdleCallback` call into a function, so that it can be
 * overridden/mocked in test environment and picked up by the runtime code.
 */
const _requestIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout;
const _cancelIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? cancelIdleCallback : clearTimeout;
/**
 * Helper service to schedule `requestIdleCallback`s for batches of defer blocks,
 * to avoid calling `requestIdleCallback` for each defer block (e.g. if
 * defer blocks are defined inside a for loop).
 */
let IdleScheduler = /*#__PURE__*/(() => {
  class IdleScheduler {
    // Indicates whether current callbacks are being invoked.
    executingCallbacks = false;
    // Currently scheduled idle callback id.
    idleId = null;
    // Set of callbacks to be invoked next.
    current = (() => new Set())();
    // Set of callbacks collected while invoking current set of callbacks.
    // Those callbacks are scheduled for the next idle period.
    deferred = (() => new Set())();
    ngZone = (() => inject(NgZone))();
    requestIdleCallbackFn = (() => _requestIdleCallback().bind(globalThis))();
    cancelIdleCallbackFn = (() => _cancelIdleCallback().bind(globalThis))();
    add(callback) {
      const target = this.executingCallbacks ? this.deferred : this.current;
      target.add(callback);
      if (this.idleId === null) {
        this.scheduleIdleCallback();
      }
    }
    remove(callback) {
      const {
        current,
        deferred
      } = this;
      current.delete(callback);
      deferred.delete(callback);
      // If the last callback was removed and there is a pending
      // idle callback - cancel it.
      if (current.size === 0 && deferred.size === 0) {
        this.cancelIdleCallback();
      }
    }
    scheduleIdleCallback() {
      const callback = () => {
        this.cancelIdleCallback();
        this.executingCallbacks = true;
        for (const callback of this.current) {
          callback();
        }
        this.current.clear();
        this.executingCallbacks = false;
        // If there are any callbacks added during an invocation
        // of the current ones - make them "current" and schedule
        // a new idle callback.
        if (this.deferred.size > 0) {
          for (const callback of this.deferred) {
            this.current.add(callback);
          }
          this.deferred.clear();
          this.scheduleIdleCallback();
        }
      };
      // Ensure that the callback runs in the NgZone since
      // the `requestIdleCallback` is not currently patched by Zone.js.
      this.idleId = this.requestIdleCallbackFn(() => this.ngZone.run(callback));
    }
    cancelIdleCallback() {
      if (this.idleId !== null) {
        this.cancelIdleCallbackFn(this.idleId);
        this.idleId = null;
      }
    }
    ngOnDestroy() {
      this.cancelIdleCallback();
      this.current.clear();
      this.deferred.clear();
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: IdleScheduler,
      providedIn: 'root',
      factory: () => new IdleScheduler()
    }))();
  }
  return IdleScheduler;
})();
/**
 * Returns a function that captures a provided delay.
 * Invoking the returned function schedules a trigger.
 */
function onTimer(delay) {
  return (callback, injector) => scheduleTimerTrigger(delay, callback, injector);
}
/**
 * Schedules a callback to be invoked after a given timeout.
 *
 * @param delay A number of ms to wait until firing a callback.
 * @param callback A function to be invoked after a timeout.
 * @param injector injector for the app.
 */
function scheduleTimerTrigger(delay, callback, injector) {
  const scheduler = injector.get(TimerScheduler);
  const cleanupFn = () => scheduler.remove(callback);
  scheduler.add(delay, callback);
  return cleanupFn;
}
/**
 * Helper service to schedule `setTimeout`s for batches of defer blocks,
 * to avoid calling `setTimeout` for each defer block (e.g. if defer blocks
 * are created inside a for loop).
 */
let TimerScheduler = /*#__PURE__*/(() => {
  class TimerScheduler {
    // Indicates whether current callbacks are being invoked.
    executingCallbacks = false;
    // Currently scheduled `setTimeout` id.
    timeoutId = null;
    // When currently scheduled timer would fire.
    invokeTimerAt = null;
    // List of callbacks to be invoked.
    // For each callback we also store a timestamp on when the callback
    // should be invoked. We store timestamps and callback functions
    // in a flat array to avoid creating new objects for each entry.
    // [timestamp1, callback1, timestamp2, callback2, ...]
    current = [];
    // List of callbacks collected while invoking current set of callbacks.
    // Those callbacks are added to the "current" queue at the end of
    // the current callback invocation. The shape of this list is the same
    // as the shape of the `current` list.
    deferred = [];
    add(delay, callback) {
      const target = this.executingCallbacks ? this.deferred : this.current;
      this.addToQueue(target, Date.now() + delay, callback);
      this.scheduleTimer();
    }
    remove(callback) {
      const {
        current,
        deferred
      } = this;
      const callbackIndex = this.removeFromQueue(current, callback);
      if (callbackIndex === -1) {
        // Try cleaning up deferred queue only in case
        // we didn't find a callback in the "current" queue.
        this.removeFromQueue(deferred, callback);
      }
      // If the last callback was removed and there is a pending timeout - cancel it.
      if (current.length === 0 && deferred.length === 0) {
        this.clearTimeout();
      }
    }
    addToQueue(target, invokeAt, callback) {
      let insertAtIndex = target.length;
      for (let i = 0; i < target.length; i += 2) {
        const invokeQueuedCallbackAt = target[i];
        if (invokeQueuedCallbackAt > invokeAt) {
          // We've reached a first timer that is scheduled
          // for a later time than what we are trying to insert.
          // This is the location at which we need to insert,
          // no need to iterate further.
          insertAtIndex = i;
          break;
        }
      }
      arrayInsert2(target, insertAtIndex, invokeAt, callback);
    }
    removeFromQueue(target, callback) {
      let index = -1;
      for (let i = 0; i < target.length; i += 2) {
        const queuedCallback = target[i + 1];
        if (queuedCallback === callback) {
          index = i;
          break;
        }
      }
      if (index > -1) {
        // Remove 2 elements: a timestamp slot and
        // the following slot with a callback function.
        arraySplice(target, index, 2);
      }
      return index;
    }
    scheduleTimer() {
      const callback = () => {
        this.clearTimeout();
        this.executingCallbacks = true;
        // Clone the current state of the queue, since it might be altered
        // as we invoke callbacks.
        const current = [...this.current];
        // Invoke callbacks that were scheduled to run before the current time.
        const now = Date.now();
        for (let i = 0; i < current.length; i += 2) {
          const invokeAt = current[i];
          const callback = current[i + 1];
          if (invokeAt <= now) {
            callback();
          } else {
            // We've reached a timer that should not be invoked yet.
            break;
          }
        }
        // The state of the queue might've changed after callbacks invocation,
        // run the cleanup logic based on the *current* state of the queue.
        let lastCallbackIndex = -1;
        for (let i = 0; i < this.current.length; i += 2) {
          const invokeAt = this.current[i];
          if (invokeAt <= now) {
            // Add +1 to account for a callback function that
            // goes after the timestamp in events array.
            lastCallbackIndex = i + 1;
          } else {
            // We've reached a timer that should not be invoked yet.
            break;
          }
        }
        if (lastCallbackIndex >= 0) {
          arraySplice(this.current, 0, lastCallbackIndex + 1);
        }
        this.executingCallbacks = false;
        // If there are any callbacks added during an invocation
        // of the current ones - move them over to the "current"
        // queue.
        if (this.deferred.length > 0) {
          for (let i = 0; i < this.deferred.length; i += 2) {
            const invokeAt = this.deferred[i];
            const callback = this.deferred[i + 1];
            this.addToQueue(this.current, invokeAt, callback);
          }
          this.deferred.length = 0;
        }
        this.scheduleTimer();
      };
      // Avoid running timer callbacks more than once per
      // average frame duration. This is needed for better
      // batching and to avoid kicking off excessive change
      // detection cycles.
      const FRAME_DURATION_MS = 16; // 1000ms / 60fps
      if (this.current.length > 0) {
        const now = Date.now();
        // First element in the queue points at the timestamp
        // of the first (earliest) event.
        const invokeAt = this.current[0];
        if (this.timeoutId === null ||
        // Reschedule a timer in case a queue contains an item with
        // an earlier timestamp and the delta is more than an average
        // frame duration.
        this.invokeTimerAt && this.invokeTimerAt - invokeAt > FRAME_DURATION_MS) {
          // There was a timeout already, but an earlier event was added
          // into the queue. In this case we drop an old timer and setup
          // a new one with an updated (smaller) timeout.
          this.clearTimeout();
          const timeout = Math.max(invokeAt - now, FRAME_DURATION_MS);
          this.invokeTimerAt = invokeAt;
          this.timeoutId = setTimeout(callback, timeout);
        }
      }
    }
    clearTimeout() {
      if (this.timeoutId !== null) {
        clearTimeout(this.timeoutId);
        this.timeoutId = null;
      }
    }
    ngOnDestroy() {
      this.clearTimeout();
      this.current.length = 0;
      this.deferred.length = 0;
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: TimerScheduler,
      providedIn: 'root',
      factory: () => new TimerScheduler()
    }))();
  }
  return TimerScheduler;
})();
/**
 * A service used by the framework to create and cache injector instances.
 *
 * This service is used to create a single injector instance for each defer
 * block definition, to avoid creating an injector for each defer block instance
 * of a certain type.
 */
let CachedInjectorService = /*#__PURE__*/(() => {
  class CachedInjectorService {
    cachedInjectors = (() => new Map())();
    getOrCreateInjector(key, parentInjector, providers, debugName) {
      if (!this.cachedInjectors.has(key)) {
        const injector = providers.length > 0 ? createEnvironmentInjector(providers, parentInjector, debugName) : null;
        this.cachedInjectors.set(key, injector);
      }
      return this.cachedInjectors.get(key);
    }
    ngOnDestroy() {
      try {
        for (const injector of this.cachedInjectors.values()) {
          if (injector !== null) {
            injector.destroy();
          }
        }
      } finally {
        this.cachedInjectors.clear();
      }
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: CachedInjectorService,
      providedIn: 'environment',
      factory: () => new CachedInjectorService()
    }))();
  }
  return CachedInjectorService;
})();
/**
 * **INTERNAL**, avoid referencing it in application code.
 * *
 * Injector token that allows to provide `DeferBlockDependencyInterceptor` class
 * implementation.
 *
 * This token is only injected in devMode
 */
const DEFER_BLOCK_DEPENDENCY_INTERCEPTOR = /*#__PURE__*/new InjectionToken('DEFER_BLOCK_DEPENDENCY_INTERCEPTOR');
/**
 * **INTERNAL**, token used for configuring defer block behavior.
 */
const DEFER_BLOCK_CONFIG = /*#__PURE__*/new InjectionToken(ngDevMode ? 'DEFER_BLOCK_CONFIG' : '');
/**
 * Checks whether there is a cached injector associated with a given defer block
 * declaration and returns if it exists. If there is no cached injector present -
 * creates a new injector and stores in the cache.
 */
function getOrCreateEnvironmentInjector(parentInjector, tDetails, providers) {
  return parentInjector.get(CachedInjectorService).getOrCreateInjector(tDetails, parentInjector, providers, ngDevMode ? 'DeferBlock Injector' : '');
}
/** Injector Helpers */
/**
 * Creates a new injector, which contains providers collected from dependencies (NgModules) of
 * defer-loaded components. This function detects different types of parent injectors and creates
 * a new injector based on that.
 */
function createDeferBlockInjector(parentInjector, tDetails, providers) {
  // Check if the parent injector is an instance of a `ChainedInjector`.
  //
  // In this case, we retain the shape of the injector and use a newly created
  // `EnvironmentInjector` as a parent in the `ChainedInjector`. That is needed to
  // make sure that the primary injector gets consulted first (since it's typically
  // a NodeInjector) and `EnvironmentInjector` tree is consulted after that.
  if (parentInjector instanceof ChainedInjector) {
    const origInjector = parentInjector.injector;
    // Guaranteed to be an environment injector
    const parentEnvInjector = parentInjector.parentInjector;
    const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
    return new ChainedInjector(origInjector, envInjector);
  }
  const parentEnvInjector = parentInjector.get(EnvironmentInjector);
  // If the `parentInjector` is *not* an `EnvironmentInjector` - we need to create
  // a new `ChainedInjector` with the following setup:
  //
  //  - the provided `parentInjector` becomes a primary injector
  //  - an existing (real) `EnvironmentInjector` becomes a parent injector for
  //    a newly-created one, which contains extra providers
  //
  // So the final order in which injectors would be consulted in this case would look like this:
  //
  //  1. Provided `parentInjector`
  //  2. Newly-created `EnvironmentInjector` with extra providers
  //  3. `EnvironmentInjector` from the `parentInjector`
  if (parentEnvInjector !== parentInjector) {
    const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
    return new ChainedInjector(parentInjector, envInjector);
  }
  // The `parentInjector` is an instance of an `EnvironmentInjector`.
  // No need for special handling, we can use `parentInjector` as a
  // parent injector directly.
  return getOrCreateEnvironmentInjector(parentInjector, tDetails, providers);
}
/** Rendering Helpers */
/**
 * Transitions a defer block to the new state. Updates the  necessary
 * data structures and renders corresponding block.
 *
 * @param newState New state that should be applied to the defer block.
 * @param tNode TNode that represents a defer block.
 * @param lContainer Represents an instance of a defer block.
 * @param skipTimerScheduling Indicates that `@loading` and `@placeholder` block
 *   should be rendered immediately, even if they have `after` or `minimum` config
 *   options setup. This flag to needed for testing APIs to transition defer block
 *   between states via `DeferFixture.render` method.
 */
function renderDeferBlockState(newState, tNode, lContainer, skipTimerScheduling = false) {
  const hostLView = lContainer[PARENT];
  const hostTView = hostLView[TVIEW];
  // Check if this view is not destroyed. Since the loading process was async,
  // the view might end up being destroyed by the time rendering happens.
  if (isDestroyed(hostLView)) return;
  // Make sure this TNode belongs to TView that represents host LView.
  ngDevMode && assertTNodeForLView(tNode, hostLView);
  const lDetails = getLDeferBlockDetails(hostLView, tNode);
  ngDevMode && assertDefined(lDetails, 'Expected a defer block state defined');
  const currentState = lDetails[DEFER_BLOCK_STATE];
  const ssrState = lDetails[SSR_BLOCK_STATE];
  if (ssrState !== null && newState < ssrState) {
    return; // trying to render a previous state, exit
  }
  if (isValidStateChange(currentState, newState) && isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState)) {
    const tDetails = getTDeferBlockDetails(hostTView, tNode);
    // Skips scheduling on the server since it can delay the server response.
    const needsScheduling = !skipTimerScheduling && (typeof ngServerMode === 'undefined' || !ngServerMode) && (getLoadingBlockAfter(tDetails) !== null || getMinimumDurationForState(tDetails, DeferBlockState.Loading) !== null || getMinimumDurationForState(tDetails, DeferBlockState.Placeholder));
    if (ngDevMode && needsScheduling) {
      assertDefined(applyDeferBlockStateWithSchedulingImpl, 'Expected scheduling function to be defined');
    }
    const applyStateFn = needsScheduling ? applyDeferBlockStateWithSchedulingImpl : applyDeferBlockState;
    try {
      applyStateFn(newState, lDetails, lContainer, tNode, hostLView);
    } catch (error) {
      handleError(hostLView, error);
    }
  }
}
function findMatchingDehydratedViewForDeferBlock(lContainer, lDetails) {
  // TODO(incremental-hydration): extract into a separate util function and use in relevant places.
  const views = lContainer[DEHYDRATED_VIEWS];
  if (views === null || views.length === 0) {
    return null;
  }
  // Find matching view based on serialized defer block state.
  // TODO(incremental-hydration): reconcile this logic with the regular logic that looks up
  // dehydrated views to see if there is anything missing in this function.
  return views.find(view => view.data[DEFER_BLOCK_STATE$1] === lDetails[DEFER_BLOCK_STATE]) ?? null;
}
/**
 * Applies changes to the DOM to reflect a given state.
 */
function applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView) {
  const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
  if (stateTmplIndex !== null) {
    lDetails[DEFER_BLOCK_STATE] = newState;
    const hostTView = hostLView[TVIEW];
    const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
    // The TNode that represents a template that will activated in the defer block
    const activeBlockTNode = getTNode(hostTView, adjustedIndex);
    // There is only 1 view that can be present in an LContainer that
    // represents a defer block, so always refer to the first one.
    const viewIndex = 0;
    removeLViewFromLContainer(lContainer, viewIndex);
    let injector;
    if (newState === DeferBlockState.Complete) {
      // When we render a defer block in completed state, there might be
      // newly loaded standalone components used within the block, which may
      // import NgModules with providers. In order to make those providers
      // available for components declared in that NgModule, we create an instance
      // of an environment injector to host those providers and pass this injector
      // to the logic that creates a view.
      const tDetails = getTDeferBlockDetails(hostTView, tNode);
      const providers = tDetails.providers;
      if (providers && providers.length > 0) {
        injector = createDeferBlockInjector(hostLView[INJECTOR], tDetails, providers);
      }
    }
    const dehydratedView = findMatchingDehydratedViewForDeferBlock(lContainer, lDetails);
    // Render either when we don't have dehydrated views at all (e.g. client rendering)
    // or when dehydrated view is found (in which case we hydrate).
    // Otherwise, do nothing, since we'd end up erasing SSR'ed content.
    // TODO(incremental-hydration): Use the util function for checking dehydrated views mentioned above
    const isClientOnly = lContainer[DEHYDRATED_VIEWS] === null || lContainer[DEHYDRATED_VIEWS].length === 0;
    if (isClientOnly || dehydratedView) {
      // Erase dehydrated view info, so that it's not removed later
      // by post-hydration cleanup process.
      // TODO(incremental-hydration): we need a better mechanism here.
      lContainer[DEHYDRATED_VIEWS] = null;
      const embeddedLView = createAndRenderEmbeddedLView(hostLView, activeBlockTNode, null, {
        injector,
        dehydratedView
      });
      addLViewToLContainer(lContainer, embeddedLView, viewIndex, shouldAddViewToDom(activeBlockTNode, dehydratedView));
      markViewDirty(embeddedLView, 2 /* NotificationSource.DeferBlockStateUpdate */);
    }
    // TODO(incremental-hydration):
    // - what if we had some views in `lContainer[DEHYDRATED_VIEWS]`, but
    //   we didn't find a view that matches the expected state?
    // - for example, handle a situation when a block was in the "completed" state
    //   on the server, but the loading failing on the client. How do we reconcile and cleanup?
    // TODO(incremental-hydration): should we also invoke if newState === DeferBlockState.Error?
    if (newState === DeferBlockState.Complete && Array.isArray(lDetails[ON_COMPLETE_FNS])) {
      for (const callback of lDetails[ON_COMPLETE_FNS]) {
        callback();
      }
      lDetails[ON_COMPLETE_FNS] = null;
    }
  }
  if (newState === DeferBlockState.Complete && Array.isArray(lDetails[ON_COMPLETE_FNS])) {
    for (const callback of lDetails[ON_COMPLETE_FNS]) {
      callback();
    }
    lDetails[ON_COMPLETE_FNS] = null;
  }
}
/**
 * Extends the `applyDeferBlockState` with timer-based scheduling.
 * This function becomes available on a page if there are defer blocks
 * that use `after` or `minimum` parameters in the `@loading` or
 * `@placeholder` blocks.
 */
function applyDeferBlockStateWithScheduling(newState, lDetails, lContainer, tNode, hostLView) {
  const now = Date.now();
  const hostTView = hostLView[TVIEW];
  const tDetails = getTDeferBlockDetails(hostTView, tNode);
  if (lDetails[STATE_IS_FROZEN_UNTIL] === null || lDetails[STATE_IS_FROZEN_UNTIL] <= now) {
    lDetails[STATE_IS_FROZEN_UNTIL] = null;
    const loadingAfter = getLoadingBlockAfter(tDetails);
    const inLoadingAfterPhase = lDetails[LOADING_AFTER_CLEANUP_FN] !== null;
    if (newState === DeferBlockState.Loading && loadingAfter !== null && !inLoadingAfterPhase) {
      // Trying to render loading, but it has an `after` config,
      // so schedule an update action after a timeout.
      lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
      const cleanupFn = scheduleDeferBlockUpdate(loadingAfter, lDetails, tNode, lContainer, hostLView);
      lDetails[LOADING_AFTER_CLEANUP_FN] = cleanupFn;
    } else {
      // If we transition to a complete or an error state and there is a pending
      // operation to render loading after a timeout - invoke a cleanup operation,
      // which stops the timer.
      if (newState > DeferBlockState.Loading && inLoadingAfterPhase) {
        lDetails[LOADING_AFTER_CLEANUP_FN]();
        lDetails[LOADING_AFTER_CLEANUP_FN] = null;
        lDetails[NEXT_DEFER_BLOCK_STATE] = null;
      }
      applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView);
      const duration = getMinimumDurationForState(tDetails, newState);
      if (duration !== null) {
        lDetails[STATE_IS_FROZEN_UNTIL] = now + duration;
        scheduleDeferBlockUpdate(duration, lDetails, tNode, lContainer, hostLView);
      }
    }
  } else {
    // We are still rendering the previous state.
    // Update the `NEXT_DEFER_BLOCK_STATE`, which would be
    // picked up once it's time to transition to the next state.
    lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
  }
}
/**
 * Schedules an update operation after a specified timeout.
 */
function scheduleDeferBlockUpdate(timeout, lDetails, tNode, lContainer, hostLView) {
  const callback = () => {
    const nextState = lDetails[NEXT_DEFER_BLOCK_STATE];
    lDetails[STATE_IS_FROZEN_UNTIL] = null;
    lDetails[NEXT_DEFER_BLOCK_STATE] = null;
    if (nextState !== null) {
      renderDeferBlockState(nextState, tNode, lContainer);
    }
  };
  return scheduleTimerTrigger(timeout, callback, hostLView[INJECTOR]);
}
/**
 * Checks whether we can transition to the next state.
 *
 * We transition to the next state if the previous state was represented
 * with a number that is less than the next state. For example, if the current
 * state is "loading" (represented as `1`), we should not show a placeholder
 * (represented as `0`), but we can show a completed state (represented as `2`)
 * or an error state (represented as `3`).
 */
function isValidStateChange(currentState, newState) {
  return currentState < newState;
}
/** Utility function to render placeholder content (if present) */
function renderPlaceholder(lView, tNode) {
  const lContainer = lView[tNode.index];
  ngDevMode && assertLContainer(lContainer);
  renderDeferBlockState(DeferBlockState.Placeholder, tNode, lContainer);
}
/**
 * Subscribes to the "loading" Promise and renders corresponding defer sub-block,
 * based on the loading results.
 *
 * @param lContainer Represents an instance of a defer block.
 * @param tNode Represents defer block info shared across all instances.
 */
function renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer) {
  ngDevMode && assertDefined(tDetails.loadingPromise, 'Expected loading Promise to exist on this defer block');
  tDetails.loadingPromise.then(() => {
    if (tDetails.loadingState === DeferDependenciesLoadingState.COMPLETE) {
      ngDevMode && assertDeferredDependenciesLoaded(tDetails);
      // Everything is loaded, show the primary block content
      renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
    } else if (tDetails.loadingState === DeferDependenciesLoadingState.FAILED) {
      renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
    }
  });
}
/**
 * Reference to the timer-based scheduler implementation of defer block state
 * rendering method. It's used to make timer-based scheduling tree-shakable.
 * If `minimum` or `after` parameters are used, compiler generates an extra
 * argument for the `ɵɵdefer` instruction, which references a timer-based
 * implementation.
 */
let applyDeferBlockStateWithSchedulingImpl = null;
/**
 * Enables timer-related scheduling if `after` or `minimum` parameters are setup
 * on the `@loading` or `@placeholder` blocks.
 */
function ɵɵdeferEnableTimerScheduling(tView, tDetails, placeholderConfigIndex, loadingConfigIndex) {
  const tViewConsts = tView.consts;
  if (placeholderConfigIndex != null) {
    tDetails.placeholderBlockConfig = getConstant(tViewConsts, placeholderConfigIndex);
  }
  if (loadingConfigIndex != null) {
    tDetails.loadingBlockConfig = getConstant(tViewConsts, loadingConfigIndex);
  }
  // Enable implementation that supports timer-based scheduling.
  if (applyDeferBlockStateWithSchedulingImpl === null) {
    applyDeferBlockStateWithSchedulingImpl = applyDeferBlockStateWithScheduling;
  }
}

/**
 * Schedules triggering of a defer block for `on idle` and `on timer` conditions.
 */
function scheduleDelayedTrigger(scheduleFn) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const injector = lView[INJECTOR];
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  renderPlaceholder(lView, tNode);
  if (shouldTriggerWhenOnClient(lView[INJECTOR], lDetails, tDetails)) {
    // Only trigger the scheduled trigger on the browser
    // since we don't want to delay the server response.
    const cleanupFn = scheduleFn(() => triggerDeferBlock(lView, tNode), injector);
    storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, cleanupFn);
  }
}
/**
 * Schedules prefetching for `on idle` and `on timer` triggers.
 *
 * @param scheduleFn A function that does the scheduling.
 */
function scheduleDelayedPrefetching(scheduleFn, trigger) {
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return;
  }
  const lView = getLView();
  const injector = lView[INJECTOR];
  // Only trigger the scheduled trigger on the browser
  // since we don't want to delay the server response.
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const prefetchTriggers = getPrefetchTriggers(tDetails);
  prefetchTriggers.add(trigger);
  if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
    const lDetails = getLDeferBlockDetails(lView, tNode);
    const prefetch = () => triggerPrefetching(tDetails, lView, tNode);
    const cleanupFn = scheduleFn(prefetch, injector);
    storeTriggerCleanupFn(1 /* TriggerType.Prefetch */, lDetails, cleanupFn);
  }
}
/**
 * Schedules hydration triggering of a defer block for `on idle` and `on timer` conditions.
 */
function scheduleDelayedHydrating(scheduleFn, lView, tNode) {
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return;
  }
  // Only trigger the scheduled trigger on the browser
  // since we don't want to delay the server response.
  const injector = lView[INJECTOR];
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  ngDevMode && assertSsrIdDefined(ssrUniqueId);
  const cleanupFn = scheduleFn(() => triggerHydrationFromBlockName(injector, ssrUniqueId), injector);
  storeTriggerCleanupFn(2 /* TriggerType.Hydrate */, lDetails, cleanupFn);
}
/**
 * Trigger prefetching of dependencies for a defer block.
 *
 * @param tDetails Static information about this defer block.
 * @param lView LView of a host view.
 */
function triggerPrefetching(tDetails, lView, tNode) {
  const tDeferBlockDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  if (lView[INJECTOR] && shouldTriggerDeferBlock(lView[INJECTOR], tDeferBlockDetails)) {
    triggerResourceLoading(tDetails, lView, tNode);
  }
}
/**
 * Trigger loading of defer block dependencies if the process hasn't started yet.
 *
 * @param tDetails Static information about this defer block.
 * @param lView LView of a host view.
 */
function triggerResourceLoading(tDetails, lView, tNode) {
  const injector = lView[INJECTOR];
  const tView = lView[TVIEW];
  if (tDetails.loadingState !== DeferDependenciesLoadingState.NOT_STARTED) {
    // If the loading status is different from initial one, it means that
    // the loading of dependencies is in progress and there is nothing to do
    // in this function. All details can be obtained from the `tDetails` object.
    return tDetails.loadingPromise ?? Promise.resolve();
  }
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const primaryBlockTNode = getPrimaryBlockTNode(tView, tDetails);
  // Switch from NOT_STARTED -> IN_PROGRESS state.
  tDetails.loadingState = DeferDependenciesLoadingState.IN_PROGRESS;
  // Prefetching is triggered, cleanup all registered prefetch triggers.
  invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  let dependenciesFn = tDetails.dependencyResolverFn;
  if (ngDevMode) {
    // Check if dependency function interceptor is configured.
    const deferDependencyInterceptor = injector.get(DEFER_BLOCK_DEPENDENCY_INTERCEPTOR, null, {
      optional: true
    });
    if (deferDependencyInterceptor) {
      dependenciesFn = deferDependencyInterceptor.intercept(dependenciesFn);
    }
  }
  // Indicate that an application is not stable and has a pending task.
  const pendingTasks = injector.get(PendingTasksInternal);
  const taskId = pendingTasks.add();
  // The `dependenciesFn` might be `null` when all dependencies within
  // a given defer block were eagerly referenced elsewhere in a file,
  // thus no dynamic `import()`s were produced.
  if (!dependenciesFn) {
    tDetails.loadingPromise = Promise.resolve().then(() => {
      tDetails.loadingPromise = null;
      tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
      pendingTasks.remove(taskId);
    });
    return tDetails.loadingPromise;
  }
  // Start downloading of defer block dependencies.
  tDetails.loadingPromise = Promise.allSettled(dependenciesFn()).then(results => {
    let failed = false;
    const directiveDefs = [];
    const pipeDefs = [];
    for (const result of results) {
      if (result.status === 'fulfilled') {
        const dependency = result.value;
        const directiveDef = getComponentDef(dependency) || getDirectiveDef(dependency);
        if (directiveDef) {
          directiveDefs.push(directiveDef);
        } else {
          const pipeDef = getPipeDef$1(dependency);
          if (pipeDef) {
            pipeDefs.push(pipeDef);
          }
        }
      } else {
        failed = true;
        break;
      }
    }
    // Loading is completed, we no longer need the loading Promise
    // and a pending task should also be removed.
    tDetails.loadingPromise = null;
    pendingTasks.remove(taskId);
    if (failed) {
      tDetails.loadingState = DeferDependenciesLoadingState.FAILED;
      if (tDetails.errorTmplIndex === null) {
        const templateLocation = ngDevMode ? getTemplateLocationDetails(lView) : '';
        const error = new RuntimeError(750 /* RuntimeErrorCode.DEFER_LOADING_FAILED */, ngDevMode && 'Loading dependencies for `@defer` block failed, ' + `but no \`@error\` block was configured${templateLocation}. ` + 'Consider using the `@error` block to render an error state.');
        handleError(lView, error);
      }
    } else {
      tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
      // Update directive and pipe registries to add newly downloaded dependencies.
      const primaryBlockTView = primaryBlockTNode.tView;
      if (directiveDefs.length > 0) {
        primaryBlockTView.directiveRegistry = addDepsToRegistry(primaryBlockTView.directiveRegistry, directiveDefs);
        // Extract providers from all NgModules imported by standalone components
        // used within this defer block.
        const directiveTypes = directiveDefs.map(def => def.type);
        const providers = internalImportProvidersFrom(false, ...directiveTypes);
        tDetails.providers = providers;
      }
      if (pipeDefs.length > 0) {
        primaryBlockTView.pipeRegistry = addDepsToRegistry(primaryBlockTView.pipeRegistry, pipeDefs);
      }
    }
  });
  return tDetails.loadingPromise;
}
/**
 * Attempts to trigger loading of defer block dependencies.
 * If the block is already in a loading, completed or an error state -
 * no additional actions are taken.
 */
function triggerDeferBlock(lView, tNode) {
  const tView = lView[TVIEW];
  const lContainer = lView[tNode.index];
  const injector = lView[INJECTOR];
  ngDevMode && assertLContainer(lContainer);
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const tDetails = getTDeferBlockDetails(tView, tNode);
  if (!shouldTriggerDeferBlock(injector, tDetails)) return;
  // Defer block is triggered, cleanup all registered trigger functions.
  invokeAllTriggerCleanupFns(lDetails);
  switch (tDetails.loadingState) {
    case DeferDependenciesLoadingState.NOT_STARTED:
      renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
      triggerResourceLoading(tDetails, lView, tNode);
      // The `loadingState` might have changed to "loading".
      if (tDetails.loadingState === DeferDependenciesLoadingState.IN_PROGRESS) {
        renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
      }
      break;
    case DeferDependenciesLoadingState.IN_PROGRESS:
      renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
      renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
      break;
    case DeferDependenciesLoadingState.COMPLETE:
      ngDevMode && assertDeferredDependenciesLoaded(tDetails);
      renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
      break;
    case DeferDependenciesLoadingState.FAILED:
      renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
      break;
    default:
      if (ngDevMode) {
        throwError('Unknown defer block state');
      }
  }
}
/**
 * Triggers hydration from a given defer block's unique SSR ID.
 * This includes firing any queued events that need to be replayed
 * and handling any post hydration cleanup.
 */
function triggerHydrationFromBlockName(_x4, _x5) {
  return _triggerHydrationFromBlockName.apply(this, arguments);
}
/**
 * Triggers the resource loading for a defer block and passes back a promise
 * to handle cleanup on completion
 */
function _triggerHydrationFromBlockName() {
  _triggerHydrationFromBlockName = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, blockName, replayFn = () => {}) {
    const {
      deferBlock,
      hydratedBlocks
    } = yield triggerBlockTreeHydrationByName(injector, blockName);
    replayFn(hydratedBlocks);
    yield cleanupDeferBlock(deferBlock, hydratedBlocks, injector);
  });
  return _triggerHydrationFromBlockName.apply(this, arguments);
}
function triggerAndWaitForCompletion(dehydratedBlockId, dehydratedBlockRegistry, injector) {
  // TODO(incremental-hydration): This is a temporary fix to resolve control flow
  // cases where nested defer blocks are inside control flow. We wait for each nested
  // defer block to load and render before triggering the next one in a sequence. This is
  // needed to ensure that corresponding LViews & LContainers are available for a block
  // before we trigger it. We need to investigate how to get rid of the `afterNextRender`
  // calls (in the nearest future) and do loading of all dependencies of nested defer blocks
  // in parallel (later).
  let resolve;
  const promise = new Promise(resolveFn => {
    resolve = resolveFn;
  });
  afterNextRender(() => {
    const deferBlock = dehydratedBlockRegistry.get(dehydratedBlockId);
    // Since we trigger hydration for nested defer blocks in a sequence (parent -> child),
    // there is a chance that a defer block may not be present at hydration time. For example,
    // when a nested block was in an `@if` condition, which has changed.
    // TODO(incremental-hydration): add tests to verify the behavior mentioned above.
    if (deferBlock !== null) {
      const {
        tNode,
        lView
      } = deferBlock;
      const lDetails = getLDeferBlockDetails(lView, tNode);
      onDeferBlockCompletion(lDetails, resolve);
      triggerDeferBlock(lView, tNode);
      // TODO(incremental-hydration): handle the cleanup for cases when
      // defer block is no longer present during hydration (e.g. `@if` condition
      // has changed during hydration/rendering).
    }
  }, {
    injector
  });
  return promise;
}
/**
 * Registers cleanup functions for a defer block when the block has finished
 * fetching and rendering
 */
function onDeferBlockCompletion(lDetails, callback) {
  if (!Array.isArray(lDetails[ON_COMPLETE_FNS])) {
    lDetails[ON_COMPLETE_FNS] = [];
  }
  lDetails[ON_COMPLETE_FNS].push(callback);
}
/**
 * The core mechanism for incremental hydration. This triggers
 * hydration for all the blocks in the tree that need to be hydrated and keeps
 * track of all those blocks that were hydrated along the way.
 */
function triggerBlockTreeHydrationByName(_x6, _x7) {
  return _triggerBlockTreeHydrationByName.apply(this, arguments);
}
/**
 * Determines whether "hydrate" triggers should be activated. Triggers are activated in the following cases:
 *  - on the server, when incremental hydration is enabled, to trigger the block and render the main content
 *  - on the client for blocks that were server-side rendered, to start hydration process
 */
function _triggerBlockTreeHydrationByName() {
  _triggerBlockTreeHydrationByName = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, blockName) {
    const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
    // Make sure we don't hydrate/trigger the same thing multiple times
    if (dehydratedBlockRegistry.hydrating.has(blockName)) return {
      deferBlock: null,
      hydratedBlocks: new Set()
    };
    // Step 1: Get the queue of items that needs to be hydrated
    const hydrationQueue = getParentBlockHydrationQueue(blockName, injector);
    // Step 2: Add all the items in the queue to the registry at once so we don't trigger hydration on them while
    // the sequence of triggers fires.
    hydrationQueue.forEach(id => dehydratedBlockRegistry.hydrating.add(id));
    // Step 3: hydrate each block in the queue. It will be in descending order from the top down.
    for (const dehydratedBlockId of hydrationQueue) {
      // Step 4: Run the actual trigger function to fetch dependencies.
      // Triggering a block adds any of its child defer blocks to the registry.
      yield triggerAndWaitForCompletion(dehydratedBlockId, dehydratedBlockRegistry, injector);
    }
    const hydratedBlocks = new Set(hydrationQueue);
    // The last item in the queue was the original target block;
    const hydratedBlockId = hydrationQueue.slice(-1)[0];
    const hydratedBlock = dehydratedBlockRegistry.get(hydratedBlockId);
    return {
      deferBlock: hydratedBlock,
      hydratedBlocks
    };
  });
  return _triggerBlockTreeHydrationByName.apply(this, arguments);
}
function shouldActivateHydrateTrigger(lView, tNode) {
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const injector = lView[INJECTOR];
  // TODO(incremental-hydration): ideally, this check should only happen once and then stored on
  // LDeferBlockDetails as a flag. This would make subsequent lookups very cheap.
  return isIncrementalHydrationEnabled(injector) && (typeof ngServerMode !== 'undefined' && ngServerMode || lDetails[SSR_UNIQUE_ID] !== null);
}
// TODO(incremental-hydration): Optimize this further by moving the calculation to earlier
// in the process. Consider a flag we can check similar to LView[FLAGS].
/**
 * Determines whether regular defer block triggers should be invoked based on client state
 * and whether incremental hydration is enabled. Hydrate triggers are invoked elsewhere.
 */
function shouldTriggerWhenOnClient(injector, lDetails, tDetails) {
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return false;
  }
  const isServerRendered = lDetails[SSR_BLOCK_STATE] && lDetails[SSR_BLOCK_STATE] === DeferBlockState.Complete;
  const hasHydrateTriggers = tDetails.hydrateTriggers && tDetails.hydrateTriggers.size > 0;
  if (hasHydrateTriggers && isServerRendered && isIncrementalHydrationEnabled(injector)) {
    return false;
  }
  return true;
}
/**
 * Returns whether defer blocks should be triggered.
 *
 * Currently, defer blocks are not triggered on the server,
 * only placeholder content is rendered (if provided).
 */
function shouldTriggerDeferBlock(injector, tDeferBlockDetails) {
  const config = injector.get(DEFER_BLOCK_CONFIG, null, {
    optional: true
  });
  if (config?.behavior === DeferBlockBehavior.Manual) {
    return false;
  }
  return typeof ngServerMode === 'undefined' || !ngServerMode || tDeferBlockDetails.hydrateTriggers !== null;
}
/**
 * Retrives a Defer Block's list of hydration triggers
 */
function getHydrateTriggers(tView, tNode) {
  const tDetails = getTDeferBlockDetails(tView, tNode);
  return tDetails.hydrateTriggers ??= new Map();
}
/**
 * Retrives a Defer Block's list of prefetch triggers
 */
function getPrefetchTriggers(tDetails) {
  return tDetails.prefetchTriggers ??= new Set();
}
/**
 * Loops through all defer block summaries and ensures all the blocks triggers are
 * properly initialized
 */
function processAndInitTriggers(injector, blockData, nodes) {
  const idleElements = [];
  const timerElements = [];
  const viewportElements = [];
  const immediateElements = [];
  for (let [blockId, blockSummary] of blockData) {
    const commentNode = nodes.get(blockId);
    if (commentNode !== undefined) {
      const numRootNodes = blockSummary.data[NUM_ROOT_NODES];
      let currentNode = commentNode;
      for (let i = 0; i < numRootNodes; i++) {
        currentNode = currentNode.previousSibling;
        if (currentNode.nodeType !== Node.ELEMENT_NODE) {
          continue;
        }
        const elementTrigger = {
          el: currentNode,
          blockName: blockId
        };
        // hydrate
        if (blockSummary.hydrate.idle) {
          idleElements.push(elementTrigger);
        }
        if (blockSummary.hydrate.immediate) {
          immediateElements.push(elementTrigger);
        }
        if (blockSummary.hydrate.timer !== null) {
          elementTrigger.delay = blockSummary.hydrate.timer;
          timerElements.push(elementTrigger);
        }
        if (blockSummary.hydrate.viewport) {
          viewportElements.push(elementTrigger);
        }
      }
    }
  }
  setIdleTriggers(injector, idleElements);
  setImmediateTriggers(injector, immediateElements);
  setViewportTriggers(injector, viewportElements);
  setTimerTriggers(injector, timerElements);
}
function setIdleTriggers(_x8, _x9) {
  return _setIdleTriggers.apply(this, arguments);
}
function _setIdleTriggers() {
  _setIdleTriggers = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, elementTriggers) {
    for (const elementTrigger of elementTriggers) {
      const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
      const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
      const cleanupFn = onIdle(onInvoke, injector);
      registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
    }
  });
  return _setIdleTriggers.apply(this, arguments);
}
function setViewportTriggers(_x10, _x11) {
  return _setViewportTriggers.apply(this, arguments);
}
function _setViewportTriggers() {
  _setViewportTriggers = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, elementTriggers) {
    if (elementTriggers.length > 0) {
      const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
      for (let elementTrigger of elementTriggers) {
        const cleanupFn = onViewport(elementTrigger.el, /*#__PURE__*/(0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
          yield triggerHydrationFromBlockName(injector, elementTrigger.blockName);
        }), injector);
        registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
      }
    }
  });
  return _setViewportTriggers.apply(this, arguments);
}
function setTimerTriggers(_x12, _x13) {
  return _setTimerTriggers.apply(this, arguments);
}
function _setTimerTriggers() {
  _setTimerTriggers = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, elementTriggers) {
    for (const elementTrigger of elementTriggers) {
      const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
      const onInvoke = /*#__PURE__*/function () {
        var _ref2 = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
          return yield triggerHydrationFromBlockName(injector, elementTrigger.blockName);
        });
        return function onInvoke() {
          return _ref2.apply(this, arguments);
        };
      }();
      const timerFn = onTimer(elementTrigger.delay);
      const cleanupFn = timerFn(onInvoke, injector);
      registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
    }
  });
  return _setTimerTriggers.apply(this, arguments);
}
function setImmediateTriggers(_x14, _x15) {
  return _setImmediateTriggers.apply(this, arguments);
}
/**
 * Creates runtime data structures for defer blocks.
 *
 * @param index Index of the `defer` instruction.
 * @param primaryTmplIndex Index of the template with the primary block content.
 * @param dependencyResolverFn Function that contains dependencies for this defer block.
 * @param loadingTmplIndex Index of the template with the loading block content.
 * @param placeholderTmplIndex Index of the template with the placeholder block content.
 * @param errorTmplIndex Index of the template with the error block content.
 * @param loadingConfigIndex Index in the constants array of the configuration of the loading.
 *     block.
 * @param placeholderConfigIndex Index in the constants array of the configuration of the
 *     placeholder block.
 * @param enableTimerScheduling Function that enables timer-related scheduling if `after`
 *     or `minimum` parameters are setup on the `@loading` or `@placeholder` blocks.
 *
 * @codeGenApi
 */
function _setImmediateTriggers() {
  _setImmediateTriggers = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (injector, elementTriggers) {
    for (const elementTrigger of elementTriggers) {
      yield triggerHydrationFromBlockName(injector, elementTrigger.blockName);
    }
  });
  return _setImmediateTriggers.apply(this, arguments);
}
function ɵɵdefer(index, primaryTmplIndex, dependencyResolverFn, loadingTmplIndex, placeholderTmplIndex, errorTmplIndex, loadingConfigIndex, placeholderConfigIndex, enableTimerScheduling) {
  const lView = getLView();
  const tView = getTView();
  const adjustedIndex = index + HEADER_OFFSET;
  const tNode = declareTemplate(lView, tView, index, null, 0, 0);
  const injector = lView[INJECTOR];
  if (tView.firstCreatePass) {
    performanceMarkFeature('NgDefer');
    const tDetails = {
      primaryTmplIndex,
      loadingTmplIndex: loadingTmplIndex ?? null,
      placeholderTmplIndex: placeholderTmplIndex ?? null,
      errorTmplIndex: errorTmplIndex ?? null,
      placeholderBlockConfig: null,
      loadingBlockConfig: null,
      dependencyResolverFn: dependencyResolverFn ?? null,
      loadingState: DeferDependenciesLoadingState.NOT_STARTED,
      loadingPromise: null,
      providers: null,
      hydrateTriggers: null,
      prefetchTriggers: null
    };
    enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex);
    setTDeferBlockDetails(tView, adjustedIndex, tDetails);
  }
  const lContainer = lView[adjustedIndex];
  // If hydration is enabled, looks up dehydrated views in the DOM
  // using hydration annotation info and stores those views on LContainer.
  // In client-only mode, this function is a noop.
  populateDehydratedViewsInLContainer(lContainer, tNode, lView);
  let ssrBlockState = null;
  let ssrUniqueId = null;
  if (lContainer[DEHYDRATED_VIEWS]?.length > 0) {
    const info = lContainer[DEHYDRATED_VIEWS][0].data;
    ssrUniqueId = info[DEFER_BLOCK_ID] ?? null;
    ssrBlockState = info[DEFER_BLOCK_STATE$1];
  }
  // Init instance-specific defer details and store it.
  const lDetails = [null,
  // NEXT_DEFER_BLOCK_STATE
  DeferBlockInternalState.Initial,
  // DEFER_BLOCK_STATE
  null,
  // STATE_IS_FROZEN_UNTIL
  null,
  // LOADING_AFTER_CLEANUP_FN
  null,
  // TRIGGER_CLEANUP_FNS
  null,
  // PREFETCH_TRIGGER_CLEANUP_FNS
  ssrUniqueId,
  // SSR_UNIQUE_ID
  ssrBlockState,
  // SSR_BLOCK_STATE
  null,
  // ON_COMPLETE_FNS
  null // HYDRATE_TRIGGER_CLEANUP_FNS
  ];
  setLDeferBlockDetails(lView, adjustedIndex, lDetails);
  let registry = null;
  if (ssrUniqueId !== null) {
    ngDevMode && assertIncrementalHydrationIsConfigured(injector);
    // Store this defer block in the registry, to have an access to
    // internal data structures from hydration runtime code.
    registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
    registry.add(ssrUniqueId, {
      lView,
      tNode,
      lContainer
    });
  }
  const onLViewDestroy = () => {
    invokeAllTriggerCleanupFns(lDetails);
    if (ssrUniqueId !== null) {
      registry?.cleanup([ssrUniqueId]);
    }
  };
  // When defer block is triggered - unsubscribe from LView destroy cleanup.
  storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, () => removeLViewOnDestroy(lView, onLViewDestroy));
  storeLViewOnDestroy(lView, onLViewDestroy);
}
/**
 * Loads defer block dependencies when a trigger value becomes truthy.
 * @codeGenApi
 */
function ɵɵdeferWhen(rawValue) {
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, rawValue)) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      const value = Boolean(rawValue); // handle truthy or falsy values
      const tNode = getSelectedTNode();
      const lDetails = getLDeferBlockDetails(lView, tNode);
      const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
      const renderedState = lDetails[DEFER_BLOCK_STATE];
      if (value === false && renderedState === DeferBlockInternalState.Initial) {
        // If nothing is rendered yet, render a placeholder (if defined).
        renderPlaceholder(lView, tNode);
      } else if (value === true && (renderedState === DeferBlockInternalState.Initial || renderedState === DeferBlockState.Placeholder) && shouldTriggerWhenOnClient(lView[INJECTOR], lDetails, tDetails)) {
        triggerDeferBlock(lView, tNode);
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
}
/**
 * Prefetches the deferred content when a value becomes truthy.
 * @codeGenApi
 */
function ɵɵdeferPrefetchWhen(rawValue) {
  const lView = getLView();
  const tNode = getSelectedTNode();
  const bindingIndex = nextBindingIndex();
  const prefetchTriggers = getPrefetchTriggers(getTDeferBlockDetails(getTView(), tNode));
  prefetchTriggers.add(6 /* DeferBlockTrigger.When */);
  if (bindingUpdated(lView, bindingIndex, rawValue)) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      const value = Boolean(rawValue); // handle truthy or falsy values
      const tView = lView[TVIEW];
      const tNode = getSelectedTNode();
      const tDetails = getTDeferBlockDetails(tView, tNode);
      if (value === true && tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
        // If loading has not been started yet, trigger it now.
        triggerPrefetching(tDetails, lView, tNode);
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  }
}
/**
 * Hydrates the deferred content when a value becomes truthy.
 * @codeGenApi
 */
function ɵɵdeferHydrateWhen(rawValue) {
  const lView = getLView();
  const tNode = getSelectedTNode();
  if (!shouldActivateHydrateTrigger(lView, tNode)) {
    return;
  }
  // TODO(incremental-hydration): audit all defer instructions to reduce unnecessary work by
  // moving function calls inside their relevant control flow blocks
  const bindingIndex = nextBindingIndex();
  const tView = getTView();
  const hydrateTriggers = getHydrateTriggers(tView, tNode);
  hydrateTriggers.set(6 /* DeferBlockTrigger.When */, null);
  if (bindingUpdated(lView, bindingIndex, rawValue)) {
    const injector = lView[INJECTOR];
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    } else {
      try {
        const value = Boolean(rawValue); // handle truthy or falsy values
        if (value === true) {
          // The `when` condition has changed to `true`, trigger defer block loading
          // if the block is either in initial (nothing is rendered) or a placeholder
          // state.
          const lDetails = getLDeferBlockDetails(lView, tNode);
          const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
          ngDevMode && assertSsrIdDefined(ssrUniqueId);
          triggerHydrationFromBlockName(injector, ssrUniqueId);
        }
      } finally {
        const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
        (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
      }
    }
  }
}
/**
 * Specifies that hydration never occurs.
 * @codeGenApi
 */
function ɵɵdeferHydrateNever() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(7 /* DeferBlockTrigger.Never */, null);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    }
  }
}
/**
 * Sets up logic to handle the `on idle` deferred trigger.
 * @codeGenApi
 */
function ɵɵdeferOnIdle() {
  scheduleDelayedTrigger(onIdle);
}
/**
 * Sets up logic to handle the `prefetch on idle` deferred trigger.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnIdle() {
  scheduleDelayedPrefetching(onIdle, 0 /* DeferBlockTrigger.Idle */);
}
/**
 * Sets up logic to handle the `on idle` deferred trigger.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnIdle() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(0 /* DeferBlockTrigger.Idle */, null);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    } else {
      scheduleDelayedHydrating(onIdle, lView, tNode);
    }
  }
}
/**
 * Sets up logic to handle the `on immediate` deferred trigger.
 * @codeGenApi
 */
function ɵɵdeferOnImmediate() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const injector = lView[INJECTOR];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const lDetails = getLDeferBlockDetails(lView, tNode);
  // Render placeholder block only if loading template is not present and we're on
  // the client to avoid content flickering, since it would be immediately replaced
  // by the loading block.
  if (!shouldTriggerDeferBlock(injector, tDetails) || tDetails.loadingTmplIndex === null) {
    renderPlaceholder(lView, tNode);
  }
  if (shouldTriggerWhenOnClient(injector, lDetails, tDetails)) {
    triggerDeferBlock(lView, tNode);
  }
}
/**
 * Sets up logic to handle the `prefetch on immediate` deferred trigger.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnImmediate() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const prefetchTriggers = getPrefetchTriggers(tDetails);
  prefetchTriggers.add(1 /* DeferBlockTrigger.Immediate */);
  if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
    triggerResourceLoading(tDetails, lView, tNode);
  }
}
/**
 * Sets up logic to handle the `on immediate` hydrate trigger.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnImmediate() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const injector = lView[INJECTOR];
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(1 /* DeferBlockTrigger.Immediate */, null);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      triggerDeferBlock(lView, tNode);
    } else {
      const lDetails = getLDeferBlockDetails(lView, tNode);
      const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
      ngDevMode && assertSsrIdDefined(ssrUniqueId);
      triggerHydrationFromBlockName(injector, ssrUniqueId);
    }
  }
}
/**
 * Creates runtime data structures for the `on timer` deferred trigger.
 * @param delay Amount of time to wait before loading the content.
 * @codeGenApi
 */
function ɵɵdeferOnTimer(delay) {
  scheduleDelayedTrigger(onTimer(delay));
}
/**
 * Creates runtime data structures for the `prefetch on timer` deferred trigger.
 * @param delay Amount of time to wait before prefetching the content.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnTimer(delay) {
  scheduleDelayedPrefetching(onTimer(delay), 5 /* DeferBlockTrigger.Timer */);
}
/**
 * Creates runtime data structures for the `on timer` hydrate trigger.
 * @param delay Amount of time to wait before loading the content.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnTimer(delay) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(5 /* DeferBlockTrigger.Timer */, delay);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    } else {
      scheduleDelayedHydrating(onTimer(delay), lView, tNode);
    }
  }
}
/**
 * Creates runtime data structures for the `on hover` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferOnHover(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  renderPlaceholder(lView, tNode);
  if (shouldTriggerWhenOnClient(lView[INJECTOR], lDetails, tDetails)) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerDeferBlock(lView, tNode), 0 /* TriggerType.Regular */);
  }
}
/**
 * Creates runtime data structures for the `prefetch on hover` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnHover(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const prefetchTriggers = getPrefetchTriggers(tDetails);
  prefetchTriggers.add(4 /* DeferBlockTrigger.Hover */);
  if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  }
}
/**
 * Creates runtime data structures for the `on hover` hydrate trigger.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnHover() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(4 /* DeferBlockTrigger.Hover */, null);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    }
  }
  // The actual triggering of hydration on hover is handled by JSAction in
  // event_replay.ts.
}
/**
 * Creates runtime data structures for the `on interaction` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferOnInteraction(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  renderPlaceholder(lView, tNode);
  if (shouldTriggerWhenOnClient(lView[INJECTOR], lDetails, tDetails)) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerDeferBlock(lView, tNode), 0 /* TriggerType.Regular */);
  }
}
/**
 * Creates runtime data structures for the `prefetch on interaction` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnInteraction(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const prefetchTriggers = getPrefetchTriggers(tDetails);
  prefetchTriggers.add(3 /* DeferBlockTrigger.Interaction */);
  if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  }
}
/**
 * Creates runtime data structures for the `on interaction` hydrate trigger.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnInteraction() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(3 /* DeferBlockTrigger.Interaction */, null);
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    }
  }
  // The actual triggering of hydration on interaction is handled by JSAction in
  // event_replay.ts.
}
/**
 * Creates runtime data structures for the `on viewport` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferOnViewport(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const lDetails = getLDeferBlockDetails(lView, tNode);
  const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  renderPlaceholder(lView, tNode);
  if (shouldTriggerWhenOnClient(lView[INJECTOR], lDetails, tDetails)) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerDeferBlock(lView, tNode), 0 /* TriggerType.Regular */);
  }
}
/**
 * Creates runtime data structures for the `prefetch on viewport` deferred trigger.
 * @param triggerIndex Index at which to find the trigger element.
 * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
 * @codeGenApi
 */
function ɵɵdeferPrefetchOnViewport(triggerIndex, walkUpTimes) {
  const lView = getLView();
  const tNode = getCurrentTNode();
  const tView = lView[TVIEW];
  const tDetails = getTDeferBlockDetails(tView, tNode);
  const prefetchTriggers = getPrefetchTriggers(tDetails);
  prefetchTriggers.add(2 /* DeferBlockTrigger.Viewport */);
  if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
    registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  }
}
/**
 * Creates runtime data structures for the `on viewport` hydrate trigger.
 * @codeGenApi
 */
function ɵɵdeferHydrateOnViewport() {
  const lView = getLView();
  const tNode = getCurrentTNode();
  if (shouldActivateHydrateTrigger(lView, tNode)) {
    const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
    hydrateTriggers.set(2 /* DeferBlockTrigger.Viewport */, null);
    const injector = lView[INJECTOR];
    if (typeof ngServerMode !== 'undefined' && ngServerMode) {
      // We are on the server and SSR for defer blocks is enabled.
      triggerDeferBlock(lView, tNode);
    }
  }
  // The actual triggering of hydration on viewport happens in incremental.ts,
  // since these instructions won't exist for dehydrated content.
}

/**
 * Updates the value of or removes a bound attribute on an Element.
 *
 * Used in the case of `[attr.title]="value"`
 *
 * @param name name The name of the attribute.
 * @param value value The attribute is removed when value is `null` or `undefined`.
 *                  Otherwise the attribute value is set to the stringified value.
 * @param sanitizer An optional function used to sanitize the value.
 * @param namespace Optional namespace to use when setting the attribute.
 *
 * @codeGenApi
 */
function ɵɵattribute(name, value, sanitizer, namespace) {
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, value)) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
  }
  return ɵɵattribute;
}

/**
 * Create interpolation bindings with a variable number of expressions.
 *
 * If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
 * Those are faster because there is no need to create an array of expressions and iterate over it.
 *
 * `values`:
 * - has static text at even indexes,
 * - has evaluated expressions at odd indexes.
 *
 * Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
 */
function interpolationV(lView, values) {
  ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
  ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
  let isBindingUpdated = false;
  let bindingIndex = getBindingIndex();
  for (let i = 1; i < values.length; i += 2) {
    // Check if bindings (odd indexes) have changed
    isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
  }
  setBindingIndex(bindingIndex);
  if (!isBindingUpdated) {
    return NO_CHANGE;
  }
  // Build the updated content
  let content = values[0];
  for (let i = 1; i < values.length; i += 2) {
    content += renderStringify(values[i]) + values[i + 1];
  }
  return content;
}
/**
 * Creates an interpolation binding with 1 expression.
 *
 * @param prefix static value used for concatenation only.
 * @param v0 value checked for change.
 * @param suffix static value used for concatenation only.
 */
function interpolation1(lView, prefix, v0, suffix) {
  const different = bindingUpdated(lView, nextBindingIndex(), v0);
  return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 2 expressions.
 */
function interpolation2(lView, prefix, v0, i0, v1, suffix) {
  const bindingIndex = getBindingIndex();
  const different = bindingUpdated2(lView, bindingIndex, v0, v1);
  incrementBindingIndex(2);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 3 expressions.
 */
function interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix) {
  const bindingIndex = getBindingIndex();
  const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
  incrementBindingIndex(3);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix : NO_CHANGE;
}
/**
 * Create an interpolation binding with 4 expressions.
 */
function interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  const bindingIndex = getBindingIndex();
  const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  incrementBindingIndex(4);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 5 expressions.
 */
function interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  const bindingIndex = getBindingIndex();
  let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
  incrementBindingIndex(5);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 6 expressions.
 */
function interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  const bindingIndex = getBindingIndex();
  let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
  incrementBindingIndex(6);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 7 expressions.
 */
function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  const bindingIndex = getBindingIndex();
  let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
  incrementBindingIndex(7);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + i5 + renderStringify(v6) + suffix : NO_CHANGE;
}
/**
 * Creates an interpolation binding with 8 expressions.
 */
function interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  const bindingIndex = getBindingIndex();
  let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
  incrementBindingIndex(8);
  return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + i5 + renderStringify(v6) + i6 + renderStringify(v7) + suffix : NO_CHANGE;
}

/**
 *
 * Update an interpolated attribute on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate1(attrName, prefix, v0, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 1, prefix, suffix);
  }
  return ɵɵattributeInterpolate1;
}
/**
 *
 * Update an interpolated attribute on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate2(attrName, prefix, v0, i0, v1, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 2, prefix, i0, suffix);
  }
  return ɵɵattributeInterpolate2;
}
/**
 *
 * Update an interpolated attribute on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate3(
 * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate3(attrName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  }
  return ɵɵattributeInterpolate3;
}
/**
 *
 * Update an interpolated attribute on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate4(
 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate4(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  }
  return ɵɵattributeInterpolate4;
}
/**
 *
 * Update an interpolated attribute on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate5(
 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate5(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  }
  return ɵɵattributeInterpolate5;
}
/**
 *
 * Update an interpolated attribute on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate6(
 *    'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate6(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  }
  return ɵɵattributeInterpolate6;
}
/**
 *
 * Update an interpolated attribute on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate7(
 *    'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate7(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  }
  return ɵɵattributeInterpolate7;
}
/**
 *
 * Update an interpolated attribute on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolate8(
 *  'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
 * ```
 *
 * @param attrName The name of the attribute to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolate8(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer, namespace) {
  const lView = getLView();
  const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
    ngDevMode && storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  }
  return ɵɵattributeInterpolate8;
}
/**
 * Update an interpolated attribute on an element with 9 or more bound values surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵattributeInterpolateV(
 *  'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *
 * @param attrName The name of the attribute to update.
 * @param values The collection of values and the strings in-between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵattributeInterpolateV(attrName, values, sanitizer, namespace) {
  const lView = getLView();
  const interpolated = interpolationV(lView, values);
  if (interpolated !== NO_CHANGE) {
    const tNode = getSelectedTNode();
    elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
    if (ngDevMode) {
      const interpolationInBetween = [values[0]]; // prefix
      for (let i = 2; i < values.length; i += 2) {
        interpolationInBetween.push(values[i]);
      }
      storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
    }
  }
  return ɵɵattributeInterpolateV;
}
function toTStylingRange(prev, next) {
  ngDevMode && assertNumberInRange(prev, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  return prev << 17 /* StylingRange.PREV_SHIFT */ | next << 2 /* StylingRange.NEXT_SHIFT */;
}
function getTStylingRangePrev(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return tStylingRange >> 17 /* StylingRange.PREV_SHIFT */ & 32767 /* StylingRange.UNSIGNED_MASK */;
}
function getTStylingRangePrevDuplicate(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return (tStylingRange & 2 /* StylingRange.PREV_DUPLICATE */) == 2 /* StylingRange.PREV_DUPLICATE */;
}
function setTStylingRangePrev(tStylingRange, previous) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  ngDevMode && assertNumberInRange(previous, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  return tStylingRange & ~4294836224 /* StylingRange.PREV_MASK */ | previous << 17 /* StylingRange.PREV_SHIFT */;
}
function setTStylingRangePrevDuplicate(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return tStylingRange | 2 /* StylingRange.PREV_DUPLICATE */;
}
function getTStylingRangeNext(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return (tStylingRange & 131068 /* StylingRange.NEXT_MASK */) >> 2 /* StylingRange.NEXT_SHIFT */;
}
function setTStylingRangeNext(tStylingRange, next) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  return tStylingRange & ~131068 /* StylingRange.NEXT_MASK */ |
  //
  next << 2 /* StylingRange.NEXT_SHIFT */;
}
function getTStylingRangeNextDuplicate(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return (tStylingRange & 1 /* StylingRange.NEXT_DUPLICATE */) === 1 /* StylingRange.NEXT_DUPLICATE */;
}
function setTStylingRangeNextDuplicate(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  return tStylingRange | 1 /* StylingRange.NEXT_DUPLICATE */;
}
function getTStylingRangeTail(tStylingRange) {
  ngDevMode && assertNumber(tStylingRange, 'expected number');
  const next = getTStylingRangeNext(tStylingRange);
  return next === 0 ? getTStylingRangePrev(tStylingRange) : next;
}

/**
 * NOTE: The word `styling` is used interchangeably as style or class styling.
 *
 * This file contains code to link styling instructions together so that they can be replayed in
 * priority order. The file exists because Ivy styling instruction execution order does not match
 * that of the priority order. The purpose of this code is to create a linked list so that the
 * instructions can be traversed in priority order when computing the styles.
 *
 * Assume we are dealing with the following code:
 * ```
 * @Component({
 *   template: `
 *     <my-cmp [style]=" {color: '#001'} "
 *             [style.color]=" #002 "
 *             dir-style-color-1
 *             dir-style-color-2> `
 * })
 * class ExampleComponent {
 *   static ngComp = ... {
 *     ...
 *     // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
 *     ɵɵstyleMap({color: '#001'});
 *     ɵɵstyleProp('color', '#002');
 *     ...
 *   }
 * }
 *
 * @Directive({
 *   selector: `[dir-style-color-1]',
 * })
 * class Style1Directive {
 *   @HostBinding('style') style = {color: '#005'};
 *   @HostBinding('style.color') color = '#006';
 *
 *   static ngDir = ... {
 *     ...
 *     // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
 *     ɵɵstyleMap({color: '#005'});
 *     ɵɵstyleProp('color', '#006');
 *     ...
 *   }
 * }
 *
 * @Directive({
 *   selector: `[dir-style-color-2]',
 * })
 * class Style2Directive {
 *   @HostBinding('style') style = {color: '#007'};
 *   @HostBinding('style.color') color = '#008';
 *
 *   static ngDir = ... {
 *     ...
 *     // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
 *     ɵɵstyleMap({color: '#007'});
 *     ɵɵstyleProp('color', '#008');
 *     ...
 *   }
 * }
 *
 * @Directive({
 *   selector: `my-cmp',
 * })
 * class MyComponent {
 *   @HostBinding('style') style = {color: '#003'};
 *   @HostBinding('style.color') color = '#004';
 *
 *   static ngComp = ... {
 *     ...
 *     // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
 *     ɵɵstyleMap({color: '#003'});
 *     ɵɵstyleProp('color', '#004');
 *     ...
 *   }
 * }
 * ```
 *
 * The Order of instruction execution is:
 *
 * NOTE: the comment binding location is for illustrative purposes only.
 *
 * ```
 * // Template: (ExampleComponent)
 *     ɵɵstyleMap({color: '#001'});   // Binding index: 10
 *     ɵɵstyleProp('color', '#002');  // Binding index: 12
 * // MyComponent
 *     ɵɵstyleMap({color: '#003'});   // Binding index: 20
 *     ɵɵstyleProp('color', '#004');  // Binding index: 22
 * // Style1Directive
 *     ɵɵstyleMap({color: '#005'});   // Binding index: 24
 *     ɵɵstyleProp('color', '#006');  // Binding index: 26
 * // Style2Directive
 *     ɵɵstyleMap({color: '#007'});   // Binding index: 28
 *     ɵɵstyleProp('color', '#008');  // Binding index: 30
 * ```
 *
 * The correct priority order of concatenation is:
 *
 * ```
 * // MyComponent
 *     ɵɵstyleMap({color: '#003'});   // Binding index: 20
 *     ɵɵstyleProp('color', '#004');  // Binding index: 22
 * // Style1Directive
 *     ɵɵstyleMap({color: '#005'});   // Binding index: 24
 *     ɵɵstyleProp('color', '#006');  // Binding index: 26
 * // Style2Directive
 *     ɵɵstyleMap({color: '#007'});   // Binding index: 28
 *     ɵɵstyleProp('color', '#008');  // Binding index: 30
 * // Template: (ExampleComponent)
 *     ɵɵstyleMap({color: '#001'});   // Binding index: 10
 *     ɵɵstyleProp('color', '#002');  // Binding index: 12
 * ```
 *
 * What color should be rendered?
 *
 * Once the items are correctly sorted in the list, the answer is simply the last item in the
 * concatenation list which is `#002`.
 *
 * To do so we keep a linked list of all of the bindings which pertain to this element.
 * Notice that the bindings are inserted in the order of execution, but the `TView.data` allows
 * us to traverse them in the order of priority.
 *
 * |Idx|`TView.data`|`LView`          | Notes
 * |---|------------|-----------------|--------------
 * |...|            |                 |
 * |10 |`null`      |`{color: '#001'}`| `ɵɵstyleMap('color', {color: '#001'})`
 * |11 |`30 | 12`   | ...             |
 * |12 |`color`     |`'#002'`         | `ɵɵstyleProp('color', '#002')`
 * |13 |`10 | 0`    | ...             |
 * |...|            |                 |
 * |20 |`null`      |`{color: '#003'}`| `ɵɵstyleMap('color', {color: '#003'})`
 * |21 |`0 | 22`    | ...             |
 * |22 |`color`     |`'#004'`         | `ɵɵstyleProp('color', '#004')`
 * |23 |`20 | 24`   | ...             |
 * |24 |`null`      |`{color: '#005'}`| `ɵɵstyleMap('color', {color: '#005'})`
 * |25 |`22 | 26`   | ...             |
 * |26 |`color`     |`'#006'`         | `ɵɵstyleProp('color', '#006')`
 * |27 |`24 | 28`   | ...             |
 * |28 |`null`      |`{color: '#007'}`| `ɵɵstyleMap('color', {color: '#007'})`
 * |29 |`26 | 30`   | ...             |
 * |30 |`color`     |`'#008'`         | `ɵɵstyleProp('color', '#008')`
 * |31 |`28 | 10`   | ...             |
 *
 * The above data structure allows us to re-concatenate the styling no matter which data binding
 * changes.
 *
 * NOTE: in addition to keeping track of next/previous index the `TView.data` also stores prev/next
 * duplicate bit. The duplicate bit if true says there either is a binding with the same name or
 * there is a map (which may contain the name). This information is useful in knowing if other
 * styles with higher priority need to be searched for overwrites.
 *
 * NOTE: See `should support example in 'tnode_linked_list.ts' documentation` in
 * `tnode_linked_list_spec.ts` for working example.
 */
let __unused_const_as_closure_does_not_like_standalone_comment_blocks__;
/**
 * Insert new `tStyleValue` at `TData` and link existing style bindings such that we maintain linked
 * list of styles and compute the duplicate flag.
 *
 * Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
 *
 * The function works by keeping track of `tStylingRange` which contains two pointers pointing to
 * the head/tail of the template portion of the styles.
 *  - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
 *  - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
 *
 * @param tData The `TData` to insert into.
 * @param tNode `TNode` associated with the styling element.
 * @param tStylingKey See `TStylingKey`.
 * @param index location of where `tStyleValue` should be stored (and linked into list.)
 * @param isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
 *               template.)
 * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
 *                       `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
 */
function insertTStylingBinding(tData, tNode, tStylingKeyWithStatic, index, isHostBinding, isClassBinding) {
  ngDevMode && assertFirstUpdatePass(getTView());
  let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
  let tmplHead = getTStylingRangePrev(tBindings);
  let tmplTail = getTStylingRangeNext(tBindings);
  tData[index] = tStylingKeyWithStatic;
  let isKeyDuplicateOfStatic = false;
  let tStylingKey;
  if (Array.isArray(tStylingKeyWithStatic)) {
    // We are case when the `TStylingKey` contains static fields as well.
    const staticKeyValueArray = tStylingKeyWithStatic;
    tStylingKey = staticKeyValueArray[1]; // unwrap.
    // We need to check if our key is present in the static so that we can mark it as duplicate.
    if (tStylingKey === null || keyValueArrayIndexOf(staticKeyValueArray, tStylingKey) > 0) {
      // tStylingKey is present in the statics, need to mark it as duplicate.
      isKeyDuplicateOfStatic = true;
    }
  } else {
    tStylingKey = tStylingKeyWithStatic;
  }
  if (isHostBinding) {
    // We are inserting host bindings
    // If we don't have template bindings then `tail` is 0.
    const hasTemplateBindings = tmplTail !== 0;
    // This is important to know because that means that the `head` can't point to the first
    // template bindings (there are none.) Instead the head points to the tail of the template.
    if (hasTemplateBindings) {
      // template head's "prev" will point to last host binding or to 0 if no host bindings yet
      const previousNode = getTStylingRangePrev(tData[tmplHead + 1]);
      tData[index + 1] = toTStylingRange(previousNode, tmplHead);
      // if a host binding has already been registered, we need to update the next of that host
      // binding to point to this one
      if (previousNode !== 0) {
        // We need to update the template-tail value to point to us.
        tData[previousNode + 1] = setTStylingRangeNext(tData[previousNode + 1], index);
      }
      // The "previous" of the template binding head should point to this host binding
      tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1], index);
    } else {
      tData[index + 1] = toTStylingRange(tmplHead, 0);
      // if a host binding has already been registered, we need to update the next of that host
      // binding to point to this one
      if (tmplHead !== 0) {
        // We need to update the template-tail value to point to us.
        tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1], index);
      }
      // if we don't have template, the head points to template-tail, and needs to be advanced.
      tmplHead = index;
    }
  } else {
    // We are inserting in template section.
    // We need to set this binding's "previous" to the current template tail
    tData[index + 1] = toTStylingRange(tmplTail, 0);
    ngDevMode && assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');
    if (tmplHead === 0) {
      tmplHead = index;
    } else {
      // We need to update the previous value "next" to point to this binding
      tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1], index);
    }
    tmplTail = index;
  }
  // Now we need to update / compute the duplicates.
  // Starting with our location search towards head (least priority)
  if (isKeyDuplicateOfStatic) {
    tData[index + 1] = setTStylingRangePrevDuplicate(tData[index + 1]);
  }
  markDuplicates(tData, tStylingKey, index, true);
  markDuplicates(tData, tStylingKey, index, false);
  markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
  tBindings = toTStylingRange(tmplHead, tmplTail);
  if (isClassBinding) {
    tNode.classBindings = tBindings;
  } else {
    tNode.styleBindings = tBindings;
  }
}
/**
 * Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
 *
 * @param tNode `TNode` where the residual is stored.
 * @param tStylingKey `TStylingKey` to store.
 * @param tData `TData` associated with the current `LView`.
 * @param index location of where `tStyleValue` should be stored (and linked into list.)
 * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
 *                       `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
 */
function markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding) {
  const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
  if (residual != null /* or undefined */ && typeof tStylingKey == 'string' && keyValueArrayIndexOf(residual, tStylingKey) >= 0) {
    // We have duplicate in the residual so mark ourselves as duplicate.
    tData[index + 1] = setTStylingRangeNextDuplicate(tData[index + 1]);
  }
}
/**
 * Marks `TStyleValue`s as duplicates if another style binding in the list has the same
 * `TStyleValue`.
 *
 * NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
 * with it set to `false` to search both the previous as well as next items in the list.
 *
 * No duplicate case
 * ```
 *   [style.color]
 *   [style.width.px] <<- index
 *   [style.height.px]
 * ```
 *
 * In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
 * duplicates because `width` is not found in any other part of the linked list.
 *
 * Duplicate case
 * ```
 *   [style.color]
 *   [style.width.em]
 *   [style.width.px] <<- index
 * ```
 * In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
 * because `width` is found in the chain.
 *
 * Map case 1
 * ```
 *   [style.width.px]
 *   [style.color]
 *   [style]  <<- index
 * ```
 * In the above case adding `[style]` will produce a duplicate with any other bindings because
 * `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
 *
 * Map case 2
 * ```
 *   [style]
 *   [style.width.px]
 *   [style.color]  <<- index
 * ```
 * In the above case adding `[style.color]` will produce a duplicate because there is already a
 * `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
 * `width`.
 *
 * NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
 * NOTE: We use `style` as example, but same logic is applied to `class`es as well.
 *
 * @param tData `TData` where the linked list is stored.
 * @param tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
 *        the linked list.
 * @param index Starting location in the linked list to search from
 * @param isPrevDir Direction.
 *        - `true` for previous (lower priority);
 *        - `false` for next (higher priority).
 */
function markDuplicates(tData, tStylingKey, index, isPrevDir) {
  const tStylingAtIndex = tData[index + 1];
  const isMap = tStylingKey === null;
  let cursor = isPrevDir ? getTStylingRangePrev(tStylingAtIndex) : getTStylingRangeNext(tStylingAtIndex);
  let foundDuplicate = false;
  // We keep iterating as long as we have a cursor
  // AND either:
  // - we found what we are looking for, OR
  // - we are a map in which case we have to continue searching even after we find what we were
  //   looking for since we are a wild card and everything needs to be flipped to duplicate.
  while (cursor !== 0 && (foundDuplicate === false || isMap)) {
    ngDevMode && assertIndexInRange(tData, cursor);
    const tStylingValueAtCursor = tData[cursor];
    const tStyleRangeAtCursor = tData[cursor + 1];
    if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
      foundDuplicate = true;
      tData[cursor + 1] = isPrevDir ? setTStylingRangeNextDuplicate(tStyleRangeAtCursor) : setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
    }
    cursor = isPrevDir ? getTStylingRangePrev(tStyleRangeAtCursor) : getTStylingRangeNext(tStyleRangeAtCursor);
  }
  if (foundDuplicate) {
    // if we found a duplicate, than mark ourselves.
    tData[index + 1] = isPrevDir ? setTStylingRangePrevDuplicate(tStylingAtIndex) : setTStylingRangeNextDuplicate(tStylingAtIndex);
  }
}
/**
 * Determines if two `TStylingKey`s are a match.
 *
 * When computing whether a binding contains a duplicate, we need to compare if the instruction
 * `TStylingKey` has a match.
 *
 * Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
 * - `color`
 *    - `color`    // Match another color
 *    - `null`     // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
 *    - `['', 'color', 'other', true]` // wrapped `color` so match
 *    - `['', null, 'other', true]`       // wrapped `null` so match
 *    - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
 * - `null`       // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
 *
 * @param tStylingKeyCursor
 * @param tStylingKey
 */
function isStylingMatch(tStylingKeyCursor, tStylingKey) {
  ngDevMode && assertNotEqual(Array.isArray(tStylingKey), true, "Expected that 'tStylingKey' has been unwrapped");
  if (tStylingKeyCursor === null ||
  // If the cursor is `null` it means that we have map at that
  // location so we must assume that we have a match.
  tStylingKey == null ||
  // If `tStylingKey` is `null` then it is a map therefor assume that it
  // contains a match.
  (Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) === tStylingKey // If the keys match explicitly than we are a match.
  ) {
    return true;
  } else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
    // if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
    // statics and we need to check those as well.
    return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >= 0; // see if we are matching the key
  }
  return false;
}

// Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
const parserState = {
  textEnd: 0,
  key: 0,
  keyEnd: 0,
  value: 0,
  valueEnd: 0
};
/**
 * Retrieves the last parsed `key` of style.
 * @param text the text to substring the key from.
 */
function getLastParsedKey(text) {
  return text.substring(parserState.key, parserState.keyEnd);
}
/**
 * Retrieves the last parsed `value` of style.
 * @param text the text to substring the key from.
 */
function getLastParsedValue(text) {
  return text.substring(parserState.value, parserState.valueEnd);
}
/**
 * Initializes `className` string for parsing and parses the first token.
 *
 * This function is intended to be used in this format:
 * ```
 * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
 *   const key = getLastParsedKey();
 *   ...
 * }
 * ```
 * @param text `className` to parse
 * @returns index where the next invocation of `parseClassNameNext` should resume.
 */
function parseClassName(text) {
  resetParserState(text);
  return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
 * Parses next `className` token.
 *
 * This function is intended to be used in this format:
 * ```
 * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
 *   const key = getLastParsedKey();
 *   ...
 * }
 * ```
 *
 * @param text `className` to parse
 * @param index where the parsing should resume.
 * @returns index where the next invocation of `parseClassNameNext` should resume.
 */
function parseClassNameNext(text, index) {
  const end = parserState.textEnd;
  if (end === index) {
    return -1;
  }
  index = parserState.keyEnd = consumeClassToken(text, parserState.key = index, end);
  return consumeWhitespace(text, index, end);
}
/**
 * Initializes `cssText` string for parsing and parses the first key/values.
 *
 * This function is intended to be used in this format:
 * ```
 * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
 *   const key = getLastParsedKey();
 *   const value = getLastParsedValue();
 *   ...
 * }
 * ```
 * @param text `cssText` to parse
 * @returns index where the next invocation of `parseStyleNext` should resume.
 */
function parseStyle(text) {
  resetParserState(text);
  return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
 * Parses the next `cssText` key/values.
 *
 * This function is intended to be used in this format:
 * ```
 * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
 *   const key = getLastParsedKey();
 *   const value = getLastParsedValue();
 *   ...
 * }
 *
 * @param text `cssText` to parse
 * @param index where the parsing should resume.
 * @returns index where the next invocation of `parseStyleNext` should resume.
 */
function parseStyleNext(text, startIndex) {
  const end = parserState.textEnd;
  let index = parserState.key = consumeWhitespace(text, startIndex, end);
  if (end === index) {
    // we reached an end so just quit
    return -1;
  }
  index = parserState.keyEnd = consumeStyleKey(text, index, end);
  index = consumeSeparator(text, index, end, 58 /* CharCode.COLON */);
  index = parserState.value = consumeWhitespace(text, index, end);
  index = parserState.valueEnd = consumeStyleValue(text, index, end);
  return consumeSeparator(text, index, end, 59 /* CharCode.SEMI_COLON */);
}
/**
 * Reset the global state of the styling parser.
 * @param text The styling text to parse.
 */
function resetParserState(text) {
  parserState.key = 0;
  parserState.keyEnd = 0;
  parserState.value = 0;
  parserState.valueEnd = 0;
  parserState.textEnd = text.length;
}
/**
 * Returns index of next non-whitespace character.
 *
 * @param text Text to scan
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
 *          that location.)
 */
function consumeWhitespace(text, startIndex, endIndex) {
  while (startIndex < endIndex && text.charCodeAt(startIndex) <= 32 /* CharCode.SPACE */) {
    startIndex++;
  }
  return startIndex;
}
/**
 * Returns index of last char in class token.
 *
 * @param text Text to scan
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index after last char in class token.
 */
function consumeClassToken(text, startIndex, endIndex) {
  while (startIndex < endIndex && text.charCodeAt(startIndex) > 32 /* CharCode.SPACE */) {
    startIndex++;
  }
  return startIndex;
}
/**
 * Consumes all of the characters belonging to style key and token.
 *
 * @param text Text to scan
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index after last style key character.
 */
function consumeStyleKey(text, startIndex, endIndex) {
  let ch;
  while (startIndex < endIndex && ((ch = text.charCodeAt(startIndex)) === 45 /* CharCode.DASH */ || ch === 95 /* CharCode.UNDERSCORE */ || (ch & -33 /* CharCode.UPPER_CASE */) >= 65 /* CharCode.A */ && (ch & -33 /* CharCode.UPPER_CASE */) <= 90 /* CharCode.Z */ || ch >= 48 /* CharCode.ZERO */ && ch <= 57 /* CharCode.NINE */)) {
    startIndex++;
  }
  return startIndex;
}
/**
 * Consumes all whitespace and the separator `:` after the style key.
 *
 * @param text Text to scan
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index after separator and surrounding whitespace.
 */
function consumeSeparator(text, startIndex, endIndex, separator) {
  startIndex = consumeWhitespace(text, startIndex, endIndex);
  if (startIndex < endIndex) {
    if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
      malformedStyleError(text, String.fromCharCode(separator), startIndex);
    }
    startIndex++;
  }
  return startIndex;
}
/**
 * Consumes style value honoring `url()` and `""` text.
 *
 * @param text Text to scan
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index after last style value character.
 */
function consumeStyleValue(text, startIndex, endIndex) {
  let ch1 = -1; // 1st previous character
  let ch2 = -1; // 2nd previous character
  let ch3 = -1; // 3rd previous character
  let i = startIndex;
  let lastChIndex = i;
  while (i < endIndex) {
    const ch = text.charCodeAt(i++);
    if (ch === 59 /* CharCode.SEMI_COLON */) {
      return lastChIndex;
    } else if (ch === 34 /* CharCode.DOUBLE_QUOTE */ || ch === 39 /* CharCode.SINGLE_QUOTE */) {
      lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
    } else if (startIndex === i - 4 &&
    // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
    ch3 === 85 /* CharCode.U */ && ch2 === 82 /* CharCode.R */ && ch1 === 76 /* CharCode.L */ && ch === 40 /* CharCode.OPEN_PAREN */) {
      lastChIndex = i = consumeQuotedText(text, 41 /* CharCode.CLOSE_PAREN */, i, endIndex);
    } else if (ch > 32 /* CharCode.SPACE */) {
      // if we have a non-whitespace character then capture its location
      lastChIndex = i;
    }
    ch3 = ch2;
    ch2 = ch1;
    ch1 = ch & -33 /* CharCode.UPPER_CASE */;
  }
  return lastChIndex;
}
/**
 * Consumes all of the quoted characters.
 *
 * @param text Text to scan
 * @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
 * @param startIndex Starting index of character where the scan should start.
 * @param endIndex Ending index of character where the scan should end.
 * @returns Index after quoted characters.
 */
function consumeQuotedText(text, quoteCharCode, startIndex, endIndex) {
  let ch1 = -1; // 1st previous character
  let index = startIndex;
  while (index < endIndex) {
    const ch = text.charCodeAt(index++);
    if (ch == quoteCharCode && ch1 !== 92 /* CharCode.BACK_SLASH */) {
      return index;
    }
    if (ch == 92 /* CharCode.BACK_SLASH */ && ch1 === 92 /* CharCode.BACK_SLASH */) {
      // two back slashes cancel each other out. For example `"\\"` should properly end the
      // quotation. (It should not assume that the last `"` is escaped.)
      ch1 = 0;
    } else {
      ch1 = ch;
    }
  }
  throw ngDevMode ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex) : new Error();
}
function malformedStyleError(text, expecting, index) {
  ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
  throw throwError(`Malformed style at location ${index} in string '` + text.substring(0, index) + '[>>' + text.substring(index, index + 1) + '<<]' + text.slice(index + 1) + `'. Expecting '${expecting}'.`);
}

/**
 * Update a property on a selected element.
 *
 * Operates on the element selected by index via the {@link select} instruction.
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled
 *
 * @param propName Name of property. Because it is going to DOM, this is not subject to
 *        renaming as part of minification.
 * @param value New value to write.
 * @param sanitizer An optional function used to sanitize the value.
 * @returns This function returns itself so that it may be chained
 * (e.g. `property('name', ctx.name)('title', ctx.title)`)
 *
 * @codeGenApi
 */
function ɵɵproperty(propName, value, sanitizer) {
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, value)) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  }
  return ɵɵproperty;
}
/**
 * Given `<div style="..." my-dir>` and `MyDir` with `@Input('style')` we need to write to
 * directive input.
 */
function setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased) {
  const inputs = tNode.inputs;
  const property = isClassBased ? 'class' : 'style';
  // We support both 'class' and `className` hence the fallback.
  setInputsForProperty(tView, lView, inputs[property], property, value);
}

/**
 * Update a style binding on an element with the provided value.
 *
 * If the style value is falsy then it will be removed from the element
 * (or assigned a different value depending if there are any styles placed
 * on the element with `styleMap` or any static styles that are
 * present from when the element was created with `styling`).
 *
 * Note that the styling element is updated as part of `stylingApply`.
 *
 * @param prop A valid CSS property.
 * @param value New value to write (`null` or an empty string to remove).
 * @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
 *
 * Note that this will apply the provided style value to the host element if this function is called
 * within a host binding function.
 *
 * @codeGenApi
 */
function ɵɵstyleProp(prop, value, suffix) {
  checkStylingProperty(prop, value, suffix, false);
  return ɵɵstyleProp;
}
/**
 * Update a class binding on an element with the provided value.
 *
 * This instruction is meant to handle the `[class.foo]="exp"` case and,
 * therefore, the class binding itself must already be allocated using
 * `styling` within the creation block.
 *
 * @param prop A valid CSS class (only one).
 * @param value A true/false value which will turn the class on or off.
 *
 * Note that this will apply the provided class value to the host element if this function
 * is called within a host binding function.
 *
 * @codeGenApi
 */
function ɵɵclassProp(className, value) {
  checkStylingProperty(className, value, null, true);
  return ɵɵclassProp;
}
/**
 * Update style bindings using an object literal on an element.
 *
 * This instruction is meant to apply styling via the `[style]="exp"` template bindings.
 * When styles are applied to the element they will then be updated with respect to
 * any styles/classes set via `styleProp`. If any styles are set to falsy
 * then they will be removed from the element.
 *
 * Note that the styling instruction will not be applied until `stylingApply` is called.
 *
 * @param styles A key/value style map of the styles that will be applied to the given element.
 *        Any missing styles (that have already been applied to the element beforehand) will be
 *        removed (unset) from the element's styling.
 *
 * Note that this will apply the provided styleMap value to the host element if this function
 * is called within a host binding.
 *
 * @codeGenApi
 */
function ɵɵstyleMap(styles) {
  checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false);
}
/**
 * Parse text as style and add values to KeyValueArray.
 *
 * This code is pulled out to a separate function so that it can be tree shaken away if it is not
 * needed. It is only referenced from `ɵɵstyleMap`.
 *
 * @param keyValueArray KeyValueArray to add parsed values to.
 * @param text text to parse.
 */
function styleStringParser(keyValueArray, text) {
  for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) {
    styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text));
  }
}
/**
 * Update class bindings using an object literal or class-string on an element.
 *
 * This instruction is meant to apply styling via the `[class]="exp"` template bindings.
 * When classes are applied to the element they will then be updated with
 * respect to any styles/classes set via `classProp`. If any
 * classes are set to falsy then they will be removed from the element.
 *
 * Note that the styling instruction will not be applied until `stylingApply` is called.
 * Note that this will the provided classMap value to the host element if this function is called
 * within a host binding.
 *
 * @param classes A key/value map or string of CSS classes that will be added to the
 *        given element. Any missing classes (that have already been applied to the element
 *        beforehand) will be removed (unset) from the element's list of CSS classes.
 *
 * @codeGenApi
 */
function ɵɵclassMap(classes) {
  checkStylingMap(classKeyValueArraySet, classStringParser, classes, true);
}
/**
 * Parse text as class and add values to KeyValueArray.
 *
 * This code is pulled out to a separate function so that it can be tree shaken away if it is not
 * needed. It is only referenced from `ɵɵclassMap`.
 *
 * @param keyValueArray KeyValueArray to add parsed values to.
 * @param text text to parse.
 */
function classStringParser(keyValueArray, text) {
  for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
    keyValueArraySet(keyValueArray, getLastParsedKey(text), true);
  }
}
/**
 * Common code between `ɵɵclassProp` and `ɵɵstyleProp`.
 *
 * @param prop property name.
 * @param value binding value.
 * @param suffix suffix for the property (e.g. `em` or `px`)
 * @param isClassBased `true` if `class` change (`false` if `style`)
 */
function checkStylingProperty(prop, value, suffix, isClassBased) {
  const lView = getLView();
  const tView = getTView();
  // Styling instructions use 2 slots per binding.
  // 1. one for the value / TStylingKey
  // 2. one for the intermittent-value / TStylingRange
  const bindingIndex = incrementBindingIndex(2);
  if (tView.firstUpdatePass) {
    stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased);
  }
  if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
    const tNode = tView.data[getSelectedIndex()];
    updateStyling(tView, tNode, lView, lView[RENDERER], prop, lView[bindingIndex + 1] = normalizeSuffix(value, suffix), isClassBased, bindingIndex);
  }
}
/**
 * Common code between `ɵɵclassMap` and `ɵɵstyleMap`.
 *
 * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
 *        function so that `style` can be processed. This is done for tree shaking purposes.
 * @param stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class`
 *        have different parsers.)
 * @param value bound value from application
 * @param isClassBased `true` if `class` change (`false` if `style`)
 */
function checkStylingMap(keyValueArraySet, stringParser, value, isClassBased) {
  const tView = getTView();
  const bindingIndex = incrementBindingIndex(2);
  if (tView.firstUpdatePass) {
    stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased);
  }
  const lView = getLView();
  if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
    // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
    // if so as not to read unnecessarily.
    const tNode = tView.data[getSelectedIndex()];
    if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) {
      if (ngDevMode) {
        // verify that if we are shadowing then `TData` is appropriately marked so that we skip
        // processing this binding in styling resolution.
        const tStylingKey = tView.data[bindingIndex];
        assertEqual(Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, "Styling linked list shadow input should be marked as 'false'");
      }
      // VE does not concatenate the static portion like we are doing here.
      // Instead VE just ignores the static completely if dynamic binding is present.
      // Because of locality we have already set the static portion because we don't know if there
      // is a dynamic portion until later. If we would ignore the static portion it would look like
      // the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong
      // thing as it would think that the static portion was removed. For this reason we
      // concatenate it so that `[ngStyle]`/`[ngClass]`  can continue to work on changed.
      let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost;
      ngDevMode && isClassBased === false && staticPrefix !== null && assertEqual(staticPrefix.endsWith(';'), true, "Expecting static portion to end with ';'");
      if (staticPrefix !== null) {
        // We want to make sure that falsy values of `value` become empty strings.
        value = concatStringsWithSpace(staticPrefix, value ? value : '');
      }
      // Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`.
      // This takes over the `[style]` binding. (Same for `[class]`)
      setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased);
    } else {
      updateStylingMap(tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value), isClassBased, bindingIndex);
    }
  }
}
/**
 * Determines when the binding is in `hostBindings` section
 *
 * @param tView Current `TView`
 * @param bindingIndex index of binding which we would like if it is in `hostBindings`
 */
function isInHostBindings(tView, bindingIndex) {
  // All host bindings are placed after the expando section.
  return bindingIndex >= tView.expandoStartIndex;
}
/**
 * Collects the necessary information to insert the binding into a linked list of style bindings
 * using `insertTStylingBinding`.
 *
 * @param tView `TView` where the binding linked list will be stored.
 * @param tStylingKey Property/key of the binding.
 * @param bindingIndex Index of binding associated with the `prop`
 * @param isClassBased `true` if `class` change (`false` if `style`)
 */
function stylingFirstUpdatePass(tView, tStylingKey, bindingIndex, isClassBased) {
  ngDevMode && assertFirstUpdatePass(tView);
  const tData = tView.data;
  if (tData[bindingIndex + 1] === null) {
    // The above check is necessary because we don't clear first update pass until first successful
    // (no exception) template execution. This prevents the styling instruction from double adding
    // itself to the list.
    // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
    // if so as not to read unnecessarily.
    const tNode = tData[getSelectedIndex()];
    ngDevMode && assertDefined(tNode, 'TNode expected');
    const isHostBindings = isInHostBindings(tView, bindingIndex);
    if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) {
      // `tStylingKey === null` implies that we are either `[style]` or `[class]` binding.
      // If there is a directive which uses `@Input('style')` or `@Input('class')` than
      // we need to neutralize this binding since that directive is shadowing it.
      // We turn this into a noop by setting the key to `false`
      tStylingKey = false;
    }
    tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased);
    insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased);
  }
}
/**
 * Adds static styling information to the binding if applicable.
 *
 * The linked list of styles not only stores the list and keys, but also stores static styling
 * information on some of the keys. This function determines if the key should contain the styling
 * information and computes it.
 *
 * See `TStylingStatic` for more details.
 *
 * @param tData `TData` where the linked list is stored.
 * @param tNode `TNode` for which the styling is being computed.
 * @param stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey`
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function wrapInStaticStylingKey(tData, tNode, stylingKey, isClassBased) {
  const hostDirectiveDef = getCurrentDirectiveDef(tData);
  let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
  if (hostDirectiveDef === null) {
    // We are in template node.
    // If template node already had styling instruction then it has already collected the static
    // styling and there is no need to collect them again. We know that we are the first styling
    // instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
    const isFirstStylingInstructionInTemplate = (isClassBased ? tNode.classBindings : tNode.styleBindings) === 0;
    if (isFirstStylingInstructionInTemplate) {
      // It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
      // they are already merged and it would not be possible to figure which property belongs where
      // in the priority.
      stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
      stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
      // We know that if we have styling binding in template we can't have residual.
      residual = null;
    }
  } else {
    // We are in host binding node and there was no binding instruction in template node.
    // This means that we need to compute the residual.
    const directiveStylingLast = tNode.directiveStylingLast;
    const isFirstStylingInstructionInHostBinding = directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
    if (isFirstStylingInstructionInHostBinding) {
      stylingKey = collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased);
      if (residual === null) {
        // - If `null` than either:
        //    - Template styling instruction already ran and it has consumed the static
        //      styling into its `TStylingKey` and so there is no need to update residual. Instead
        //      we need to update the `TStylingKey` associated with the first template node
        //      instruction. OR
        //    - Some other styling instruction ran and determined that there are no residuals
        let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
        if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
          // Only recompute if `templateStylingKey` had static values. (If no static value found
          // then there is nothing to do since this operation can only produce less static keys, not
          // more.)
          templateStylingKey = collectStylingFromDirectives(null, tData, tNode, templateStylingKey[1] /* unwrap previous statics */, isClassBased);
          templateStylingKey = collectStylingFromTAttrs(templateStylingKey, tNode.attrs, isClassBased);
          setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
        }
      } else {
        // We only need to recompute residual if it is not `null`.
        // - If existing residual (implies there was no template styling). This means that some of
        //   the statics may have moved from the residual to the `stylingKey` and so we have to
        //   recompute.
        // - If `undefined` this is the first time we are running.
        residual = collectResidual(tData, tNode, isClassBased);
      }
    }
  }
  if (residual !== undefined) {
    isClassBased ? tNode.residualClasses = residual : tNode.residualStyles = residual;
  }
  return stylingKey;
}
/**
 * Retrieve the `TStylingKey` for the template styling instruction.
 *
 * This is needed since `hostBinding` styling instructions are inserted after the template
 * instruction. While the template instruction needs to update the residual in `TNode` the
 * `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
 * the template instruction is downstream from the `hostBindings` instructions.
 *
 * @param tData `TData` where the linked list is stored.
 * @param tNode `TNode` for which the styling is being computed.
 * @param isClassBased `true` if `class` (`false` if `style`)
 * @return `TStylingKey` if found or `undefined` if not found.
 */
function getTemplateHeadTStylingKey(tData, tNode, isClassBased) {
  const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  if (getTStylingRangeNext(bindings) === 0) {
    // There does not seem to be a styling instruction in the `template`.
    return undefined;
  }
  return tData[getTStylingRangePrev(bindings)];
}
/**
 * Update the `TStylingKey` of the first template instruction in `TNode`.
 *
 * Logically `hostBindings` styling instructions are of lower priority than that of the template.
 * However, they execute after the template styling instructions. This means that they get inserted
 * in front of the template styling instructions.
 *
 * If we have a template styling instruction and a new `hostBindings` styling instruction is
 * executed it means that it may need to steal static fields from the template instruction. This
 * method allows us to update the first template instruction `TStylingKey` with a new value.
 *
 * Assume:
 * ```
 * <div my-dir style="color: red" [style.color]="tmplExp"></div>
 *
 * @Directive({
 *   host: {
 *     'style': 'width: 100px',
 *     '[style.color]': 'dirExp',
 *   }
 * })
 * class MyDir {}
 * ```
 *
 * when `[style.color]="tmplExp"` executes it creates this data structure.
 * ```
 *  ['', 'color', 'color', 'red', 'width', '100px'],
 * ```
 *
 * The reason for this is that the template instruction does not know if there are styling
 * instructions and must assume that there are none and must collect all of the static styling.
 * (both
 * `color' and 'width`)
 *
 * When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
 * ```
 *  ['', 'color', 'width', '100px'],  // newly inserted
 *  ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
 * ```
 *
 * Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
 * update it like so:
 * ```
 *  ['', 'color', 'width', '100px'],
 *  ['', 'color', 'color', 'red'],    // UPDATE
 * ```
 *
 * @param tData `TData` where the linked list is stored.
 * @param tNode `TNode` for which the styling is being computed.
 * @param isClassBased `true` if `class` (`false` if `style`)
 * @param tStylingKey New `TStylingKey` which is replacing the old one.
 */
function setTemplateHeadTStylingKey(tData, tNode, isClassBased, tStylingKey) {
  const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  ngDevMode && assertNotEqual(getTStylingRangeNext(bindings), 0, 'Expecting to have at least one template styling binding.');
  tData[getTStylingRangePrev(bindings)] = tStylingKey;
}
/**
 * Collect all static values after the current `TNode.directiveStylingLast` index.
 *
 * Collect the remaining styling information which has not yet been collected by an existing
 * styling instruction.
 *
 * @param tData `TData` where the `DirectiveDefs` are stored.
 * @param tNode `TNode` which contains the directive range.
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function collectResidual(tData, tNode, isClassBased) {
  let residual = undefined;
  const directiveEnd = tNode.directiveEnd;
  ngDevMode && assertNotEqual(tNode.directiveStylingLast, -1, 'By the time this function gets called at least one hostBindings-node styling instruction must have executed.');
  // We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
  // collecting things after the last `hostBindings` directive which had a styling instruction.)
  for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
    const attrs = tData[i].hostAttrs;
    residual = collectStylingFromTAttrs(residual, attrs, isClassBased);
  }
  return collectStylingFromTAttrs(residual, tNode.attrs, isClassBased);
}
/**
 * Collect the static styling information with lower priority than `hostDirectiveDef`.
 *
 * (This is opposite of residual styling.)
 *
 * @param hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
 *        styling. (Or `null` if template styling)
 * @param tData `TData` where the linked list is stored.
 * @param tNode `TNode` for which the styling is being computed.
 * @param stylingKey Existing `TStylingKey` to update or wrap.
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased) {
  // We need to loop because there can be directives which have `hostAttrs` but don't have
  // `hostBindings` so this loop catches up to the current directive..
  let currentDirective = null;
  const directiveEnd = tNode.directiveEnd;
  let directiveStylingLast = tNode.directiveStylingLast;
  if (directiveStylingLast === -1) {
    directiveStylingLast = tNode.directiveStart;
  } else {
    directiveStylingLast++;
  }
  while (directiveStylingLast < directiveEnd) {
    currentDirective = tData[directiveStylingLast];
    ngDevMode && assertDefined(currentDirective, 'expected to be defined');
    stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
    if (currentDirective === hostDirectiveDef) break;
    directiveStylingLast++;
  }
  if (hostDirectiveDef !== null) {
    // we only advance the styling cursor if we are collecting data from host bindings.
    // Template executes before host bindings and so if we would update the index,
    // host bindings would not get their statics.
    tNode.directiveStylingLast = directiveStylingLast;
  }
  return stylingKey;
}
/**
 * Convert `TAttrs` into `TStylingStatic`.
 *
 * @param stylingKey existing `TStylingKey` to update or wrap.
 * @param attrs `TAttributes` to process.
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function collectStylingFromTAttrs(stylingKey, attrs, isClassBased) {
  const desiredMarker = isClassBased ? 1 /* AttributeMarker.Classes */ : 2 /* AttributeMarker.Styles */;
  let currentMarker = -1 /* AttributeMarker.ImplicitAttributes */;
  if (attrs !== null) {
    for (let i = 0; i < attrs.length; i++) {
      const item = attrs[i];
      if (typeof item === 'number') {
        currentMarker = item;
      } else {
        if (currentMarker === desiredMarker) {
          if (!Array.isArray(stylingKey)) {
            stylingKey = stylingKey === undefined ? [] : ['', stylingKey];
          }
          keyValueArraySet(stylingKey, item, isClassBased ? true : attrs[++i]);
        }
      }
    }
  }
  return stylingKey === undefined ? null : stylingKey;
}
/**
 * Convert user input to `KeyValueArray`.
 *
 * This function takes user input which could be `string`, Object literal, or iterable and converts
 * it into a consistent representation. The output of this is `KeyValueArray` (which is an array
 * where
 * even indexes contain keys and odd indexes contain values for those keys).
 *
 * The advantage of converting to `KeyValueArray` is that we can perform diff in an input
 * independent
 * way.
 * (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
 * applied)
 *
 * The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
 * difference in linear fashion without the need to allocate any additional data.
 *
 * For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
 * which values need to be deleted, over the new `Map` to determine additions, and we would have to
 * keep additional `Map` to keep track of duplicates or items which have not yet been visited.
 *
 * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
 *        function so that `style` can be processed. This is done
 *        for tree shaking purposes.
 * @param stringParser The parser is passed in so that it will be tree shakable. See
 *        `styleStringParser` and `classStringParser`
 * @param value The value to parse/convert to `KeyValueArray`
 */
function toStylingKeyValueArray(keyValueArraySet, stringParser, value) {
  if (value == null /*|| value === undefined */ || value === '') return EMPTY_ARRAY;
  const styleKeyValueArray = [];
  const unwrappedValue = unwrapSafeValue(value);
  if (Array.isArray(unwrappedValue)) {
    for (let i = 0; i < unwrappedValue.length; i++) {
      keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
    }
  } else if (typeof unwrappedValue === 'object') {
    for (const key in unwrappedValue) {
      if (unwrappedValue.hasOwnProperty(key)) {
        keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
      }
    }
  } else if (typeof unwrappedValue === 'string') {
    stringParser(styleKeyValueArray, unwrappedValue);
  } else {
    ngDevMode && throwError('Unsupported styling type ' + typeof unwrappedValue + ': ' + unwrappedValue);
  }
  return styleKeyValueArray;
}
/**
 * Set a `value` for a `key`.
 *
 * See: `keyValueArraySet` for details
 *
 * @param keyValueArray KeyValueArray to add to.
 * @param key Style key to add.
 * @param value The value to set.
 */
function styleKeyValueArraySet(keyValueArray, key, value) {
  keyValueArraySet(keyValueArray, key, unwrapSafeValue(value));
}
/**
 * Class-binding-specific function for setting the `value` for a `key`.
 *
 * See: `keyValueArraySet` for details
 *
 * @param keyValueArray KeyValueArray to add to.
 * @param key Style key to add.
 * @param value The value to set.
 */
function classKeyValueArraySet(keyValueArray, key, value) {
  // We use `classList.add` to eventually add the CSS classes to the DOM node. Any value passed into
  // `add` is stringified and added to the `class` attribute, e.g. even null, undefined or numbers
  // will be added. Stringify the key here so that our internal data structure matches the value in
  // the DOM. The only exceptions are empty strings and strings that contain spaces for which
  // the browser throws an error. We ignore such values, because the error is somewhat cryptic.
  const stringKey = String(key);
  if (stringKey !== '' && !stringKey.includes(' ')) {
    keyValueArraySet(keyValueArray, stringKey, value);
  }
}
/**
 * Update map based styling.
 *
 * Map based styling could be anything which contains more than one binding. For example `string`,
 * or object literal. Dealing with all of these types would complicate the logic so
 * instead this function expects that the complex input is first converted into normalized
 * `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
 * very cheap to compute deltas between the previous and current value.
 *
 * @param tView Associated `TView.data` contains the linked list of binding priorities.
 * @param tNode `TNode` where the binding is located.
 * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
 * @param renderer Renderer to use if any updates.
 * @param oldKeyValueArray Previous value represented as `KeyValueArray`
 * @param newKeyValueArray Current value represented as `KeyValueArray`
 * @param isClassBased `true` if `class` (`false` if `style`)
 * @param bindingIndex Binding index of the binding.
 */
function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
  if (oldKeyValueArray === NO_CHANGE) {
    // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
    oldKeyValueArray = EMPTY_ARRAY;
  }
  let oldIndex = 0;
  let newIndex = 0;
  let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
  let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
  while (oldKey !== null || newKey !== null) {
    ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
    ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
    const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
    const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
    let setKey = null;
    let setValue = undefined;
    if (oldKey === newKey) {
      // UPDATE: Keys are equal => new value is overwriting old value.
      oldIndex += 2;
      newIndex += 2;
      if (oldValue !== newValue) {
        setKey = newKey;
        setValue = newValue;
      }
    } else if (newKey === null || oldKey !== null && oldKey < newKey) {
      // DELETE: oldKey key is missing or we did not find the oldKey in the newValue
      // (because the keyValueArray is sorted and `newKey` is found later alphabetically).
      // `"background" < "color"` so we need to delete `"background"` because it is not found in the
      // new array.
      oldIndex += 2;
      setKey = oldKey;
    } else {
      // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
      // `"color" > "background"` so we need to add `color` because it is in new array but not in
      // old array.
      ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
      newIndex += 2;
      setKey = newKey;
      setValue = newValue;
    }
    if (setKey !== null) {
      updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
    }
    oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
    newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
  }
}
/**
 * Update a simple (property name) styling.
 *
 * This function takes `prop` and updates the DOM to that value. The function takes the binding
 * value as well as binding priority into consideration to determine which value should be written
 * to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
 * the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
 *
 * @param tView Associated `TView.data` contains the linked list of binding priorities.
 * @param tNode `TNode` where the binding is located.
 * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
 * @param renderer Renderer to use if any updates.
 * @param prop Either style property name or a class name.
 * @param value Either style value for `prop` or `true`/`false` if `prop` is class.
 * @param isClassBased `true` if `class` (`false` if `style`)
 * @param bindingIndex Binding index of the binding.
 */
function updateStyling(tView, tNode, lView, renderer, prop, value, isClassBased, bindingIndex) {
  if (!(tNode.type & 3 /* TNodeType.AnyRNode */)) {
    // It is possible to have styling on non-elements (such as ng-container).
    // This is rare, but it does happen. In such a case, just ignore the binding.
    return;
  }
  const tData = tView.data;
  const tRange = tData[bindingIndex + 1];
  const higherPriorityValue = getTStylingRangeNextDuplicate(tRange) ? findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased) : undefined;
  if (!isStylingValuePresent(higherPriorityValue)) {
    // We don't have a next duplicate, or we did not find a duplicate value.
    if (!isStylingValuePresent(value)) {
      // We should delete current value or restore to lower priority value.
      if (getTStylingRangePrevDuplicate(tRange)) {
        // We have a possible prev duplicate, let's retrieve it.
        value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
      }
    }
    const rNode = getNativeByIndex(getSelectedIndex(), lView);
    applyStyling(renderer, isClassBased, rNode, prop, value);
  }
}
/**
 * Search for styling value with higher priority which is overwriting current value, or a
 * value of lower priority to which we should fall back if the value is `undefined`.
 *
 * When value is being applied at a location, related values need to be consulted.
 * - If there is a higher priority binding, we should be using that one instead.
 *   For example `<div  [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
 *   requires that we check `exp2` to see if it is set to value other than `undefined`.
 * - If there is a lower priority binding and we are changing to `undefined`
 *   For example `<div  [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
 *   `undefined` requires that we check `exp1` (and static values) and use that as new value.
 *
 * NOTE: The styling stores two values.
 * 1. The raw value which came from the application is stored at `index + 0` location. (This value
 *    is used for dirty checking).
 * 2. The normalized value is stored at `index + 1`.
 *
 * @param tData `TData` used for traversing the priority.
 * @param tNode `TNode` to use for resolving static styling. Also controls search direction.
 *   - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
 *      If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
 *   - `null` search prev and go all the way to end. Return last value where
 *     `isStylingValuePresent(value)` is true.
 * @param lView `LView` used for retrieving the actual values.
 * @param prop Property which we are interested in.
 * @param index Starting index in the linked list of styling bindings where the search should start.
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function findStylingValue(tData, tNode, lView, prop, index, isClassBased) {
  // `TNode` to use for resolving static styling. Also controls search direction.
  //   - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
  //      If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
  //   - `null` search prev and go all the way to end. Return last value where
  //     `isStylingValuePresent(value)` is true.
  const isPrevDirection = tNode === null;
  let value = undefined;
  while (index > 0) {
    const rawKey = tData[index];
    const containsStatics = Array.isArray(rawKey);
    // Unwrap the key if we contain static values.
    const key = containsStatics ? rawKey[1] : rawKey;
    const isStylingMap = key === null;
    let valueAtLViewIndex = lView[index + 1];
    if (valueAtLViewIndex === NO_CHANGE) {
      // In firstUpdatePass the styling instructions create a linked list of styling.
      // On subsequent passes it is possible for a styling instruction to try to read a binding
      // which
      // has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
      // we have `undefined` (or empty array in case of styling-map instruction) instead. This
      // allows the resolution to apply the value (which may later be overwritten when the
      // binding actually executes.)
      valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY : undefined;
    }
    let currentValue = isStylingMap ? keyValueArrayGet(valueAtLViewIndex, prop) : key === prop ? valueAtLViewIndex : undefined;
    if (containsStatics && !isStylingValuePresent(currentValue)) {
      currentValue = keyValueArrayGet(rawKey, prop);
    }
    if (isStylingValuePresent(currentValue)) {
      value = currentValue;
      if (isPrevDirection) {
        return value;
      }
    }
    const tRange = tData[index + 1];
    index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
  }
  if (tNode !== null) {
    // in case where we are going in next direction AND we did not find anything, we need to
    // consult residual styling
    let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
    if (residual != null /** OR residual !=== undefined */) {
      value = keyValueArrayGet(residual, prop);
    }
  }
  return value;
}
/**
 * Determines if the binding value should be used (or if the value is 'undefined' and hence priority
 * resolution should be used.)
 *
 * @param value Binding style value.
 */
function isStylingValuePresent(value) {
  // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
  // have an opinion as to what this binding should be and you should consult other bindings by
  // priority to determine the valid value.
  // This is extracted into a single function so that we have a single place to control this.
  return value !== undefined;
}
/**
 * Normalizes and/or adds a suffix to the value.
 *
 * If value is `null`/`undefined` no suffix is added
 * @param value
 * @param suffix
 */
function normalizeSuffix(value, suffix) {
  if (value == null || value === '') {
    // do nothing
    // Do not add the suffix if the value is going to be empty.
    // As it produce invalid CSS, which the browsers will automatically omit but Domino will not.
    // Example: `"left": "px;"` instead of `"left": ""`.
  } else if (typeof suffix === 'string') {
    value = value + suffix;
  } else if (typeof value === 'object') {
    value = stringify(unwrapSafeValue(value));
  }
  return value;
}
/**
 * Tests if the `TNode` has input shadow.
 *
 * An input shadow is when a directive steals (shadows) the input by using `@Input('style')` or
 * `@Input('class')` as input.
 *
 * @param tNode `TNode` which we would like to see if it has shadow.
 * @param isClassBased `true` if `class` (`false` if `style`)
 */
function hasStylingInputShadow(tNode, isClassBased) {
  return (tNode.flags & (isClassBased ? 8 /* TNodeFlags.hasClassInput */ : 16 /* TNodeFlags.hasStyleInput */)) !== 0;
}

/**
 *
 * Update an interpolated class on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div class="prefix{{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate1(prefix, v0, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate2(prefix, v0, i0, v1, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate3(
 * 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate4(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate5(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate6(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate7(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 *
 * Update an interpolated class on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolate8(
 *  'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵclassMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}
/**
 * Update an interpolated class on an element with 9 or more bound values surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵclassMapInterpolateV(
 *  ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *.
 * @param values The collection of values and the strings in-between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 * @codeGenApi
 */
function ɵɵclassMapInterpolateV(values) {
  const lView = getLView();
  const interpolatedValue = interpolationV(lView, values);
  checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Instruction that returns the component instance in which the current instruction is executing.
 * This is a constant-time version of `nextContent` for the case where we know that we need the
 * component instance specifically, rather than the context of a particular template.
 *
 * @codeGenApi
 */
function ɵɵcomponentInstance() {
  const instance = getLView()[DECLARATION_COMPONENT_VIEW][CONTEXT];
  ngDevMode && assertDefined(instance, 'Expected component instance to be defined');
  return instance;
}

/**
 * A type representing the live collection to be reconciled with any new (incoming) collection. This
 * is an adapter class that makes it possible to work with different internal data structures,
 * regardless of the actual values of the incoming collection.
 */
class LiveCollection {
  destroy(item) {
    // noop by default
  }
  updateValue(index, value) {
    // noop by default
  }
  // operations below could be implemented on top of the operations defined so far, but having
  // them explicitly allow clear expression of intent and potentially more performant
  // implementations
  swap(index1, index2) {
    const startIdx = Math.min(index1, index2);
    const endIdx = Math.max(index1, index2);
    const endItem = this.detach(endIdx);
    if (endIdx - startIdx > 1) {
      const startItem = this.detach(startIdx);
      this.attach(startIdx, endItem);
      this.attach(endIdx, startItem);
    } else {
      this.attach(startIdx, endItem);
    }
  }
  move(prevIndex, newIdx) {
    this.attach(newIdx, this.detach(prevIndex));
  }
}
function valuesMatching(liveIdx, liveValue, newIdx, newValue, trackBy) {
  if (liveIdx === newIdx && Object.is(liveValue, newValue)) {
    // matching and no value identity to update
    return 1;
  } else if (Object.is(trackBy(liveIdx, liveValue), trackBy(newIdx, newValue))) {
    // matching but requires value identity update
    return -1;
  }
  return 0;
}
function recordDuplicateKeys(keyToIdx, key, idx) {
  const idxSoFar = keyToIdx.get(key);
  if (idxSoFar !== undefined) {
    idxSoFar.add(idx);
  } else {
    keyToIdx.set(key, new Set([idx]));
  }
}
/**
 * The live collection reconciliation algorithm that perform various in-place operations, so it
 * reflects the content of the new (incoming) collection.
 *
 * The reconciliation algorithm has 2 code paths:
 * - "fast" path that don't require any memory allocation;
 * - "slow" path that requires additional memory allocation for intermediate data structures used to
 * collect additional information about the live collection.
 * It might happen that the algorithm switches between the two modes in question in a single
 * reconciliation path - generally it tries to stay on the "fast" path as much as possible.
 *
 * The overall complexity of the algorithm is O(n + m) for speed and O(n) for memory (where n is the
 * length of the live collection and m is the length of the incoming collection). Given the problem
 * at hand the complexity / performance constraints makes it impossible to perform the absolute
 * minimum of operation to reconcile the 2 collections. The algorithm makes different tradeoffs to
 * stay within reasonable performance bounds and may apply sub-optimal number of operations in
 * certain situations.
 *
 * @param liveCollection the current, live collection;
 * @param newCollection the new, incoming collection;
 * @param trackByFn key generation function that determines equality between items in the life and
 *     incoming collection;
 */
function reconcile(liveCollection, newCollection, trackByFn) {
  let detachedItems = undefined;
  let liveKeysInTheFuture = undefined;
  let liveStartIdx = 0;
  let liveEndIdx = liveCollection.length - 1;
  const duplicateKeys = ngDevMode ? new Map() : undefined;
  if (Array.isArray(newCollection)) {
    let newEndIdx = newCollection.length - 1;
    while (liveStartIdx <= liveEndIdx && liveStartIdx <= newEndIdx) {
      // compare from the beginning
      const liveStartValue = liveCollection.at(liveStartIdx);
      const newStartValue = newCollection[liveStartIdx];
      if (ngDevMode) {
        recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newStartValue), liveStartIdx);
      }
      const isStartMatching = valuesMatching(liveStartIdx, liveStartValue, liveStartIdx, newStartValue, trackByFn);
      if (isStartMatching !== 0) {
        if (isStartMatching < 0) {
          liveCollection.updateValue(liveStartIdx, newStartValue);
        }
        liveStartIdx++;
        continue;
      }
      // compare from the end
      // TODO(perf): do _all_ the matching from the end
      const liveEndValue = liveCollection.at(liveEndIdx);
      const newEndValue = newCollection[newEndIdx];
      if (ngDevMode) {
        recordDuplicateKeys(duplicateKeys, trackByFn(newEndIdx, newEndValue), newEndIdx);
      }
      const isEndMatching = valuesMatching(liveEndIdx, liveEndValue, newEndIdx, newEndValue, trackByFn);
      if (isEndMatching !== 0) {
        if (isEndMatching < 0) {
          liveCollection.updateValue(liveEndIdx, newEndValue);
        }
        liveEndIdx--;
        newEndIdx--;
        continue;
      }
      // Detect swap and moves:
      const liveStartKey = trackByFn(liveStartIdx, liveStartValue);
      const liveEndKey = trackByFn(liveEndIdx, liveEndValue);
      const newStartKey = trackByFn(liveStartIdx, newStartValue);
      if (Object.is(newStartKey, liveEndKey)) {
        const newEndKey = trackByFn(newEndIdx, newEndValue);
        // detect swap on both ends;
        if (Object.is(newEndKey, liveStartKey)) {
          liveCollection.swap(liveStartIdx, liveEndIdx);
          liveCollection.updateValue(liveEndIdx, newEndValue);
          newEndIdx--;
          liveEndIdx--;
        } else {
          // the new item is the same as the live item with the end pointer - this is a move forward
          // to an earlier index;
          liveCollection.move(liveEndIdx, liveStartIdx);
        }
        liveCollection.updateValue(liveStartIdx, newStartValue);
        liveStartIdx++;
        continue;
      }
      // Fallback to the slow path: we need to learn more about the content of the live and new
      // collections.
      detachedItems ??= new UniqueValueMultiKeyMap();
      liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
      // Check if I'm inserting a previously detached item: if so, attach it here
      if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newStartKey)) {
        liveCollection.updateValue(liveStartIdx, newStartValue);
        liveStartIdx++;
        liveEndIdx++;
      } else if (!liveKeysInTheFuture.has(newStartKey)) {
        // Check if we seen a new item that doesn't exist in the old collection and must be INSERTED
        const newItem = liveCollection.create(liveStartIdx, newCollection[liveStartIdx]);
        liveCollection.attach(liveStartIdx, newItem);
        liveStartIdx++;
        liveEndIdx++;
      } else {
        // We know that the new item exists later on in old collection but we don't know its index
        // and as the consequence can't move it (don't know where to find it). Detach the old item,
        // hoping that it unlocks the fast path again.
        detachedItems.set(liveStartKey, liveCollection.detach(liveStartIdx));
        liveEndIdx--;
      }
    }
    // Final cleanup steps:
    // - more items in the new collection => insert
    while (liveStartIdx <= newEndIdx) {
      createOrAttach(liveCollection, detachedItems, trackByFn, liveStartIdx, newCollection[liveStartIdx]);
      liveStartIdx++;
    }
  } else if (newCollection != null) {
    // iterable - immediately fallback to the slow path
    const newCollectionIterator = newCollection[Symbol.iterator]();
    let newIterationResult = newCollectionIterator.next();
    while (!newIterationResult.done && liveStartIdx <= liveEndIdx) {
      const liveValue = liveCollection.at(liveStartIdx);
      const newValue = newIterationResult.value;
      if (ngDevMode) {
        recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newValue), liveStartIdx);
      }
      const isStartMatching = valuesMatching(liveStartIdx, liveValue, liveStartIdx, newValue, trackByFn);
      if (isStartMatching !== 0) {
        // found a match - move on, but update value
        if (isStartMatching < 0) {
          liveCollection.updateValue(liveStartIdx, newValue);
        }
        liveStartIdx++;
        newIterationResult = newCollectionIterator.next();
      } else {
        detachedItems ??= new UniqueValueMultiKeyMap();
        liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
        // Check if I'm inserting a previously detached item: if so, attach it here
        const newKey = trackByFn(liveStartIdx, newValue);
        if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newKey)) {
          liveCollection.updateValue(liveStartIdx, newValue);
          liveStartIdx++;
          liveEndIdx++;
          newIterationResult = newCollectionIterator.next();
        } else if (!liveKeysInTheFuture.has(newKey)) {
          liveCollection.attach(liveStartIdx, liveCollection.create(liveStartIdx, newValue));
          liveStartIdx++;
          liveEndIdx++;
          newIterationResult = newCollectionIterator.next();
        } else {
          // it is a move forward - detach the current item without advancing in collections
          const liveKey = trackByFn(liveStartIdx, liveValue);
          detachedItems.set(liveKey, liveCollection.detach(liveStartIdx));
          liveEndIdx--;
        }
      }
    }
    // this is a new item as we run out of the items in the old collection - create or attach a
    // previously detached one
    while (!newIterationResult.done) {
      createOrAttach(liveCollection, detachedItems, trackByFn, liveCollection.length, newIterationResult.value);
      newIterationResult = newCollectionIterator.next();
    }
  }
  // Cleanups common to the array and iterable:
  // - more items in the live collection => delete starting from the end;
  while (liveStartIdx <= liveEndIdx) {
    liveCollection.destroy(liveCollection.detach(liveEndIdx--));
  }
  // - destroy items that were detached but never attached again.
  detachedItems?.forEach(item => {
    liveCollection.destroy(item);
  });
  // report duplicate keys (dev mode only)
  if (ngDevMode) {
    let duplicatedKeysMsg = [];
    for (const [key, idxSet] of duplicateKeys) {
      if (idxSet.size > 1) {
        const idx = [...idxSet].sort((a, b) => a - b);
        for (let i = 1; i < idx.length; i++) {
          duplicatedKeysMsg.push(`key "${stringifyForError(key)}" at index "${idx[i - 1]}" and "${idx[i]}"`);
        }
      }
    }
    if (duplicatedKeysMsg.length > 0) {
      const message = formatRuntimeError(-955 /* RuntimeErrorCode.LOOP_TRACK_DUPLICATE_KEYS */, 'The provided track expression resulted in duplicated keys for a given collection. ' + 'Adjust the tracking expression such that it uniquely identifies all the items in the collection. ' + 'Duplicated keys were: \n' + duplicatedKeysMsg.join(', \n') + '.');
      // tslint:disable-next-line:no-console
      console.warn(message);
    }
  }
}
function attachPreviouslyDetached(prevCollection, detachedItems, index, key) {
  if (detachedItems !== undefined && detachedItems.has(key)) {
    prevCollection.attach(index, detachedItems.get(key));
    detachedItems.delete(key);
    return true;
  }
  return false;
}
function createOrAttach(liveCollection, detachedItems, trackByFn, index, value) {
  if (!attachPreviouslyDetached(liveCollection, detachedItems, index, trackByFn(index, value))) {
    const newItem = liveCollection.create(index, value);
    liveCollection.attach(index, newItem);
  } else {
    liveCollection.updateValue(index, value);
  }
}
function initLiveItemsInTheFuture(liveCollection, start, end, trackByFn) {
  const keys = new Set();
  for (let i = start; i <= end; i++) {
    keys.add(trackByFn(i, liveCollection.at(i)));
  }
  return keys;
}
/**
 * A specific, partial implementation of the Map interface with the following characteristics:
 * - allows multiple values for a given key;
 * - maintain FIFO order for multiple values corresponding to a given key;
 * - assumes that all values are unique.
 *
 * The implementation aims at having the minimal overhead for cases where keys are _not_ duplicated
 * (the most common case in the list reconciliation algorithm). To achieve this, the first value for
 * a given key is stored in a regular map. Then, when more values are set for a given key, we
 * maintain a form of linked list in a separate map. To maintain this linked list we assume that all
 * values (in the entire collection) are unique.
 */
class UniqueValueMultiKeyMap {
  // A map from a key to the first value corresponding to this key.
  kvMap = /*#__PURE__*/(() => new Map())();
  // A map that acts as a linked list of values - each value maps to the next value in this "linked
  // list" (this only works if values are unique). Allocated lazily to avoid memory consumption when
  // there are no duplicated values.
  _vMap = /*#__PURE__*/(() => undefined)();
  has(key) {
    return this.kvMap.has(key);
  }
  delete(key) {
    if (!this.has(key)) return false;
    const value = this.kvMap.get(key);
    if (this._vMap !== undefined && this._vMap.has(value)) {
      this.kvMap.set(key, this._vMap.get(value));
      this._vMap.delete(value);
    } else {
      this.kvMap.delete(key);
    }
    return true;
  }
  get(key) {
    return this.kvMap.get(key);
  }
  set(key, value) {
    if (this.kvMap.has(key)) {
      let prevValue = this.kvMap.get(key);
      // Note: we don't use `assertNotSame`, because the value needs to be stringified even if
      // there is no error which can freeze the browser for large values (see #58509).
      if (ngDevMode && prevValue === value) {
        throw new Error(`Detected a duplicated value ${value} for the key ${key}`);
      }
      if (this._vMap === undefined) {
        this._vMap = new Map();
      }
      const vMap = this._vMap;
      while (vMap.has(prevValue)) {
        prevValue = vMap.get(prevValue);
      }
      vMap.set(prevValue, value);
    } else {
      this.kvMap.set(key, value);
    }
  }
  forEach(cb) {
    for (let [key, value] of this.kvMap) {
      cb(value, key);
      if (this._vMap !== undefined) {
        const vMap = this._vMap;
        while (vMap.has(value)) {
          value = vMap.get(value);
          cb(value, key);
        }
      }
    }
  }
}

/**
 * The conditional instruction represents the basic building block on the runtime side to support
 * built-in "if" and "switch". On the high level this instruction is responsible for adding and
 * removing views selected by a conditional expression.
 *
 * @param matchingTemplateIndex Index of a template TNode representing a conditional view to be
 *     inserted; -1 represents a special case when there is no view to insert.
 * @param contextValue Value that should be exposed as the context of the conditional.
 * @codeGenApi
 */
function ɵɵconditional(matchingTemplateIndex, contextValue) {
  performanceMarkFeature('NgControlFlow');
  const hostLView = getLView();
  const bindingIndex = nextBindingIndex();
  const prevMatchingTemplateIndex = hostLView[bindingIndex] !== NO_CHANGE ? hostLView[bindingIndex] : -1;
  const prevContainer = prevMatchingTemplateIndex !== -1 ? getLContainer(hostLView, HEADER_OFFSET + prevMatchingTemplateIndex) : undefined;
  const viewInContainerIdx = 0;
  if (bindingUpdated(hostLView, bindingIndex, matchingTemplateIndex)) {
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
    try {
      // The index of the view to show changed - remove the previously displayed one
      // (it is a noop if there are no active views in a container).
      if (prevContainer !== undefined) {
        removeLViewFromLContainer(prevContainer, viewInContainerIdx);
      }
      // Index -1 is a special case where none of the conditions evaluates to
      // a truthy value and as the consequence we've got no view to show.
      if (matchingTemplateIndex !== -1) {
        const nextLContainerIndex = HEADER_OFFSET + matchingTemplateIndex;
        const nextContainer = getLContainer(hostLView, nextLContainerIndex);
        const templateTNode = getExistingTNode(hostLView[TVIEW], nextLContainerIndex);
        const dehydratedView = findMatchingDehydratedView(nextContainer, templateTNode.tView.ssrId);
        const embeddedLView = createAndRenderEmbeddedLView(hostLView, templateTNode, contextValue, {
          dehydratedView
        });
        addLViewToLContainer(nextContainer, embeddedLView, viewInContainerIdx, shouldAddViewToDom(templateTNode, dehydratedView));
      }
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
    }
  } else if (prevContainer !== undefined) {
    // We might keep displaying the same template but the actual value of the expression could have
    // changed - re-bind in context.
    const lView = getLViewFromLContainer(prevContainer, viewInContainerIdx);
    if (lView !== undefined) {
      lView[CONTEXT] = contextValue;
    }
  }
}
class RepeaterContext {
  lContainer;
  $implicit;
  $index;
  constructor(lContainer, $implicit, $index) {
    this.lContainer = lContainer;
    this.$implicit = $implicit;
    this.$index = $index;
  }
  get $count() {
    return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  }
}
/**
 * A built-in trackBy function used for situations where users specified collection index as a
 * tracking expression. Having this function body in the runtime avoids unnecessary code generation.
 *
 * @param index
 * @returns
 */
function ɵɵrepeaterTrackByIndex(index) {
  return index;
}
/**
 * A built-in trackBy function used for situations where users specified collection item reference
 * as a tracking expression. Having this function body in the runtime avoids unnecessary code
 * generation.
 *
 * @param index
 * @returns
 */
function ɵɵrepeaterTrackByIdentity(_, value) {
  return value;
}
class RepeaterMetadata {
  hasEmptyBlock;
  trackByFn;
  liveCollection;
  constructor(hasEmptyBlock, trackByFn, liveCollection) {
    this.hasEmptyBlock = hasEmptyBlock;
    this.trackByFn = trackByFn;
    this.liveCollection = liveCollection;
  }
}
/**
 * The repeaterCreate instruction runs in the creation part of the template pass and initializes
 * internal data structures required by the update pass of the built-in repeater logic. Repeater
 * metadata are allocated in the data part of LView with the following layout:
 * - LView[HEADER_OFFSET + index] - metadata
 * - LView[HEADER_OFFSET + index + 1] - reference to a template function rendering an item
 * - LView[HEADER_OFFSET + index + 2] - optional reference to a template function rendering an empty
 * block
 *
 * @param index Index at which to store the metadata of the repeater.
 * @param templateFn Reference to the template of the main repeater block.
 * @param decls The number of nodes, local refs, and pipes for the main block.
 * @param vars The number of bindings for the main block.
 * @param tagName The name of the container element, if applicable
 * @param attrsIndex Index of template attributes in the `consts` array.
 * @param trackByFn Reference to the tracking function.
 * @param trackByUsesComponentInstance Whether the tracking function has any references to the
 *  component instance. If it doesn't, we can avoid rebinding it.
 * @param emptyTemplateFn Reference to the template function of the empty block.
 * @param emptyDecls The number of nodes, local refs, and pipes for the empty block.
 * @param emptyVars The number of bindings for the empty block.
 * @param emptyTagName The name of the empty block container element, if applicable
 * @param emptyAttrsIndex Index of the empty block template attributes in the `consts` array.
 *
 * @codeGenApi
 */
function ɵɵrepeaterCreate(index, templateFn, decls, vars, tagName, attrsIndex, trackByFn, trackByUsesComponentInstance, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, emptyAttrsIndex) {
  performanceMarkFeature('NgControlFlow');
  ngDevMode && assertFunction(trackByFn, `A track expression must be a function, was ${typeof trackByFn} instead.`);
  const lView = getLView();
  const tView = getTView();
  const hasEmptyBlock = emptyTemplateFn !== undefined;
  const hostLView = getLView();
  const boundTrackBy = trackByUsesComponentInstance ?
  // We only want to bind when necessary, because it produces a
  // new function. For pure functions it's not necessary.
  trackByFn.bind(hostLView[DECLARATION_COMPONENT_VIEW][CONTEXT]) : trackByFn;
  const metadata = new RepeaterMetadata(hasEmptyBlock, boundTrackBy);
  hostLView[HEADER_OFFSET + index] = metadata;
  declareTemplate(lView, tView, index + 1, templateFn, decls, vars, tagName, getConstant(tView.consts, attrsIndex));
  if (hasEmptyBlock) {
    ngDevMode && assertDefined(emptyDecls, 'Missing number of declarations for the empty repeater block.');
    ngDevMode && assertDefined(emptyVars, 'Missing number of bindings for the empty repeater block.');
    declareTemplate(lView, tView, index + 2, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, getConstant(tView.consts, emptyAttrsIndex));
  }
}
function isViewExpensiveToRecreate(lView) {
  // assumption: anything more than a text node with a binding is considered "expensive"
  return lView.length - HEADER_OFFSET > 2;
}
class OperationsCounter {
  created = 0;
  destroyed = 0;
  reset() {
    this.created = 0;
    this.destroyed = 0;
  }
  recordCreate() {
    this.created++;
  }
  recordDestroy() {
    this.destroyed++;
  }
  /**
   * A method indicating if the entire collection was re-created as part of the reconciliation pass.
   * Used to warn developers about the usage of a tracking function that might result in excessive
   * amount of view creation / destroy operations.
   *
   * @returns boolean value indicating if a live collection was re-created
   */
  wasReCreated(collectionLen) {
    return collectionLen > 0 && this.created === this.destroyed && this.created === collectionLen;
  }
}
class LiveCollectionLContainerImpl extends LiveCollection {
  lContainer;
  hostLView;
  templateTNode;
  operationsCounter = /*#__PURE__*/(() => ngDevMode ? new OperationsCounter() : undefined)();
  /**
   Property indicating if indexes in the repeater context need to be updated following the live
   collection changes. Index updates are necessary if and only if views are inserted / removed in
   the middle of LContainer. Adds and removals at the end don't require index updates.
  */
  needsIndexUpdate = false;
  constructor(lContainer, hostLView, templateTNode) {
    super();
    this.lContainer = lContainer;
    this.hostLView = hostLView;
    this.templateTNode = templateTNode;
  }
  get length() {
    return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  }
  at(index) {
    return this.getLView(index)[CONTEXT].$implicit;
  }
  attach(index, lView) {
    const dehydratedView = lView[HYDRATION];
    this.needsIndexUpdate ||= index !== this.length;
    addLViewToLContainer(this.lContainer, lView, index, shouldAddViewToDom(this.templateTNode, dehydratedView));
  }
  detach(index) {
    this.needsIndexUpdate ||= index !== this.length - 1;
    return detachExistingView(this.lContainer, index);
  }
  create(index, value) {
    const dehydratedView = findMatchingDehydratedView(this.lContainer, this.templateTNode.tView.ssrId);
    const embeddedLView = createAndRenderEmbeddedLView(this.hostLView, this.templateTNode, new RepeaterContext(this.lContainer, value, index), {
      dehydratedView
    });
    this.operationsCounter?.recordCreate();
    return embeddedLView;
  }
  destroy(lView) {
    destroyLView(lView[TVIEW], lView);
    this.operationsCounter?.recordDestroy();
  }
  updateValue(index, value) {
    this.getLView(index)[CONTEXT].$implicit = value;
  }
  reset() {
    this.needsIndexUpdate = false;
    this.operationsCounter?.reset();
  }
  updateIndexes() {
    if (this.needsIndexUpdate) {
      for (let i = 0; i < this.length; i++) {
        this.getLView(i)[CONTEXT].$index = i;
      }
    }
  }
  getLView(index) {
    return getExistingLViewFromLContainer(this.lContainer, index);
  }
}
/**
 * The repeater instruction does update-time diffing of a provided collection (against the
 * collection seen previously) and maps changes in the collection to views structure (by adding,
 * removing or moving views as needed).
 * @param collection - the collection instance to be checked for changes
 * @codeGenApi
 */
function ɵɵrepeater(collection) {
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  const metadataSlotIdx = getSelectedIndex();
  try {
    const hostLView = getLView();
    const hostTView = hostLView[TVIEW];
    const metadata = hostLView[metadataSlotIdx];
    const containerIndex = metadataSlotIdx + 1;
    const lContainer = getLContainer(hostLView, containerIndex);
    if (metadata.liveCollection === undefined) {
      const itemTemplateTNode = getExistingTNode(hostTView, containerIndex);
      metadata.liveCollection = new LiveCollectionLContainerImpl(lContainer, hostLView, itemTemplateTNode);
    } else {
      metadata.liveCollection.reset();
    }
    const liveCollection = metadata.liveCollection;
    reconcile(liveCollection, collection, metadata.trackByFn);
    // Warn developers about situations where the entire collection was re-created as part of the
    // reconciliation pass. Note that this warning might be "overreacting" and report cases where
    // the collection re-creation is the intended behavior. Still, the assumption is that most of
    // the time it is undesired.
    if (ngDevMode && metadata.trackByFn === ɵɵrepeaterTrackByIdentity && liveCollection.operationsCounter?.wasReCreated(liveCollection.length) && isViewExpensiveToRecreate(getExistingLViewFromLContainer(lContainer, 0))) {
      const message = formatRuntimeError(-956 /* RuntimeErrorCode.LOOP_TRACK_RECREATE */, `The configured tracking expression (track by identity) caused re-creation of the entire collection of size ${liveCollection.length}. ` + 'This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. ' + 'Please review the "track expression" and make sure that it uniquely identifies items in a collection.');
      console.warn(message);
    }
    // moves in the container might caused context's index to get out of order, re-adjust if needed
    liveCollection.updateIndexes();
    // handle empty blocks
    if (metadata.hasEmptyBlock) {
      const bindingIndex = nextBindingIndex();
      const isCollectionEmpty = liveCollection.length === 0;
      if (bindingUpdated(hostLView, bindingIndex, isCollectionEmpty)) {
        const emptyTemplateIndex = metadataSlotIdx + 2;
        const lContainerForEmpty = getLContainer(hostLView, emptyTemplateIndex);
        if (isCollectionEmpty) {
          const emptyTemplateTNode = getExistingTNode(hostTView, emptyTemplateIndex);
          const dehydratedView = findMatchingDehydratedView(lContainerForEmpty, emptyTemplateTNode.tView.ssrId);
          const embeddedLView = createAndRenderEmbeddedLView(hostLView, emptyTemplateTNode, undefined, {
            dehydratedView
          });
          addLViewToLContainer(lContainerForEmpty, embeddedLView, 0, shouldAddViewToDom(emptyTemplateTNode, dehydratedView));
        } else {
          removeLViewFromLContainer(lContainerForEmpty, 0);
        }
      }
    }
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
function getLContainer(lView, index) {
  const lContainer = lView[index];
  ngDevMode && assertLContainer(lContainer);
  return lContainer;
}
function detachExistingView(lContainer, index) {
  const existingLView = detachView(lContainer, index);
  ngDevMode && assertLView(existingLView);
  return existingLView;
}
function getExistingLViewFromLContainer(lContainer, index) {
  const existingLView = getLViewFromLContainer(lContainer, index);
  ngDevMode && assertLView(existingLView);
  return existingLView;
}
function getExistingTNode(tView, index) {
  const tNode = getTNode(tView, index);
  ngDevMode && assertTNode(tNode);
  return tNode;
}
function elementStartFirstCreatePass(index, tView, lView, name, attrsIndex, localRefsIndex) {
  ngDevMode && assertFirstCreatePass(tView);
  ngDevMode && ngDevMode.firstCreatePass++;
  const tViewConsts = tView.consts;
  const attrs = getConstant(tViewConsts, attrsIndex);
  const tNode = getOrCreateTNode(tView, index, 2 /* TNodeType.Element */, name, attrs);
  resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
  if (tNode.attrs !== null) {
    computeStaticStyling(tNode, tNode.attrs, false);
  }
  if (tNode.mergedAttrs !== null) {
    computeStaticStyling(tNode, tNode.mergedAttrs, true);
  }
  if (tView.queries !== null) {
    tView.queries.elementStart(tView, tNode);
  }
  return tNode;
}
/**
 * Create DOM element. The instruction must later be followed by `elementEnd()` call.
 *
 * @param index Index of the element in the LView array
 * @param name Name of the DOM Node
 * @param attrsIndex Index of the element's attributes in the `consts` array.
 * @param localRefsIndex Index of the element's local references in the `consts` array.
 * @returns This function returns itself so that it may be chained.
 *
 * Attributes and localRefs are passed as an array of strings where elements with an even index
 * hold an attribute name and elements with an odd index hold an attribute value, ex.:
 * ['id', 'warning5', 'class', 'alert']
 *
 * @codeGenApi
 */
function ɵɵelementStart(index, name, attrsIndex, localRefsIndex) {
  const lView = getLView();
  const tView = getTView();
  const adjustedIndex = HEADER_OFFSET + index;
  ngDevMode && assertEqual(getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings');
  ngDevMode && assertIndexInRange(lView, adjustedIndex);
  const renderer = lView[RENDERER];
  const tNode = tView.firstCreatePass ? elementStartFirstCreatePass(adjustedIndex, tView, lView, name, attrsIndex, localRefsIndex) : tView.data[adjustedIndex];
  const native = _locateOrCreateElementNode(tView, lView, tNode, renderer, name, index);
  lView[adjustedIndex] = native;
  const hasDirectives = isDirectiveHost(tNode);
  if (ngDevMode && tView.firstCreatePass) {
    validateElementIsKnown(native, lView, tNode.value, tView.schemas, hasDirectives);
  }
  setCurrentTNode(tNode, true);
  setupStaticAttributes(renderer, native, tNode);
  if (!isDetachedByI18n(tNode) && wasLastNodeCreated()) {
    // In the i18n case, the translation may have removed this element, so only add it if it is not
    // detached. See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
    appendChild(tView, lView, native, tNode);
  }
  // any immediate children of a component or template container must be pre-emptively
  // monkey-patched with the component view data so that the element can be inspected
  // later on using any element discovery utility methods (see `element_discovery.ts`)
  if (getElementDepthCount() === 0) {
    attachPatchData(native, lView);
  }
  increaseElementDepthCount();
  if (hasDirectives) {
    createDirectivesInstances(tView, lView, tNode);
    executeContentQueries(tView, tNode, lView);
  }
  if (localRefsIndex !== null) {
    saveResolvedLocalsInData(lView, tNode);
  }
  return ɵɵelementStart;
}
/**
 * Mark the end of the element.
 * @returns This function returns itself so that it may be chained.
 *
 * @codeGenApi
 */
function ɵɵelementEnd() {
  let currentTNode = getCurrentTNode();
  ngDevMode && assertDefined(currentTNode, 'No parent node to close.');
  if (isCurrentTNodeParent()) {
    setCurrentTNodeAsNotParent();
  } else {
    ngDevMode && assertHasParent(getCurrentTNode());
    currentTNode = currentTNode.parent;
    setCurrentTNode(currentTNode, false);
  }
  const tNode = currentTNode;
  ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
  if (isSkipHydrationRootTNode(tNode)) {
    leaveSkipHydrationBlock();
  }
  decreaseElementDepthCount();
  const tView = getTView();
  if (tView.firstCreatePass) {
    registerPostOrderHooks(tView, currentTNode);
    if (isContentQueryHost(currentTNode)) {
      tView.queries.elementEnd(currentTNode);
    }
  }
  if (tNode.classesWithoutHost != null && hasClassInput(tNode)) {
    setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true);
  }
  if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) {
    setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false);
  }
  return ɵɵelementEnd;
}
/**
 * Creates an empty element using {@link elementStart} and {@link elementEnd}
 *
 * @param index Index of the element in the data array
 * @param name Name of the DOM Node
 * @param attrsIndex Index of the element's attributes in the `consts` array.
 * @param localRefsIndex Index of the element's local references in the `consts` array.
 * @returns This function returns itself so that it may be chained.
 *
 * @codeGenApi
 */
function ɵɵelement(index, name, attrsIndex, localRefsIndex) {
  ɵɵelementStart(index, name, attrsIndex, localRefsIndex);
  ɵɵelementEnd();
  return ɵɵelement;
}
let _locateOrCreateElementNode = (tView, lView, tNode, renderer, name, index) => {
  lastNodeWasCreated(true);
  return createElementNode(renderer, name, getNamespace$1());
};
/**
 * Enables hydration code path (to lookup existing elements in DOM)
 * in addition to the regular creation mode of element nodes.
 */
function locateOrCreateElementNodeImpl(tView, lView, tNode, renderer, name, index) {
  const hydrationInfo = lView[HYDRATION];
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1() || isDetachedByI18n(tNode) || isDisconnectedNode$1(hydrationInfo, index);
  lastNodeWasCreated(isNodeCreationMode);
  // Regular creation mode.
  if (isNodeCreationMode) {
    return createElementNode(renderer, name, getNamespace$1());
  }
  // Hydration mode, looking up an existing element in DOM.
  const native = locateNextRNode(hydrationInfo, tView, lView, tNode);
  ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode);
  ngDevMode && markRNodeAsClaimedByHydration(native);
  // This element might also be an anchor of a view container.
  if (getSerializedContainerViews(hydrationInfo, index)) {
    // Important note: this element acts as an anchor, but it's **not** a part
    // of the embedded view, so we start the segment **after** this element, taking
    // a reference to the next sibling. For example, the following template:
    // `<div #vcrTarget>` is represented in the DOM as `<div></div>...<!--container-->`,
    // so while processing a `<div>` instruction, point to the next sibling as a
    // start of a segment.
    ngDevMode && validateNodeExists(native.nextSibling, lView, tNode);
    setSegmentHead(hydrationInfo, index, native.nextSibling);
  }
  // Checks if the skip hydration attribute is present during hydration so we know to
  // skip attempting to hydrate this block. We check both TNode and RElement for an
  // attribute: the RElement case is needed for i18n cases, when we add it to host
  // elements during the annotation phase (after all internal data structures are setup).
  if (hydrationInfo && (hasSkipHydrationAttrOnTNode(tNode) || hasSkipHydrationAttrOnRElement(native))) {
    if (isComponentHost(tNode)) {
      enterSkipHydrationBlock(tNode);
      // Since this isn't hydratable, we need to empty the node
      // so there's no duplicate content after render
      clearElementContents(native);
      ngDevMode && markRNodeAsSkippedByHydration(native);
    } else if (ngDevMode) {
      // If this is not a component host, throw an error.
      // Hydration can be skipped on per-component basis only.
      throw invalidSkipHydrationHost(native);
    }
  }
  return native;
}
function enableLocateOrCreateElementNodeImpl() {
  _locateOrCreateElementNode = locateOrCreateElementNodeImpl;
}
function elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) {
  ngDevMode && ngDevMode.firstCreatePass++;
  const tViewConsts = tView.consts;
  const attrs = getConstant(tViewConsts, attrsIndex);
  const tNode = getOrCreateTNode(tView, index, 8 /* TNodeType.ElementContainer */, 'ng-container', attrs);
  // While ng-container doesn't necessarily support styling, we use the style context to identify
  // and execute directives on the ng-container.
  if (attrs !== null) {
    computeStaticStyling(tNode, attrs, true);
  }
  const localRefs = getConstant(tViewConsts, localRefsIndex);
  resolveDirectives(tView, lView, tNode, localRefs);
  if (tView.queries !== null) {
    tView.queries.elementStart(tView, tNode);
  }
  return tNode;
}
/**
 * Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
 * The instruction must later be followed by `elementContainerEnd()` call.
 *
 * @param index Index of the element in the LView array
 * @param attrsIndex Index of the container attributes in the `consts` array.
 * @param localRefsIndex Index of the container's local references in the `consts` array.
 * @returns This function returns itself so that it may be chained.
 *
 * Even if this instruction accepts a set of attributes no actual attribute values are propagated to
 * the DOM (as a comment node can't have attributes). Attributes are here only for directive
 * matching purposes and setting initial inputs of directives.
 *
 * @codeGenApi
 */
function ɵɵelementContainerStart(index, attrsIndex, localRefsIndex) {
  const lView = getLView();
  const tView = getTView();
  const adjustedIndex = index + HEADER_OFFSET;
  ngDevMode && assertIndexInRange(lView, adjustedIndex);
  ngDevMode && assertEqual(getBindingIndex(), tView.bindingStartIndex, 'element containers should be created before any bindings');
  const tNode = tView.firstCreatePass ? elementContainerStartFirstCreatePass(adjustedIndex, tView, lView, attrsIndex, localRefsIndex) : tView.data[adjustedIndex];
  setCurrentTNode(tNode, true);
  const comment = _locateOrCreateElementContainerNode(tView, lView, tNode, index);
  lView[adjustedIndex] = comment;
  if (wasLastNodeCreated()) {
    appendChild(tView, lView, comment, tNode);
  }
  attachPatchData(comment, lView);
  if (isDirectiveHost(tNode)) {
    createDirectivesInstances(tView, lView, tNode);
    executeContentQueries(tView, tNode, lView);
  }
  if (localRefsIndex != null) {
    saveResolvedLocalsInData(lView, tNode);
  }
  return ɵɵelementContainerStart;
}
/**
 * Mark the end of the <ng-container>.
 * @returns This function returns itself so that it may be chained.
 *
 * @codeGenApi
 */
function ɵɵelementContainerEnd() {
  let currentTNode = getCurrentTNode();
  const tView = getTView();
  if (isCurrentTNodeParent()) {
    setCurrentTNodeAsNotParent();
  } else {
    ngDevMode && assertHasParent(currentTNode);
    currentTNode = currentTNode.parent;
    setCurrentTNode(currentTNode, false);
  }
  ngDevMode && assertTNodeType(currentTNode, 8 /* TNodeType.ElementContainer */);
  if (tView.firstCreatePass) {
    registerPostOrderHooks(tView, currentTNode);
    if (isContentQueryHost(currentTNode)) {
      tView.queries.elementEnd(currentTNode);
    }
  }
  return ɵɵelementContainerEnd;
}
/**
 * Creates an empty logical container using {@link elementContainerStart}
 * and {@link elementContainerEnd}
 *
 * @param index Index of the element in the LView array
 * @param attrsIndex Index of the container attributes in the `consts` array.
 * @param localRefsIndex Index of the container's local references in the `consts` array.
 * @returns This function returns itself so that it may be chained.
 *
 * @codeGenApi
 */
function ɵɵelementContainer(index, attrsIndex, localRefsIndex) {
  ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
  ɵɵelementContainerEnd();
  return ɵɵelementContainer;
}
let _locateOrCreateElementContainerNode = (tView, lView, tNode, index) => {
  lastNodeWasCreated(true);
  return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
};
/**
 * Enables hydration code path (to lookup existing elements in DOM)
 * in addition to the regular creation mode of comment nodes that
 * represent <ng-container>'s anchor.
 */
function locateOrCreateElementContainerNode(tView, lView, tNode, index) {
  let comment;
  const hydrationInfo = lView[HYDRATION];
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1() || isDisconnectedNode$1(hydrationInfo, index) || isDetachedByI18n(tNode);
  lastNodeWasCreated(isNodeCreationMode);
  // Regular creation mode.
  if (isNodeCreationMode) {
    return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
  }
  // Hydration mode, looking up existing elements in DOM.
  const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  const ngContainerSize = getNgContainerSize(hydrationInfo, index);
  ngDevMode && assertNumber(ngContainerSize, 'Unexpected state: hydrating an <ng-container>, ' + 'but no hydration info is available.');
  setSegmentHead(hydrationInfo, index, currentRNode);
  comment = siblingAfter(ngContainerSize, currentRNode);
  if (ngDevMode) {
    validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
    markRNodeAsClaimedByHydration(comment);
  }
  return comment;
}
function enableLocateOrCreateElementContainerNodeImpl() {
  _locateOrCreateElementContainerNode = locateOrCreateElementContainerNode;
}

/**
 * Returns the current OpaqueViewState instance.
 *
 * Used in conjunction with the restoreView() instruction to save a snapshot
 * of the current view and restore it when listeners are invoked. This allows
 * walking the declaration view tree in listeners to get vars from parent views.
 *
 * @codeGenApi
 */
function ɵɵgetCurrentView() {
  return getLView();
}

/**
 * Update a property on a host element. Only applies to native node properties, not inputs.
 *
 * Operates on the element selected by index via the {@link select} instruction.
 *
 * @param propName Name of property. Because it is going to DOM, this is not subject to
 *        renaming as part of minification.
 * @param value New value to write.
 * @param sanitizer An optional function used to sanitize the value.
 * @returns This function returns itself so that it may be chained
 * (e.g. `property('name', ctx.name)('title', ctx.title)`)
 *
 * @codeGenApi
 */
function ɵɵhostProperty(propName, value, sanitizer) {
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, value)) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  }
  return ɵɵhostProperty;
}
/**
 * Updates a synthetic host binding (e.g. `[@foo]`) on a component or directive.
 *
 * This instruction is for compatibility purposes and is designed to ensure that a
 * synthetic host binding (e.g. `@HostBinding('@foo')`) properly gets rendered in
 * the component's renderer. Normally all host bindings are evaluated with the parent
 * component's renderer, but, in the case of animation @triggers, they need to be
 * evaluated with the sub component's renderer (because that's where the animation
 * triggers are defined).
 *
 * Do not use this instruction as a replacement for `elementProperty`. This instruction
 * only exists to ensure compatibility with the ViewEngine's host binding behavior.
 *
 * @param index The index of the element to update in the data array
 * @param propName Name of property. Because it is going to DOM, this is not subject to
 *        renaming as part of minification.
 * @param value New value to write.
 * @param sanitizer An optional function used to sanitize the value.
 *
 * @codeGenApi
 */
function ɵɵsyntheticHostProperty(propName, value, sanitizer) {
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, value)) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    const currentDef = getCurrentDirectiveDef(tView.data);
    const renderer = loadComponentRenderer(currentDef, tNode, lView);
    elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  }
  return ɵɵsyntheticHostProperty;
}

/**
 * NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
 */
if (typeof ngI18nClosureMode === 'undefined') {
  // These property accesses can be ignored because ngI18nClosureMode will be set to false
  // when optimizing code and the whole if statement will be dropped.
  // Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
  // NOTE: we need to have it in IIFE so that the tree-shaker is happy.
  /*#__PURE__*/(function () {
    // tslint:disable-next-line:no-toplevel-property-access
    _global['ngI18nClosureMode'] =
    // TODO(FW-1250): validate that this actually, you know, works.
    // tslint:disable-next-line:no-toplevel-property-access
    typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
  })();
}

// THIS CODE IS GENERATED - DO NOT MODIFY.
const u = undefined;
function plural(val) {
  const n = val,
    i = Math.floor(Math.abs(val)),
    v = val.toString().replace(/^[^.]*\.?/, '').length;
  if (i === 1 && v === 0) return 1;
  return 5;
}
var localeEn = ["en", [["a", "p"], ["AM", "PM"], u], [["AM", "PM"], u, u], [["S", "M", "T", "W", "T", "F", "S"], ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]], u, [["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]], u, [["B", "A"], ["BC", "AD"], ["Before Christ", "Anno Domini"]], 0, [6, 0], ["M/d/yy", "MMM d, y", "MMMM d, y", "EEEE, MMMM d, y"], ["h:mm a", "h:mm:ss a", "h:mm:ss a z", "h:mm:ss a zzzz"], ["{1}, {0}", u, "{1} 'at' {0}", u], [".", ",", ";", "%", "+", "-", "E", "×", "‰", "∞", "NaN", ":"], ["#,##0.###", "#,##0%", "¤#,##0.00", "#E0"], "USD", "$", "US Dollar", {}, "ltr", plural];

/**
 * This const is used to store the locale data registered with `registerLocaleData`
 */
let LOCALE_DATA = {};
/**
 * Register locale data to be used internally by Angular. See the
 * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
 * data.
 *
 * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
 */
function registerLocaleData(data, localeId, extraData) {
  if (typeof localeId !== 'string') {
    extraData = localeId;
    localeId = data[LocaleDataIndex.LocaleId];
  }
  localeId = localeId.toLowerCase().replace(/_/g, '-');
  LOCALE_DATA[localeId] = data;
  if (extraData) {
    LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
  }
}
/**
 * Finds the locale data for a given locale.
 *
 * @param locale The locale code.
 * @returns The locale data.
 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
 */
function findLocaleData(locale) {
  const normalizedLocale = normalizeLocale(locale);
  let match = getLocaleData(normalizedLocale);
  if (match) {
    return match;
  }
  // let's try to find a parent locale
  const parentLocale = normalizedLocale.split('-')[0];
  match = getLocaleData(parentLocale);
  if (match) {
    return match;
  }
  if (parentLocale === 'en') {
    return localeEn;
  }
  throw new RuntimeError(701 /* RuntimeErrorCode.MISSING_LOCALE_DATA */, ngDevMode && `Missing locale data for the locale "${locale}".`);
}
/**
 * Retrieves the default currency code for the given locale.
 *
 * The default is defined as the first currency which is still in use.
 *
 * @param locale The code of the locale whose currency code we want.
 * @returns The code of the default currency for the given locale.
 *
 */
function getLocaleCurrencyCode(locale) {
  const data = findLocaleData(locale);
  return data[LocaleDataIndex.CurrencyCode] || null;
}
/**
 * Retrieves the plural function used by ICU expressions to determine the plural case to use
 * for a given locale.
 * @param locale A locale code for the locale format rules to use.
 * @returns The plural function for the locale.
 * @see {@link NgPlural}
 * @see [Internationalization (i18n) Guide](guide/i18n)
 */
function getLocalePluralCase(locale) {
  const data = findLocaleData(locale);
  return data[LocaleDataIndex.PluralCase];
}
/**
 * Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
 * or from the global `ng.common.locale`.
 */
function getLocaleData(normalizedLocale) {
  if (!(normalizedLocale in LOCALE_DATA)) {
    LOCALE_DATA[normalizedLocale] = _global.ng && _global.ng.common && _global.ng.common.locales && _global.ng.common.locales[normalizedLocale];
  }
  return LOCALE_DATA[normalizedLocale];
}
/**
 * Helper function to remove all the locale data from `LOCALE_DATA`.
 */
function unregisterAllLocaleData() {
  LOCALE_DATA = {};
}
/**
 * Index of each type of locale data from the locale data array
 */
var LocaleDataIndex = /*#__PURE__*/function (LocaleDataIndex) {
  LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
  LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
  LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
  LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
  LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
  LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
  LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
  LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
  LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
  LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
  LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
  LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
  LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
  LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
  LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
  LocaleDataIndex[LocaleDataIndex["CurrencyCode"] = 15] = "CurrencyCode";
  LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 16] = "CurrencySymbol";
  LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 17] = "CurrencyName";
  LocaleDataIndex[LocaleDataIndex["Currencies"] = 18] = "Currencies";
  LocaleDataIndex[LocaleDataIndex["Directionality"] = 19] = "Directionality";
  LocaleDataIndex[LocaleDataIndex["PluralCase"] = 20] = "PluralCase";
  LocaleDataIndex[LocaleDataIndex["ExtraData"] = 21] = "ExtraData";
  return LocaleDataIndex;
}(LocaleDataIndex || {});
/**
 * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
 */
function normalizeLocale(locale) {
  return locale.toLowerCase().replace(/_/g, '-');
}
const pluralMapping = ['zero', 'one', 'two', 'few', 'many'];
/**
 * Returns the plural case based on the locale
 */
function getPluralCase(value, locale) {
  const plural = getLocalePluralCase(locale)(parseInt(value, 10));
  const result = pluralMapping[plural];
  return result !== undefined ? result : 'other';
}
/**
 * The locale id that the application is using by default (for translations and ICU expressions).
 */
const DEFAULT_LOCALE_ID = 'en-US';
/**
 * USD currency code that the application uses by default for CurrencyPipe when no
 * DEFAULT_CURRENCY_CODE is provided.
 */
const USD_CURRENCY_CODE = 'USD';

/**
 * Marks that the next string is an element name.
 *
 * See `I18nMutateOpCodes` documentation.
 */
const ELEMENT_MARKER = {
  marker: 'element'
};
/**
 * Marks that the next string is comment text need for ICU.
 *
 * See `I18nMutateOpCodes` documentation.
 */
const ICU_MARKER = {
  marker: 'ICU'
};
/**
 * See `I18nCreateOpCodes`
 */
var I18nCreateOpCode = /*#__PURE__*/function (I18nCreateOpCode) {
  /**
   * Number of bits to shift index so that it can be combined with the `APPEND_EAGERLY` and
   * `COMMENT`.
   */
  I18nCreateOpCode[I18nCreateOpCode["SHIFT"] = 2] = "SHIFT";
  /**
   * Should the node be appended to parent immediately after creation.
   */
  I18nCreateOpCode[I18nCreateOpCode["APPEND_EAGERLY"] = 1] = "APPEND_EAGERLY";
  /**
   * If set the node should be comment (rather than a text) node.
   */
  I18nCreateOpCode[I18nCreateOpCode["COMMENT"] = 2] = "COMMENT";
  return I18nCreateOpCode;
}(I18nCreateOpCode || {});
/**
 * The locale id that the application is currently using (for translations and ICU expressions).
 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
 * but is now defined as a global value.
 */
let LOCALE_ID$1 = DEFAULT_LOCALE_ID;
/**
 * Sets the locale id that will be used for translations and ICU expressions.
 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
 * but is now defined as a global value.
 *
 * @param localeId
 */
function setLocaleId(localeId) {
  ngDevMode && assertDefined(localeId, `Expected localeId to be defined`);
  if (typeof localeId === 'string') {
    LOCALE_ID$1 = localeId.toLowerCase().replace(/_/g, '-');
  }
}
/**
 * Gets the locale id that will be used for translations and ICU expressions.
 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
 * but is now defined as a global value.
 */
function getLocaleId() {
  return LOCALE_ID$1;
}

/**
 * Keep track of which input bindings in `ɵɵi18nExp` have changed.
 *
 * This is used to efficiently update expressions in i18n only when the corresponding input has
 * changed.
 *
 * 1) Each bit represents which of the `ɵɵi18nExp` has changed.
 * 2) There are 32 bits allowed in JS.
 * 3) Bit 32 is special as it is shared for all changes past 32. (In other words if you have more
 * than 32 `ɵɵi18nExp` then all changes past 32nd `ɵɵi18nExp` will be mapped to same bit. This means
 * that we may end up changing more than we need to. But i18n expressions with 32 bindings is rare
 * so in practice it should not be an issue.)
 */
let changeMask = 0b0;
/**
 * Keeps track of which bit needs to be updated in `changeMask`
 *
 * This value gets incremented on every call to `ɵɵi18nExp`
 */
let changeMaskCounter = 0;
/**
 * Keep track of which input bindings in `ɵɵi18nExp` have changed.
 *
 * `setMaskBit` gets invoked by each call to `ɵɵi18nExp`.
 *
 * @param hasChange did `ɵɵi18nExp` detect a change.
 */
function setMaskBit(hasChange) {
  if (hasChange) {
    changeMask = changeMask | 1 << Math.min(changeMaskCounter, 31);
  }
  changeMaskCounter++;
}
function applyI18n(tView, lView, index) {
  if (changeMaskCounter > 0) {
    ngDevMode && assertDefined(tView, `tView should be defined`);
    const tI18n = tView.data[index];
    // When `index` points to an `ɵɵi18nAttributes` then we have an array otherwise `TI18n`
    const updateOpCodes = Array.isArray(tI18n) ? tI18n : tI18n.update;
    const bindingsStartIndex = getBindingIndex() - changeMaskCounter - 1;
    applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask);
  }
  // Reset changeMask & maskBit to default for the next update cycle
  changeMask = 0b0;
  changeMaskCounter = 0;
}
function createNodeWithoutHydration(lView, textOrName, nodeType) {
  const renderer = lView[RENDERER];
  switch (nodeType) {
    case Node.COMMENT_NODE:
      return createCommentNode(renderer, textOrName);
    case Node.TEXT_NODE:
      return createTextNode(renderer, textOrName);
    case Node.ELEMENT_NODE:
      return createElementNode(renderer, textOrName, null);
  }
}
let _locateOrCreateNode = (lView, index, textOrName, nodeType) => {
  lastNodeWasCreated(true);
  return createNodeWithoutHydration(lView, textOrName, nodeType);
};
function locateOrCreateNodeImpl(lView, index, textOrName, nodeType) {
  const hydrationInfo = lView[HYDRATION];
  const noOffsetIndex = index - HEADER_OFFSET;
  const isNodeCreationMode = !isI18nHydrationSupportEnabled() || !hydrationInfo || isInSkipHydrationBlock$1() || isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  lastNodeWasCreated(isNodeCreationMode);
  if (isNodeCreationMode) {
    return createNodeWithoutHydration(lView, textOrName, nodeType);
  }
  const native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  // TODO: Improve error handling
  //
  // Other hydration paths use validateMatchingNode() in order to provide
  // detailed information in development mode about the expected DOM.
  // However, not every node in an i18n block has a TNode. Instead, we
  // need to be able to use the AST to generate a similar message.
  ngDevMode && assertDefined(native, 'expected native element');
  ngDevMode && assertEqual(native.nodeType, nodeType, 'expected matching nodeType');
  ngDevMode && nodeType === Node.ELEMENT_NODE && assertEqual(native.tagName.toLowerCase(), textOrName.toLowerCase(), 'expecting matching tagName');
  ngDevMode && markRNodeAsClaimedByHydration(native);
  return native;
}
function enableLocateOrCreateI18nNodeImpl() {
  _locateOrCreateNode = locateOrCreateNodeImpl;
}
/**
 * Apply `I18nCreateOpCodes` op-codes as stored in `TI18n.create`.
 *
 * Creates text (and comment) nodes which are internationalized.
 *
 * @param lView Current lView
 * @param createOpCodes Set of op-codes to apply
 * @param parentRNode Parent node (so that direct children can be added eagerly) or `null` if it is
 *     a root node.
 * @param insertInFrontOf DOM node that should be used as an anchor.
 */
function applyCreateOpCodes(lView, createOpCodes, parentRNode, insertInFrontOf) {
  const renderer = lView[RENDERER];
  for (let i = 0; i < createOpCodes.length; i++) {
    const opCode = createOpCodes[i++];
    const text = createOpCodes[i];
    const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
    const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
    const index = opCode >>> I18nCreateOpCode.SHIFT;
    let rNode = lView[index];
    let lastNodeWasCreated = false;
    if (rNode === null) {
      // We only create new DOM nodes if they don't already exist: If ICU switches case back to a
      // case which was already instantiated, no need to create new DOM nodes.
      rNode = lView[index] = _locateOrCreateNode(lView, index, text, isComment ? Node.COMMENT_NODE : Node.TEXT_NODE);
      lastNodeWasCreated = wasLastNodeCreated();
    }
    if (appendNow && parentRNode !== null && lastNodeWasCreated) {
      nativeInsertBefore(renderer, parentRNode, rNode, insertInFrontOf, false);
    }
  }
}
/**
 * Apply `I18nMutateOpCodes` OpCodes.
 *
 * @param tView Current `TView`
 * @param mutableOpCodes Mutable OpCodes to process
 * @param lView Current `LView`
 * @param anchorRNode place where the i18n node should be inserted.
 */
function applyMutableOpCodes(tView, mutableOpCodes, lView, anchorRNode) {
  ngDevMode && assertDomNode(anchorRNode);
  const renderer = lView[RENDERER];
  // `rootIdx` represents the node into which all inserts happen.
  let rootIdx = null;
  // `rootRNode` represents the real node into which we insert. This can be different from
  // `lView[rootIdx]` if we have projection.
  //  - null we don't have a parent (as can be the case in when we are inserting into a root of
  //    LView which has no parent.)
  //  - `RElement` The element representing the root after taking projection into account.
  let rootRNode;
  for (let i = 0; i < mutableOpCodes.length; i++) {
    const opCode = mutableOpCodes[i];
    if (typeof opCode == 'string') {
      const textNodeIndex = mutableOpCodes[++i];
      if (lView[textNodeIndex] === null) {
        ngDevMode && ngDevMode.rendererCreateTextNode++;
        ngDevMode && assertIndexInRange(lView, textNodeIndex);
        lView[textNodeIndex] = _locateOrCreateNode(lView, textNodeIndex, opCode, Node.TEXT_NODE);
      }
    } else if (typeof opCode == 'number') {
      switch (opCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */) {
        case 0 /* IcuCreateOpCode.AppendChild */:
          const parentIdx = getParentFromIcuCreateOpCode(opCode);
          if (rootIdx === null) {
            // The first operation should save the `rootIdx` because the first operation
            // must insert into the root. (Only subsequent operations can insert into a dynamic
            // parent)
            rootIdx = parentIdx;
            rootRNode = nativeParentNode(renderer, anchorRNode);
          }
          let insertInFrontOf;
          let parentRNode;
          if (parentIdx === rootIdx) {
            insertInFrontOf = anchorRNode;
            parentRNode = rootRNode;
          } else {
            insertInFrontOf = null;
            parentRNode = unwrapRNode(lView[parentIdx]);
          }
          // FIXME(misko): Refactor with `processI18nText`
          if (parentRNode !== null) {
            // This can happen if the `LView` we are adding to is not attached to a parent `LView`.
            // In such a case there is no "root" we can attach to. This is fine, as we still need to
            // create the elements. When the `LView` gets later added to a parent these "root" nodes
            // get picked up and added.
            ngDevMode && assertDomNode(parentRNode);
            const refIdx = getRefFromIcuCreateOpCode(opCode);
            ngDevMode && assertGreaterThan(refIdx, HEADER_OFFSET, 'Missing ref');
            // `unwrapRNode` is not needed here as all of these point to RNodes as part of the i18n
            // which can't have components.
            const child = lView[refIdx];
            ngDevMode && assertDomNode(child);
            nativeInsertBefore(renderer, parentRNode, child, insertInFrontOf, false);
            const tIcu = getTIcu(tView, refIdx);
            if (tIcu !== null && typeof tIcu === 'object') {
              // If we just added a comment node which has ICU then that ICU may have already been
              // rendered and therefore we need to re-add it here.
              ngDevMode && assertTIcu(tIcu);
              const caseIndex = getCurrentICUCaseIndex(tIcu, lView);
              if (caseIndex !== null) {
                applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, lView[tIcu.anchorIdx]);
              }
            }
          }
          break;
        case 1 /* IcuCreateOpCode.Attr */:
          const elementNodeIndex = opCode >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
          const attrName = mutableOpCodes[++i];
          const attrValue = mutableOpCodes[++i];
          // This code is used for ICU expressions only, since we don't support
          // directives/components in ICUs, we don't need to worry about inputs here
          setElementAttribute(renderer, getNativeByIndex(elementNodeIndex, lView), null, null, attrName, attrValue, null);
          break;
        default:
          if (ngDevMode) {
            throw new RuntimeError(700 /* RuntimeErrorCode.INVALID_I18N_STRUCTURE */, `Unable to determine the type of mutate operation for "${opCode}"`);
          }
      }
    } else {
      switch (opCode) {
        case ICU_MARKER:
          const commentValue = mutableOpCodes[++i];
          const commentNodeIndex = mutableOpCodes[++i];
          if (lView[commentNodeIndex] === null) {
            ngDevMode && assertEqual(typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`);
            ngDevMode && ngDevMode.rendererCreateComment++;
            ngDevMode && assertIndexInExpandoRange(lView, commentNodeIndex);
            const commentRNode = lView[commentNodeIndex] = _locateOrCreateNode(lView, commentNodeIndex, commentValue, Node.COMMENT_NODE);
            // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
            attachPatchData(commentRNode, lView);
          }
          break;
        case ELEMENT_MARKER:
          const tagName = mutableOpCodes[++i];
          const elementNodeIndex = mutableOpCodes[++i];
          if (lView[elementNodeIndex] === null) {
            ngDevMode && assertEqual(typeof tagName, 'string', `Expected "${tagName}" to be an element node tag name`);
            ngDevMode && ngDevMode.rendererCreateElement++;
            ngDevMode && assertIndexInExpandoRange(lView, elementNodeIndex);
            const elementRNode = lView[elementNodeIndex] = _locateOrCreateNode(lView, elementNodeIndex, tagName, Node.ELEMENT_NODE);
            // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
            attachPatchData(elementRNode, lView);
          }
          break;
        default:
          ngDevMode && throwError(`Unable to determine the type of mutate operation for "${opCode}"`);
      }
    }
  }
}
/**
 * Apply `I18nUpdateOpCodes` OpCodes
 *
 * @param tView Current `TView`
 * @param lView Current `LView`
 * @param updateOpCodes OpCodes to process
 * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
 * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from
 *     `bindingsStartIndex`)
 */
function applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask) {
  for (let i = 0; i < updateOpCodes.length; i++) {
    // bit code to check if we should apply the next update
    const checkBit = updateOpCodes[i];
    // Number of opCodes to skip until next set of update codes
    const skipCodes = updateOpCodes[++i];
    if (checkBit & changeMask) {
      // The value has been updated since last checked
      let value = '';
      for (let j = i + 1; j <= i + skipCodes; j++) {
        const opCode = updateOpCodes[j];
        if (typeof opCode == 'string') {
          value += opCode;
        } else if (typeof opCode == 'number') {
          if (opCode < 0) {
            // Negative opCode represent `i18nExp` values offset.
            value += renderStringify(lView[bindingsStartIndex - opCode]);
          } else {
            const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
            switch (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) {
              case 1 /* I18nUpdateOpCode.Attr */:
                const propName = updateOpCodes[++j];
                const sanitizeFn = updateOpCodes[++j];
                const tNodeOrTagName = tView.data[nodeIndex];
                ngDevMode && assertDefined(tNodeOrTagName, 'Experting TNode or string');
                if (typeof tNodeOrTagName === 'string') {
                  // IF we don't have a `TNode`, then we are an element in ICU (as ICU content does
                  // not have TNode), in which case we know that there are no directives, and hence
                  // we use attribute setting.
                  setElementAttribute(lView[RENDERER], lView[nodeIndex], null, tNodeOrTagName, propName, value, sanitizeFn);
                } else {
                  elementPropertyInternal(tView, tNodeOrTagName, lView, propName, value, lView[RENDERER], sanitizeFn, false);
                }
                break;
              case 0 /* I18nUpdateOpCode.Text */:
                const rText = lView[nodeIndex];
                rText !== null && updateTextNode(lView[RENDERER], rText, value);
                break;
              case 2 /* I18nUpdateOpCode.IcuSwitch */:
                applyIcuSwitchCase(tView, getTIcu(tView, nodeIndex), lView, value);
                break;
              case 3 /* I18nUpdateOpCode.IcuUpdate */:
                applyIcuUpdateCase(tView, getTIcu(tView, nodeIndex), bindingsStartIndex, lView);
                break;
            }
          }
        }
      }
    } else {
      const opCode = updateOpCodes[i + 1];
      if (opCode > 0 && (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) === 3 /* I18nUpdateOpCode.IcuUpdate */) {
        // Special case for the `icuUpdateCase`. It could be that the mask did not match, but
        // we still need to execute `icuUpdateCase` because the case has changed recently due to
        // previous `icuSwitchCase` instruction. (`icuSwitchCase` and `icuUpdateCase` always come in
        // pairs.)
        const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
        const tIcu = getTIcu(tView, nodeIndex);
        const currentIndex = lView[tIcu.currentCaseLViewIndex];
        if (currentIndex < 0) {
          applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView);
        }
      }
    }
    i += skipCodes;
  }
}
/**
 * Apply OpCodes associated with updating an existing ICU.
 *
 * @param tView Current `TView`
 * @param tIcu Current `TIcu`
 * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
 * @param lView Current `LView`
 */
function applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView) {
  ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex);
  let activeCaseIndex = lView[tIcu.currentCaseLViewIndex];
  if (activeCaseIndex !== null) {
    let mask = changeMask;
    if (activeCaseIndex < 0) {
      // Clear the flag.
      // Negative number means that the ICU was freshly created and we need to force the update.
      activeCaseIndex = lView[tIcu.currentCaseLViewIndex] = ~activeCaseIndex;
      // -1 is same as all bits on, which simulates creation since it marks all bits dirty
      mask = -1;
    }
    applyUpdateOpCodes(tView, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask);
  }
}
/**
 * Apply OpCodes associated with switching a case on ICU.
 *
 * This involves tearing down existing case and than building up a new case.
 *
 * @param tView Current `TView`
 * @param tIcu Current `TIcu`
 * @param lView Current `LView`
 * @param value Value of the case to update to.
 */
function applyIcuSwitchCase(tView, tIcu, lView, value) {
  // Rebuild a new case for this ICU
  const caseIndex = getCaseIndex(tIcu, value);
  let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  if (activeCaseIndex !== caseIndex) {
    applyIcuSwitchCaseRemove(tView, tIcu, lView);
    lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex;
    if (caseIndex !== null) {
      // Add the nodes for the new case
      const anchorRNode = lView[tIcu.anchorIdx];
      if (anchorRNode) {
        ngDevMode && assertDomNode(anchorRNode);
        applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, anchorRNode);
      }
      claimDehydratedIcuCase(lView, tIcu.anchorIdx, caseIndex);
    }
  }
}
/**
 * Apply OpCodes associated with tearing ICU case.
 *
 * This involves tearing down existing case and than building up a new case.
 *
 * @param tView Current `TView`
 * @param tIcu Current `TIcu`
 * @param lView Current `LView`
 */
function applyIcuSwitchCaseRemove(tView, tIcu, lView) {
  let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  if (activeCaseIndex !== null) {
    const removeCodes = tIcu.remove[activeCaseIndex];
    for (let i = 0; i < removeCodes.length; i++) {
      const nodeOrIcuIndex = removeCodes[i];
      if (nodeOrIcuIndex > 0) {
        // Positive numbers are `RNode`s.
        const rNode = getNativeByIndex(nodeOrIcuIndex, lView);
        rNode !== null && nativeRemoveNode(lView[RENDERER], rNode);
      } else {
        // Negative numbers are ICUs
        applyIcuSwitchCaseRemove(tView, getTIcu(tView, ~nodeOrIcuIndex), lView);
      }
    }
  }
}
/**
 * Returns the index of the current case of an ICU expression depending on the main binding value
 *
 * @param icuExpression
 * @param bindingValue The value of the main binding used by this ICU expression
 */
function getCaseIndex(icuExpression, bindingValue) {
  let index = icuExpression.cases.indexOf(bindingValue);
  if (index === -1) {
    switch (icuExpression.type) {
      case 1 /* IcuType.plural */:
        {
          const resolvedCase = getPluralCase(bindingValue, getLocaleId());
          index = icuExpression.cases.indexOf(resolvedCase);
          if (index === -1 && resolvedCase !== 'other') {
            index = icuExpression.cases.indexOf('other');
          }
          break;
        }
      case 0 /* IcuType.select */:
        {
          index = icuExpression.cases.indexOf('other');
          break;
        }
    }
  }
  return index === -1 ? null : index;
}

/**
 * Converts `I18nCreateOpCodes` array into a human readable format.
 *
 * This function is attached to the `I18nCreateOpCodes.debug` property if `ngDevMode` is enabled.
 * This function provides a human readable view of the opcodes. This is useful when debugging the
 * application as well as writing more readable tests.
 *
 * @param this `I18nCreateOpCodes` if attached as a method.
 * @param opcodes `I18nCreateOpCodes` if invoked as a function.
 */
function i18nCreateOpCodesToString(opcodes) {
  const createOpCodes = opcodes || (Array.isArray(this) ? this : []);
  let lines = [];
  for (let i = 0; i < createOpCodes.length; i++) {
    const opCode = createOpCodes[i++];
    const text = createOpCodes[i];
    const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
    const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
    const index = opCode >>> I18nCreateOpCode.SHIFT;
    lines.push(`lView[${index}] = document.${isComment ? 'createComment' : 'createText'}(${JSON.stringify(text)});`);
    if (appendNow) {
      lines.push(`parent.appendChild(lView[${index}]);`);
    }
  }
  return lines;
}
/**
 * Converts `I18nUpdateOpCodes` array into a human readable format.
 *
 * This function is attached to the `I18nUpdateOpCodes.debug` property if `ngDevMode` is enabled.
 * This function provides a human readable view of the opcodes. This is useful when debugging the
 * application as well as writing more readable tests.
 *
 * @param this `I18nUpdateOpCodes` if attached as a method.
 * @param opcodes `I18nUpdateOpCodes` if invoked as a function.
 */
function i18nUpdateOpCodesToString(opcodes) {
  const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  let lines = [];
  function consumeOpCode(value) {
    const ref = value >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
    const opCode = value & 3 /* I18nUpdateOpCode.MASK_OPCODE */;
    switch (opCode) {
      case 0 /* I18nUpdateOpCode.Text */:
        return `(lView[${ref}] as Text).textContent = $$$`;
      case 1 /* I18nUpdateOpCode.Attr */:
        const attrName = parser.consumeString();
        const sanitizationFn = parser.consumeFunction();
        const value = sanitizationFn ? `(${sanitizationFn})($$$)` : '$$$';
        return `(lView[${ref}] as Element).setAttribute('${attrName}', ${value})`;
      case 2 /* I18nUpdateOpCode.IcuSwitch */:
        return `icuSwitchCase(${ref}, $$$)`;
      case 3 /* I18nUpdateOpCode.IcuUpdate */:
        return `icuUpdateCase(${ref})`;
    }
    throw new Error('unexpected OpCode');
  }
  while (parser.hasMore()) {
    let mask = parser.consumeNumber();
    let size = parser.consumeNumber();
    const end = parser.i + size;
    const statements = [];
    let statement = '';
    while (parser.i < end) {
      let value = parser.consumeNumberOrString();
      if (typeof value === 'string') {
        statement += value;
      } else if (value < 0) {
        // Negative numbers are ref indexes
        // Here `i` refers to current binding index. It is to signify that the value is relative,
        // rather than absolute.
        statement += '${lView[i' + value + ']}';
      } else {
        // Positive numbers are operations.
        const opCodeText = consumeOpCode(value);
        statements.push(opCodeText.replace('$$$', '`' + statement + '`') + ';');
        statement = '';
      }
    }
    lines.push(`if (mask & 0b${mask.toString(2)}) { ${statements.join(' ')} }`);
  }
  return lines;
}
/**
 * Converts `I18nCreateOpCodes` array into a human readable format.
 *
 * This function is attached to the `I18nCreateOpCodes.debug` if `ngDevMode` is enabled. This
 * function provides a human readable view of the opcodes. This is useful when debugging the
 * application as well as writing more readable tests.
 *
 * @param this `I18nCreateOpCodes` if attached as a method.
 * @param opcodes `I18nCreateOpCodes` if invoked as a function.
 */
function icuCreateOpCodesToString(opcodes) {
  const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  let lines = [];
  function consumeOpCode(opCode) {
    const parent = getParentFromIcuCreateOpCode(opCode);
    const ref = getRefFromIcuCreateOpCode(opCode);
    switch (getInstructionFromIcuCreateOpCode(opCode)) {
      case 0 /* IcuCreateOpCode.AppendChild */:
        return `(lView[${parent}] as Element).appendChild(lView[${lastRef}])`;
      case 1 /* IcuCreateOpCode.Attr */:
        return `(lView[${ref}] as Element).setAttribute("${parser.consumeString()}", "${parser.consumeString()}")`;
    }
    throw new Error('Unexpected OpCode: ' + getInstructionFromIcuCreateOpCode(opCode));
  }
  let lastRef = -1;
  while (parser.hasMore()) {
    let value = parser.consumeNumberStringOrMarker();
    if (value === ICU_MARKER) {
      const text = parser.consumeString();
      lastRef = parser.consumeNumber();
      lines.push(`lView[${lastRef}] = document.createComment("${text}")`);
    } else if (value === ELEMENT_MARKER) {
      const text = parser.consumeString();
      lastRef = parser.consumeNumber();
      lines.push(`lView[${lastRef}] = document.createElement("${text}")`);
    } else if (typeof value === 'string') {
      lastRef = parser.consumeNumber();
      lines.push(`lView[${lastRef}] = document.createTextNode("${value}")`);
    } else if (typeof value === 'number') {
      const line = consumeOpCode(value);
      line && lines.push(line);
    } else {
      throw new Error('Unexpected value');
    }
  }
  return lines;
}
/**
 * Converts `I18nRemoveOpCodes` array into a human readable format.
 *
 * This function is attached to the `I18nRemoveOpCodes.debug` if `ngDevMode` is enabled. This
 * function provides a human readable view of the opcodes. This is useful when debugging the
 * application as well as writing more readable tests.
 *
 * @param this `I18nRemoveOpCodes` if attached as a method.
 * @param opcodes `I18nRemoveOpCodes` if invoked as a function.
 */
function i18nRemoveOpCodesToString(opcodes) {
  const removeCodes = opcodes || (Array.isArray(this) ? this : []);
  let lines = [];
  for (let i = 0; i < removeCodes.length; i++) {
    const nodeOrIcuIndex = removeCodes[i];
    if (nodeOrIcuIndex > 0) {
      // Positive numbers are `RNode`s.
      lines.push(`remove(lView[${nodeOrIcuIndex}])`);
    } else {
      // Negative numbers are ICUs
      lines.push(`removeNestedICU(${~nodeOrIcuIndex})`);
    }
  }
  return lines;
}
class OpCodeParser {
  i = 0;
  codes;
  constructor(codes) {
    this.codes = codes;
  }
  hasMore() {
    return this.i < this.codes.length;
  }
  consumeNumber() {
    let value = this.codes[this.i++];
    assertNumber(value, 'expecting number in OpCode');
    return value;
  }
  consumeString() {
    let value = this.codes[this.i++];
    assertString(value, 'expecting string in OpCode');
    return value;
  }
  consumeFunction() {
    let value = this.codes[this.i++];
    if (value === null || typeof value === 'function') {
      return value;
    }
    throw new Error('expecting function in OpCode');
  }
  consumeNumberOrString() {
    let value = this.codes[this.i++];
    if (typeof value === 'string') {
      return value;
    }
    assertNumber(value, 'expecting number or string in OpCode');
    return value;
  }
  consumeNumberStringOrMarker() {
    let value = this.codes[this.i++];
    if (typeof value === 'string' || typeof value === 'number' || value == ICU_MARKER || value == ELEMENT_MARKER) {
      return value;
    }
    assertNumber(value, 'expecting number, string, ICU_MARKER or ELEMENT_MARKER in OpCode');
    return value;
  }
}
const BINDING_REGEXP = /�(\d+):?\d*�/gi;
const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi;
const NESTED_ICU = /�(\d+)�/;
const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/;
const MARKER = `�`;
const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi;
const PH_REGEXP = /�(\/?[#*]\d+):?\d*�/gi;
/**
 * Angular uses the special entity &ngsp; as a placeholder for non-removable space.
 * It's replaced by the 0xE500 PUA (Private Use Areas) unicode character and later on replaced by a
 * space.
 * We are re-implementing the same idea since translations might contain this special character.
 */
const NGSP_UNICODE_REGEXP = /\uE500/g;
function replaceNgsp(value) {
  return value.replace(NGSP_UNICODE_REGEXP, ' ');
}
/**
 * Patch a `debug` property getter on top of the existing object.
 *
 * NOTE: always call this method with `ngDevMode && attachDebugObject(...)`
 *
 * @param obj Object to patch
 * @param debugGetter Getter returning a value to patch
 */
function attachDebugGetter(obj, debugGetter) {
  if (ngDevMode) {
    Object.defineProperty(obj, 'debug', {
      get: debugGetter,
      enumerable: false
    });
  } else {
    throw new Error('This method should be guarded with `ngDevMode` so that it can be tree shaken in production!');
  }
}
/**
 * Create dynamic nodes from i18n translation block.
 *
 * - Text nodes are created synchronously
 * - TNodes are linked into tree lazily
 *
 * @param tView Current `TView`
 * @parentTNodeIndex index to the parent TNode of this i18n block
 * @param lView Current `LView`
 * @param index Index of `ɵɵi18nStart` instruction.
 * @param message Message to translate.
 * @param subTemplateIndex Index into the sub template of message translation. (ie in case of
 *     `ngIf`) (-1 otherwise)
 */
function i18nStartFirstCreatePass(tView, parentTNodeIndex, lView, index, message, subTemplateIndex) {
  const rootTNode = getCurrentParentTNode();
  const createOpCodes = [];
  const updateOpCodes = [];
  const existingTNodeStack = [[]];
  const astStack = [[]];
  if (ngDevMode) {
    attachDebugGetter(createOpCodes, i18nCreateOpCodesToString);
    attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  }
  message = getTranslationForTemplate(message, subTemplateIndex);
  const msgParts = replaceNgsp(message).split(PH_REGEXP);
  for (let i = 0; i < msgParts.length; i++) {
    let value = msgParts[i];
    if ((i & 1) === 0) {
      // Even indexes are text (including bindings & ICU expressions)
      const parts = i18nParseTextIntoPartsAndICU(value);
      for (let j = 0; j < parts.length; j++) {
        let part = parts[j];
        if ((j & 1) === 0) {
          // `j` is odd therefore `part` is string
          const text = part;
          ngDevMode && assertString(text, 'Parsed ICU part should be string');
          if (text !== '') {
            i18nStartFirstCreatePassProcessTextNode(astStack[0], tView, rootTNode, existingTNodeStack[0], createOpCodes, updateOpCodes, lView, text);
          }
        } else {
          // `j` is Even therefor `part` is an `ICUExpression`
          const icuExpression = part;
          // Verify that ICU expression has the right shape. Translations might contain invalid
          // constructions (while original messages were correct), so ICU parsing at runtime may
          // not succeed (thus `icuExpression` remains a string).
          // Note: we intentionally retain the error here by not using `ngDevMode`, because
          // the value can change based on the locale and users aren't guaranteed to hit
          // an invalid string while they're developing.
          if (typeof icuExpression !== 'object') {
            throw new Error(`Unable to parse ICU expression in "${message}" message.`);
          }
          const icuContainerTNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodeStack[0], lView, createOpCodes, ngDevMode ? `ICU ${index}:${icuExpression.mainBinding}` : '', true);
          const icuNodeIndex = icuContainerTNode.index;
          ngDevMode && assertGreaterThanOrEqual(icuNodeIndex, HEADER_OFFSET, 'Index must be in absolute LView offset');
          icuStart(astStack[0], tView, lView, updateOpCodes, parentTNodeIndex, icuExpression, icuNodeIndex);
        }
      }
    } else {
      // Odd indexes are placeholders (elements and sub-templates)
      // At this point value is something like: '/#1:2' (originally coming from '�/#1:2�')
      const isClosing = value.charCodeAt(0) === 47 /* CharCode.SLASH */;
      const type = value.charCodeAt(isClosing ? 1 : 0);
      ngDevMode && assertOneOf(type, 42 /* CharCode.STAR */, 35 /* CharCode.HASH */);
      const index = HEADER_OFFSET + Number.parseInt(value.substring(isClosing ? 2 : 1));
      if (isClosing) {
        existingTNodeStack.shift();
        astStack.shift();
        setCurrentTNode(getCurrentParentTNode(), false);
      } else {
        const tNode = createTNodePlaceholder(tView, existingTNodeStack[0], index);
        existingTNodeStack.unshift([]);
        setCurrentTNode(tNode, true);
        const placeholderNode = {
          kind: 2 /* I18nNodeKind.PLACEHOLDER */,
          index,
          children: [],
          type: type === 35 /* CharCode.HASH */ ? 0 /* I18nPlaceholderType.ELEMENT */ : 1 /* I18nPlaceholderType.SUBTEMPLATE */
        };
        astStack[0].push(placeholderNode);
        astStack.unshift(placeholderNode.children);
      }
    }
  }
  tView.data[index] = {
    create: createOpCodes,
    update: updateOpCodes,
    ast: astStack[0],
    parentTNodeIndex
  };
}
/**
 * Allocate space in i18n Range add create OpCode instruction to create a text or comment node.
 *
 * @param tView Current `TView` needed to allocate space in i18n range.
 * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will be
 *     added as part of the `i18nStart` instruction or as part of the `TNode.insertBeforeIndex`.
 * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
 * @param lView Current `LView` needed to allocate space in i18n range.
 * @param createOpCodes Array storing `I18nCreateOpCodes` where new opCodes will be added.
 * @param text Text to be added when the `Text` or `Comment` node will be created.
 * @param isICU true if a `Comment` node for ICU (instead of `Text`) node should be created.
 */
function createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, text, isICU) {
  const i18nNodeIdx = allocExpando(tView, lView, 1, null);
  let opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT;
  let parentTNode = getCurrentParentTNode();
  if (rootTNode === parentTNode) {
    // FIXME(misko): A null `parentTNode` should represent when we fall of the `LView` boundary.
    // (there is no parent), but in some circumstances (because we are inconsistent about how we set
    // `previousOrParentTNode`) it could point to `rootTNode` So this is a work around.
    parentTNode = null;
  }
  if (parentTNode === null) {
    // If we don't have a parent that means that we can eagerly add nodes.
    // If we have a parent than these nodes can't be added now (as the parent has not been created
    // yet) and instead the `parentTNode` is responsible for adding it. See
    // `TNode.insertBeforeIndex`
    opCode |= I18nCreateOpCode.APPEND_EAGERLY;
  }
  if (isICU) {
    opCode |= I18nCreateOpCode.COMMENT;
    ensureIcuContainerVisitorLoaded(loadIcuContainerVisitor);
  }
  createOpCodes.push(opCode, text === null ? '' : text);
  // We store `{{?}}` so that when looking at debug `TNodeType.template` we can see where the
  // bindings are.
  const tNode = createTNodeAtIndex(tView, i18nNodeIdx, isICU ? 32 /* TNodeType.Icu */ : 1 /* TNodeType.Text */, text === null ? ngDevMode ? '{{?}}' : '' : text, null);
  addTNodeAndUpdateInsertBeforeIndex(existingTNodes, tNode);
  const tNodeIdx = tNode.index;
  setCurrentTNode(tNode, false /* Text nodes are self closing */);
  if (parentTNode !== null && rootTNode !== parentTNode) {
    // We are a child of deeper node (rather than a direct child of `i18nStart` instruction.)
    // We have to make sure to add ourselves to the parent.
    setTNodeInsertBeforeIndex(parentTNode, tNodeIdx);
  }
  return tNode;
}
/**
 * Processes text node in i18n block.
 *
 * Text nodes can have:
 * - Create instruction in `createOpCodes` for creating the text node.
 * - Allocate spec for text node in i18n range of `LView`
 * - If contains binding:
 *    - bindings => allocate space in i18n range of `LView` to store the binding value.
 *    - populate `updateOpCodes` with update instructions.
 *
 * @param tView Current `TView`
 * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will
 *     be added as part of the `i18nStart` instruction or as part of the
 *     `TNode.insertBeforeIndex`.
 * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
 * @param createOpCodes Location where the creation OpCodes will be stored.
 * @param lView Current `LView`
 * @param text The translated text (which may contain binding)
 */
function i18nStartFirstCreatePassProcessTextNode(ast, tView, rootTNode, existingTNodes, createOpCodes, updateOpCodes, lView, text) {
  const hasBinding = text.match(BINDING_REGEXP);
  const tNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, hasBinding ? null : text, false);
  const index = tNode.index;
  if (hasBinding) {
    generateBindingUpdateOpCodes(updateOpCodes, text, index, null, 0, null);
  }
  ast.push({
    kind: 0 /* I18nNodeKind.TEXT */,
    index
  });
}
/**
 * See `i18nAttributes` above.
 */
function i18nAttributesFirstPass(tView, index, values) {
  const previousElement = getCurrentTNode();
  const previousElementIndex = previousElement.index;
  const updateOpCodes = [];
  if (ngDevMode) {
    attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  }
  if (tView.firstCreatePass && tView.data[index] === null) {
    for (let i = 0; i < values.length; i += 2) {
      const attrName = values[i];
      const message = values[i + 1];
      if (message !== '') {
        // Check if attribute value contains an ICU and throw an error if that's the case.
        // ICUs in element attributes are not supported.
        // Note: we intentionally retain the error here by not using `ngDevMode`, because
        // the `value` can change based on the locale and users aren't guaranteed to hit
        // an invalid string while they're developing.
        if (ICU_REGEXP.test(message)) {
          throw new Error(`ICU expressions are not supported in attributes. Message: "${message}".`);
        }
        // i18n attributes that hit this code path are guaranteed to have bindings, because
        // the compiler treats static i18n attributes as regular attribute bindings.
        // Since this may not be the first i18n attribute on this element we need to pass in how
        // many previous bindings there have already been.
        generateBindingUpdateOpCodes(updateOpCodes, message, previousElementIndex, attrName, countBindings(updateOpCodes), null);
      }
    }
    tView.data[index] = updateOpCodes;
  }
}
/**
 * Generate the OpCodes to update the bindings of a string.
 *
 * @param updateOpCodes Place where the update opcodes will be stored.
 * @param str The string containing the bindings.
 * @param destinationNode Index of the destination node which will receive the binding.
 * @param attrName Name of the attribute, if the string belongs to an attribute.
 * @param sanitizeFn Sanitization function used to sanitize the string after update, if necessary.
 * @param bindingStart The lView index of the next expression that can be bound via an opCode.
 * @returns The mask value for these bindings
 */
function generateBindingUpdateOpCodes(updateOpCodes, str, destinationNode, attrName, bindingStart, sanitizeFn) {
  ngDevMode && assertGreaterThanOrEqual(destinationNode, HEADER_OFFSET, 'Index must be in absolute LView offset');
  const maskIndex = updateOpCodes.length; // Location of mask
  const sizeIndex = maskIndex + 1; // location of size for skipping
  updateOpCodes.push(null, null); // Alloc space for mask and size
  const startIndex = maskIndex + 2; // location of first allocation.
  if (ngDevMode) {
    attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  }
  const textParts = str.split(BINDING_REGEXP);
  let mask = 0;
  for (let j = 0; j < textParts.length; j++) {
    const textValue = textParts[j];
    if (j & 1) {
      // Odd indexes are bindings
      const bindingIndex = bindingStart + parseInt(textValue, 10);
      updateOpCodes.push(-1 - bindingIndex);
      mask = mask | toMaskBit(bindingIndex);
    } else if (textValue !== '') {
      // Even indexes are text
      updateOpCodes.push(textValue);
    }
  }
  updateOpCodes.push(destinationNode << 2 /* I18nUpdateOpCode.SHIFT_REF */ | (attrName ? 1 /* I18nUpdateOpCode.Attr */ : 0 /* I18nUpdateOpCode.Text */));
  if (attrName) {
    updateOpCodes.push(attrName, sanitizeFn);
  }
  updateOpCodes[maskIndex] = mask;
  updateOpCodes[sizeIndex] = updateOpCodes.length - startIndex;
  return mask;
}
/**
 * Count the number of bindings in the given `opCodes`.
 *
 * It could be possible to speed this up, by passing the number of bindings found back from
 * `generateBindingUpdateOpCodes()` to `i18nAttributesFirstPass()` but this would then require more
 * complexity in the code and/or transient objects to be created.
 *
 * Since this function is only called once when the template is instantiated, is trivial in the
 * first instance (since `opCodes` will be an empty array), and it is not common for elements to
 * contain multiple i18n bound attributes, it seems like this is a reasonable compromise.
 */
function countBindings(opCodes) {
  let count = 0;
  for (let i = 0; i < opCodes.length; i++) {
    const opCode = opCodes[i];
    // Bindings are negative numbers.
    if (typeof opCode === 'number' && opCode < 0) {
      count++;
    }
  }
  return count;
}
/**
 * Convert binding index to mask bit.
 *
 * Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make
 * the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to
 * have more than 32 bindings this will be hit very rarely. The downside of hitting this corner
 * case is that we will execute binding code more often than necessary. (penalty of performance)
 */
function toMaskBit(bindingIndex) {
  return 1 << Math.min(bindingIndex, 31);
}
/**
 * Removes everything inside the sub-templates of a message.
 */
function removeInnerTemplateTranslation(message) {
  let match;
  let res = '';
  let index = 0;
  let inTemplate = false;
  let tagMatched;
  while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) {
    if (!inTemplate) {
      res += message.substring(index, match.index + match[0].length);
      tagMatched = match[1];
      inTemplate = true;
    } else {
      if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) {
        index = match.index;
        inTemplate = false;
      }
    }
  }
  ngDevMode && assertEqual(inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`);
  res += message.slice(index);
  return res;
}
/**
 * Extracts a part of a message and removes the rest.
 *
 * This method is used for extracting a part of the message associated with a template. A
 * translated message can span multiple templates.
 *
 * Example:
 * ```
 * <div i18n>Translate <span *ngIf>me</span>!</div>
 * ```
 *
 * @param message The message to crop
 * @param subTemplateIndex Index of the sub-template to extract. If undefined it returns the
 * external template and removes all sub-templates.
 */
function getTranslationForTemplate(message, subTemplateIndex) {
  if (isRootTemplateMessage(subTemplateIndex)) {
    // We want the root template message, ignore all sub-templates
    return removeInnerTemplateTranslation(message);
  } else {
    // We want a specific sub-template
    const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length;
    const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`));
    return removeInnerTemplateTranslation(message.substring(start, end));
  }
}
/**
 * Generate the OpCodes for ICU expressions.
 *
 * @param icuExpression
 * @param index Index where the anchor is stored and an optional `TIcuContainerNode`
 *   - `lView[anchorIdx]` points to a `Comment` node representing the anchor for the ICU.
 *   - `tView.data[anchorIdx]` points to the `TIcuContainerNode` if ICU is root (`null` otherwise)
 */
function icuStart(ast, tView, lView, updateOpCodes, parentIdx, icuExpression, anchorIdx) {
  ngDevMode && assertDefined(icuExpression, 'ICU expression must be defined');
  let bindingMask = 0;
  const tIcu = {
    type: icuExpression.type,
    currentCaseLViewIndex: allocExpando(tView, lView, 1, null),
    anchorIdx,
    cases: [],
    create: [],
    remove: [],
    update: []
  };
  addUpdateIcuSwitch(updateOpCodes, icuExpression, anchorIdx);
  setTIcu(tView, anchorIdx, tIcu);
  const values = icuExpression.values;
  const cases = [];
  for (let i = 0; i < values.length; i++) {
    // Each value is an array of strings & other ICU expressions
    const valueArr = values[i];
    const nestedIcus = [];
    for (let j = 0; j < valueArr.length; j++) {
      const value = valueArr[j];
      if (typeof value !== 'string') {
        // It is an nested ICU expression
        const icuIndex = nestedIcus.push(value) - 1;
        // Replace nested ICU expression by a comment node
        valueArr[j] = `<!--�${icuIndex}�-->`;
      }
    }
    const caseAst = [];
    cases.push(caseAst);
    bindingMask = parseIcuCase(caseAst, tView, tIcu, lView, updateOpCodes, parentIdx, icuExpression.cases[i], valueArr.join(''), nestedIcus) | bindingMask;
  }
  if (bindingMask) {
    addUpdateIcuUpdate(updateOpCodes, bindingMask, anchorIdx);
  }
  ast.push({
    kind: 3 /* I18nNodeKind.ICU */,
    index: anchorIdx,
    cases,
    currentCaseLViewIndex: tIcu.currentCaseLViewIndex
  });
}
/**
 * Parses text containing an ICU expression and produces a JSON object for it.
 * Original code from closure library, modified for Angular.
 *
 * @param pattern Text containing an ICU expression that needs to be parsed.
 *
 */
function parseICUBlock(pattern) {
  const cases = [];
  const values = [];
  let icuType = 1 /* IcuType.plural */;
  let mainBinding = 0;
  pattern = pattern.replace(ICU_BLOCK_REGEXP, function (str, binding, type) {
    if (type === 'select') {
      icuType = 0 /* IcuType.select */;
    } else {
      icuType = 1 /* IcuType.plural */;
    }
    mainBinding = parseInt(binding.slice(1), 10);
    return '';
  });
  const parts = i18nParseTextIntoPartsAndICU(pattern);
  // Looking for (key block)+ sequence. One of the keys has to be "other".
  for (let pos = 0; pos < parts.length;) {
    let key = parts[pos++].trim();
    if (icuType === 1 /* IcuType.plural */) {
      // Key can be "=x", we just want "x"
      key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1');
    }
    if (key.length) {
      cases.push(key);
    }
    const blocks = i18nParseTextIntoPartsAndICU(parts[pos++]);
    if (cases.length > values.length) {
      values.push(blocks);
    }
  }
  // TODO(ocombe): support ICU expressions in attributes, see #21615
  return {
    type: icuType,
    mainBinding: mainBinding,
    cases,
    values
  };
}
/**
 * Breaks pattern into strings and top level {...} blocks.
 * Can be used to break a message into text and ICU expressions, or to break an ICU expression
 * into keys and cases. Original code from closure library, modified for Angular.
 *
 * @param pattern (sub)Pattern to be broken.
 * @returns An `Array<string|IcuExpression>` where:
 *   - odd positions: `string` => text between ICU expressions
 *   - even positions: `ICUExpression` => ICU expression parsed into `ICUExpression` record.
 */
function i18nParseTextIntoPartsAndICU(pattern) {
  if (!pattern) {
    return [];
  }
  let prevPos = 0;
  const braceStack = [];
  const results = [];
  const braces = /[{}]/g;
  // lastIndex doesn't get set to 0 so we have to.
  braces.lastIndex = 0;
  let match;
  while (match = braces.exec(pattern)) {
    const pos = match.index;
    if (match[0] == '}') {
      braceStack.pop();
      if (braceStack.length == 0) {
        // End of the block.
        const block = pattern.substring(prevPos, pos);
        if (ICU_BLOCK_REGEXP.test(block)) {
          results.push(parseICUBlock(block));
        } else {
          results.push(block);
        }
        prevPos = pos + 1;
      }
    } else {
      if (braceStack.length == 0) {
        const substring = pattern.substring(prevPos, pos);
        results.push(substring);
        prevPos = pos + 1;
      }
      braceStack.push('{');
    }
  }
  const substring = pattern.substring(prevPos);
  results.push(substring);
  return results;
}
/**
 * Parses a node, its children and its siblings, and generates the mutate & update OpCodes.
 *
 */
function parseIcuCase(ast, tView, tIcu, lView, updateOpCodes, parentIdx, caseName, unsafeCaseHtml, nestedIcus) {
  const create = [];
  const remove = [];
  const update = [];
  if (ngDevMode) {
    attachDebugGetter(create, icuCreateOpCodesToString);
    attachDebugGetter(remove, i18nRemoveOpCodesToString);
    attachDebugGetter(update, i18nUpdateOpCodesToString);
  }
  tIcu.cases.push(caseName);
  tIcu.create.push(create);
  tIcu.remove.push(remove);
  tIcu.update.push(update);
  const inertBodyHelper = getInertBodyHelper(getDocument());
  const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeCaseHtml);
  ngDevMode && assertDefined(inertBodyElement, 'Unable to generate inert body element');
  const inertRootNode = getTemplateContent(inertBodyElement) || inertBodyElement;
  if (inertRootNode) {
    return walkIcuTree(ast, tView, tIcu, lView, updateOpCodes, create, remove, update, inertRootNode, parentIdx, nestedIcus, 0);
  } else {
    return 0;
  }
}
function walkIcuTree(ast, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, parentNode, parentIdx, nestedIcus, depth) {
  let bindingMask = 0;
  let currentNode = parentNode.firstChild;
  while (currentNode) {
    const newIndex = allocExpando(tView, lView, 1, null);
    switch (currentNode.nodeType) {
      case Node.ELEMENT_NODE:
        const element = currentNode;
        const tagName = element.tagName.toLowerCase();
        if (VALID_ELEMENTS.hasOwnProperty(tagName)) {
          addCreateNodeAndAppend(create, ELEMENT_MARKER, tagName, parentIdx, newIndex);
          tView.data[newIndex] = tagName;
          const elAttrs = element.attributes;
          for (let i = 0; i < elAttrs.length; i++) {
            const attr = elAttrs.item(i);
            const lowerAttrName = attr.name.toLowerCase();
            const hasBinding = !!attr.value.match(BINDING_REGEXP);
            // we assume the input string is safe, unless it's using a binding
            if (hasBinding) {
              if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) {
                if (URI_ATTRS[lowerAttrName]) {
                  generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, _sanitizeUrl);
                } else {
                  generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, null);
                }
              } else {
                ngDevMode && console.warn(`WARNING: ignoring unsafe attribute value ` + `${lowerAttrName} on element ${tagName} ` + `(see ${XSS_SECURITY_URL})`);
              }
            } else {
              addCreateAttribute(create, newIndex, attr);
            }
          }
          const elementNode = {
            kind: 1 /* I18nNodeKind.ELEMENT */,
            index: newIndex,
            children: []
          };
          ast.push(elementNode);
          // Parse the children of this node (if any)
          bindingMask = walkIcuTree(elementNode.children, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, currentNode, newIndex, nestedIcus, depth + 1) | bindingMask;
          addRemoveNode(remove, newIndex, depth);
        }
        break;
      case Node.TEXT_NODE:
        const value = currentNode.textContent || '';
        const hasBinding = value.match(BINDING_REGEXP);
        addCreateNodeAndAppend(create, null, hasBinding ? '' : value, parentIdx, newIndex);
        addRemoveNode(remove, newIndex, depth);
        if (hasBinding) {
          bindingMask = generateBindingUpdateOpCodes(update, value, newIndex, null, 0, null) | bindingMask;
        }
        ast.push({
          kind: 0 /* I18nNodeKind.TEXT */,
          index: newIndex
        });
        break;
      case Node.COMMENT_NODE:
        // Check if the comment node is a placeholder for a nested ICU
        const isNestedIcu = NESTED_ICU.exec(currentNode.textContent || '');
        if (isNestedIcu) {
          const nestedIcuIndex = parseInt(isNestedIcu[1], 10);
          const icuExpression = nestedIcus[nestedIcuIndex];
          // Create the comment node that will anchor the ICU expression
          addCreateNodeAndAppend(create, ICU_MARKER, ngDevMode ? `nested ICU ${nestedIcuIndex}` : '', parentIdx, newIndex);
          icuStart(ast, tView, lView, sharedUpdateOpCodes, parentIdx, icuExpression, newIndex);
          addRemoveNestedIcu(remove, newIndex, depth);
        }
        break;
    }
    currentNode = currentNode.nextSibling;
  }
  return bindingMask;
}
function addRemoveNode(remove, index, depth) {
  if (depth === 0) {
    remove.push(index);
  }
}
function addRemoveNestedIcu(remove, index, depth) {
  if (depth === 0) {
    remove.push(~index); // remove ICU at `index`
    remove.push(index); // remove ICU comment at `index`
  }
}
function addUpdateIcuSwitch(update, icuExpression, index) {
  update.push(toMaskBit(icuExpression.mainBinding), 2, -1 - icuExpression.mainBinding, index << 2 /* I18nUpdateOpCode.SHIFT_REF */ | 2 /* I18nUpdateOpCode.IcuSwitch */);
}
function addUpdateIcuUpdate(update, bindingMask, index) {
  update.push(bindingMask, 1, index << 2 /* I18nUpdateOpCode.SHIFT_REF */ | 3 /* I18nUpdateOpCode.IcuUpdate */);
}
function addCreateNodeAndAppend(create, marker, text, appendToParentIdx, createAtIdx) {
  if (marker !== null) {
    create.push(marker);
  }
  create.push(text, createAtIdx, icuCreateOpCode(0 /* IcuCreateOpCode.AppendChild */, appendToParentIdx, createAtIdx));
}
function addCreateAttribute(create, newIndex, attr) {
  create.push(newIndex << 1 /* IcuCreateOpCode.SHIFT_REF */ | 1 /* IcuCreateOpCode.Attr */, attr.name, attr.value);
}

// i18nPostprocess consts
const ROOT_TEMPLATE_ID = 0;
const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/;
const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g;
const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g;
const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g;
const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g;
const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/;
const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/;
/**
 * Handles message string post-processing for internationalization.
 *
 * Handles message string post-processing by transforming it from intermediate
 * format (that might contain some markers that we need to replace) to the final
 * form, consumable by i18nStart instruction. Post processing steps include:
 *
 * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
 * 2. Replace all ICU vars (like "VAR_PLURAL")
 * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
 * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
 *    in case multiple ICUs have the same placeholder name
 *
 * @param message Raw translation string for post processing
 * @param replacements Set of replacements that should be applied
 *
 * @returns Transformed string that can be consumed by i18nStart instruction
 *
 * @codeGenApi
 */
function i18nPostprocess(message, replacements = {}) {
  /**
   * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�]
   *
   * Note: due to the way we process nested templates (BFS), multi-value placeholders are typically
   * grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root
   * template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index
   * 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in
   * front of �#6�. The post processing step restores the right order by keeping track of the
   * template id stack and looks for placeholders that belong to the currently active template.
   */
  let result = message;
  if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) {
    const matches = {};
    const templateIdsStack = [ROOT_TEMPLATE_ID];
    result = result.replace(PP_PLACEHOLDERS_REGEXP, (m, phs, tmpl) => {
      const content = phs || tmpl;
      const placeholders = matches[content] || [];
      if (!placeholders.length) {
        content.split('|').forEach(placeholder => {
          const match = placeholder.match(PP_TEMPLATE_ID_REGEXP);
          const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID;
          const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder);
          placeholders.push([templateId, isCloseTemplateTag, placeholder]);
        });
        matches[content] = placeholders;
      }
      if (!placeholders.length) {
        throw new Error(`i18n postprocess: unmatched placeholder - ${content}`);
      }
      const currentTemplateId = templateIdsStack[templateIdsStack.length - 1];
      let idx = 0;
      // find placeholder index that matches current template id
      for (let i = 0; i < placeholders.length; i++) {
        if (placeholders[i][0] === currentTemplateId) {
          idx = i;
          break;
        }
      }
      // update template id stack based on the current tag extracted
      const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx];
      if (isCloseTemplateTag) {
        templateIdsStack.pop();
      } else if (currentTemplateId !== templateId) {
        templateIdsStack.push(templateId);
      }
      // remove processed tag from the list
      placeholders.splice(idx, 1);
      return placeholder;
    });
  }
  // return current result if no replacements specified
  if (!Object.keys(replacements).length) {
    return result;
  }
  /**
   * Step 2: replace all ICU vars (like "VAR_PLURAL")
   */
  result = result.replace(PP_ICU_VARS_REGEXP, (match, start, key, _type, _idx, end) => {
    return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match;
  });
  /**
   * Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
   */
  result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (match, key) => {
    return replacements.hasOwnProperty(key) ? replacements[key] : match;
  });
  /**
   * Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case
   * multiple ICUs have the same placeholder name
   */
  result = result.replace(PP_ICUS_REGEXP, (match, key) => {
    if (replacements.hasOwnProperty(key)) {
      const list = replacements[key];
      if (!list.length) {
        throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`);
      }
      return list.shift();
    }
    return match;
  });
  return result;
}

/**
 * Marks a block of text as translatable.
 *
 * The instructions `i18nStart` and `i18nEnd` mark the translation block in the template.
 * The translation `message` is the value which is locale specific. The translation string may
 * contain placeholders which associate inner elements and sub-templates within the translation.
 *
 * The translation `message` placeholders are:
 * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
 *   interpolated into. The placeholder `index` points to the expression binding index. An optional
 *   `block` that matches the sub-template in which it was declared.
 * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*:  Marks the beginning
 *   and end of DOM element that were embedded in the original translation block. The placeholder
 *   `index` points to the element index in the template instructions set. An optional `block` that
 *   matches the sub-template in which it was declared.
 * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
 *   split up and translated separately in each angular template function. The `index` points to the
 *   `template` instruction index. A `block` that matches the sub-template in which it was declared.
 *
 * @param index A unique index of the translation in the static block.
 * @param messageIndex An index of the translation message from the `def.consts` array.
 * @param subTemplateIndex Optional sub-template index in the `message`.
 *
 * @codeGenApi
 */
function ɵɵi18nStart(index, messageIndex, subTemplateIndex = -1) {
  const tView = getTView();
  const lView = getLView();
  const adjustedIndex = HEADER_OFFSET + index;
  ngDevMode && assertDefined(tView, `tView should be defined`);
  const message = getConstant(tView.consts, messageIndex);
  const parentTNode = getCurrentParentTNode();
  if (tView.firstCreatePass) {
    i18nStartFirstCreatePass(tView, parentTNode === null ? 0 : parentTNode.index, lView, adjustedIndex, message, subTemplateIndex);
  }
  // Set a flag that this LView has i18n blocks.
  // The flag is later used to determine whether this component should
  // be hydrated (currently hydration is not supported for i18n blocks).
  if (tView.type === 2 /* TViewType.Embedded */) {
    // Annotate host component's LView (not embedded view's LView),
    // since hydration can be skipped on per-component basis only.
    const componentLView = lView[DECLARATION_COMPONENT_VIEW];
    componentLView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  } else {
    lView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  }
  const tI18n = tView.data[adjustedIndex];
  const sameViewParentTNode = parentTNode === lView[T_HOST] ? null : parentTNode;
  const parentRNode = getClosestRElement(tView, sameViewParentTNode, lView);
  // If `parentTNode` is an `ElementContainer` than it has `<!--ng-container--->`.
  // When we do inserts we have to make sure to insert in front of `<!--ng-container--->`.
  const insertInFrontOf = parentTNode && parentTNode.type & 8 /* TNodeType.ElementContainer */ ? lView[parentTNode.index] : null;
  prepareI18nBlockForHydration(lView, adjustedIndex, parentTNode, subTemplateIndex);
  applyCreateOpCodes(lView, tI18n.create, parentRNode, insertInFrontOf);
  setInI18nBlock(true);
}
/**
 * Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes
 * into the render tree, moves the placeholder nodes and removes the deleted nodes.
 *
 * @codeGenApi
 */
function ɵɵi18nEnd() {
  setInI18nBlock(false);
}
/**
 *
 * Use this instruction to create a translation block that doesn't contain any placeholder.
 * It calls both {@link i18nStart} and {@link i18nEnd} in one instruction.
 *
 * The translation `message` is the value which is locale specific. The translation string may
 * contain placeholders which associate inner elements and sub-templates within the translation.
 *
 * The translation `message` placeholders are:
 * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
 *   interpolated into. The placeholder `index` points to the expression binding index. An optional
 *   `block` that matches the sub-template in which it was declared.
 * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*:  Marks the beginning
 *   and end of DOM element that were embedded in the original translation block. The placeholder
 *   `index` points to the element index in the template instructions set. An optional `block` that
 *   matches the sub-template in which it was declared.
 * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
 *   split up and translated separately in each angular template function. The `index` points to the
 *   `template` instruction index. A `block` that matches the sub-template in which it was declared.
 *
 * @param index A unique index of the translation in the static block.
 * @param messageIndex An index of the translation message from the `def.consts` array.
 * @param subTemplateIndex Optional sub-template index in the `message`.
 *
 * @codeGenApi
 */
function ɵɵi18n(index, messageIndex, subTemplateIndex) {
  ɵɵi18nStart(index, messageIndex, subTemplateIndex);
  ɵɵi18nEnd();
}
/**
 * Marks a list of attributes as translatable.
 *
 * @param index A unique index in the static block
 * @param values
 *
 * @codeGenApi
 */
function ɵɵi18nAttributes(index, attrsIndex) {
  const tView = getTView();
  ngDevMode && assertDefined(tView, `tView should be defined`);
  const attrs = getConstant(tView.consts, attrsIndex);
  i18nAttributesFirstPass(tView, index + HEADER_OFFSET, attrs);
}
/**
 * Stores the values of the bindings during each update cycle in order to determine if we need to
 * update the translated nodes.
 *
 * @param value The binding's value
 * @returns This function returns itself so that it may be chained
 * (e.g. `i18nExp(ctx.name)(ctx.title)`)
 *
 * @codeGenApi
 */
function ɵɵi18nExp(value) {
  const lView = getLView();
  setMaskBit(bindingUpdated(lView, nextBindingIndex(), value));
  return ɵɵi18nExp;
}
/**
 * Updates a translation block or an i18n attribute when the bindings have changed.
 *
 * @param index Index of either {@link i18nStart} (translation block) or {@link i18nAttributes}
 * (i18n attribute) on which it should update the content.
 *
 * @codeGenApi
 */
function ɵɵi18nApply(index) {
  applyI18n(getTView(), getLView(), index + HEADER_OFFSET);
}
/**
 * Handles message string post-processing for internationalization.
 *
 * Handles message string post-processing by transforming it from intermediate
 * format (that might contain some markers that we need to replace) to the final
 * form, consumable by i18nStart instruction. Post processing steps include:
 *
 * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
 * 2. Replace all ICU vars (like "VAR_PLURAL")
 * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
 * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
 *    in case multiple ICUs have the same placeholder name
 *
 * @param message Raw translation string for post processing
 * @param replacements Set of replacements that should be applied
 *
 * @returns Transformed string that can be consumed by i18nStart instruction
 *
 * @codeGenApi
 */
function ɵɵi18nPostprocess(message, replacements = {}) {
  return i18nPostprocess(message, replacements);
}

/**
 * Contains a reference to a function that disables event replay feature
 * for server-side rendered applications. This function is overridden with
 * an actual implementation when the event replay feature is enabled via
 * `withEventReplay()` call.
 */
let stashEventListener = (el, eventName, listenerFn) => {};
function setStashFn(fn) {
  stashEventListener = fn;
}
/**
 * Adds an event listener to the current node.
 *
 * If an output exists on one of the node's directives, it also subscribes to the output
 * and saves the subscription for later cleanup.
 *
 * @param eventName Name of the event
 * @param listenerFn The function to be called when event emits
 * @param useCapture Whether or not to use capture in event listener - this argument is a reminder
 *     from the Renderer3 infrastructure and should be removed from the instruction arguments
 * @param eventTargetResolver Function that returns global target information in case this listener
 * should be attached to a global object like window, document or body
 *
 * @codeGenApi
 */
function ɵɵlistener(eventName, listenerFn, useCapture, eventTargetResolver) {
  const lView = getLView();
  const tView = getTView();
  const tNode = getCurrentTNode();
  listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn, eventTargetResolver);
  return ɵɵlistener;
}
/**
 * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component or directive.
 *
 * This instruction is for compatibility purposes and is designed to ensure that a
 * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered
 * in the component's renderer. Normally all host listeners are evaluated with the
 * parent component's renderer, but, in the case of animation @triggers, they need
 * to be evaluated with the sub component's renderer (because that's where the
 * animation triggers are defined).
 *
 * Do not use this instruction as a replacement for `listener`. This instruction
 * only exists to ensure compatibility with the ViewEngine's host binding behavior.
 *
 * @param eventName Name of the event
 * @param listenerFn The function to be called when event emits
 * @param useCapture Whether or not to use capture in event listener
 * @param eventTargetResolver Function that returns global target information in case this listener
 * should be attached to a global object like window, document or body
 *
 * @codeGenApi
 */
function ɵɵsyntheticHostListener(eventName, listenerFn) {
  const tNode = getCurrentTNode();
  const lView = getLView();
  const tView = getTView();
  const currentDef = getCurrentDirectiveDef(tView.data);
  const renderer = loadComponentRenderer(currentDef, tNode, lView);
  listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn);
  return ɵɵsyntheticHostListener;
}
/**
 * A utility function that checks if a given element has already an event handler registered for an
 * event with a specified name. The TView.cleanup data structure is used to find out which events
 * are registered for a given element.
 */
function findExistingListener(tView, lView, eventName, tNodeIdx) {
  const tCleanup = tView.cleanup;
  if (tCleanup != null) {
    for (let i = 0; i < tCleanup.length - 1; i += 2) {
      const cleanupEventName = tCleanup[i];
      if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) {
        // We have found a matching event name on the same node but it might not have been
        // registered yet, so we must explicitly verify entries in the LView cleanup data
        // structures.
        const lCleanup = lView[CLEANUP];
        const listenerIdxInLCleanup = tCleanup[i + 2];
        return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null;
      }
      // TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or
      // 2-element entries (for directive and queries destroy hooks). As such we can encounter
      // blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements
      // first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check
      // documentation of TView.cleanup for more details of this data structure layout.
      if (typeof cleanupEventName === 'string') {
        i += 2;
      }
    }
  }
  return null;
}
function listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, eventTargetResolver) {
  const isTNodeDirectiveHost = isDirectiveHost(tNode);
  const firstCreatePass = tView.firstCreatePass;
  const tCleanup = firstCreatePass && getOrCreateTViewCleanup(tView);
  const context = lView[CONTEXT];
  // When the ɵɵlistener instruction was generated and is executed we know that there is either a
  // native listener or a directive output on this element. As such we we know that we will have to
  // register a listener and store its cleanup function on LView.
  const lCleanup = getOrCreateLViewCleanup(lView);
  ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  let processOutputs = true;
  // Adding a native event listener is applicable when:
  // - The corresponding TNode represents a DOM element.
  // - The event target has a resolver (usually resulting in a global object,
  //   such as `window` or `document`).
  if (tNode.type & 3 /* TNodeType.AnyRNode */ || eventTargetResolver) {
    const native = getNativeByTNode(tNode, lView);
    const target = eventTargetResolver ? eventTargetResolver(native) : native;
    const lCleanupIndex = lCleanup.length;
    const idxOrTargetGetter = eventTargetResolver ? _lView => eventTargetResolver(unwrapRNode(_lView[tNode.index])) : tNode.index;
    // In order to match current behavior, native DOM event listeners must be added for all
    // events (including outputs).
    // There might be cases where multiple directives on the same element try to register an event
    // handler function for the same event. In this situation we want to avoid registration of
    // several native listeners as each registration would be intercepted by NgZone and
    // trigger change detection. This would mean that a single user action would result in several
    // change detections being invoked. To avoid this situation we want to have only one call to
    // native handler registration (for the same element and same type of event).
    //
    // In order to have just one native event handler in presence of multiple handler functions,
    // we just register a first handler function as a native event listener and then chain
    // (coalesce) other handler functions on top of the first native handler function.
    let existingListener = null;
    // Please note that the coalescing described here doesn't happen for events specifying an
    // alternative target (ex. (document:click)) - this is to keep backward compatibility with the
    // view engine.
    // Also, we don't have to search for existing listeners is there are no directives
    // matching on a given node as we can't register multiple event handlers for the same event in
    // a template (this would mean having duplicate attributes).
    if (!eventTargetResolver && isTNodeDirectiveHost) {
      existingListener = findExistingListener(tView, lView, eventName, tNode.index);
    }
    if (existingListener !== null) {
      // Attach a new listener to coalesced listeners list, maintaining the order in which
      // listeners are registered. For performance reasons, we keep a reference to the last
      // listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
      // the entire set each time we need to add a new listener.
      const lastListenerFn = existingListener.__ngLastListenerFn__ || existingListener;
      lastListenerFn.__ngNextListenerFn__ = listenerFn;
      existingListener.__ngLastListenerFn__ = listenerFn;
      processOutputs = false;
    } else {
      listenerFn = wrapListener(tNode, lView, context, listenerFn);
      stashEventListener(native, eventName, listenerFn);
      const cleanupFn = renderer.listen(target, eventName, listenerFn);
      ngDevMode && ngDevMode.rendererAddEventListener++;
      lCleanup.push(listenerFn, cleanupFn);
      tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1);
    }
  } else {
    // Even if there is no native listener to add, we still need to wrap the listener so that OnPush
    // ancestors are marked dirty when an event occurs.
    listenerFn = wrapListener(tNode, lView, context, listenerFn);
  }
  // subscribe to directive outputs
  const outputs = tNode.outputs;
  let props;
  if (processOutputs && outputs !== null && (props = outputs[eventName])) {
    const propsLength = props.length;
    if (propsLength) {
      for (let i = 0; i < propsLength; i += 2) {
        const index = props[i];
        ngDevMode && assertIndexInRange(lView, index);
        const minifiedName = props[i + 1];
        const directiveInstance = lView[index];
        const output = directiveInstance[minifiedName];
        if (ngDevMode && !isOutputSubscribable(output)) {
          throw new Error(`@Output ${minifiedName} not initialized in '${directiveInstance.constructor.name}'.`);
        }
        const subscription = output.subscribe(listenerFn);
        const idx = lCleanup.length;
        lCleanup.push(listenerFn, subscription);
        tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1));
      }
    }
  }
}
function executeListenerWithErrorHandling(lView, context, listenerFn, e) {
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  try {
    profiler(6 /* ProfilerEvent.OutputStart */, context, listenerFn);
    // Only explicitly returning false from a listener should preventDefault
    return listenerFn(e) !== false;
  } catch (error) {
    handleError(lView, error);
    return false;
  } finally {
    profiler(7 /* ProfilerEvent.OutputEnd */, context, listenerFn);
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
/**
 * Wraps an event listener with a function that marks ancestors dirty and prevents default behavior,
 * if applicable.
 *
 * @param tNode The TNode associated with this listener
 * @param lView The LView that contains this listener
 * @param listenerFn The listener function to call
 * @param wrapWithPreventDefault Whether or not to prevent default behavior
 * (the procedural renderer does this already, so in those cases, we should skip)
 */
function wrapListener(tNode, lView, context, listenerFn) {
  // Note: we are performing most of the work in the listener function itself
  // to optimize listener registration.
  return function wrapListenerIn_markDirtyAndPreventDefault(e) {
    // Ivy uses `Function` as a special token that allows us to unwrap the function
    // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`.
    if (e === Function) {
      return listenerFn;
    }
    // In order to be backwards compatible with View Engine, events on component host nodes
    // must also mark the component view itself dirty (i.e. the view that it owns).
    const startView = tNode.componentOffset > -1 ? getComponentLViewByIndex(tNode.index, lView) : lView;
    markViewDirty(startView, 5 /* NotificationSource.Listener */);
    let result = executeListenerWithErrorHandling(lView, context, listenerFn, e);
    // A just-invoked listener function might have coalesced listeners so we need to check for
    // their presence and invoke as needed.
    let nextListenerFn = wrapListenerIn_markDirtyAndPreventDefault.__ngNextListenerFn__;
    while (nextListenerFn) {
      // We should prevent default if any of the listeners explicitly return false
      result = executeListenerWithErrorHandling(lView, context, nextListenerFn, e) && result;
      nextListenerFn = nextListenerFn.__ngNextListenerFn__;
    }
    return result;
  };
}
/**
 * Whether the given value represents a subscribable output.
 *
 * For example, an `EventEmitter, a `Subject`, an `Observable` or an
 * `OutputEmitter`.
 */
function isOutputSubscribable(value) {
  return value != null && typeof value.subscribe === 'function';
}

/**
 * Retrieves a context at the level specified and saves it as the global, contextViewData.
 * Will get the next level up if level is not specified.
 *
 * This is used to save contexts of parent views so they can be bound in embedded views, or
 * in conjunction with reference() to bind a ref from a parent view.
 *
 * @param level The relative level of the view from which to grab context compared to contextVewData
 * @returns context
 *
 * @codeGenApi
 */
function ɵɵnextContext(level = 1) {
  return nextContextImpl(level);
}

/**
 * Checks a given node against matching projection slots and returns the
 * determined slot index. Returns "null" if no slot matched the given node.
 *
 * This function takes into account the parsed ngProjectAs selector from the
 * node's attributes. If present, it will check whether the ngProjectAs selector
 * matches any of the projection slot selectors.
 */
function matchingProjectionSlotIndex(tNode, projectionSlots) {
  let wildcardNgContentIndex = null;
  const ngProjectAsAttrVal = getProjectAsAttrValue(tNode);
  for (let i = 0; i < projectionSlots.length; i++) {
    const slotValue = projectionSlots[i];
    // The last wildcard projection slot should match all nodes which aren't matching
    // any selector. This is necessary to be backwards compatible with view engine.
    if (slotValue === '*') {
      wildcardNgContentIndex = i;
      continue;
    }
    // If we ran into an `ngProjectAs` attribute, we should match its parsed selector
    // to the list of selectors, otherwise we fall back to matching against the node.
    if (ngProjectAsAttrVal === null ? isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */true) : isSelectorInSelectorList(ngProjectAsAttrVal, slotValue)) {
      return i; // first matching selector "captures" a given node
    }
  }
  return wildcardNgContentIndex;
}
/**
 * Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
 * It takes all the selectors from the entire component's template and decides where
 * each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
 * backed by a selector).
 *
 * This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
 * un-parsed form.
 *
 * The parsed form is needed for efficient matching of a node against a given CSS selector.
 * The un-parsed, textual form is needed for support of the ngProjectAs attribute.
 *
 * Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
 * drawbacks:
 * - having only a textual form would require runtime parsing of CSS selectors;
 * - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
 * template author).
 *
 * @param projectionSlots? A collection of projection slots. A projection slot can be based
 *        on a parsed CSS selectors or set to the wildcard selector ("*") in order to match
 *        all nodes which do not match any selector. If not specified, a single wildcard
 *        selector projection slot will be defined.
 *
 * @codeGenApi
 */
function ɵɵprojectionDef(projectionSlots) {
  const componentNode = getLView()[DECLARATION_COMPONENT_VIEW][T_HOST];
  if (!componentNode.projection) {
    // If no explicit projection slots are defined, fall back to a single
    // projection slot with the wildcard selector.
    const numProjectionSlots = projectionSlots ? projectionSlots.length : 1;
    const projectionHeads = componentNode.projection = newArray(numProjectionSlots, null);
    const tails = projectionHeads.slice();
    let componentChild = componentNode.child;
    while (componentChild !== null) {
      // Do not project let declarations so they don't occupy a slot.
      if (componentChild.type !== 128 /* TNodeType.LetDeclaration */) {
        const slotIndex = projectionSlots ? matchingProjectionSlotIndex(componentChild, projectionSlots) : 0;
        if (slotIndex !== null) {
          if (tails[slotIndex]) {
            tails[slotIndex].projectionNext = componentChild;
          } else {
            projectionHeads[slotIndex] = componentChild;
          }
          tails[slotIndex] = componentChild;
        }
      }
      componentChild = componentChild.next;
    }
  }
}
/**
 * Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
 * to the projectionDef instruction.
 *
 * @param nodeIndex Index of the projection node.
 * @param selectorIndex Index of the slot selector.
 *  - 0 when the selector is `*` (or unspecified as this is the default value),
 *  - 1 based index of the selector from the {@link projectionDef}
 * @param attrs Static attributes set on the `ng-content` node.
 * @param fallbackTemplateFn Template function with fallback content.
 *   Will be rendered if the slot is empty at runtime.
 * @param fallbackDecls Number of declarations in the fallback template.
 * @param fallbackVars Number of variables in the fallback template.
 *
 * @codeGenApi
 */
function ɵɵprojection(nodeIndex, selectorIndex = 0, attrs, fallbackTemplateFn, fallbackDecls, fallbackVars) {
  const lView = getLView();
  const tView = getTView();
  const fallbackIndex = fallbackTemplateFn ? nodeIndex + 1 : null;
  // Fallback content needs to be declared no matter whether the slot is empty since different
  // instances of the component may or may not insert it. Also it needs to be declare *before*
  // the projection node in order to work correctly with hydration.
  if (fallbackIndex !== null) {
    declareTemplate(lView, tView, fallbackIndex, fallbackTemplateFn, fallbackDecls, fallbackVars, null, attrs);
  }
  const tProjectionNode = getOrCreateTNode(tView, HEADER_OFFSET + nodeIndex, 16 /* TNodeType.Projection */, null, attrs || null);
  // We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views.
  if (tProjectionNode.projection === null) {
    tProjectionNode.projection = selectorIndex;
  }
  // `<ng-content>` has no content. Even if there's fallback
  // content, the fallback is shown next to it.
  setCurrentTNodeAsNotParent();
  const hydrationInfo = lView[HYDRATION];
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1();
  const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST];
  const isEmpty = componentHostNode.projection[tProjectionNode.projection] === null;
  if (isEmpty && fallbackIndex !== null) {
    insertFallbackContent(lView, tView, fallbackIndex);
  } else if (isNodeCreationMode && (tProjectionNode.flags & 32 /* TNodeFlags.isDetached */) !== 32 /* TNodeFlags.isDetached */) {
    // re-distribution of projectable nodes is stored on a component's view level
    applyProjection(tView, lView, tProjectionNode);
  }
}
/** Inserts the fallback content of a projection slot. Assumes there's no projected content. */
function insertFallbackContent(lView, tView, fallbackIndex) {
  const adjustedIndex = HEADER_OFFSET + fallbackIndex;
  const fallbackTNode = tView.data[adjustedIndex];
  const fallbackLContainer = lView[adjustedIndex];
  ngDevMode && assertTNode(fallbackTNode);
  ngDevMode && assertLContainer(fallbackLContainer);
  const dehydratedView = findMatchingDehydratedView(fallbackLContainer, fallbackTNode.tView.ssrId);
  const fallbackLView = createAndRenderEmbeddedLView(lView, fallbackTNode, undefined, {
    dehydratedView
  });
  addLViewToLContainer(fallbackLContainer, fallbackLView, 0, shouldAddViewToDom(fallbackTNode, dehydratedView));
}

/**
 *
 * Update an interpolated property on an element with a lone bound value
 *
 * Used when the value passed to a property has 1 interpolated value in it, an no additional text
 * surrounds that interpolated value:
 *
 * ```html
 * <div title="{{v0}}"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate('title', v0);
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate(propName, v0, sanitizer) {
  ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer);
  return ɵɵpropertyInterpolate;
}
/**
 *
 * Update an interpolated property on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div title="prefix{{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate1(propName, prefix, v0, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix);
  }
  return ɵɵpropertyInterpolate1;
}
/**
 *
 * Update an interpolated property on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate2(propName, prefix, v0, i0, v1, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix);
  }
  return ɵɵpropertyInterpolate2;
}
/**
 *
 * Update an interpolated property on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate3(
 * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate3(propName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  }
  return ɵɵpropertyInterpolate3;
}
/**
 *
 * Update an interpolated property on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate4(
 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate4(propName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  }
  return ɵɵpropertyInterpolate4;
}
/**
 *
 * Update an interpolated property on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate5(
 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate5(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  }
  return ɵɵpropertyInterpolate5;
}
/**
 *
 * Update an interpolated property on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate6(
 *    'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate6(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  }
  return ɵɵpropertyInterpolate6;
}
/**
 *
 * Update an interpolated property on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate7(
 *    'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate7(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  }
  return ɵɵpropertyInterpolate7;
}
/**
 *
 * Update an interpolated property on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolate8(
 *  'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolate8(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  }
  return ɵɵpropertyInterpolate8;
}
/**
 * Update an interpolated property on an element with 9 or more bound values surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
 * ```
 *
 * Its compiled representation is::
 *
 * ```ts
 * ɵɵpropertyInterpolateV(
 *  'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *
 * If the property name also exists as an input property on one of the element's directives,
 * the component property will be set instead of the element property. This check must
 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
 *
 * @param propName The name of the property to update.
 * @param values The collection of values and the strings in between those values, beginning with a
 * string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 * @param sanitizer An optional sanitizer function
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵpropertyInterpolateV(propName, values, sanitizer) {
  const lView = getLView();
  const interpolatedValue = interpolationV(lView, values);
  if (interpolatedValue !== NO_CHANGE) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
    if (ngDevMode) {
      const interpolationInBetween = [values[0]]; // prefix
      for (let i = 2; i < values.length; i += 2) {
        interpolationInBetween.push(values[i]);
      }
      storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
    }
  }
  return ɵɵpropertyInterpolateV;
}

/**
 * Registers a QueryList, associated with a content query, for later refresh (part of a view
 * refresh).
 *
 * @param directiveIndex Current directive index
 * @param predicate The type for which the query will search
 * @param flags Flags associated with the query
 * @param read What to save in the query
 * @returns QueryList<T>
 *
 * @codeGenApi
 */
function ɵɵcontentQuery(directiveIndex, predicate, flags, read) {
  createContentQuery(directiveIndex, predicate, flags, read);
}
/**
 * Creates a new view query by initializing internal data structures.
 *
 * @param predicate The type for which the query will search
 * @param flags Flags associated with the query
 * @param read What to save in the query
 *
 * @codeGenApi
 */
function ɵɵviewQuery(predicate, flags, read) {
  createViewQuery(predicate, flags, read);
}
/**
 * Refreshes a query by combining matches from all active views and removing matches from deleted
 * views.
 *
 * @returns `true` if a query got dirty during change detection or if this is a static query
 * resolving in creation mode, `false` otherwise.
 *
 * @codeGenApi
 */
function ɵɵqueryRefresh(queryList) {
  const lView = getLView();
  const tView = getTView();
  const queryIndex = getCurrentQueryIndex();
  setCurrentQueryIndex(queryIndex + 1);
  const tQuery = getTQuery(tView, queryIndex);
  if (queryList.dirty && isCreationMode(lView) === ((tQuery.metadata.flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */)) {
    if (tQuery.matches === null) {
      queryList.reset([]);
    } else {
      const result = getQueryResults(lView, queryIndex);
      queryList.reset(result, unwrapElementRef);
      queryList.notifyOnChanges();
    }
    return true;
  }
  return false;
}
/**
 * Loads a QueryList corresponding to the current view or content query.
 *
 * @codeGenApi
 */
function ɵɵloadQuery() {
  return loadQueryInternal(getLView(), getCurrentQueryIndex());
}

/**
 * Creates a new content query and binds it to a signal created by an authoring function.
 *
 * @param directiveIndex Current directive index
 * @param target The target signal to which the query should be bound
 * @param predicate The type for which the query will search
 * @param flags Flags associated with the query
 * @param read What to save in the query
 *
 * @codeGenApi
 */
function ɵɵcontentQuerySignal(directiveIndex, target, predicate, flags, read) {
  bindQueryToSignal(target, createContentQuery(directiveIndex, predicate, flags, read));
}
/**
 * Creates a new view query by initializing internal data structures and binding a new query to the
 * target signal.
 *
 * @param target The target signal to assign the query results to.
 * @param predicate The type or label that should match a given query
 * @param flags Flags associated with the query
 * @param read What to save in the query
 *
 * @codeGenApi
 */
function ɵɵviewQuerySignal(target, predicate, flags, read) {
  bindQueryToSignal(target, createViewQuery(predicate, flags, read));
}
/**
 * Advances the current query index by a specified offset.
 *
 * Adjusting the current query index is necessary in cases where a given directive has a mix of
 * zone-based and signal-based queries. The signal-based queries don't require tracking of the
 * current index (those are refreshed on demand and not during change detection) so this instruction
 * is only necessary for backward-compatibility.
 *
 * @param index offset to apply to the current query index (defaults to 1)
 *
 * @codeGenApi
 */
function ɵɵqueryAdvance(indexOffset = 1) {
  setCurrentQueryIndex(getCurrentQueryIndex() + indexOffset);
}

/** Store a value in the `data` at a given `index`. */
function store(tView, lView, index, value) {
  // We don't store any static data for local variables, so the first time
  // we see the template, we should store as null to avoid a sparse array
  if (index >= tView.data.length) {
    tView.data[index] = null;
    tView.blueprint[index] = null;
  }
  lView[index] = value;
}
/**
 * Retrieves a local reference from the current contextViewData.
 *
 * If the reference to retrieve is in a parent view, this instruction is used in conjunction
 * with a nextContext() call, which walks up the tree and updates the contextViewData instance.
 *
 * @param index The index of the local ref in contextViewData.
 *
 * @codeGenApi
 */
function ɵɵreference(index) {
  const contextLView = getContextLView();
  return load(contextLView, HEADER_OFFSET + index);
}

/**
 *
 * Update an interpolated style on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div style="key: {{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate1('key: ', v0, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate1(prefix, v0, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', v1, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate2(prefix, v0, i0, v1, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate3(
 *     'key: ', v0, '; key1: ', v1, '; key2: ', v2, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate4(
 *     'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate5(
 *     'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
 *             key5: {{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate6(
 *    'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
 *    'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
 *             key6: {{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate7(
 *    'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
 *    '; key6: ', v6, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 *
 * Update an interpolated style on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
 *             key6: {{v6}}; key7: {{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolate8(
 *    'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
 *    '; key6: ', v6, '; key7: ', v7, 'suffix');
 * ```
 *
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @codeGenApi
 */
function ɵɵstyleMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  const lView = getLView();
  const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  ɵɵstyleMap(interpolatedValue);
}
/**
 * Update an interpolated style on an element with 9 or more bound values surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
 *         key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstyleMapInterpolateV(
 *    ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
 *     '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', v9, 'suffix']);
 * ```
 *.
 * @param values The collection of values and the strings in-between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
 * @codeGenApi
 */
function ɵɵstyleMapInterpolateV(values) {
  const lView = getLView();
  const interpolatedValue = interpolationV(lView, values);
  ɵɵstyleMap(interpolatedValue);
}

/**
 *
 * Update an interpolated style property on an element with single bound value surrounded by text.
 *
 * Used when the value passed to a property has 1 interpolated value in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate1(prop, prefix, v0, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate1;
}
/**
 *
 * Update an interpolated style property on an element with 2 bound values surrounded by text.
 *
 * Used when the value passed to a property has 2 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate2(prop, prefix, v0, i0, v1, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate2;
}
/**
 *
 * Update an interpolated style property on an element with 3 bound values surrounded by text.
 *
 * Used when the value passed to a property has 3 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate3(prop, prefix, v0, i0, v1, i1, v2, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate3;
}
/**
 *
 * Update an interpolated style property on an element with 4 bound values surrounded by text.
 *
 * Used when the value passed to a property has 4 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate4(prop, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate4;
}
/**
 *
 * Update an interpolated style property on an element with 5 bound values surrounded by text.
 *
 * Used when the value passed to a property has 5 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate5(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate5;
}
/**
 *
 * Update an interpolated style property on an element with 6 bound values surrounded by text.
 *
 * Used when the value passed to a property has 6 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate6(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate6;
}
/**
 *
 * Update an interpolated style property on an element with 7 bound values surrounded by text.
 *
 * Used when the value passed to a property has 7 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate7(
 *    0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate7(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate7;
}
/**
 *
 * Update an interpolated style property on an element with 8 bound values surrounded by text.
 *
 * Used when the value passed to a property has 8 interpolated values in it:
 *
 * ```html
 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
 * '-', v7, 'suffix');
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`.
 * @param prefix Static value used for concatenation only.
 * @param v0 Value checked for change.
 * @param i0 Static value used for concatenation only.
 * @param v1 Value checked for change.
 * @param i1 Static value used for concatenation only.
 * @param v2 Value checked for change.
 * @param i2 Static value used for concatenation only.
 * @param v3 Value checked for change.
 * @param i3 Static value used for concatenation only.
 * @param v4 Value checked for change.
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change.
 * @param i5 Static value used for concatenation only.
 * @param v6 Value checked for change.
 * @param i6 Static value used for concatenation only.
 * @param v7 Value checked for change.
 * @param suffix Static value used for concatenation only.
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolate8(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolate8;
}
/**
 * Update an interpolated style property on an element with 9 or more bound values surrounded by
 * text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div
 *  style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
 * </div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵstylePropInterpolateV(
 *  0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *
 * @param styleIndex Index of style to update. This index value refers to the
 *        index of the style in the style bindings array that was passed into
 *        `styling`..
 * @param values The collection of values and the strings in-between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵstylePropInterpolateV(prop, values, valueSuffix) {
  const lView = getLView();
  const interpolatedValue = interpolationV(lView, values);
  checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  return ɵɵstylePropInterpolateV;
}

/**
 * Create static text node
 *
 * @param index Index of the node in the data array
 * @param value Static string value to write.
 *
 * @codeGenApi
 */
function ɵɵtext(index, value = '') {
  const lView = getLView();
  const tView = getTView();
  const adjustedIndex = index + HEADER_OFFSET;
  ngDevMode && assertEqual(getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings');
  ngDevMode && assertIndexInRange(lView, adjustedIndex);
  const tNode = tView.firstCreatePass ? getOrCreateTNode(tView, adjustedIndex, 1 /* TNodeType.Text */, value, null) : tView.data[adjustedIndex];
  const textNative = _locateOrCreateTextNode(tView, lView, tNode, value, index);
  lView[adjustedIndex] = textNative;
  if (wasLastNodeCreated()) {
    appendChild(tView, lView, textNative, tNode);
  }
  // Text nodes are self closing.
  setCurrentTNode(tNode, false);
}
let _locateOrCreateTextNode = (tView, lView, tNode, value, index) => {
  lastNodeWasCreated(true);
  return createTextNode(lView[RENDERER], value);
};
/**
 * Enables hydration code path (to lookup existing elements in DOM)
 * in addition to the regular creation mode of text nodes.
 */
function locateOrCreateTextNodeImpl(tView, lView, tNode, value, index) {
  const hydrationInfo = lView[HYDRATION];
  const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1() || isDetachedByI18n(tNode) || isDisconnectedNode$1(hydrationInfo, index);
  lastNodeWasCreated(isNodeCreationMode);
  // Regular creation mode.
  if (isNodeCreationMode) {
    return createTextNode(lView[RENDERER], value);
  }
  // Hydration mode, looking up an existing element in DOM.
  const textNative = locateNextRNode(hydrationInfo, tView, lView, tNode);
  ngDevMode && validateMatchingNode(textNative, Node.TEXT_NODE, null, lView, tNode);
  ngDevMode && markRNodeAsClaimedByHydration(textNative);
  return textNative;
}
function enableLocateOrCreateTextNodeImpl() {
  _locateOrCreateTextNode = locateOrCreateTextNodeImpl;
}

/**
 *
 * Update text content with a lone bound value
 *
 * Used when a text node has 1 interpolated value in it, an no additional text
 * surrounds that interpolated value:
 *
 * ```html
 * <div>{{v0}}</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate(v0);
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate(v0) {
  ɵɵtextInterpolate1('', v0, '');
  return ɵɵtextInterpolate;
}
/**
 *
 * Update text content with single bound value surrounded by other text.
 *
 * Used when a text node has 1 interpolated value in it:
 *
 * ```html
 * <div>prefix{{v0}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate1('prefix', v0, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate1(prefix, v0, suffix) {
  const lView = getLView();
  const interpolated = interpolation1(lView, prefix, v0, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate1;
}
/**
 *
 * Update text content with 2 bound values surrounded by other text.
 *
 * Used when a text node has 2 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate2(prefix, v0, i0, v1, suffix) {
  const lView = getLView();
  const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate2;
}
/**
 *
 * Update text content with 3 bound values surrounded by other text.
 *
 * Used when a text node has 3 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate3(
 * 'prefix', v0, '-', v1, '-', v2, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  const lView = getLView();
  const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate3;
}
/**
 *
 * Update text content with 4 bound values surrounded by other text.
 *
 * Used when a text node has 4 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate4(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see ɵɵtextInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  const lView = getLView();
  const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate4;
}
/**
 *
 * Update text content with 5 bound values surrounded by other text.
 *
 * Used when a text node has 5 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate5(
 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  const lView = getLView();
  const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate5;
}
/**
 *
 * Update text content with 6 bound values surrounded by other text.
 *
 * Used when a text node has 6 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate6(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
 * ```
 *
 * @param i4 Static value used for concatenation only.
 * @param v5 Value checked for change. @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  const lView = getLView();
  const interpolated = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate6;
}
/**
 *
 * Update text content with 7 bound values surrounded by other text.
 *
 * Used when a text node has 7 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate7(
 *    'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  const lView = getLView();
  const interpolated = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate7;
}
/**
 *
 * Update text content with 8 bound values surrounded by other text.
 *
 * Used when a text node has 8 interpolated values in it:
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolate8(
 *  'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
 * ```
 * @returns itself, so that it may be chained.
 * @see textInterpolateV
 * @codeGenApi
 */
function ɵɵtextInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  const lView = getLView();
  const interpolated = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolate8;
}
/**
 * Update text content with 9 or more bound values other surrounded by text.
 *
 * Used when the number of interpolated values exceeds 8.
 *
 * ```html
 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div>
 * ```
 *
 * Its compiled representation is:
 *
 * ```ts
 * ɵɵtextInterpolateV(
 *  ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
 *  'suffix']);
 * ```
 *.
 * @param values The collection of values and the strings in between those values, beginning with
 * a string prefix and ending with a string suffix.
 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
 *
 * @returns itself, so that it may be chained.
 * @codeGenApi
 */
function ɵɵtextInterpolateV(values) {
  const lView = getLView();
  const interpolated = interpolationV(lView, values);
  if (interpolated !== NO_CHANGE) {
    textBindingInternal(lView, getSelectedIndex(), interpolated);
  }
  return ɵɵtextInterpolateV;
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Update a two-way bound property on a selected element.
 *
 * Operates on the element selected by index via the {@link select} instruction.
 *
 * @param propName Name of property.
 * @param value New value to write.
 * @param sanitizer An optional function used to sanitize the value.
 * @returns This function returns itself so that it may be chained
 * (e.g. `twoWayProperty('name', ctx.name)('title', ctx.title)`)
 *
 * @codeGenApi
 */
function ɵɵtwoWayProperty(propName, value, sanitizer) {
  // TODO(crisbeto): perf impact of re-evaluating this on each change detection?
  if (isWritableSignal(value)) {
    value = value();
  }
  const lView = getLView();
  const bindingIndex = nextBindingIndex();
  if (bindingUpdated(lView, bindingIndex, value)) {
    const tView = getTView();
    const tNode = getSelectedTNode();
    elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
    ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  }
  return ɵɵtwoWayProperty;
}
/**
 * Function used inside two-way listeners to conditionally set the value of the bound expression.
 *
 * @param target Field on which to set the value.
 * @param value Value to be set to the field.
 *
 * @codeGenApi
 */
function ɵɵtwoWayBindingSet(target, value) {
  const canWrite = isWritableSignal(target);
  canWrite && target.set(value);
  return canWrite;
}
/**
 * Adds an event listener that updates a two-way binding to the current node.
 *
 * @param eventName Name of the event.
 * @param listenerFn The function to be called when event emits.
 *
 * @codeGenApi
 */
function ɵɵtwoWayListener(eventName, listenerFn) {
  const lView = getLView();
  const tView = getTView();
  const tNode = getCurrentTNode();
  listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn);
  return ɵɵtwoWayListener;
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/** Object that indicates the value of a `@let` declaration that hasn't been initialized yet. */
const UNINITIALIZED_LET = {};
/**
 * Declares an `@let` at a specific data slot. Returns itself to allow chaining.
 *
 * @param index Index at which to declare the `@let`.
 *
 * @codeGenApi
 */
function ɵɵdeclareLet(index) {
  const tView = getTView();
  const lView = getLView();
  const adjustedIndex = index + HEADER_OFFSET;
  const tNode = getOrCreateTNode(tView, adjustedIndex, 128 /* TNodeType.LetDeclaration */, null, null);
  setCurrentTNode(tNode, false);
  store(tView, lView, adjustedIndex, UNINITIALIZED_LET);
  return ɵɵdeclareLet;
}
/**
 * Instruction that stores the value of a `@let` declaration on the current view.
 * Returns the value to allow usage inside variable initializers.
 *
 * @codeGenApi
 */
function ɵɵstoreLet(value) {
  performanceMarkFeature('NgLet');
  const tView = getTView();
  const lView = getLView();
  const index = getSelectedIndex();
  store(tView, lView, index, value);
  return value;
}
/**
 * Retrieves the value of a `@let` declaration defined in a parent view.
 *
 * @param index Index of the declaration within the view.
 *
 * @codeGenApi
 */
function ɵɵreadContextLet(index) {
  const contextLView = getContextLView();
  const value = load(contextLView, HEADER_OFFSET + index);
  if (value === UNINITIALIZED_LET) {
    throw new RuntimeError(314 /* RuntimeErrorCode.UNINITIALIZED_LET_ACCESS */, ngDevMode && 'Attempting to access a @let declaration whose value is not available yet');
  }
  return value;
}

/*
 * This file re-exports all symbols contained in this directory.
 *
 * Why is this file not `index.ts`?
 *
 * There seems to be an inconsistent path resolution of an `index.ts` file
 * when only the parent directory is referenced. This could be due to the
 * node module resolution configuration differing from rollup and/or typescript.
 *
 * With commit
 * https://github.com/angular/angular/commit/d5e3f2c64bd13ce83e7c70788b7fc514ca4a9918
 * the `instructions.ts` file was moved to `instructions/instructions.ts` and an
 * `index.ts` file was used to re-export everything. Having had file names that were
 * importing from `instructions' directly (not the from the sub file or the `index.ts`
 * file) caused strange CI issues. `index.ts` had to be renamed to `all.ts` for this
 * to work.
 *
 * Jira Issue = FW-1184
 */

/**
 * Resolves the providers which are defined in the DirectiveDef.
 *
 * When inserting the tokens and the factories in their respective arrays, we can assume that
 * this method is called first for the component (if any), and then for other directives on the same
 * node.
 * As a consequence,the providers are always processed in that order:
 * 1) The view providers of the component
 * 2) The providers of the component
 * 3) The providers of the other directives
 * This matches the structure of the injectables arrays of a view (for each node).
 * So the tokens and the factories can be pushed at the end of the arrays, except
 * in one case for multi providers.
 *
 * @param def the directive definition
 * @param providers: Array of `providers`.
 * @param viewProviders: Array of `viewProviders`.
 */
function providersResolver(def, providers, viewProviders) {
  const tView = getTView();
  if (tView.firstCreatePass) {
    const isComponent = isComponentDef(def);
    // The list of view providers is processed first, and the flags are updated
    resolveProvider(viewProviders, tView.data, tView.blueprint, isComponent, true);
    // Then, the list of providers is processed, and the flags are updated
    resolveProvider(providers, tView.data, tView.blueprint, isComponent, false);
  }
}
/**
 * Resolves a provider and publishes it to the DI system.
 */
function resolveProvider(provider, tInjectables, lInjectablesBlueprint, isComponent, isViewProvider) {
  provider = resolveForwardRef(provider);
  if (Array.isArray(provider)) {
    // Recursively call `resolveProvider`
    // Recursion is OK in this case because this code will not be in hot-path once we implement
    // cloning of the initial state.
    for (let i = 0; i < provider.length; i++) {
      resolveProvider(provider[i], tInjectables, lInjectablesBlueprint, isComponent, isViewProvider);
    }
  } else {
    const tView = getTView();
    const lView = getLView();
    const tNode = getCurrentTNode();
    let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
    const providerFactory = providerToFactory(provider);
    if (ngDevMode) {
      const injector = new NodeInjector(tNode, lView);
      runInInjectorProfilerContext(injector, token, () => {
        emitProviderConfiguredEvent(provider, isViewProvider);
      });
    }
    const beginIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
    const endIndex = tNode.directiveStart;
    const cptViewProvidersCount = tNode.providerIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
    if (isTypeProvider(provider) || !provider.multi) {
      // Single provider case: the factory is created and pushed immediately
      const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
      const existingFactoryIndex = indexOf(token, tInjectables, isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount, endIndex);
      if (existingFactoryIndex === -1) {
        diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
        registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
        tInjectables.push(token);
        tNode.directiveStart++;
        tNode.directiveEnd++;
        if (isViewProvider) {
          tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
        }
        lInjectablesBlueprint.push(factory);
        lView.push(factory);
      } else {
        lInjectablesBlueprint[existingFactoryIndex] = factory;
        lView[existingFactoryIndex] = factory;
      }
    } else {
      // Multi provider case:
      // We create a multi factory which is going to aggregate all the values.
      // Since the output of such a factory depends on content or view injection,
      // we create two of them, which are linked together.
      //
      // The first one (for view providers) is always in the first block of the injectables array,
      // and the second one (for providers) is always in the second block.
      // This is important because view providers have higher priority. When a multi token
      // is being looked up, the view providers should be found first.
      // Note that it is not possible to have a multi factory in the third block (directive block).
      //
      // The algorithm to process multi providers is as follows:
      // 1) If the multi provider comes from the `viewProviders` of the component:
      //   a) If the special view providers factory doesn't exist, it is created and pushed.
      //   b) Else, the multi provider is added to the existing multi factory.
      // 2) If the multi provider comes from the `providers` of the component or of another
      // directive:
      //   a) If the multi factory doesn't exist, it is created and provider pushed into it.
      //      It is also linked to the multi factory for view providers, if it exists.
      //   b) Else, the multi provider is added to the existing multi factory.
      const existingProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex + cptViewProvidersCount, endIndex);
      const existingViewProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex, beginIndex + cptViewProvidersCount);
      const doesProvidersFactoryExist = existingProvidersFactoryIndex >= 0 && lInjectablesBlueprint[existingProvidersFactoryIndex];
      const doesViewProvidersFactoryExist = existingViewProvidersFactoryIndex >= 0 && lInjectablesBlueprint[existingViewProvidersFactoryIndex];
      if (isViewProvider && !doesViewProvidersFactoryExist || !isViewProvider && !doesProvidersFactoryExist) {
        // Cases 1.a and 2.a
        diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
        const factory = multiFactory(isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver, lInjectablesBlueprint.length, isViewProvider, isComponent, providerFactory);
        if (!isViewProvider && doesViewProvidersFactoryExist) {
          lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
        }
        registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
        tInjectables.push(token);
        tNode.directiveStart++;
        tNode.directiveEnd++;
        if (isViewProvider) {
          tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
        }
        lInjectablesBlueprint.push(factory);
        lView.push(factory);
      } else {
        // Cases 1.b and 2.b
        const indexInFactory = multiFactoryAdd(lInjectablesBlueprint[isViewProvider ? existingViewProvidersFactoryIndex : existingProvidersFactoryIndex], providerFactory, !isViewProvider && isComponent);
        registerDestroyHooksIfSupported(tView, provider, existingProvidersFactoryIndex > -1 ? existingProvidersFactoryIndex : existingViewProvidersFactoryIndex, indexInFactory);
      }
      if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
        lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders++;
      }
    }
  }
}
/**
 * Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
 * @param tView `TView` in which to register the hook.
 * @param provider Provider whose hook should be registered.
 * @param contextIndex Index under which to find the context for the hook when it's being invoked.
 * @param indexInFactory Only required for `multi` providers. Index of the provider in the multi
 * provider factory.
 */
function registerDestroyHooksIfSupported(tView, provider, contextIndex, indexInFactory) {
  const providerIsTypeProvider = isTypeProvider(provider);
  const providerIsClassProvider = isClassProvider(provider);
  if (providerIsTypeProvider || providerIsClassProvider) {
    // Resolve forward references as `useClass` can hold a forward reference.
    const classToken = providerIsClassProvider ? resolveForwardRef(provider.useClass) : provider;
    const prototype = classToken.prototype;
    const ngOnDestroy = prototype.ngOnDestroy;
    if (ngOnDestroy) {
      const hooks = tView.destroyHooks || (tView.destroyHooks = []);
      if (!providerIsTypeProvider && provider.multi) {
        ngDevMode && assertDefined(indexInFactory, 'indexInFactory when registering multi factory destroy hook');
        const existingCallbacksIndex = hooks.indexOf(contextIndex);
        if (existingCallbacksIndex === -1) {
          hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
        } else {
          hooks[existingCallbacksIndex + 1].push(indexInFactory, ngOnDestroy);
        }
      } else {
        hooks.push(contextIndex, ngOnDestroy);
      }
    }
  }
}
/**
 * Add a factory in a multi factory.
 * @returns Index at which the factory was inserted.
 */
function multiFactoryAdd(multiFactory, factory, isComponentProvider) {
  if (isComponentProvider) {
    multiFactory.componentProviders++;
  }
  return multiFactory.multi.push(factory) - 1;
}
/**
 * Returns the index of item in the array, but only in the begin to end range.
 */
function indexOf(item, arr, begin, end) {
  for (let i = begin; i < end; i++) {
    if (arr[i] === item) return i;
  }
  return -1;
}
/**
 * Use this with `multi` `providers`.
 */
function multiProvidersFactoryResolver(_, tData, lData, tNode) {
  return multiResolve(this.multi, []);
}
/**
 * Use this with `multi` `viewProviders`.
 *
 * This factory knows how to concatenate itself with the existing `multi` `providers`.
 */
function multiViewProvidersFactoryResolver(_, tData, lView, tNode) {
  const factories = this.multi;
  let result;
  if (this.providerFactory) {
    const componentCount = this.providerFactory.componentProviders;
    const multiProviders = getNodeInjectable(lView, lView[TVIEW], this.providerFactory.index, tNode);
    // Copy the section of the array which contains `multi` `providers` from the component
    result = multiProviders.slice(0, componentCount);
    // Insert the `viewProvider` instances.
    multiResolve(factories, result);
    // Copy the section of the array which contains `multi` `providers` from other directives
    for (let i = componentCount; i < multiProviders.length; i++) {
      result.push(multiProviders[i]);
    }
  } else {
    result = [];
    // Insert the `viewProvider` instances.
    multiResolve(factories, result);
  }
  return result;
}
/**
 * Maps an array of factories into an array of values.
 */
function multiResolve(factories, result) {
  for (let i = 0; i < factories.length; i++) {
    const factory = factories[i];
    result.push(factory());
  }
  return result;
}
/**
 * Creates a multi factory.
 */
function multiFactory(factoryFn, index, isViewProvider, isComponent, f) {
  const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
  factory.multi = [];
  factory.index = index;
  factory.componentProviders = 0;
  multiFactoryAdd(factory, f, isComponent && !isViewProvider);
  return factory;
}

/**
 * This feature resolves the providers of a directive (or component),
 * and publish them into the DI system, making it visible to others for injection.
 *
 * For example:
 * ```ts
 * class ComponentWithProviders {
 *   constructor(private greeter: GreeterDE) {}
 *
 *   static ɵcmp = defineComponent({
 *     type: ComponentWithProviders,
 *     selectors: [['component-with-providers']],
 *    factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
 *    decls: 1,
 *    vars: 1,
 *    template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
 *      if (fs & RenderFlags.Create) {
 *        ɵɵtext(0);
 *      }
 *      if (fs & RenderFlags.Update) {
 *        ɵɵtextInterpolate(ctx.greeter.greet());
 *      }
 *    },
 *    features: [ɵɵProvidersFeature([GreeterDE])]
 *  });
 * }
 * ```
 *
 * @param definition
 *
 * @codeGenApi
 */
function ɵɵProvidersFeature(providers, viewProviders = []) {
  return definition => {
    definition.providersResolver = (def, processProvidersFn) => {
      return providersResolver(def,
      //
      processProvidersFn ? processProvidersFn(providers) : providers,
      //
      viewProviders);
    };
  };
}

/**
 * A feature that adds support for external runtime styles for a component.
 * An external runtime style is a URL to a CSS stylesheet that contains the styles
 * for a given component. For browsers, this URL will be used in an appended `link` element
 * when the component is rendered. This feature is typically used for Hot Module Replacement
 * (HMR) of component stylesheets by leveraging preexisting global stylesheet HMR available
 * in most development servers.
 *
 * @codeGenApi
 */
function ɵɵExternalStylesFeature(styleUrls) {
  return definition => {
    if (styleUrls.length < 1) {
      return;
    }
    definition.getExternalStyles = encapsulationId => {
      // Add encapsulation ID search parameter `ngcomp` to support external style encapsulation as well as the encapsulation mode
      // for usage tracking.
      const urls = styleUrls.map(value => value + '?ngcomp' + (encapsulationId ? '=' + encodeURIComponent(encapsulationId) : '') + '&e=' + definition.encapsulation);
      return urls;
    };
  };
}

/**
 * Generated next to NgModules to monkey-patch directive and pipe references onto a component's
 * definition, when generating a direct reference in the component file would otherwise create an
 * import cycle.
 *
 * See [this explanation](https://hackmd.io/Odw80D0pR6yfsOjg_7XCJg?view) for more details.
 *
 * @codeGenApi
 */
function ɵɵsetComponentScope(type, directives, pipes) {
  const def = type.ɵcmp;
  def.directiveDefs = extractDefListOrFactory(directives, /* pipeDef */false);
  def.pipeDefs = extractDefListOrFactory(pipes, /* pipeDef */true);
}
/**
 * Adds the module metadata that is necessary to compute the module's transitive scope to an
 * existing module definition.
 *
 * Scope metadata of modules is not used in production builds, so calls to this function can be
 * marked pure to tree-shake it from the bundle, allowing for all referenced declarations
 * to become eligible for tree-shaking as well.
 *
 * @codeGenApi
 */
function ɵɵsetNgModuleScope(type, scope) {
  return noSideEffects(() => {
    const ngModuleDef = getNgModuleDef(type, true);
    ngModuleDef.declarations = convertToTypeArray(scope.declarations || EMPTY_ARRAY);
    ngModuleDef.imports = convertToTypeArray(scope.imports || EMPTY_ARRAY);
    ngModuleDef.exports = convertToTypeArray(scope.exports || EMPTY_ARRAY);
    if (scope.bootstrap) {
      // This only happens in local compilation mode.
      ngModuleDef.bootstrap = convertToTypeArray(scope.bootstrap);
    }
    depsTracker.registerNgModule(type, scope);
  });
}
function convertToTypeArray(values) {
  if (typeof values === 'function') {
    return values;
  }
  const flattenValues = flatten(values);
  if (flattenValues.some(isForwardRef)) {
    return () => flattenValues.map(resolveForwardRef).map(maybeUnwrapModuleWithProviders);
  } else {
    return flattenValues.map(maybeUnwrapModuleWithProviders);
  }
}
function maybeUnwrapModuleWithProviders(value) {
  return isModuleWithProviders(value) ? value.ngModule : value;
}

/**
 * Bindings for pure functions are stored after regular bindings.
 *
 * |-------decls------|---------vars---------|                 |----- hostVars (dir1) ------|
 * ------------------------------------------------------------------------------------------
 * | nodes/refs/pipes | bindings | fn slots  | injector | dir1 | host bindings | host slots |
 * ------------------------------------------------------------------------------------------
 *                    ^                      ^
 *      TView.bindingStartIndex      TView.expandoStartIndex
 *
 * Pure function instructions are given an offset from the binding root. Adding the offset to the
 * binding root gives the first index where the bindings are stored. In component views, the binding
 * root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
 * any directive instances + any hostVars in directives evaluated before it.
 *
 * See VIEW_DATA.md for more information about host binding resolution.
 */
/**
 * If the value hasn't been saved, calls the pure function to store and return the
 * value. If it has been saved, returns the saved value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn Function that returns a value
 * @param thisArg Optional calling context of pureFn
 * @returns value
 *
 * @codeGenApi
 */
function ɵɵpureFunction0(slotOffset, pureFn, thisArg) {
  const bindingIndex = getBindingRoot() + slotOffset;
  const lView = getLView();
  return lView[bindingIndex] === NO_CHANGE ? updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn()) : getBinding(lView, bindingIndex);
}
/**
 * If the value of the provided exp has changed, calls the pure function to return
 * an updated value. Or if the value has not changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn Function that returns an updated value
 * @param exp Updated expression value
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction1(slotOffset, pureFn, exp, thisArg) {
  return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction2(slotOffset, pureFn, exp1, exp2, thisArg) {
  return pureFunction2Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, thisArg);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction3(slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  return pureFunction3Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, thisArg);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction4(slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  return pureFunction4Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param exp5
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction5(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, thisArg) {
  const bindingIndex = getBindingRoot() + slotOffset;
  const lView = getLView();
  const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  return bindingUpdated(lView, bindingIndex + 4, exp5) || different ? updateBinding(lView, bindingIndex + 5, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) : pureFn(exp1, exp2, exp3, exp4, exp5)) : getBinding(lView, bindingIndex + 5);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param exp5
 * @param exp6
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction6(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, thisArg) {
  const bindingIndex = getBindingRoot() + slotOffset;
  const lView = getLView();
  const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different ? updateBinding(lView, bindingIndex + 6, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) : pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) : getBinding(lView, bindingIndex + 6);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param exp5
 * @param exp6
 * @param exp7
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction7(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, thisArg) {
  const bindingIndex = getBindingRoot() + slotOffset;
  const lView = getLView();
  let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different ? updateBinding(lView, bindingIndex + 7, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) : getBinding(lView, bindingIndex + 7);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param exp5
 * @param exp6
 * @param exp7
 * @param exp8
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunction8(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, thisArg) {
  const bindingIndex = getBindingRoot() + slotOffset;
  const lView = getLView();
  const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different ? updateBinding(lView, bindingIndex + 8, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) : getBinding(lView, bindingIndex + 8);
}
/**
 * pureFunction instruction that can support any number of bindings.
 *
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn A pure function that takes binding values and builds an object or array
 * containing those values.
 * @param exps An array of binding values
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 * @codeGenApi
 */
function ɵɵpureFunctionV(slotOffset, pureFn, exps, thisArg) {
  return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
}
/**
 * Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
 * to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
 * invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
 * value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
 * it to `undefined`.
 */
function getPureFunctionReturnValue(lView, returnValueIndex) {
  ngDevMode && assertIndexInRange(lView, returnValueIndex);
  const lastReturnValue = lView[returnValueIndex];
  return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
}
/**
 * If the value of the provided exp has changed, calls the pure function to return
 * an updated value. Or if the value has not changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn Function that returns an updated value
 * @param exp Updated expression value
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 */
function pureFunction1Internal(lView, bindingRoot, slotOffset, pureFn, exp, thisArg) {
  const bindingIndex = bindingRoot + slotOffset;
  return bindingUpdated(lView, bindingIndex, exp) ? updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp)) : getPureFunctionReturnValue(lView, bindingIndex + 1);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 */
function pureFunction2Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, thisArg) {
  const bindingIndex = bindingRoot + slotOffset;
  return bindingUpdated2(lView, bindingIndex, exp1, exp2) ? updateBinding(lView, bindingIndex + 2, thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2)) : getPureFunctionReturnValue(lView, bindingIndex + 2);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 */
function pureFunction3Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  const bindingIndex = bindingRoot + slotOffset;
  return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) ? updateBinding(lView, bindingIndex + 3, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3)) : getPureFunctionReturnValue(lView, bindingIndex + 3);
}
/**
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn
 * @param exp1
 * @param exp2
 * @param exp3
 * @param exp4
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 *
 */
function pureFunction4Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  const bindingIndex = bindingRoot + slotOffset;
  return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) ? updateBinding(lView, bindingIndex + 4, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4)) : getPureFunctionReturnValue(lView, bindingIndex + 4);
}
/**
 * pureFunction instruction that can support any number of bindings.
 *
 * If the value of any provided exp has changed, calls the pure function to return
 * an updated value. Or if no values have changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn A pure function that takes binding values and builds an object or array
 * containing those values.
 * @param exps An array of binding values
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 */
function pureFunctionVInternal(lView, bindingRoot, slotOffset, pureFn, exps, thisArg) {
  let bindingIndex = bindingRoot + slotOffset;
  let different = false;
  for (let i = 0; i < exps.length; i++) {
    bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
  }
  return different ? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps)) : getPureFunctionReturnValue(lView, bindingIndex);
}

/**
 * Create a pipe.
 *
 * @param index Pipe index where the pipe will be stored.
 * @param pipeName The name of the pipe
 * @returns T the instance of the pipe.
 *
 * @codeGenApi
 */
function ɵɵpipe(index, pipeName) {
  const tView = getTView();
  let pipeDef;
  const adjustedIndex = index + HEADER_OFFSET;
  if (tView.firstCreatePass) {
    // The `getPipeDef` throws if a pipe with a given name is not found
    // (so we use non-null assertion below).
    pipeDef = getPipeDef(pipeName, tView.pipeRegistry);
    tView.data[adjustedIndex] = pipeDef;
    if (pipeDef.onDestroy) {
      (tView.destroyHooks ??= []).push(adjustedIndex, pipeDef.onDestroy);
    }
  } else {
    pipeDef = tView.data[adjustedIndex];
  }
  const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
  let previousInjectorProfilerContext;
  if (ngDevMode) {
    previousInjectorProfilerContext = setInjectorProfilerContext({
      injector: new NodeInjector(getCurrentTNode(), getLView()),
      token: pipeDef.type
    });
  }
  const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
  try {
    // DI for pipes is supposed to behave like directives when placed on a component
    // host node, which means that we have to disable access to `viewProviders`.
    const previousIncludeViewProviders = setIncludeViewProviders(false);
    const pipeInstance = pipeFactory();
    setIncludeViewProviders(previousIncludeViewProviders);
    store(tView, getLView(), adjustedIndex, pipeInstance);
    return pipeInstance;
  } finally {
    // we have to restore the injector implementation in finally, just in case the creation of the
    // pipe throws an error.
    setInjectImplementation(previousInjectImplementation);
    ngDevMode && setInjectorProfilerContext(previousInjectorProfilerContext);
  }
}
/**
 * Searches the pipe registry for a pipe with the given name. If one is found,
 * returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
 *
 * @param name Name of pipe to resolve
 * @param registry Full list of available pipes
 * @returns Matching PipeDef
 */
function getPipeDef(name, registry) {
  if (registry) {
    if (ngDevMode) {
      const pipes = registry.filter(pipe => pipe.name === name);
      // TODO: Throw an error in the next major
      if (pipes.length > 1) {
        console.warn(formatRuntimeError(313 /* RuntimeErrorCode.MULTIPLE_MATCHING_PIPES */, getMultipleMatchingPipesMessage(name)));
      }
    }
    for (let i = registry.length - 1; i >= 0; i--) {
      const pipeDef = registry[i];
      if (name === pipeDef.name) {
        return pipeDef;
      }
    }
  }
  if (ngDevMode) {
    throw new RuntimeError(-302 /* RuntimeErrorCode.PIPE_NOT_FOUND */, getPipeNotFoundErrorMessage(name));
  }
  return;
}
/**
 * Generates a helpful error message for the user when multiple pipes match the name.
 *
 * @param name Name of the pipe
 * @returns The error message
 */
function getMultipleMatchingPipesMessage(name) {
  const lView = getLView();
  const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  const context = declarationLView[CONTEXT];
  const hostIsStandalone = isHostComponentStandalone(lView);
  const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  const verifyMessage = `check ${hostIsStandalone ? "'@Component.imports' of this component" : 'the imports of this module'}`;
  const errorMessage = `Multiple pipes match the name \`${name}\`${componentInfoMessage}. ${verifyMessage}`;
  return errorMessage;
}
/**
 * Generates a helpful error message for the user when a pipe is not found.
 *
 * @param name Name of the missing pipe
 * @returns The error message
 */
function getPipeNotFoundErrorMessage(name) {
  const lView = getLView();
  const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  const context = declarationLView[CONTEXT];
  const hostIsStandalone = isHostComponentStandalone(lView);
  const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  const verifyMessage = `Verify that it is ${hostIsStandalone ? "included in the '@Component.imports' of this component" : 'declared or imported in this module'}`;
  const errorMessage = `The pipe '${name}' could not be found${componentInfoMessage}. ${verifyMessage}`;
  return errorMessage;
}
/**
 * Invokes a pipe with 1 arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param offset the binding offset
 * @param v1 1st argument to {@link PipeTransform#transform}.
 *
 * @codeGenApi
 */
function ɵɵpipeBind1(index, offset, v1) {
  const adjustedIndex = index + HEADER_OFFSET;
  const lView = getLView();
  const pipeInstance = load(lView, adjustedIndex);
  return isPure(lView, adjustedIndex) ? pureFunction1Internal(lView, getBindingRoot(), offset, pipeInstance.transform, v1, pipeInstance) : pipeInstance.transform(v1);
}
/**
 * Invokes a pipe with 2 arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param slotOffset the offset in the reserved slot space
 * @param v1 1st argument to {@link PipeTransform#transform}.
 * @param v2 2nd argument to {@link PipeTransform#transform}.
 *
 * @codeGenApi
 */
function ɵɵpipeBind2(index, slotOffset, v1, v2) {
  const adjustedIndex = index + HEADER_OFFSET;
  const lView = getLView();
  const pipeInstance = load(lView, adjustedIndex);
  return isPure(lView, adjustedIndex) ? pureFunction2Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance) : pipeInstance.transform(v1, v2);
}
/**
 * Invokes a pipe with 3 arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param slotOffset the offset in the reserved slot space
 * @param v1 1st argument to {@link PipeTransform#transform}.
 * @param v2 2nd argument to {@link PipeTransform#transform}.
 * @param v3 4rd argument to {@link PipeTransform#transform}.
 *
 * @codeGenApi
 */
function ɵɵpipeBind3(index, slotOffset, v1, v2, v3) {
  const adjustedIndex = index + HEADER_OFFSET;
  const lView = getLView();
  const pipeInstance = load(lView, adjustedIndex);
  return isPure(lView, adjustedIndex) ? pureFunction3Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, pipeInstance) : pipeInstance.transform(v1, v2, v3);
}
/**
 * Invokes a pipe with 4 arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param slotOffset the offset in the reserved slot space
 * @param v1 1st argument to {@link PipeTransform#transform}.
 * @param v2 2nd argument to {@link PipeTransform#transform}.
 * @param v3 3rd argument to {@link PipeTransform#transform}.
 * @param v4 4th argument to {@link PipeTransform#transform}.
 *
 * @codeGenApi
 */
function ɵɵpipeBind4(index, slotOffset, v1, v2, v3, v4) {
  const adjustedIndex = index + HEADER_OFFSET;
  const lView = getLView();
  const pipeInstance = load(lView, adjustedIndex);
  return isPure(lView, adjustedIndex) ? pureFunction4Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, v4, pipeInstance) : pipeInstance.transform(v1, v2, v3, v4);
}
/**
 * Invokes a pipe with variable number of arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param slotOffset the offset in the reserved slot space
 * @param values Array of arguments to pass to {@link PipeTransform#transform} method.
 *
 * @codeGenApi
 */
function ɵɵpipeBindV(index, slotOffset, values) {
  const adjustedIndex = index + HEADER_OFFSET;
  const lView = getLView();
  const pipeInstance = load(lView, adjustedIndex);
  return isPure(lView, adjustedIndex) ? pureFunctionVInternal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance) : pipeInstance.transform.apply(pipeInstance, values);
}
function isPure(lView, index) {
  return lView[TVIEW].data[index].pure;
}

/**
 * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the
 * `<ng-template>` element.
 *
 * @codeGenApi
 */
function ɵɵtemplateRefExtractor(tNode, lView) {
  return createTemplateRef(tNode, lView);
}
function ɵɵgetComponentDepsFactory(type, rawImports) {
  return () => {
    try {
      return depsTracker.getComponentDependencies(type, rawImports).dependencies;
    } catch (e) {
      console.error(`Computing dependencies in local compilation mode for the component "${type.name}" failed with the exception:`, e);
      throw e;
    }
  };
}

/**
 * Sets the debug info for an Angular class.
 *
 * This runtime is guarded by ngDevMode flag.
 */
function ɵsetClassDebugInfo(type, debugInfo) {
  const def = getComponentDef(type);
  if (def !== null) {
    def.debugInfo = debugInfo;
  }
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Replaces the metadata of a component type and re-renders all live instances of the component.
 * @param type Class whose metadata will be replaced.
 * @param applyMetadata Callback that will apply a new set of metadata on the `type` when invoked.
 * @param environment Core runtime environment to use when applying the HMR update.
 * @param locals Local symbols from the source location that have to be exposed to the callback.
 * @codeGenApi
 */
function ɵɵreplaceMetadata(type, applyMetadata, environment, locals) {
  ngDevMode && assertComponentDef(type);
  const oldDef = getComponentDef(type);
  // The reason `applyMetadata` is a callback that is invoked (almost) immediately is because
  // the compiler usually produces more code than just the component definition, e.g. there
  // can be functions for embedded views, the variables for the constant pool and `setClassMetadata`
  // calls. The callback allows us to keep them isolate from the rest of the app and to invoke
  // them at the right time.
  applyMetadata.apply(null, [type, environment, ...locals]);
  // If a `tView` hasn't been created yet, it means that this component hasn't been instantianted
  // before. In this case there's nothing left for us to do aside from patching it in.
  if (oldDef.tView) {
    const trackedViews = getTrackedLViews().values();
    for (const root of trackedViews) {
      // Note: we have the additional check, because `IsRoot` can also indicate
      // a component created through something like `createComponent`.
      if (root[FLAGS] & 512 /* LViewFlags.IsRoot */ && root[PARENT] === null) {
        recreateMatchingLViews(oldDef, root);
      }
    }
  }
}
/**
 * Finds all LViews matching a specific component definition and recreates them.
 * @param def Component definition to search for.
 * @param rootLView View from which to start the search.
 */
function recreateMatchingLViews(def, rootLView) {
  ngDevMode && assertDefined(def.tView, 'Expected a component definition that has been instantiated at least once');
  const tView = rootLView[TVIEW];
  // Use `tView` to match the LView since `instanceof` can
  // produce false positives when using inheritance.
  if (tView === def.tView) {
    ngDevMode && assertComponentDef(def.type);
    recreateLView(getComponentDef(def.type), rootLView);
    return;
  }
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    const current = rootLView[i];
    if (isLContainer(current)) {
      for (let i = CONTAINER_HEADER_OFFSET; i < current.length; i++) {
        recreateMatchingLViews(def, current[i]);
      }
    } else if (isLView(current)) {
      recreateMatchingLViews(def, current);
    }
  }
}
/**
 * Removes any cached renderers from the factory for the provided type.
 * This is currently used by the HMR logic to ensure Renderers are kept
 * synchronized with any definition metadata updates.
 * @param factory A RendererFactory2 instance.
 * @param def A ComponentDef instance.
 */
function clearRendererCache(factory, def) {
  // Cast to `any` to read a private field.
  // NOTE: This must be kept synchronized with the renderer factory implementation in platform-browser.
  factory.rendererByCompId?.remove(def.id);
}
/**
 * Recreates an LView in-place from a new component definition.
 * @param def Definition from which to recreate the view.
 * @param lView View to be recreated.
 */
function recreateLView(def, lView) {
  const instance = lView[CONTEXT];
  const host = lView[HOST];
  // In theory the parent can also be an LContainer, but it appears like that's
  // only the case for embedded views which we won't be replacing here.
  const parentLView = lView[PARENT];
  ngDevMode && assertLView(parentLView);
  const tNode = lView[T_HOST];
  ngDevMode && assertTNodeType(tNode, 2 /* TNodeType.Element */);
  // Recreate the TView since the template might've changed.
  const newTView = getOrCreateComponentTView(def);
  // Always force the creation of a new renderer to ensure state captured during construction
  // stays consistent with the new component definition by clearing any old cached factories.
  const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  clearRendererCache(rendererFactory, def);
  // Create a new LView from the new TView, but reusing the existing TNode and DOM node.
  const newLView = createLView(parentLView, newTView, instance, getInitialLViewFlagsFromDef(def), host, tNode, null, rendererFactory.createRenderer(host, def), null, null, null);
  // Detach the LView from its current place in the tree so we don't
  // start traversing any siblings and modifying their structure.
  replaceLViewInTree(parentLView, lView, newLView, tNode.index);
  // Destroy the detached LView.
  destroyLView(lView[TVIEW], lView);
  // Remove the nodes associated with the destroyed LView. This removes the
  // descendants, but not the host which we want to stay in place.
  removeViewFromDOM(lView[TVIEW], lView);
  // Reset the content projection state of the TNode before the first render.
  // Note that this has to happen after the LView has been destroyed or we
  // risk some projected nodes not being removed correctly.
  resetProjectionState(tNode);
  // Creation pass for the new view.
  renderView(newTView, newLView, instance);
  // Update pass for the new view.
  refreshView(newTView, newLView, newTView.template, instance);
}
/**
 * Replaces one LView in the tree with another one.
 * @param parentLView Parent of the LView being replaced.
 * @param oldLView LView being replaced.
 * @param newLView Replacement LView to be inserted.
 * @param index Index at which the LView should be inserted.
 */
function replaceLViewInTree(parentLView, oldLView, newLView, index) {
  // Update the sibling whose `NEXT` pointer refers to the old view.
  for (let i = HEADER_OFFSET; i < parentLView[TVIEW].bindingStartIndex; i++) {
    const current = parentLView[i];
    if ((isLView(current) || isLContainer(current)) && current[NEXT] === oldLView) {
      current[NEXT] = newLView;
      break;
    }
  }
  // Set the new view as the head, if the old view was first.
  if (parentLView[CHILD_HEAD] === oldLView) {
    parentLView[CHILD_HEAD] = newLView;
  }
  // Set the new view as the tail, if the old view was last.
  if (parentLView[CHILD_TAIL] === oldLView) {
    parentLView[CHILD_TAIL] = newLView;
  }
  // Update the `NEXT` pointer to the same as the old view.
  newLView[NEXT] = oldLView[NEXT];
  // Clear out the `NEXT` of the old view.
  oldLView[NEXT] = null;
  // Insert the new LView at the correct index.
  parentLView[index] = newLView;
}
/**
 * Child nodes mutate the `projection` state of their parent node as they're being projected.
 * This function resets the `project` back to its initial state.
 * @param tNode
 */
function resetProjectionState(tNode) {
  // The `projection` is mutated by child nodes as they're being projected. We need to
  // reset it to the initial state so projection works after the template is swapped out.
  if (tNode.projection !== null) {
    for (const current of tNode.projection) {
      if (isTNodeShape(current)) {
        // Reset `projectionNext` since it can affect the traversal order during projection.
        current.projectionNext = null;
        current.flags &= ~2 /* TNodeFlags.isProjected */;
      }
    }
    tNode.projection = null;
  }
}

/**
 * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
 *
 * This should be kept up to date with the public exports of @angular/core.
 */
const angularCoreEnv = /*#__PURE__*/(() => ({
  'ɵɵattribute': ɵɵattribute,
  'ɵɵattributeInterpolate1': ɵɵattributeInterpolate1,
  'ɵɵattributeInterpolate2': ɵɵattributeInterpolate2,
  'ɵɵattributeInterpolate3': ɵɵattributeInterpolate3,
  'ɵɵattributeInterpolate4': ɵɵattributeInterpolate4,
  'ɵɵattributeInterpolate5': ɵɵattributeInterpolate5,
  'ɵɵattributeInterpolate6': ɵɵattributeInterpolate6,
  'ɵɵattributeInterpolate7': ɵɵattributeInterpolate7,
  'ɵɵattributeInterpolate8': ɵɵattributeInterpolate8,
  'ɵɵattributeInterpolateV': ɵɵattributeInterpolateV,
  'ɵɵdefineComponent': ɵɵdefineComponent,
  'ɵɵdefineDirective': ɵɵdefineDirective,
  'ɵɵdefineInjectable': ɵɵdefineInjectable,
  'ɵɵdefineInjector': ɵɵdefineInjector,
  'ɵɵdefineNgModule': ɵɵdefineNgModule,
  'ɵɵdefinePipe': ɵɵdefinePipe,
  'ɵɵdirectiveInject': ɵɵdirectiveInject,
  'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory,
  'ɵɵinject': ɵɵinject,
  'ɵɵinjectAttribute': ɵɵinjectAttribute,
  'ɵɵinvalidFactory': ɵɵinvalidFactory,
  'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor,
  'ɵɵresetView': ɵɵresetView,
  'ɵɵHostDirectivesFeature': ɵɵHostDirectivesFeature,
  'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature,
  'ɵɵProvidersFeature': ɵɵProvidersFeature,
  'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature,
  'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature,
  'ɵɵInputTransformsFeature': ɵɵInputTransformsFeature,
  'ɵɵExternalStylesFeature': ɵɵExternalStylesFeature,
  'ɵɵnextContext': ɵɵnextContext,
  'ɵɵnamespaceHTML': ɵɵnamespaceHTML,
  'ɵɵnamespaceMathML': ɵɵnamespaceMathML,
  'ɵɵnamespaceSVG': ɵɵnamespaceSVG,
  'ɵɵenableBindings': ɵɵenableBindings,
  'ɵɵdisableBindings': ɵɵdisableBindings,
  'ɵɵelementStart': ɵɵelementStart,
  'ɵɵelementEnd': ɵɵelementEnd,
  'ɵɵelement': ɵɵelement,
  'ɵɵelementContainerStart': ɵɵelementContainerStart,
  'ɵɵelementContainerEnd': ɵɵelementContainerEnd,
  'ɵɵelementContainer': ɵɵelementContainer,
  'ɵɵpureFunction0': ɵɵpureFunction0,
  'ɵɵpureFunction1': ɵɵpureFunction1,
  'ɵɵpureFunction2': ɵɵpureFunction2,
  'ɵɵpureFunction3': ɵɵpureFunction3,
  'ɵɵpureFunction4': ɵɵpureFunction4,
  'ɵɵpureFunction5': ɵɵpureFunction5,
  'ɵɵpureFunction6': ɵɵpureFunction6,
  'ɵɵpureFunction7': ɵɵpureFunction7,
  'ɵɵpureFunction8': ɵɵpureFunction8,
  'ɵɵpureFunctionV': ɵɵpureFunctionV,
  'ɵɵgetCurrentView': ɵɵgetCurrentView,
  'ɵɵrestoreView': ɵɵrestoreView,
  'ɵɵlistener': ɵɵlistener,
  'ɵɵprojection': ɵɵprojection,
  'ɵɵsyntheticHostProperty': ɵɵsyntheticHostProperty,
  'ɵɵsyntheticHostListener': ɵɵsyntheticHostListener,
  'ɵɵpipeBind1': ɵɵpipeBind1,
  'ɵɵpipeBind2': ɵɵpipeBind2,
  'ɵɵpipeBind3': ɵɵpipeBind3,
  'ɵɵpipeBind4': ɵɵpipeBind4,
  'ɵɵpipeBindV': ɵɵpipeBindV,
  'ɵɵprojectionDef': ɵɵprojectionDef,
  'ɵɵhostProperty': ɵɵhostProperty,
  'ɵɵproperty': ɵɵproperty,
  'ɵɵpropertyInterpolate': ɵɵpropertyInterpolate,
  'ɵɵpropertyInterpolate1': ɵɵpropertyInterpolate1,
  'ɵɵpropertyInterpolate2': ɵɵpropertyInterpolate2,
  'ɵɵpropertyInterpolate3': ɵɵpropertyInterpolate3,
  'ɵɵpropertyInterpolate4': ɵɵpropertyInterpolate4,
  'ɵɵpropertyInterpolate5': ɵɵpropertyInterpolate5,
  'ɵɵpropertyInterpolate6': ɵɵpropertyInterpolate6,
  'ɵɵpropertyInterpolate7': ɵɵpropertyInterpolate7,
  'ɵɵpropertyInterpolate8': ɵɵpropertyInterpolate8,
  'ɵɵpropertyInterpolateV': ɵɵpropertyInterpolateV,
  'ɵɵpipe': ɵɵpipe,
  'ɵɵqueryRefresh': ɵɵqueryRefresh,
  'ɵɵqueryAdvance': ɵɵqueryAdvance,
  'ɵɵviewQuery': ɵɵviewQuery,
  'ɵɵviewQuerySignal': ɵɵviewQuerySignal,
  'ɵɵloadQuery': ɵɵloadQuery,
  'ɵɵcontentQuery': ɵɵcontentQuery,
  'ɵɵcontentQuerySignal': ɵɵcontentQuerySignal,
  'ɵɵreference': ɵɵreference,
  'ɵɵclassMap': ɵɵclassMap,
  'ɵɵclassMapInterpolate1': ɵɵclassMapInterpolate1,
  'ɵɵclassMapInterpolate2': ɵɵclassMapInterpolate2,
  'ɵɵclassMapInterpolate3': ɵɵclassMapInterpolate3,
  'ɵɵclassMapInterpolate4': ɵɵclassMapInterpolate4,
  'ɵɵclassMapInterpolate5': ɵɵclassMapInterpolate5,
  'ɵɵclassMapInterpolate6': ɵɵclassMapInterpolate6,
  'ɵɵclassMapInterpolate7': ɵɵclassMapInterpolate7,
  'ɵɵclassMapInterpolate8': ɵɵclassMapInterpolate8,
  'ɵɵclassMapInterpolateV': ɵɵclassMapInterpolateV,
  'ɵɵstyleMap': ɵɵstyleMap,
  'ɵɵstyleMapInterpolate1': ɵɵstyleMapInterpolate1,
  'ɵɵstyleMapInterpolate2': ɵɵstyleMapInterpolate2,
  'ɵɵstyleMapInterpolate3': ɵɵstyleMapInterpolate3,
  'ɵɵstyleMapInterpolate4': ɵɵstyleMapInterpolate4,
  'ɵɵstyleMapInterpolate5': ɵɵstyleMapInterpolate5,
  'ɵɵstyleMapInterpolate6': ɵɵstyleMapInterpolate6,
  'ɵɵstyleMapInterpolate7': ɵɵstyleMapInterpolate7,
  'ɵɵstyleMapInterpolate8': ɵɵstyleMapInterpolate8,
  'ɵɵstyleMapInterpolateV': ɵɵstyleMapInterpolateV,
  'ɵɵstyleProp': ɵɵstyleProp,
  'ɵɵstylePropInterpolate1': ɵɵstylePropInterpolate1,
  'ɵɵstylePropInterpolate2': ɵɵstylePropInterpolate2,
  'ɵɵstylePropInterpolate3': ɵɵstylePropInterpolate3,
  'ɵɵstylePropInterpolate4': ɵɵstylePropInterpolate4,
  'ɵɵstylePropInterpolate5': ɵɵstylePropInterpolate5,
  'ɵɵstylePropInterpolate6': ɵɵstylePropInterpolate6,
  'ɵɵstylePropInterpolate7': ɵɵstylePropInterpolate7,
  'ɵɵstylePropInterpolate8': ɵɵstylePropInterpolate8,
  'ɵɵstylePropInterpolateV': ɵɵstylePropInterpolateV,
  'ɵɵclassProp': ɵɵclassProp,
  'ɵɵadvance': ɵɵadvance,
  'ɵɵtemplate': ɵɵtemplate,
  'ɵɵconditional': ɵɵconditional,
  'ɵɵdefer': ɵɵdefer,
  'ɵɵdeferWhen': ɵɵdeferWhen,
  'ɵɵdeferOnIdle': ɵɵdeferOnIdle,
  'ɵɵdeferOnImmediate': ɵɵdeferOnImmediate,
  'ɵɵdeferOnTimer': ɵɵdeferOnTimer,
  'ɵɵdeferOnHover': ɵɵdeferOnHover,
  'ɵɵdeferOnInteraction': ɵɵdeferOnInteraction,
  'ɵɵdeferOnViewport': ɵɵdeferOnViewport,
  'ɵɵdeferPrefetchWhen': ɵɵdeferPrefetchWhen,
  'ɵɵdeferPrefetchOnIdle': ɵɵdeferPrefetchOnIdle,
  'ɵɵdeferPrefetchOnImmediate': ɵɵdeferPrefetchOnImmediate,
  'ɵɵdeferPrefetchOnTimer': ɵɵdeferPrefetchOnTimer,
  'ɵɵdeferPrefetchOnHover': ɵɵdeferPrefetchOnHover,
  'ɵɵdeferPrefetchOnInteraction': ɵɵdeferPrefetchOnInteraction,
  'ɵɵdeferPrefetchOnViewport': ɵɵdeferPrefetchOnViewport,
  'ɵɵdeferHydrateWhen': ɵɵdeferHydrateWhen,
  'ɵɵdeferHydrateNever': ɵɵdeferHydrateNever,
  'ɵɵdeferHydrateOnIdle': ɵɵdeferHydrateOnIdle,
  'ɵɵdeferHydrateOnImmediate': ɵɵdeferHydrateOnImmediate,
  'ɵɵdeferHydrateOnTimer': ɵɵdeferHydrateOnTimer,
  'ɵɵdeferHydrateOnHover': ɵɵdeferHydrateOnHover,
  'ɵɵdeferHydrateOnInteraction': ɵɵdeferHydrateOnInteraction,
  'ɵɵdeferHydrateOnViewport': ɵɵdeferHydrateOnViewport,
  'ɵɵdeferEnableTimerScheduling': ɵɵdeferEnableTimerScheduling,
  'ɵɵrepeater': ɵɵrepeater,
  'ɵɵrepeaterCreate': ɵɵrepeaterCreate,
  'ɵɵrepeaterTrackByIndex': ɵɵrepeaterTrackByIndex,
  'ɵɵrepeaterTrackByIdentity': ɵɵrepeaterTrackByIdentity,
  'ɵɵcomponentInstance': ɵɵcomponentInstance,
  'ɵɵtext': ɵɵtext,
  'ɵɵtextInterpolate': ɵɵtextInterpolate,
  'ɵɵtextInterpolate1': ɵɵtextInterpolate1,
  'ɵɵtextInterpolate2': ɵɵtextInterpolate2,
  'ɵɵtextInterpolate3': ɵɵtextInterpolate3,
  'ɵɵtextInterpolate4': ɵɵtextInterpolate4,
  'ɵɵtextInterpolate5': ɵɵtextInterpolate5,
  'ɵɵtextInterpolate6': ɵɵtextInterpolate6,
  'ɵɵtextInterpolate7': ɵɵtextInterpolate7,
  'ɵɵtextInterpolate8': ɵɵtextInterpolate8,
  'ɵɵtextInterpolateV': ɵɵtextInterpolateV,
  'ɵɵi18n': ɵɵi18n,
  'ɵɵi18nAttributes': ɵɵi18nAttributes,
  'ɵɵi18nExp': ɵɵi18nExp,
  'ɵɵi18nStart': ɵɵi18nStart,
  'ɵɵi18nEnd': ɵɵi18nEnd,
  'ɵɵi18nApply': ɵɵi18nApply,
  'ɵɵi18nPostprocess': ɵɵi18nPostprocess,
  'ɵɵresolveWindow': ɵɵresolveWindow,
  'ɵɵresolveDocument': ɵɵresolveDocument,
  'ɵɵresolveBody': ɵɵresolveBody,
  'ɵɵsetComponentScope': ɵɵsetComponentScope,
  'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope,
  'ɵɵregisterNgModuleType': registerNgModuleType,
  'ɵɵgetComponentDepsFactory': ɵɵgetComponentDepsFactory,
  'ɵsetClassDebugInfo': ɵsetClassDebugInfo,
  'ɵɵdeclareLet': ɵɵdeclareLet,
  'ɵɵstoreLet': ɵɵstoreLet,
  'ɵɵreadContextLet': ɵɵreadContextLet,
  'ɵɵsanitizeHtml': ɵɵsanitizeHtml,
  'ɵɵsanitizeStyle': ɵɵsanitizeStyle,
  'ɵɵsanitizeResourceUrl': ɵɵsanitizeResourceUrl,
  'ɵɵsanitizeScript': ɵɵsanitizeScript,
  'ɵɵsanitizeUrl': ɵɵsanitizeUrl,
  'ɵɵsanitizeUrlOrResourceUrl': ɵɵsanitizeUrlOrResourceUrl,
  'ɵɵtrustConstantHtml': ɵɵtrustConstantHtml,
  'ɵɵtrustConstantResourceUrl': ɵɵtrustConstantResourceUrl,
  'ɵɵvalidateIframeAttribute': ɵɵvalidateIframeAttribute,
  'forwardRef': forwardRef,
  'resolveForwardRef': resolveForwardRef,
  'ɵɵtwoWayProperty': ɵɵtwoWayProperty,
  'ɵɵtwoWayBindingSet': ɵɵtwoWayBindingSet,
  'ɵɵtwoWayListener': ɵɵtwoWayListener,
  'ɵɵreplaceMetadata': ɵɵreplaceMetadata
}))();
let jitOptions = null;
function setJitOptions(options) {
  if (jitOptions !== null) {
    if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
      ngDevMode && console.error('Provided value for `defaultEncapsulation` can not be changed once it has been set.');
      return;
    }
    if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
      ngDevMode && console.error('Provided value for `preserveWhitespaces` can not be changed once it has been set.');
      return;
    }
  }
  jitOptions = options;
}
function getJitOptions() {
  return jitOptions;
}
function resetJitOptions() {
  jitOptions = null;
}
function patchModuleCompilation() {
  // Does nothing, but exists as a target for patching.
}
const moduleQueue = [];
/**
 * Enqueues moduleDef to be checked later to see if scope can be set on its
 * component declarations.
 */
function enqueueModuleForDelayedScoping(moduleType, ngModule) {
  moduleQueue.push({
    moduleType,
    ngModule
  });
}
let flushingModuleQueue = false;
/**
 * Loops over queued module definitions, if a given module definition has all of its
 * declarations resolved, it dequeues that module definition and sets the scope on
 * its declarations.
 */
function flushModuleScopingQueueAsMuchAsPossible() {
  if (!flushingModuleQueue) {
    flushingModuleQueue = true;
    try {
      for (let i = moduleQueue.length - 1; i >= 0; i--) {
        const {
          moduleType,
          ngModule
        } = moduleQueue[i];
        if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
          // dequeue
          moduleQueue.splice(i, 1);
          setScopeOnDeclaredComponents(moduleType, ngModule);
        }
      }
    } finally {
      flushingModuleQueue = false;
    }
  }
}
/**
 * Returns truthy if a declaration has resolved. If the declaration happens to be
 * an array of declarations, it will recurse to check each declaration in that array
 * (which may also be arrays).
 */
function isResolvedDeclaration(declaration) {
  if (Array.isArray(declaration)) {
    return declaration.every(isResolvedDeclaration);
  }
  return !!resolveForwardRef(declaration);
}
/**
 * Compiles a module in JIT mode.
 *
 * This function automatically gets called when a class has a `@NgModule` decorator.
 */
function compileNgModule(moduleType, ngModule = {}) {
  patchModuleCompilation();
  compileNgModuleDefs(moduleType, ngModule);
  if (ngModule.id !== undefined) {
    registerNgModuleType(moduleType, ngModule.id);
  }
  // Because we don't know if all declarations have resolved yet at the moment the
  // NgModule decorator is executing, we're enqueueing the setting of module scope
  // on its declarations to be run at a later time when all declarations for the module,
  // including forward refs, have resolved.
  enqueueModuleForDelayedScoping(moduleType, ngModule);
}
/**
 * Compiles and adds the `ɵmod`, `ɵfac` and `ɵinj` properties to the module class.
 *
 * It's possible to compile a module via this API which will allow duplicate declarations in its
 * root.
 */
function compileNgModuleDefs(moduleType, ngModule, allowDuplicateDeclarationsInRoot = false) {
  ngDevMode && assertDefined(moduleType, 'Required value moduleType');
  ngDevMode && assertDefined(ngModule, 'Required value ngModule');
  const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  let ngModuleDef = null;
  Object.defineProperty(moduleType, NG_MOD_DEF, {
    configurable: true,
    get: () => {
      if (ngModuleDef === null) {
        if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
          // We need to assert this immediately, because allowing it to continue will cause it to
          // go into an infinite loop before we've reached the point where we throw all the errors.
          throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
        }
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'NgModule',
          type: moduleType
        });
        ngModuleDef = compiler.compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
          type: moduleType,
          bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY).map(resolveForwardRef),
          declarations: declarations.map(resolveForwardRef),
          imports: flatten(ngModule.imports || EMPTY_ARRAY).map(resolveForwardRef).map(expandModuleWithProviders),
          exports: flatten(ngModule.exports || EMPTY_ARRAY).map(resolveForwardRef).map(expandModuleWithProviders),
          schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
          id: ngModule.id || null
        });
        // Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
        // should verify that there are no unknown elements in a template. In AOT mode, that check
        // happens at compile time and `schemas` information is not present on Component and Module
        // defs after compilation (so the check doesn't happen the second time at runtime).
        if (!ngModuleDef.schemas) {
          ngModuleDef.schemas = [];
        }
      }
      return ngModuleDef;
    }
  });
  let ngFactoryDef = null;
  Object.defineProperty(moduleType, NG_FACTORY_DEF, {
    get: () => {
      if (ngFactoryDef === null) {
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'NgModule',
          type: moduleType
        });
        ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${moduleType.name}/ɵfac.js`, {
          name: moduleType.name,
          type: moduleType,
          deps: reflectDependencies(moduleType),
          target: compiler.FactoryTarget.NgModule,
          typeArgumentCount: 0
        });
      }
      return ngFactoryDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
  let ngInjectorDef = null;
  Object.defineProperty(moduleType, NG_INJ_DEF, {
    get: () => {
      if (ngInjectorDef === null) {
        ngDevMode && verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot);
        const meta = {
          name: moduleType.name,
          type: moduleType,
          providers: ngModule.providers || EMPTY_ARRAY,
          imports: [(ngModule.imports || EMPTY_ARRAY).map(resolveForwardRef), (ngModule.exports || EMPTY_ARRAY).map(resolveForwardRef)]
        };
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'NgModule',
          type: moduleType
        });
        ngInjectorDef = compiler.compileInjector(angularCoreEnv, `ng:///${moduleType.name}/ɵinj.js`, meta);
      }
      return ngInjectorDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
}
function generateStandaloneInDeclarationsError(type, location) {
  const prefix = `Unexpected "${stringifyForError(type)}" found in the "declarations" array of the`;
  const suffix = `"${stringifyForError(type)}" is marked as standalone and can't be declared ` + 'in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?';
  return `${prefix} ${location}, ${suffix}`;
}
function verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot, importingModule) {
  if (verifiedNgModule.get(moduleType)) return;
  // skip verifications of standalone components, directives, and pipes
  if (isStandalone(moduleType)) return;
  verifiedNgModule.set(moduleType, true);
  moduleType = resolveForwardRef(moduleType);
  let ngModuleDef;
  if (importingModule) {
    ngModuleDef = getNgModuleDef(moduleType);
    if (!ngModuleDef) {
      throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
    }
  } else {
    ngModuleDef = getNgModuleDef(moduleType, true);
  }
  const errors = [];
  const declarations = maybeUnwrapFn(ngModuleDef.declarations);
  const imports = maybeUnwrapFn(ngModuleDef.imports);
  flatten(imports).map(unwrapModuleWithProvidersImports).forEach(modOrStandaloneCmpt => {
    verifySemanticsOfNgModuleImport(modOrStandaloneCmpt, moduleType);
    verifySemanticsOfNgModuleDef(modOrStandaloneCmpt, false, moduleType);
  });
  const exports = maybeUnwrapFn(ngModuleDef.exports);
  declarations.forEach(verifyDeclarationsHaveDefinitions);
  declarations.forEach(verifyDirectivesHaveSelector);
  declarations.forEach(declarationType => verifyNotStandalone(declarationType, moduleType));
  const combinedDeclarations = [...declarations.map(resolveForwardRef), ...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef)];
  exports.forEach(verifyExportsAreDeclaredOrReExported);
  declarations.forEach(decl => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot));
  const ngModule = getAnnotation(moduleType, 'NgModule');
  if (ngModule) {
    ngModule.imports && flatten(ngModule.imports).map(unwrapModuleWithProvidersImports).forEach(mod => {
      verifySemanticsOfNgModuleImport(mod, moduleType);
      verifySemanticsOfNgModuleDef(mod, false, moduleType);
    });
    ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
    ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
  }
  // Throw Error if any errors were detected.
  if (errors.length) {
    throw new Error(errors.join('\n'));
  }
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function verifyDeclarationsHaveDefinitions(type) {
    type = resolveForwardRef(type);
    const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
    if (!def) {
      errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`);
    }
  }
  function verifyDirectivesHaveSelector(type) {
    type = resolveForwardRef(type);
    const def = getDirectiveDef(type);
    if (!getComponentDef(type) && def && def.selectors.length == 0) {
      errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
    }
  }
  function verifyNotStandalone(type, moduleType) {
    type = resolveForwardRef(type);
    const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
    if (def?.standalone) {
      const location = `"${stringifyForError(moduleType)}" NgModule`;
      errors.push(generateStandaloneInDeclarationsError(type, location));
    }
  }
  function verifyExportsAreDeclaredOrReExported(type) {
    type = resolveForwardRef(type);
    const kind = getComponentDef(type) && 'component' || getDirectiveDef(type) && 'directive' || getPipeDef$1(type) && 'pipe';
    if (kind) {
      // only checked if we are declared as Component, Directive, or Pipe
      // Modules don't need to be declared or imported.
      if (combinedDeclarations.lastIndexOf(type) === -1) {
        // We are exporting something which we don't explicitly declare or import.
        errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`);
      }
    }
  }
  function verifyDeclarationIsUnique(type, suppressErrors) {
    type = resolveForwardRef(type);
    const existingModule = ownerNgModule.get(type);
    if (existingModule && existingModule !== moduleType) {
      if (!suppressErrors) {
        const modules = [existingModule, moduleType].map(stringifyForError).sort();
        errors.push(`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` + `Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` + `You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`);
      }
    } else {
      // Mark type as having owner.
      ownerNgModule.set(type, moduleType);
    }
  }
  function verifyComponentIsPartOfNgModule(type) {
    type = resolveForwardRef(type);
    const existingModule = ownerNgModule.get(type);
    if (!existingModule && !isStandalone(type)) {
      errors.push(`Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`);
    }
  }
  function verifyCorrectBootstrapType(type) {
    type = resolveForwardRef(type);
    if (!getComponentDef(type)) {
      errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
    }
    if (isStandalone(type)) {
      // Note: this error should be the same as the
      // `NGMODULE_BOOTSTRAP_IS_STANDALONE` one in AOT compiler.
      errors.push(`The \`${stringifyForError(type)}\` class is a standalone component, which can ` + `not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` ` + `function for bootstrap instead.`);
    }
  }
  function verifySemanticsOfNgModuleImport(type, importingModule) {
    type = resolveForwardRef(type);
    const directiveDef = getComponentDef(type) || getDirectiveDef(type);
    if (directiveDef !== null && !directiveDef.standalone) {
      throw new Error(`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
    }
    const pipeDef = getPipeDef$1(type);
    if (pipeDef !== null && !pipeDef.standalone) {
      throw new Error(`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
    }
  }
}
function unwrapModuleWithProvidersImports(typeOrWithProviders) {
  typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
  return typeOrWithProviders.ngModule || typeOrWithProviders;
}
function getAnnotation(type, name) {
  let annotation = null;
  collect(type.__annotations__);
  collect(type.decorators);
  return annotation;
  function collect(annotations) {
    if (annotations) {
      annotations.forEach(readAnnotation);
    }
  }
  function readAnnotation(decorator) {
    if (!annotation) {
      const proto = Object.getPrototypeOf(decorator);
      if (proto.ngMetadataName == name) {
        annotation = decorator;
      } else if (decorator.type) {
        const proto = Object.getPrototypeOf(decorator.type);
        if (proto.ngMetadataName == name) {
          annotation = decorator.args[0];
        }
      }
    }
  }
}
/**
 * Keep track of compiled components. This is needed because in tests we often want to compile the
 * same component with more than one NgModule. This would cause an error unless we reset which
 * NgModule the component belongs to. We keep the list of compiled components here so that the
 * TestBed can reset it later.
 */
let ownerNgModule = /*#__PURE__*/new WeakMap();
let verifiedNgModule = /*#__PURE__*/new WeakMap();
function resetCompiledComponents() {
  ownerNgModule = new WeakMap();
  verifiedNgModule = new WeakMap();
  moduleQueue.length = 0;
  GENERATED_COMP_IDS.clear();
}
/**
 * Computes the combined declarations of explicit declarations, as well as declarations inherited by
 * traversing the exports of imported modules.
 * @param type
 */
function computeCombinedExports(type) {
  type = resolveForwardRef(type);
  const ngModuleDef = getNgModuleDef(type);
  // a standalone component, directive or pipe
  if (ngModuleDef === null) {
    return [type];
  }
  return flatten(maybeUnwrapFn(ngModuleDef.exports).map(type => {
    const ngModuleDef = getNgModuleDef(type);
    if (ngModuleDef) {
      verifySemanticsOfNgModuleDef(type, false);
      return computeCombinedExports(type);
    } else {
      return type;
    }
  }));
}
/**
 * Some declared components may be compiled asynchronously, and thus may not have their
 * ɵcmp set yet. If this is the case, then a reference to the module is written into
 * the `ngSelectorScope` property of the declared type.
 */
function setScopeOnDeclaredComponents(moduleType, ngModule) {
  const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  const transitiveScopes = transitiveScopesFor(moduleType);
  declarations.forEach(declaration => {
    declaration = resolveForwardRef(declaration);
    if (declaration.hasOwnProperty(NG_COMP_DEF)) {
      // A `ɵcmp` field exists - go ahead and patch the component directly.
      const component = declaration;
      const componentDef = getComponentDef(component);
      patchComponentDefWithScope(componentDef, transitiveScopes);
    } else if (!declaration.hasOwnProperty(NG_DIR_DEF) && !declaration.hasOwnProperty(NG_PIPE_DEF)) {
      // Set `ngSelectorScope` for future reference when the component compilation finishes.
      declaration.ngSelectorScope = moduleType;
    }
  });
}
/**
 * Patch the definition of a component with directives and pipes from the compilation scope of
 * a given module.
 */
function patchComponentDefWithScope(componentDef, transitiveScopes) {
  componentDef.directiveDefs = () => Array.from(transitiveScopes.compilation.directives).map(dir => dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir) : getDirectiveDef(dir)).filter(def => !!def);
  componentDef.pipeDefs = () => Array.from(transitiveScopes.compilation.pipes).map(pipe => getPipeDef$1(pipe));
  componentDef.schemas = transitiveScopes.schemas;
  // Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
  // may face a problem where previously compiled defs available to a given Component/Directive
  // are cached in TView and may become stale (in case any of these defs gets recompiled). In
  // order to avoid this problem, we force fresh TView to be created.
  componentDef.tView = null;
}
/**
 * Compute the pair of transitive scopes (compilation scope and exported scope) for a given type
 * (either a NgModule or a standalone component / directive / pipe).
 */
function transitiveScopesFor(type) {
  if (isNgModule(type)) {
    if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
      const scope = depsTracker.getNgModuleScope(type);
      const def = getNgModuleDef(type, true);
      return {
        schemas: def.schemas || null,
        ...scope
      };
    } else {
      return transitiveScopesForNgModule(type);
    }
  } else if (isStandalone(type)) {
    const directiveDef = getComponentDef(type) || getDirectiveDef(type);
    if (directiveDef !== null) {
      return {
        schemas: null,
        compilation: {
          directives: new Set(),
          pipes: new Set()
        },
        exported: {
          directives: new Set([type]),
          pipes: new Set()
        }
      };
    }
    const pipeDef = getPipeDef$1(type);
    if (pipeDef !== null) {
      return {
        schemas: null,
        compilation: {
          directives: new Set(),
          pipes: new Set()
        },
        exported: {
          directives: new Set(),
          pipes: new Set([type])
        }
      };
    }
  }
  // TODO: change the error message to be more user-facing and take standalone into account
  throw new Error(`${type.name} does not have a module def (ɵmod property)`);
}
/**
 * Compute the pair of transitive scopes (compilation scope and exported scope) for a given module.
 *
 * This operation is memoized and the result is cached on the module's definition. This function can
 * be called on modules with components that have not fully compiled yet, but the result should not
 * be used until they have.
 *
 * @param moduleType module that transitive scope should be calculated for.
 */
function transitiveScopesForNgModule(moduleType) {
  const def = getNgModuleDef(moduleType, true);
  if (def.transitiveCompileScopes !== null) {
    return def.transitiveCompileScopes;
  }
  const scopes = {
    schemas: def.schemas || null,
    compilation: {
      directives: new Set(),
      pipes: new Set()
    },
    exported: {
      directives: new Set(),
      pipes: new Set()
    }
  };
  maybeUnwrapFn(def.imports).forEach(imported => {
    // When this module imports another, the imported module's exported directives and pipes are
    // added to the compilation scope of this module.
    const importedScope = transitiveScopesFor(imported);
    importedScope.exported.directives.forEach(entry => scopes.compilation.directives.add(entry));
    importedScope.exported.pipes.forEach(entry => scopes.compilation.pipes.add(entry));
  });
  maybeUnwrapFn(def.declarations).forEach(declared => {
    const declaredWithDefs = declared;
    if (getPipeDef$1(declaredWithDefs)) {
      scopes.compilation.pipes.add(declared);
    } else {
      // Either declared has a ɵcmp or ɵdir, or it's a component which hasn't
      // had its template compiled yet. In either case, it gets added to the compilation's
      // directives.
      scopes.compilation.directives.add(declared);
    }
  });
  maybeUnwrapFn(def.exports).forEach(exported => {
    const exportedType = exported;
    // Either the type is a module, a pipe, or a component/directive (which may not have a
    // ɵcmp as it might be compiled asynchronously).
    if (isNgModule(exportedType)) {
      // When this module exports another, the exported module's exported directives and pipes are
      // added to both the compilation and exported scopes of this module.
      const exportedScope = transitiveScopesFor(exportedType);
      exportedScope.exported.directives.forEach(entry => {
        scopes.compilation.directives.add(entry);
        scopes.exported.directives.add(entry);
      });
      exportedScope.exported.pipes.forEach(entry => {
        scopes.compilation.pipes.add(entry);
        scopes.exported.pipes.add(entry);
      });
    } else if (getPipeDef$1(exportedType)) {
      scopes.exported.pipes.add(exportedType);
    } else {
      scopes.exported.directives.add(exportedType);
    }
  });
  def.transitiveCompileScopes = scopes;
  return scopes;
}
function expandModuleWithProviders(value) {
  if (isModuleWithProviders(value)) {
    return value.ngModule;
  }
  return value;
}

/**
 * Keep track of the compilation depth to avoid reentrancy issues during JIT compilation. This
 * matters in the following scenario:
 *
 * Consider a component 'A' that extends component 'B', both declared in module 'M'. During
 * the compilation of 'A' the definition of 'B' is requested to capture the inheritance chain,
 * potentially triggering compilation of 'B'. If this nested compilation were to trigger
 * `flushModuleScopingQueueAsMuchAsPossible` it may happen that module 'M' is still pending in the
 * queue, resulting in 'A' and 'B' to be patched with the NgModule scope. As the compilation of
 * 'A' is still in progress, this would introduce a circular dependency on its compilation. To avoid
 * this issue, the module scope queue is only flushed for compilations at the depth 0, to ensure
 * all compilations have finished.
 */
let compilationDepth = 0;
/**
 * Compile an Angular component according to its decorator metadata, and patch the resulting
 * component def (ɵcmp) onto the component type.
 *
 * Compilation may be asynchronous (due to the need to resolve URLs for the component template or
 * other resources, for example). In the event that compilation is not immediate, `compileComponent`
 * will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
 * until the global queue has been resolved with a call to `resolveComponentResources`.
 */
function compileComponent(type, metadata) {
  // Initialize ngDevMode. This must be the first statement in compileComponent.
  // See the `initNgDevMode` docstring for more information.
  (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
  let ngComponentDef = null;
  // Metadata may have resources which need to be resolved.
  maybeQueueResolutionOfComponentResources(type, metadata);
  // Note that we're using the same function as `Directive`, because that's only subset of metadata
  // that we need to create the ngFactoryDef. We're avoiding using the component metadata
  // because we'd have to resolve the asynchronous templates.
  addDirectiveFactoryDef(type, metadata);
  Object.defineProperty(type, NG_COMP_DEF, {
    get: () => {
      if (ngComponentDef === null) {
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'component',
          type: type
        });
        if (componentNeedsResolution(metadata)) {
          const error = [`Component '${type.name}' is not resolved:`];
          if (metadata.templateUrl) {
            error.push(` - templateUrl: ${metadata.templateUrl}`);
          }
          if (metadata.styleUrls && metadata.styleUrls.length) {
            error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
          }
          if (metadata.styleUrl) {
            error.push(` - styleUrl: ${metadata.styleUrl}`);
          }
          error.push(`Did you run and wait for 'resolveComponentResources()'?`);
          throw new Error(error.join('\n'));
        }
        // This const was called `jitOptions` previously but had to be renamed to `options` because
        // of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
        // This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
        // We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
        const options = getJitOptions();
        let preserveWhitespaces = metadata.preserveWhitespaces;
        if (preserveWhitespaces === undefined) {
          if (options !== null && options.preserveWhitespaces !== undefined) {
            preserveWhitespaces = options.preserveWhitespaces;
          } else {
            preserveWhitespaces = false;
          }
        }
        let encapsulation = metadata.encapsulation;
        if (encapsulation === undefined) {
          if (options !== null && options.defaultEncapsulation !== undefined) {
            encapsulation = options.defaultEncapsulation;
          } else {
            encapsulation = ViewEncapsulation.Emulated;
          }
        }
        const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
        const meta = {
          ...directiveMetadata(type, metadata),
          typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
          template: metadata.template || '',
          preserveWhitespaces,
          styles: typeof metadata.styles === 'string' ? [metadata.styles] : metadata.styles || EMPTY_ARRAY,
          animations: metadata.animations,
          // JIT components are always compiled against an empty set of `declarations`. Instead, the
          // `directiveDefs` and `pipeDefs` are updated at a later point:
          //  * for NgModule-based components, they're set when the NgModule which declares the
          //    component resolves in the module scoping queue
          //  * for standalone components, they're set just below, after `compileComponent`.
          declarations: [],
          changeDetection: metadata.changeDetection,
          encapsulation,
          interpolation: metadata.interpolation,
          viewProviders: metadata.viewProviders || null
        };
        compilationDepth++;
        try {
          if (meta.usesInheritance) {
            addDirectiveDefToUndecoratedParents(type);
          }
          ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
          if (meta.isStandalone) {
            // Patch the component definition for standalone components with `directiveDefs` and
            // `pipeDefs` functions which lazily compute the directives/pipes available in the
            // standalone component. Also set `dependencies` to the lazily resolved list of imports.
            const imports = flatten(metadata.imports || EMPTY_ARRAY);
            const {
              directiveDefs,
              pipeDefs
            } = getStandaloneDefFunctions(type, imports);
            ngComponentDef.directiveDefs = directiveDefs;
            ngComponentDef.pipeDefs = pipeDefs;
            ngComponentDef.dependencies = () => imports.map(resolveForwardRef);
          }
        } finally {
          // Ensure that the compilation depth is decremented even when the compilation failed.
          compilationDepth--;
        }
        if (compilationDepth === 0) {
          // When NgModule decorator executed, we enqueued the module definition such that
          // it would only dequeue and add itself as module scope to all of its declarations,
          // but only if  if all of its declarations had resolved. This call runs the check
          // to see if any modules that are in the queue can be dequeued and add scope to
          // their declarations.
          flushModuleScopingQueueAsMuchAsPossible();
        }
        // If component compilation is async, then the @NgModule annotation which declares the
        // component may execute and set an ngSelectorScope property on the component type. This
        // allows the component to patch itself with directiveDefs from the module after it
        // finishes compiling.
        if (hasSelectorScope(type)) {
          const scopes = transitiveScopesFor(type.ngSelectorScope);
          patchComponentDefWithScope(ngComponentDef, scopes);
        }
        if (metadata.schemas) {
          if (meta.isStandalone) {
            ngComponentDef.schemas = metadata.schemas;
          } else {
            throw new Error(`The 'schemas' was specified for the ${stringifyForError(type)} but is only valid on a component that is standalone.`);
          }
        } else if (meta.isStandalone) {
          ngComponentDef.schemas = [];
        }
      }
      return ngComponentDef;
    },
    set: def => {
      ngComponentDef = def;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
}
/**
 * Build memoized `directiveDefs` and `pipeDefs` functions for the component definition of a
 * standalone component, which process `imports` and filter out directives and pipes. The use of
 * memoized functions here allows for the delayed resolution of any `forwardRef`s present in the
 * component's `imports`.
 */
function getStandaloneDefFunctions(type, imports) {
  let cachedDirectiveDefs = null;
  let cachedPipeDefs = null;
  const directiveDefs = () => {
    if (!USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
      if (cachedDirectiveDefs === null) {
        // Standalone components are always able to self-reference, so include the component's own
        // definition in its `directiveDefs`.
        cachedDirectiveDefs = [getComponentDef(type)];
        const seen = new Set([type]);
        for (const rawDep of imports) {
          ngDevMode && verifyStandaloneImport(rawDep, type);
          const dep = resolveForwardRef(rawDep);
          if (seen.has(dep)) {
            continue;
          }
          seen.add(dep);
          if (!!getNgModuleDef(dep)) {
            const scope = transitiveScopesFor(dep);
            for (const dir of scope.exported.directives) {
              const def = getComponentDef(dir) || getDirectiveDef(dir);
              if (def && !seen.has(dir)) {
                seen.add(dir);
                cachedDirectiveDefs.push(def);
              }
            }
          } else {
            const def = getComponentDef(dep) || getDirectiveDef(dep);
            if (def) {
              cachedDirectiveDefs.push(def);
            }
          }
        }
      }
      return cachedDirectiveDefs;
    } else {
      if (ngDevMode) {
        for (const rawDep of imports) {
          verifyStandaloneImport(rawDep, type);
        }
      }
      if (!isComponent(type)) {
        return [];
      }
      const scope = depsTracker.getStandaloneComponentScope(type, imports);
      return [...scope.compilation.directives].map(p => getComponentDef(p) || getDirectiveDef(p)).filter(d => d !== null);
    }
  };
  const pipeDefs = () => {
    if (!USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
      if (cachedPipeDefs === null) {
        cachedPipeDefs = [];
        const seen = new Set();
        for (const rawDep of imports) {
          const dep = resolveForwardRef(rawDep);
          if (seen.has(dep)) {
            continue;
          }
          seen.add(dep);
          if (!!getNgModuleDef(dep)) {
            const scope = transitiveScopesFor(dep);
            for (const pipe of scope.exported.pipes) {
              const def = getPipeDef$1(pipe);
              if (def && !seen.has(pipe)) {
                seen.add(pipe);
                cachedPipeDefs.push(def);
              }
            }
          } else {
            const def = getPipeDef$1(dep);
            if (def) {
              cachedPipeDefs.push(def);
            }
          }
        }
      }
      return cachedPipeDefs;
    } else {
      if (ngDevMode) {
        for (const rawDep of imports) {
          verifyStandaloneImport(rawDep, type);
        }
      }
      if (!isComponent(type)) {
        return [];
      }
      const scope = depsTracker.getStandaloneComponentScope(type, imports);
      return [...scope.compilation.pipes].map(p => getPipeDef$1(p)).filter(d => d !== null);
    }
  };
  return {
    directiveDefs,
    pipeDefs
  };
}
function hasSelectorScope(component) {
  return component.ngSelectorScope !== undefined;
}
/**
 * Compile an Angular directive according to its decorator metadata, and patch the resulting
 * directive def onto the component type.
 *
 * In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
 * will resolve when compilation completes and the directive becomes usable.
 */
function compileDirective(type, directive) {
  let ngDirectiveDef = null;
  addDirectiveFactoryDef(type, directive || {});
  Object.defineProperty(type, NG_DIR_DEF, {
    get: () => {
      if (ngDirectiveDef === null) {
        // `directive` can be null in the case of abstract directives as a base class
        // that use `@Directive()` with no selector. In that case, pass empty object to the
        // `directiveMetadata` function instead of null.
        const meta = getDirectiveMetadata(type, directive || {});
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'directive',
          type
        });
        ngDirectiveDef = compiler.compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
      }
      return ngDirectiveDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
}
function getDirectiveMetadata(type, metadata) {
  const name = type && type.name;
  const sourceMapUrl = `ng:///${name}/ɵdir.js`;
  const compiler = getCompilerFacade({
    usage: 0 /* JitCompilerUsage.Decorator */,
    kind: 'directive',
    type
  });
  const facade = directiveMetadata(type, metadata);
  facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
  if (facade.usesInheritance) {
    addDirectiveDefToUndecoratedParents(type);
  }
  return {
    metadata: facade,
    sourceMapUrl
  };
}
function addDirectiveFactoryDef(type, metadata) {
  let ngFactoryDef = null;
  Object.defineProperty(type, NG_FACTORY_DEF, {
    get: () => {
      if (ngFactoryDef === null) {
        const meta = getDirectiveMetadata(type, metadata);
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'directive',
          type
        });
        ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, {
          name: meta.metadata.name,
          type: meta.metadata.type,
          typeArgumentCount: 0,
          deps: reflectDependencies(type),
          target: compiler.FactoryTarget.Directive
        });
      }
      return ngFactoryDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
}
function extendsDirectlyFromObject(type) {
  return Object.getPrototypeOf(type.prototype) === Object.prototype;
}
/**
 * Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
 * `Component`).
 */
function directiveMetadata(type, metadata) {
  // Reflect inputs and outputs.
  const reflect = getReflect();
  const propMetadata = reflect.ownPropMetadata(type);
  return {
    name: type.name,
    type: type,
    selector: metadata.selector !== undefined ? metadata.selector : null,
    host: metadata.host || EMPTY_OBJ,
    propMetadata: propMetadata,
    inputs: metadata.inputs || EMPTY_ARRAY,
    outputs: metadata.outputs || EMPTY_ARRAY,
    queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
    lifecycle: {
      usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges')
    },
    typeSourceSpan: null,
    usesInheritance: !extendsDirectlyFromObject(type),
    exportAs: extractExportAs(metadata.exportAs),
    providers: metadata.providers || null,
    viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery),
    isStandalone: metadata.standalone === undefined ? true : !!metadata.standalone,
    isSignal: !!metadata.signals,
    hostDirectives: metadata.hostDirectives?.map(directive => typeof directive === 'function' ? {
      directive
    } : directive) || null
  };
}
/**
 * Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
 */
function addDirectiveDefToUndecoratedParents(type) {
  const objPrototype = Object.prototype;
  let parent = Object.getPrototypeOf(type.prototype).constructor;
  // Go up the prototype until we hit `Object`.
  while (parent && parent !== objPrototype) {
    // Since inheritance works if the class was annotated already, we only need to add
    // the def if there are no annotations and the def hasn't been created already.
    if (!getDirectiveDef(parent) && !getComponentDef(parent) && shouldAddAbstractDirective(parent)) {
      compileDirective(parent, null);
    }
    parent = Object.getPrototypeOf(parent);
  }
}
function convertToR3QueryPredicate(selector) {
  return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
}
function convertToR3QueryMetadata(propertyName, ann) {
  return {
    propertyName: propertyName,
    predicate: convertToR3QueryPredicate(ann.selector),
    descendants: ann.descendants,
    first: ann.first,
    read: ann.read ? ann.read : null,
    static: !!ann.static,
    emitDistinctChangesOnly: !!ann.emitDistinctChangesOnly,
    isSignal: !!ann.isSignal
  };
}
function extractQueriesMetadata(type, propMetadata, isQueryAnn) {
  const queriesMeta = [];
  for (const field in propMetadata) {
    if (propMetadata.hasOwnProperty(field)) {
      const annotations = propMetadata[field];
      annotations.forEach(ann => {
        if (isQueryAnn(ann)) {
          if (!ann.selector) {
            throw new Error(`Can't construct a query for the property "${field}" of ` + `"${stringifyForError(type)}" since the query selector wasn't defined.`);
          }
          if (annotations.some(isInputAnnotation)) {
            throw new Error(`Cannot combine @Input decorators with query decorators`);
          }
          queriesMeta.push(convertToR3QueryMetadata(field, ann));
        }
      });
    }
  }
  return queriesMeta;
}
function extractExportAs(exportAs) {
  return exportAs === undefined ? null : splitByComma(exportAs);
}
function isContentQuery(value) {
  const name = value.ngMetadataName;
  return name === 'ContentChild' || name === 'ContentChildren';
}
function isViewQuery(value) {
  const name = value.ngMetadataName;
  return name === 'ViewChild' || name === 'ViewChildren';
}
function isInputAnnotation(value) {
  return value.ngMetadataName === 'Input';
}
function splitByComma(value) {
  return value.split(',').map(piece => piece.trim());
}
const LIFECYCLE_HOOKS = ['ngOnChanges', 'ngOnInit', 'ngOnDestroy', 'ngDoCheck', 'ngAfterViewInit', 'ngAfterViewChecked', 'ngAfterContentInit', 'ngAfterContentChecked'];
function shouldAddAbstractDirective(type) {
  const reflect = getReflect();
  if (LIFECYCLE_HOOKS.some(hookName => reflect.hasLifecycleHook(type, hookName))) {
    return true;
  }
  const propMetadata = reflect.propMetadata(type);
  for (const field in propMetadata) {
    const annotations = propMetadata[field];
    for (let i = 0; i < annotations.length; i++) {
      const current = annotations[i];
      const metadataName = current.ngMetadataName;
      if (isInputAnnotation(current) || isContentQuery(current) || isViewQuery(current) || metadataName === 'Output' || metadataName === 'HostBinding' || metadataName === 'HostListener') {
        return true;
      }
    }
  }
  return false;
}
function compilePipe(type, meta) {
  let ngPipeDef = null;
  let ngFactoryDef = null;
  Object.defineProperty(type, NG_FACTORY_DEF, {
    get: () => {
      if (ngFactoryDef === null) {
        const metadata = getPipeMetadata(type, meta);
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'pipe',
          type: metadata.type
        });
        ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, {
          name: metadata.name,
          type: metadata.type,
          typeArgumentCount: 0,
          deps: reflectDependencies(type),
          target: compiler.FactoryTarget.Pipe
        });
      }
      return ngFactoryDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
  Object.defineProperty(type, NG_PIPE_DEF, {
    get: () => {
      if (ngPipeDef === null) {
        const metadata = getPipeMetadata(type, meta);
        const compiler = getCompilerFacade({
          usage: 0 /* JitCompilerUsage.Decorator */,
          kind: 'pipe',
          type: metadata.type
        });
        ngPipeDef = compiler.compilePipe(angularCoreEnv, `ng:///${metadata.name}/ɵpipe.js`, metadata);
      }
      return ngPipeDef;
    },
    // Make the property configurable in dev mode to allow overriding in tests
    configurable: !!ngDevMode
  });
}
function getPipeMetadata(type, meta) {
  return {
    type: type,
    name: type.name,
    pipeName: meta.name,
    pure: meta.pure !== undefined ? meta.pure : true,
    isStandalone: meta.standalone === undefined ? true : !!meta.standalone
  };
}

/**
 * Type of the Directive metadata.
 *
 * @publicApi
 */
const Directive = /*#__PURE__*/makeDecorator('Directive', (dir = {}) => dir, undefined, undefined, (type, meta) => compileDirective(type, meta));
/**
 * Component decorator and metadata.
 *
 * @Annotation
 * @publicApi
 */
const Component = /*#__PURE__*/makeDecorator('Component', (c = {}) => ({
  changeDetection: ChangeDetectionStrategy.Default,
  ...c
}), Directive, undefined, (type, meta) => compileComponent(type, meta));
/**
 * @Annotation
 * @publicApi
 */
const Pipe = /*#__PURE__*/makeDecorator('Pipe', p => ({
  pure: true,
  ...p
}), undefined, undefined, (type, meta) => compilePipe(type, meta));
/**
 * @Annotation
 * @publicApi
 */
const Input = /*#__PURE__*/makePropDecorator('Input', arg => {
  if (!arg) {
    return {};
  }
  return typeof arg === 'string' ? {
    alias: arg
  } : arg;
});
/**
 * @Annotation
 * @publicApi
 */
const Output = /*#__PURE__*/makePropDecorator('Output', alias => ({
  alias
}));
/**
 * @Annotation
 * @publicApi
 */
const HostBinding = /*#__PURE__*/makePropDecorator('HostBinding', hostPropertyName => ({
  hostPropertyName
}));
/**
 * @Annotation
 * @publicApi
 */
const HostListener = /*#__PURE__*/makePropDecorator('HostListener', (eventName, args) => ({
  eventName,
  args
}));

/**
 * @Annotation
 */
const NgModule = /*#__PURE__*/makeDecorator('NgModule', ngModule => ngModule, undefined, undefined,
/**
 * Decorator that marks the following class as an NgModule, and supplies
 * configuration metadata for it.
 *
 * * The `declarations` option configures the compiler
 * with information about what belongs to the NgModule.
 * * The `providers` options configures the NgModule's injector to provide
 * dependencies the NgModule members.
 * * The `imports` and `exports` options bring in members from other modules, and make
 * this module's members available to others.
 */
(type, meta) => compileNgModule(type, meta));

/**
 * This indirection is needed to free up Component, etc symbols in the public API
 * to be used by the decorator versions of these annotations.
 */

/**
 * @description Represents the version of Angular
 *
 * @publicApi
 */
class Version {
  full;
  major;
  minor;
  patch;
  constructor(full) {
    this.full = full;
    const parts = full.split('.');
    this.major = parts[0];
    this.minor = parts[1];
    this.patch = parts.slice(2).join('.');
  }
}
/**
 * @publicApi
 */
const VERSION = /*#__PURE__*/new Version('19.0.0');

/**
 * Combination of NgModuleFactory and ComponentFactories.
 *
 * @publicApi
 *
 * @deprecated
 * Ivy JIT mode doesn't require accessing this symbol.
 */
class ModuleWithComponentFactories {
  ngModuleFactory;
  componentFactories;
  constructor(ngModuleFactory, componentFactories) {
    this.ngModuleFactory = ngModuleFactory;
    this.componentFactories = componentFactories;
  }
}
/**
 * Low-level service for running the angular compiler during runtime
 * to create {@link ComponentFactory}s, which
 * can later be used to create and render a Component instance.
 *
 * Each `@NgModule` provides an own `Compiler` to its injector,
 * that will use the directives/pipes of the ng module for compilation
 * of components.
 *
 * @publicApi
 *
 * @deprecated
 * Ivy JIT mode doesn't require accessing this symbol.
 */
let Compiler = /*#__PURE__*/(() => {
  class Compiler {
    /**
     * Compiles the given NgModule and all of its components. All templates of the components
     * have to be inlined.
     */
    compileModuleSync(moduleType) {
      return new NgModuleFactory(moduleType);
    }
    /**
     * Compiles the given NgModule and all of its components
     */
    compileModuleAsync(moduleType) {
      return Promise.resolve(this.compileModuleSync(moduleType));
    }
    /**
     * Same as {@link Compiler#compileModuleSync compileModuleSync} but also creates ComponentFactories for all components.
     */
    compileModuleAndAllComponentsSync(moduleType) {
      const ngModuleFactory = this.compileModuleSync(moduleType);
      const moduleDef = getNgModuleDef(moduleType);
      const componentFactories = maybeUnwrapFn(moduleDef.declarations).reduce((factories, declaration) => {
        const componentDef = getComponentDef(declaration);
        componentDef && factories.push(new ComponentFactory(componentDef));
        return factories;
      }, []);
      return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
    }
    /**
     * Same as {@link Compiler#compileModuleAsync compileModuleAsync} but also creates ComponentFactories for all components.
     */
    compileModuleAndAllComponentsAsync(moduleType) {
      return Promise.resolve(this.compileModuleAndAllComponentsSync(moduleType));
    }
    /**
     * Clears all caches.
     */
    clearCache() {}
    /**
     * Clears the cache for the given component/ngModule.
     */
    clearCacheFor(type) {}
    /**
     * Returns the id for a given NgModule, if one is defined and known to the compiler.
     */
    getModuleId(moduleType) {
      return undefined;
    }
    static ɵfac = function Compiler_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Compiler)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: Compiler,
      factory: Compiler.ɵfac,
      providedIn: 'root'
    }))();
  }
  return Compiler;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Compiler, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], null, null);
})();
/**
 * Token to provide CompilerOptions in the platform injector.
 *
 * @publicApi
 */
const COMPILER_OPTIONS = /*#__PURE__*/new InjectionToken(ngDevMode ? 'compilerOptions' : '');
/**
 * A factory for creating a Compiler
 *
 * @publicApi
 *
 * @deprecated
 * Ivy JIT mode doesn't require accessing this symbol.
 */
class CompilerFactory {}
function compileNgModuleFactory(injector, options, moduleType) {
  ngDevMode && assertNgModuleType(moduleType);
  const moduleFactory = new NgModuleFactory(moduleType);
  // All of the logic below is irrelevant for AOT-compiled code.
  if (typeof ngJitMode !== 'undefined' && !ngJitMode) {
    return Promise.resolve(moduleFactory);
  }
  const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options);
  // Configure the compiler to use the provided options. This call may fail when multiple modules
  // are bootstrapped with incompatible options, as a component can only be compiled according to
  // a single set of options.
  setJitOptions({
    defaultEncapsulation: _lastDefined(compilerOptions.map(opts => opts.defaultEncapsulation)),
    preserveWhitespaces: _lastDefined(compilerOptions.map(opts => opts.preserveWhitespaces))
  });
  if (isComponentResourceResolutionQueueEmpty()) {
    return Promise.resolve(moduleFactory);
  }
  const compilerProviders = compilerOptions.flatMap(option => option.providers ?? []);
  // In case there are no compiler providers, we just return the module factory as
  // there won't be any resource loader. This can happen with Ivy, because AOT compiled
  // modules can be still passed through "bootstrapModule". In that case we shouldn't
  // unnecessarily require the JIT compiler.
  if (compilerProviders.length === 0) {
    return Promise.resolve(moduleFactory);
  }
  const compiler = getCompilerFacade({
    usage: 0 /* JitCompilerUsage.Decorator */,
    kind: 'NgModule',
    type: moduleType
  });
  const compilerInjector = Injector.create({
    providers: compilerProviders
  });
  const resourceLoader = compilerInjector.get(compiler.ResourceLoader);
  // The resource loader can also return a string while the "resolveComponentResources"
  // always expects a promise. Therefore we need to wrap the returned value in a promise.
  return resolveComponentResources(url => Promise.resolve(resourceLoader.get(url))).then(() => moduleFactory);
}
function _lastDefined(args) {
  for (let i = args.length - 1; i >= 0; i--) {
    if (args[i] !== undefined) {
      return args[i];
    }
  }
  return undefined;
}
let NgZoneChangeDetectionScheduler = /*#__PURE__*/(() => {
  class NgZoneChangeDetectionScheduler {
    zone = (() => inject(NgZone))();
    changeDetectionScheduler = (() => inject(ChangeDetectionScheduler))();
    applicationRef = (() => inject(ApplicationRef))();
    _onMicrotaskEmptySubscription;
    initialize() {
      if (this._onMicrotaskEmptySubscription) {
        return;
      }
      this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({
        next: () => {
          // `onMicroTaskEmpty` can happen _during_ the zoneless scheduler change detection because
          // zone.run(() => {}) will result in `checkStable` at the end of the `zone.run` closure
          // and emit `onMicrotaskEmpty` synchronously if run coalsecing is false.
          if (this.changeDetectionScheduler.runningTick) {
            return;
          }
          this.zone.run(() => {
            this.applicationRef.tick();
          });
        }
      });
    }
    ngOnDestroy() {
      this._onMicrotaskEmptySubscription?.unsubscribe();
    }
    static ɵfac = function NgZoneChangeDetectionScheduler_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgZoneChangeDetectionScheduler)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: NgZoneChangeDetectionScheduler,
      factory: NgZoneChangeDetectionScheduler.ɵfac,
      providedIn: 'root'
    }))();
  }
  return NgZoneChangeDetectionScheduler;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(NgZoneChangeDetectionScheduler, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], null, null);
})();
/**
 * Internal token used to verify that `provideZoneChangeDetection` is not used
 * with the bootstrapModule API.
 */
const PROVIDED_NG_ZONE = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '', {
  factory: () => false
});
function internalProvideZoneChangeDetection({
  ngZoneFactory,
  ignoreChangesOutsideZone,
  scheduleInRootZone
}) {
  ngZoneFactory ??= () => new NgZone({
    ...getNgZoneOptions(),
    scheduleInRootZone
  });
  return [{
    provide: NgZone,
    useFactory: ngZoneFactory
  }, {
    provide: ENVIRONMENT_INITIALIZER,
    multi: true,
    useFactory: () => {
      const ngZoneChangeDetectionScheduler = inject(NgZoneChangeDetectionScheduler, {
        optional: true
      });
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && ngZoneChangeDetectionScheduler === null) {
        throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, `A required Injectable was not found in the dependency injection tree. ` + 'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.');
      }
      return () => ngZoneChangeDetectionScheduler.initialize();
    }
  }, {
    provide: ENVIRONMENT_INITIALIZER,
    multi: true,
    useFactory: () => {
      const service = inject(ZoneStablePendingTask);
      return () => {
        service.initialize();
      };
    }
  },
  // Always disable scheduler whenever explicitly disabled, even if another place called
  // `provideZoneChangeDetection` without the 'ignore' option.
  ignoreChangesOutsideZone === true ? {
    provide: ZONELESS_SCHEDULER_DISABLED,
    useValue: true
  } : [], {
    provide: SCHEDULE_IN_ROOT_ZONE,
    useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT
  }];
}
/**
 * Provides `NgZone`-based change detection for the application bootstrapped using
 * `bootstrapApplication`.
 *
 * `NgZone` is already provided in applications by default. This provider allows you to configure
 * options like `eventCoalescing` in the `NgZone`.
 * This provider is not available for `platformBrowser().bootstrapModule`, which uses
 * `BootstrapOptions` instead.
 *
 * @usageNotes
 * ```typescript
 * bootstrapApplication(MyApp, {providers: [
 *   provideZoneChangeDetection({eventCoalescing: true}),
 * ]});
 * ```
 *
 * @publicApi
 * @see {@link bootstrapApplication}
 * @see {@link NgZoneOptions}
 */
function provideZoneChangeDetection(options) {
  const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
  const scheduleInRootZone = options?.scheduleInRootZone;
  const zoneProviders = internalProvideZoneChangeDetection({
    ngZoneFactory: () => {
      const ngZoneOptions = getNgZoneOptions(options);
      ngZoneOptions.scheduleInRootZone = scheduleInRootZone;
      if (ngZoneOptions.shouldCoalesceEventChangeDetection) {
        performanceMarkFeature('NgZone_CoalesceEvent');
      }
      return new NgZone(ngZoneOptions);
    },
    ignoreChangesOutsideZone,
    scheduleInRootZone
  });
  return makeEnvironmentProviders([{
    provide: PROVIDED_NG_ZONE,
    useValue: true
  }, {
    provide: ZONELESS_ENABLED,
    useValue: false
  }, zoneProviders]);
}
// Transforms a set of `BootstrapOptions` (supported by the NgModule-based bootstrap APIs) ->
// `NgZoneOptions` that are recognized by the NgZone constructor. Passing no options will result in
// a set of default options returned.
function getNgZoneOptions(options) {
  return {
    enableLongStackTrace: typeof ngDevMode === 'undefined' ? false : !!ngDevMode,
    shouldCoalesceEventChangeDetection: options?.eventCoalescing ?? false,
    shouldCoalesceRunChangeDetection: options?.runCoalescing ?? false
  };
}
let ZoneStablePendingTask = /*#__PURE__*/(() => {
  class ZoneStablePendingTask {
    subscription = (() => new rxjs__WEBPACK_IMPORTED_MODULE_4__.Subscription())();
    initialized = false;
    zone = (() => inject(NgZone))();
    pendingTasks = (() => inject(PendingTasksInternal))();
    initialize() {
      if (this.initialized) {
        return;
      }
      this.initialized = true;
      let task = null;
      if (!this.zone.isStable && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks) {
        task = this.pendingTasks.add();
      }
      this.zone.runOutsideAngular(() => {
        this.subscription.add(this.zone.onStable.subscribe(() => {
          NgZone.assertNotInAngularZone();
          // Check whether there are no pending macro/micro tasks in the next tick
          // to allow for NgZone to update the state.
          queueMicrotask(() => {
            if (task !== null && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks) {
              this.pendingTasks.remove(task);
              task = null;
            }
          });
        }));
      });
      this.subscription.add(this.zone.onUnstable.subscribe(() => {
        NgZone.assertInAngularZone();
        task ??= this.pendingTasks.add();
      }));
    }
    ngOnDestroy() {
      this.subscription.unsubscribe();
    }
    static ɵfac = function ZoneStablePendingTask_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ZoneStablePendingTask)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: ZoneStablePendingTask,
      factory: ZoneStablePendingTask.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ZoneStablePendingTask;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ZoneStablePendingTask, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], null, null);
})();
const CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT = 100;
let consecutiveMicrotaskNotifications = 0;
let stackFromLastFewNotifications = [];
function trackMicrotaskNotificationForDebugging() {
  consecutiveMicrotaskNotifications++;
  if (CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT - consecutiveMicrotaskNotifications < 5) {
    const stack = new Error().stack;
    if (stack) {
      stackFromLastFewNotifications.push(stack);
    }
  }
  if (consecutiveMicrotaskNotifications === CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT) {
    throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, 'Angular could not stabilize because there were endless change notifications within the browser event loop. ' + 'The stack from the last several notifications: \n' + stackFromLastFewNotifications.join('\n'));
  }
}
let ChangeDetectionSchedulerImpl = /*#__PURE__*/(() => {
  class ChangeDetectionSchedulerImpl {
    appRef = (() => inject(ApplicationRef))();
    taskService = (() => inject(PendingTasksInternal))();
    ngZone = (() => inject(NgZone))();
    zonelessEnabled = (() => inject(ZONELESS_ENABLED))();
    disableScheduling = (() => inject(ZONELESS_SCHEDULER_DISABLED, {
      optional: true
    }) ?? false)();
    zoneIsDefined = (() => typeof Zone !== 'undefined' && !!Zone.root.run)();
    schedulerTickApplyArgs = [{
      data: {
        '__scheduler_tick__': true
      }
    }];
    subscriptions = (() => new rxjs__WEBPACK_IMPORTED_MODULE_4__.Subscription())();
    angularZoneId = (() => this.zoneIsDefined ? this.ngZone._inner?.get(angularZoneInstanceIdProperty) : null)();
    scheduleInRootZone = (() => !this.zonelessEnabled && this.zoneIsDefined && (inject(SCHEDULE_IN_ROOT_ZONE, {
      optional: true
    }) ?? false))();
    cancelScheduledCallback = null;
    useMicrotaskScheduler = false;
    runningTick = false;
    pendingRenderTaskId = null;
    constructor() {
      this.subscriptions.add(this.appRef.afterTick.subscribe(() => {
        // If the scheduler isn't running a tick but the application ticked, that means
        // someone called ApplicationRef.tick manually. In this case, we should cancel
        // any change detections that had been scheduled so we don't run an extra one.
        if (!this.runningTick) {
          this.cleanup();
        }
      }));
      this.subscriptions.add(this.ngZone.onUnstable.subscribe(() => {
        // If the zone becomes unstable when we're not running tick (this happens from the zone.run),
        // we should cancel any scheduled change detection here because at this point we
        // know that the zone will stabilize at some point and run change detection itself.
        if (!this.runningTick) {
          this.cleanup();
        }
      }));
      // TODO(atscott): These conditions will need to change when zoneless is the default
      // Instead, they should flip to checking if ZoneJS scheduling is provided
      this.disableScheduling ||= !this.zonelessEnabled && (
      // NoopNgZone without enabling zoneless means no scheduling whatsoever
      this.ngZone instanceof NoopNgZone ||
      // The same goes for the lack of Zone without enabling zoneless scheduling
      !this.zoneIsDefined);
    }
    notify(source) {
      if (!this.zonelessEnabled && source === 5 /* NotificationSource.Listener */) {
        // When the notification comes from a listener, we skip the notification unless the
        // application has enabled zoneless. Ideally, listeners wouldn't notify the scheduler at all
        // automatically. We do not know that a developer made a change in the listener callback that
        // requires an `ApplicationRef.tick` (synchronize templates / run render hooks). We do this
        // only for an easier migration from OnPush components to zoneless. Because listeners are
        // usually executed inside the Angular zone and listeners automatically call `markViewDirty`,
        // developers never needed to manually use `ChangeDetectorRef.markForCheck` or some other API
        // to make listener callbacks work correctly with `OnPush` components.
        return;
      }
      let force = false;
      switch (source) {
        case 0 /* NotificationSource.MarkAncestorsForTraversal */:
          {
            this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
            break;
          }
        case 3 /* NotificationSource.DebugApplyChanges */:
        case 2 /* NotificationSource.DeferBlockStateUpdate */:
        case 4 /* NotificationSource.MarkForCheck */:
        case 5 /* NotificationSource.Listener */:
        case 1 /* NotificationSource.SetInput */:
          {
            this.appRef.dirtyFlags |= 4 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
            break;
          }
        case 8 /* NotificationSource.DeferredRenderHook */:
          {
            // Render hooks are "deferred" when they're triggered from other render hooks. Using the
            // deferred dirty flags ensures that adding new hooks doesn't automatically trigger a loop
            // inside tick().
            this.appRef.deferredDirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
            break;
          }
        case 6 /* NotificationSource.CustomElement */:
          {
            // We use `ViewTreeTraversal` to ensure we refresh the element even if this is triggered
            // during CD. In practice this is a no-op since the elements code also calls via a
            // `markForRefresh()` API which sends `NotificationSource.MarkAncestorsForTraversal` anyway.
            this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
            force = true;
            break;
          }
        case 13 /* NotificationSource.RootEffect */:
          {
            this.appRef.dirtyFlags |= 16 /* ApplicationRefDirtyFlags.RootEffects */;
            // Root effects still force a CD, even if the scheduler is disabled. This ensures that
            // effects always run, even when triggered from outside the zone when the scheduler is
            // otherwise disabled.
            force = true;
            break;
          }
        case 14 /* NotificationSource.ViewEffect */:
          {
            // This is technically a no-op, since view effects will also send a
            // `MarkAncestorsForTraversal` notification. Still, we set this for logical consistency.
            this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
            // View effects still force a CD, even if the scheduler is disabled. This ensures that
            // effects always run, even when triggered from outside the zone when the scheduler is
            // otherwise disabled.
            force = true;
            break;
          }
        case 12 /* NotificationSource.PendingTaskRemoved */:
          {
            // Removing a pending task via the public API forces a scheduled tick, ensuring that
            // stability is async and delayed until there was at least an opportunity to run
            // application synchronization. This prevents some footguns when working with the
            // public API for pending tasks where developers attempt to update application state
            // immediately after removing the last task.
            force = true;
            break;
          }
        case 10 /* NotificationSource.ViewDetachedFromDOM */:
        case 9 /* NotificationSource.ViewAttached */:
        case 7 /* NotificationSource.RenderHook */:
        case 11 /* NotificationSource.AsyncAnimationsLoaded */:
        default:
          {
            // These notifications only schedule a tick but do not change whether we should refresh
            // views. Instead, we only need to run render hooks unless another notification from the
            // other set is also received before `tick` happens.
            this.appRef.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
          }
      }
      if (!this.shouldScheduleTick(force)) {
        return;
      }
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        if (this.useMicrotaskScheduler) {
          trackMicrotaskNotificationForDebugging();
        } else {
          consecutiveMicrotaskNotifications = 0;
          stackFromLastFewNotifications.length = 0;
        }
      }
      const scheduleCallback = this.useMicrotaskScheduler ? scheduleCallbackWithMicrotask : scheduleCallbackWithRafRace;
      this.pendingRenderTaskId = this.taskService.add();
      if (this.scheduleInRootZone) {
        this.cancelScheduledCallback = Zone.root.run(() => scheduleCallback(() => this.tick()));
      } else {
        this.cancelScheduledCallback = this.ngZone.runOutsideAngular(() => scheduleCallback(() => this.tick()));
      }
    }
    shouldScheduleTick(force) {
      if (this.disableScheduling && !force || this.appRef.destroyed) {
        return false;
      }
      // already scheduled or running
      if (this.pendingRenderTaskId !== null || this.runningTick || this.appRef._runningTick) {
        return false;
      }
      // If we're inside the zone don't bother with scheduler. Zone will stabilize
      // eventually and run change detection.
      if (!this.zonelessEnabled && this.zoneIsDefined && Zone.current.get(angularZoneInstanceIdProperty + this.angularZoneId)) {
        return false;
      }
      return true;
    }
    /**
     * Calls ApplicationRef._tick inside the `NgZone`.
     *
     * Calling `tick` directly runs change detection and cancels any change detection that had been
     * scheduled previously.
     *
     * @param shouldRefreshViews Passed directly to `ApplicationRef._tick` and skips straight to
     *     render hooks when `false`.
     */
    tick() {
      // When ngZone.run below exits, onMicrotaskEmpty may emit if the zone is
      // stable. We want to prevent double ticking so we track whether the tick is
      // already running and skip it if so.
      if (this.runningTick || this.appRef.destroyed) {
        return;
      }
      // If we reach the tick and there is no work to be done in ApplicationRef.tick,
      // skip it altogether and clean up. There may be no work if, for example, the only
      // event that notified the scheduler was the removal of a pending task.
      if (this.appRef.dirtyFlags === 0 /* ApplicationRefDirtyFlags.None */) {
        this.cleanup();
        return;
      }
      // The scheduler used to pass "whether to check views" as a boolean flag instead of setting
      // fine-grained dirtiness flags, and global checking was always used on the first pass. This
      // created an interesting edge case: if a notification made a view dirty and then ticked via the
      // scheduler (and not the zone) a global check was still performed.
      //
      // Ideally, this would not be the case, and only zone-based ticks would do global passes.
      // However this is a breaking change and requires fixes in g3. Until this cleanup can be done,
      // we add the `ViewTreeGlobal` flag to request a global check if any views are dirty in a
      // scheduled tick (unless zoneless is enabled, in which case global checks aren't really a
      // thing).
      //
      // TODO(alxhub): clean up and remove this workaround as a breaking change.
      if (!this.zonelessEnabled && this.appRef.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
        this.appRef.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
      }
      const task = this.taskService.add();
      try {
        this.ngZone.run(() => {
          this.runningTick = true;
          this.appRef._tick();
        }, undefined, this.schedulerTickApplyArgs);
      } catch (e) {
        this.taskService.remove(task);
        throw e;
      } finally {
        this.cleanup();
      }
      // If we're notified of a change within 1 microtask of running change
      // detection, run another round in the same event loop. This allows code
      // which uses Promise.resolve (see NgModel) to avoid
      // ExpressionChanged...Error to still be reflected in a single browser
      // paint, even if that spans multiple rounds of change detection.
      this.useMicrotaskScheduler = true;
      scheduleCallbackWithMicrotask(() => {
        this.useMicrotaskScheduler = false;
        this.taskService.remove(task);
      });
    }
    ngOnDestroy() {
      this.subscriptions.unsubscribe();
      this.cleanup();
    }
    cleanup() {
      this.runningTick = false;
      this.cancelScheduledCallback?.();
      this.cancelScheduledCallback = null;
      // If this is the last task, the service will synchronously emit a stable
      // notification. If there is a subscriber that then acts in a way that
      // tries to notify the scheduler again, we need to be able to respond to
      // schedule a new change detection. Therefore, we should clear the task ID
      // before removing it from the pending tasks (or the tasks service should
      // not synchronously emit stable, similar to how Zone stableness only
      // happens if it's still stable after a microtask).
      if (this.pendingRenderTaskId !== null) {
        const taskId = this.pendingRenderTaskId;
        this.pendingRenderTaskId = null;
        this.taskService.remove(taskId);
      }
    }
    static ɵfac = function ChangeDetectionSchedulerImpl_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ChangeDetectionSchedulerImpl)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: ChangeDetectionSchedulerImpl,
      factory: ChangeDetectionSchedulerImpl.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ChangeDetectionSchedulerImpl;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ChangeDetectionSchedulerImpl, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], () => [], null);
})();
/**
 * Provides change detection without ZoneJS for the application bootstrapped using
 * `bootstrapApplication`.
 *
 * This function allows you to configure the application to not use the state/state changes of
 * ZoneJS to schedule change detection in the application. This will work when ZoneJS is not present
 * on the page at all or if it exists because something else is using it (either another Angular
 * application which uses ZoneJS for scheduling or some other library that relies on ZoneJS).
 *
 * This can also be added to the `TestBed` providers to configure the test environment to more
 * closely match production behavior. This will help give higher confidence that components are
 * compatible with zoneless change detection.
 *
 * ZoneJS uses browser events to trigger change detection. When using this provider, Angular will
 * instead use Angular APIs to schedule change detection. These APIs include:
 *
 * - `ChangeDetectorRef.markForCheck`
 * - `ComponentRef.setInput`
 * - updating a signal that is read in a template
 * - when bound host or template listeners are triggered
 * - attaching a view that was marked dirty by one of the above
 * - removing a view
 * - registering a render hook (templates are only refreshed if render hooks do one of the above)
 *
 * @usageNotes
 * ```typescript
 * bootstrapApplication(MyApp, {providers: [
 *   provideExperimentalZonelessChangeDetection(),
 * ]});
 * ```
 *
 * This API is experimental. Neither the shape, nor the underlying behavior is stable and can change
 * in patch versions. There are known feature gaps and API ergonomic considerations. We will iterate
 * on the exact API based on the feedback and our understanding of the problem and solution space.
 *
 * @publicApi
 * @experimental
 * @see [bootstrapApplication](/api/platform-browser/bootstrapApplication)
 */
function provideExperimentalZonelessChangeDetection() {
  performanceMarkFeature('NgZoneless');
  if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) {
    const message = formatRuntimeError(914 /* RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE */, `The application is using zoneless change detection, but is still loading Zone.js. ` + `Consider removing Zone.js to get the full benefits of zoneless. ` + `In applications using the Angular CLI, Zone.js is typically included in the "polyfills" section of the angular.json file.`);
    console.warn(message);
  }
  return makeEnvironmentProviders([{
    provide: ChangeDetectionScheduler,
    useExisting: ChangeDetectionSchedulerImpl
  }, {
    provide: NgZone,
    useClass: NoopNgZone
  }, {
    provide: ZONELESS_ENABLED,
    useValue: true
  }, {
    provide: SCHEDULE_IN_ROOT_ZONE,
    useValue: false
  }, typeof ngDevMode === 'undefined' || ngDevMode ? [{
    provide: PROVIDED_ZONELESS,
    useValue: true
  }] : []]);
}

/**
 * Work out the locale from the potential global properties.
 *
 * * Closure Compiler: use `goog.LOCALE`.
 * * Ivy enabled: use `$localize.locale`
 */
function getGlobalLocale() {
  if (typeof ngI18nClosureMode !== 'undefined' && ngI18nClosureMode && typeof goog !== 'undefined' && goog.LOCALE !== 'en') {
    // * The default `goog.LOCALE` value is `en`, while Angular used `en-US`.
    // * In order to preserve backwards compatibility, we use Angular default value over
    //   Closure Compiler's one.
    return goog.LOCALE;
  } else {
    // KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE
    // COMPILE-TIME INLINER.
    //
    // * During compile time inlining of translations the expression will be replaced
    //   with a string literal that is the current locale. Other forms of this expression are not
    //   guaranteed to be replaced.
    //
    // * During runtime translation evaluation, the developer is required to set `$localize.locale`
    //   if required, or just to provide their own `LOCALE_ID` provider.
    return typeof $localize !== 'undefined' && $localize.locale || DEFAULT_LOCALE_ID;
  }
}
/**
 * Provide this token to set the locale of your application.
 * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
 * DecimalPipe and PercentPipe) and by ICU expressions.
 *
 * See the [i18n guide](guide/i18n/locale-id) for more information.
 *
 * @usageNotes
 * ### Example
 *
 * ```typescript
 * import { LOCALE_ID } from '@angular/core';
 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 * import { AppModule } from './app/app.module';
 *
 * platformBrowserDynamic().bootstrapModule(AppModule, {
 *   providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
 * });
 * ```
 *
 * @publicApi
 */
const LOCALE_ID = /*#__PURE__*/new InjectionToken(ngDevMode ? 'LocaleId' : '', {
  providedIn: 'root',
  factory: () => inject(LOCALE_ID, InjectFlags.Optional | InjectFlags.SkipSelf) || getGlobalLocale()
});
/**
 * Provide this token to set the default currency code your application uses for
 * CurrencyPipe when there is no currency code passed into it. This is only used by
 * CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured.
 *
 * See the [i18n guide](guide/i18n/locale-id) for more information.
 *
 * <div class="alert is-helpful">
 *
 * **Deprecation notice:**
 *
 * The default currency code is currently always `USD` but this is deprecated from v9.
 *
 * **In v10 the default currency code will be taken from the current locale.**
 *
 * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
 * your application `NgModule`:
 *
 * ```ts
 * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
 * ```
 *
 * </div>
 *
 * @usageNotes
 * ### Example
 *
 * ```typescript
 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 * import { AppModule } from './app/app.module';
 *
 * platformBrowserDynamic().bootstrapModule(AppModule, {
 *   providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }]
 * });
 * ```
 *
 * @publicApi
 */
const DEFAULT_CURRENCY_CODE = /*#__PURE__*/new InjectionToken(ngDevMode ? 'DefaultCurrencyCode' : '', {
  providedIn: 'root',
  factory: () => USD_CURRENCY_CODE
});
/**
 * Use this token at bootstrap to provide the content of your translation file (`xtb`,
 * `xlf` or `xlf2`) when you want to translate your application in another language.
 *
 * See the [i18n guide](guide/i18n/merge) for more information.
 *
 * @usageNotes
 * ### Example
 *
 * ```typescript
 * import { TRANSLATIONS } from '@angular/core';
 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 * import { AppModule } from './app/app.module';
 *
 * // content of your translation file
 * const translations = '....';
 *
 * platformBrowserDynamic().bootstrapModule(AppModule, {
 *   providers: [{provide: TRANSLATIONS, useValue: translations }]
 * });
 * ```
 *
 * @publicApi
 */
const TRANSLATIONS = /*#__PURE__*/new InjectionToken(ngDevMode ? 'Translations' : '');
/**
 * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`,
 * `xlf` or `xlf2`.
 *
 * See the [i18n guide](guide/i18n/merge) for more information.
 *
 * @usageNotes
 * ### Example
 *
 * ```typescript
 * import { TRANSLATIONS_FORMAT } from '@angular/core';
 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 * import { AppModule } from './app/app.module';
 *
 * platformBrowserDynamic().bootstrapModule(AppModule, {
 *   providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
 * });
 * ```
 *
 * @publicApi
 */
const TRANSLATIONS_FORMAT = /*#__PURE__*/new InjectionToken(ngDevMode ? 'TranslationsFormat' : '');
/**
 * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy
 * that the compiler should use in case of missing translations:
 * - Error: throw if you have missing translations.
 * - Warning (default): show a warning in the console and/or shell.
 * - Ignore: do nothing.
 *
 * See the [i18n guide](guide/i18n/merge#report-missing-translations) for more information.
 *
 * @usageNotes
 * ### Example
 * ```typescript
 * import { MissingTranslationStrategy } from '@angular/core';
 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 * import { AppModule } from './app/app.module';
 *
 * platformBrowserDynamic().bootstrapModule(AppModule, {
 *   missingTranslation: MissingTranslationStrategy.Error
 * });
 * ```
 *
 * @publicApi
 */
var MissingTranslationStrategy = /*#__PURE__*/function (MissingTranslationStrategy) {
  MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  return MissingTranslationStrategy;
}(MissingTranslationStrategy || {});
// A delay in milliseconds before the scan is run after onLoad, to avoid any
// potential race conditions with other LCP-related functions. This delay
// happens outside of the main JavaScript execution and will only effect the timing
// on when the warning becomes visible in the console.
const SCAN_DELAY = 200;
const OVERSIZED_IMAGE_TOLERANCE = 1200;
let ImagePerformanceWarning = /*#__PURE__*/(() => {
  class ImagePerformanceWarning {
    // Map of full image URLs -> original `ngSrc` values.
    window = null;
    observer = null;
    options = (() => inject(IMAGE_CONFIG))();
    isBrowser = (() => inject(PLATFORM_ID) === 'browser')();
    lcpImageUrl;
    start() {
      if (!this.isBrowser || typeof PerformanceObserver === 'undefined' || this.options?.disableImageSizeWarning && this.options?.disableImageLazyLoadWarning) {
        return;
      }
      this.observer = this.initPerformanceObserver();
      const doc = getDocument();
      const win = doc.defaultView;
      if (typeof win !== 'undefined') {
        this.window = win;
        // Wait to avoid race conditions where LCP image triggers
        // load event before it's recorded by the performance observer
        const waitToScan = () => {
          setTimeout(this.scanImages.bind(this), SCAN_DELAY);
        };
        const setup = () => {
          // Consider the case when the application is created and destroyed multiple times.
          // Typically, applications are created instantly once the page is loaded, and the
          // `window.load` listener is always triggered. However, the `window.load` event will never
          // be fired if the page is loaded, and the application is created later. Checking for
          // `readyState` is the easiest way to determine whether the page has been loaded or not.
          if (doc.readyState === 'complete') {
            waitToScan();
          } else {
            this.window?.addEventListener('load', waitToScan, {
              once: true
            });
          }
        };
        // Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
        // the scope of this functionality.
        if (typeof Zone !== 'undefined') {
          Zone.root.run(() => setup());
        } else {
          setup();
        }
      }
    }
    ngOnDestroy() {
      this.observer?.disconnect();
    }
    initPerformanceObserver() {
      if (typeof PerformanceObserver === 'undefined') {
        return null;
      }
      const observer = new PerformanceObserver(entryList => {
        const entries = entryList.getEntries();
        if (entries.length === 0) return;
        // We use the latest entry produced by the `PerformanceObserver` as the best
        // signal on which element is actually an LCP one. As an example, the first image to load on
        // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
        // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
        const lcpElement = entries[entries.length - 1];
        // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
        // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
        const imgSrc = lcpElement.element?.src ?? '';
        // Exclude `data:` and `blob:` URLs, since they are fetched resources.
        if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:')) return;
        this.lcpImageUrl = imgSrc;
      });
      observer.observe({
        type: 'largest-contentful-paint',
        buffered: true
      });
      return observer;
    }
    scanImages() {
      const images = getDocument().querySelectorAll('img');
      let lcpElementFound,
        lcpElementLoadedCorrectly = false;
      images.forEach(image => {
        if (!this.options?.disableImageSizeWarning) {
          // Image elements using the NgOptimizedImage directive are excluded,
          // as that directive has its own version of this check.
          if (!image.getAttribute('ng-img') && this.isOversized(image)) {
            logOversizedImageWarning(image.src);
          }
        }
        if (!this.options?.disableImageLazyLoadWarning && this.lcpImageUrl) {
          if (image.src === this.lcpImageUrl) {
            lcpElementFound = true;
            if (image.loading !== 'lazy' || image.getAttribute('ng-img')) {
              // This variable is set to true and never goes back to false to account
              // for the case where multiple images have the same src url, and some
              // have lazy loading while others don't.
              // Also ignore NgOptimizedImage because there's a different warning for that.
              lcpElementLoadedCorrectly = true;
            }
          }
        }
      });
      if (lcpElementFound && !lcpElementLoadedCorrectly && this.lcpImageUrl && !this.options?.disableImageLazyLoadWarning) {
        logLazyLCPWarning(this.lcpImageUrl);
      }
    }
    isOversized(image) {
      if (!this.window) {
        return false;
      }
      // The `isOversized` check may not be applicable or may require adjustments
      // for several types of image formats or scenarios. Currently, we specify only
      // `svg`, but this may also include `gif` since their quality isn’t tied to
      // dimensions in the same way as raster images.
      const nonOversizedImageExtentions = [
      // SVG images are vector-based, which means they can scale
      // to any size without losing quality.
      '.svg'];
      // Convert it to lowercase because this may have uppercase
      // extensions, such as `IMAGE.SVG`.
      // We fallback to an empty string because `src` may be `undefined`
      // if it is explicitly set to `null` by some third-party code
      // (e.g., `image.src = null`).
      const imageSource = (image.src || '').toLowerCase();
      if (nonOversizedImageExtentions.some(extension => imageSource.endsWith(extension))) {
        return false;
      }
      const computedStyle = this.window.getComputedStyle(image);
      let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
      let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
      const boxSizing = computedStyle.getPropertyValue('box-sizing');
      const objectFit = computedStyle.getPropertyValue('object-fit');
      if (objectFit === `cover`) {
        // Object fit cover may indicate a use case such as a sprite sheet where
        // this warning does not apply.
        return false;
      }
      if (boxSizing === 'border-box') {
        // If the image `box-sizing` is set to `border-box`, we adjust the rendered
        // dimensions by subtracting padding values.
        const paddingTop = computedStyle.getPropertyValue('padding-top');
        const paddingRight = computedStyle.getPropertyValue('padding-right');
        const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
        const paddingLeft = computedStyle.getPropertyValue('padding-left');
        renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
        renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
      }
      const intrinsicWidth = image.naturalWidth;
      const intrinsicHeight = image.naturalHeight;
      const recommendedWidth = this.window.devicePixelRatio * renderedWidth;
      const recommendedHeight = this.window.devicePixelRatio * renderedHeight;
      const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
      const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
      return oversizedWidth || oversizedHeight;
    }
    static ɵfac = function ImagePerformanceWarning_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ImagePerformanceWarning)();
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: ImagePerformanceWarning,
      factory: ImagePerformanceWarning.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ImagePerformanceWarning;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ImagePerformanceWarning, [{
    type: Injectable,
    args: [{
      providedIn: 'root'
    }]
  }], null, null);
})();
function logLazyLCPWarning(src) {
  console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} is the Largest Contentful Paint (LCP) element ` + `but was given a "loading" value of "lazy", which can negatively impact ` + `application loading performance. This warning can be addressed by ` + `changing the loading value of the LCP image to "eager", or by using the ` + `NgOptimizedImage directive's prioritization utilities. For more ` + `information about addressing or disabling this warning, see ` + `https://angular.dev/errors/NG0913`));
}
function logOversizedImageWarning(src) {
  console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} has intrinsic file dimensions much larger than its ` + `rendered size. This can negatively impact application loading performance. ` + `For more information about addressing or disabling this warning, see ` + `https://angular.dev/errors/NG0913`));
}

/**
 * Internal token that allows to register extra callbacks that should be invoked during the
 * `PlatformRef.destroy` operation. This token is needed to avoid a direct reference to the
 * `PlatformRef` class (i.e. register the callback via `PlatformRef.onDestroy`), thus making the
 * entire class tree-shakeable.
 */
const PLATFORM_DESTROY_LISTENERS = /*#__PURE__*/new InjectionToken(ngDevMode ? 'PlatformDestroyListeners' : '');
function isApplicationBootstrapConfig(config) {
  return !config.moduleRef;
}
function bootstrap(config) {
  const envInjector = isApplicationBootstrapConfig(config) ? config.r3Injector : config.moduleRef.injector;
  const ngZone = envInjector.get(NgZone);
  return ngZone.run(() => {
    if (isApplicationBootstrapConfig(config)) {
      config.r3Injector.resolveInjectorInitializers();
    } else {
      config.moduleRef.resolveInjectorInitializers();
    }
    const exceptionHandler = envInjector.get(ErrorHandler, null);
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      if (exceptionHandler === null) {
        const errorMessage = isApplicationBootstrapConfig(config) ? 'No `ErrorHandler` found in the Dependency Injection tree.' : 'No ErrorHandler. Is platform module (BrowserModule) included';
        throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, errorMessage);
      }
      if (envInjector.get(PROVIDED_ZONELESS) && envInjector.get(PROVIDED_NG_ZONE)) {
        throw new RuntimeError(408 /* RuntimeErrorCode.PROVIDED_BOTH_ZONE_AND_ZONELESS */, 'Invalid change detection configuration: ' + 'provideZoneChangeDetection and provideExperimentalZonelessChangeDetection cannot be used together.');
      }
    }
    let onErrorSubscription;
    ngZone.runOutsideAngular(() => {
      onErrorSubscription = ngZone.onError.subscribe({
        next: error => {
          exceptionHandler.handleError(error);
        }
      });
    });
    // If the whole platform is destroyed, invoke the `destroy` method
    // for all bootstrapped applications as well.
    if (isApplicationBootstrapConfig(config)) {
      const destroyListener = () => envInjector.destroy();
      const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
      onPlatformDestroyListeners.add(destroyListener);
      envInjector.onDestroy(() => {
        onErrorSubscription.unsubscribe();
        onPlatformDestroyListeners.delete(destroyListener);
      });
    } else {
      const destroyListener = () => config.moduleRef.destroy();
      const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
      onPlatformDestroyListeners.add(destroyListener);
      config.moduleRef.onDestroy(() => {
        remove(config.allPlatformModules, config.moduleRef);
        onErrorSubscription.unsubscribe();
        onPlatformDestroyListeners.delete(destroyListener);
      });
    }
    return _callAndReportToErrorHandler(exceptionHandler, ngZone, () => {
      const initStatus = envInjector.get(ApplicationInitStatus);
      initStatus.runInitializers();
      return initStatus.donePromise.then(() => {
        // If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
        const localeId = envInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
        setLocaleId(localeId || DEFAULT_LOCALE_ID);
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          const imagePerformanceService = envInjector.get(ImagePerformanceWarning);
          imagePerformanceService.start();
        }
        if (isApplicationBootstrapConfig(config)) {
          const appRef = envInjector.get(ApplicationRef);
          if (config.rootComponent !== undefined) {
            appRef.bootstrap(config.rootComponent);
          }
          return appRef;
        } else {
          moduleDoBootstrap(config.moduleRef, config.allPlatformModules);
          return config.moduleRef;
        }
      });
    });
  });
}
function moduleDoBootstrap(moduleRef, allPlatformModules) {
  const appRef = moduleRef.injector.get(ApplicationRef);
  if (moduleRef._bootstrapComponents.length > 0) {
    moduleRef._bootstrapComponents.forEach(f => appRef.bootstrap(f));
  } else if (moduleRef.instance.ngDoBootstrap) {
    moduleRef.instance.ngDoBootstrap(appRef);
  } else {
    throw new RuntimeError(-403 /* RuntimeErrorCode.BOOTSTRAP_COMPONENTS_NOT_FOUND */, ngDevMode && `The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, ` + `but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` + `Please define one of these.`);
  }
  allPlatformModules.push(moduleRef);
}

/**
 * The Angular platform is the entry point for Angular on a web page.
 * Each page has exactly one platform. Services (such as reflection) which are common
 * to every Angular application running on the page are bound in its scope.
 * A page's platform is initialized implicitly when a platform is created using a platform
 * factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function.
 *
 * @publicApi
 */
let PlatformRef = /*#__PURE__*/(() => {
  class PlatformRef {
    _injector;
    _modules = [];
    _destroyListeners = [];
    _destroyed = false;
    /** @internal */
    constructor(_injector) {
      this._injector = _injector;
    }
    /**
     * Creates an instance of an `@NgModule` for the given platform.
     *
     * @deprecated Passing NgModule factories as the `PlatformRef.bootstrapModuleFactory` function
     *     argument is deprecated. Use the `PlatformRef.bootstrapModule` API instead.
     */
    bootstrapModuleFactory(moduleFactory, options) {
      const scheduleInRootZone = options?.scheduleInRootZone;
      const ngZoneFactory = () => getNgZone(options?.ngZone, {
        ...getNgZoneOptions({
          eventCoalescing: options?.ngZoneEventCoalescing,
          runCoalescing: options?.ngZoneRunCoalescing
        }),
        scheduleInRootZone
      });
      const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
      const allAppProviders = [internalProvideZoneChangeDetection({
        ngZoneFactory,
        ignoreChangesOutsideZone
      }), {
        provide: ChangeDetectionScheduler,
        useExisting: ChangeDetectionSchedulerImpl
      }];
      const moduleRef = createNgModuleRefWithProviders(moduleFactory.moduleType, this.injector, allAppProviders);
      return bootstrap({
        moduleRef,
        allPlatformModules: this._modules,
        platformInjector: this.injector
      });
    }
    /**
     * Creates an instance of an `@NgModule` for a given platform.
     *
     * @usageNotes
     * ### Simple Example
     *
     * ```typescript
     * @NgModule({
     *   imports: [BrowserModule]
     * })
     * class MyModule {}
     *
     * let moduleRef = platformBrowser().bootstrapModule(MyModule);
     * ```
     *
     */
    bootstrapModule(moduleType, compilerOptions = []) {
      const options = optionsReducer({}, compilerOptions);
      return compileNgModuleFactory(this.injector, options, moduleType).then(moduleFactory => this.bootstrapModuleFactory(moduleFactory, options));
    }
    /**
     * Registers a listener to be called when the platform is destroyed.
     */
    onDestroy(callback) {
      this._destroyListeners.push(callback);
    }
    /**
     * Retrieves the platform {@link Injector}, which is the parent injector for
     * every Angular application on the page and provides singleton providers.
     */
    get injector() {
      return this._injector;
    }
    /**
     * Destroys the current Angular platform and all Angular applications on the page.
     * Destroys all modules and listeners registered with the platform.
     */
    destroy() {
      if (this._destroyed) {
        throw new RuntimeError(404 /* RuntimeErrorCode.PLATFORM_ALREADY_DESTROYED */, ngDevMode && 'The platform has already been destroyed!');
      }
      this._modules.slice().forEach(module => module.destroy());
      this._destroyListeners.forEach(listener => listener());
      const destroyListeners = this._injector.get(PLATFORM_DESTROY_LISTENERS, null);
      if (destroyListeners) {
        destroyListeners.forEach(listener => listener());
        destroyListeners.clear();
      }
      this._destroyed = true;
    }
    /**
     * Indicates whether this instance was destroyed.
     */
    get destroyed() {
      return this._destroyed;
    }
    static ɵfac = function PlatformRef_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PlatformRef)(ɵɵinject(Injector));
    };
    static ɵprov = (() => /*@__PURE__*/ɵɵdefineInjectable({
      token: PlatformRef,
      factory: PlatformRef.ɵfac,
      providedIn: 'platform'
    }))();
  }
  return PlatformRef;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(PlatformRef, [{
    type: Injectable,
    args: [{
      providedIn: 'platform'
    }]
  }], () => [{
    type: Injector
  }], null);
})();
let _platformInjector = null;
/**
 * Internal token to indicate whether having multiple bootstrapped platform should be allowed (only
 * one bootstrapped platform is allowed by default). This token helps to support SSR scenarios.
 */
const ALLOW_MULTIPLE_PLATFORMS = /*#__PURE__*/new InjectionToken(ngDevMode ? 'AllowMultipleToken' : '');
/**
 * Creates a platform.
 * Platforms must be created on launch using this function.
 *
 * @publicApi
 */
function createPlatform(injector) {
  if (_platformInjector && !_platformInjector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
    throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, ngDevMode && 'There can be only one platform. Destroy the previous one to create a new one.');
  }
  publishDefaultGlobalUtils();
  publishSignalConfiguration();
  _platformInjector = injector;
  const platform = injector.get(PlatformRef);
  runPlatformInitializers(injector);
  return platform;
}
/**
 * Creates a factory for a platform. Can be used to provide or override `Providers` specific to
 * your application's runtime needs, such as `PLATFORM_INITIALIZER` and `PLATFORM_ID`.
 * @param parentPlatformFactory Another platform factory to modify. Allows you to compose factories
 * to build up configurations that might be required by different libraries or parts of the
 * application.
 * @param name Identifies the new platform factory.
 * @param providers A set of dependency providers for platforms created with the new factory.
 *
 * @publicApi
 */
function createPlatformFactory(parentPlatformFactory, name, providers = []) {
  const desc = `Platform: ${name}`;
  const marker = new InjectionToken(desc);
  return (extraProviders = []) => {
    let platform = getPlatform();
    if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
      const platformProviders = [...providers, ...extraProviders, {
        provide: marker,
        useValue: true
      }];
      if (parentPlatformFactory) {
        parentPlatformFactory(platformProviders);
      } else {
        createPlatform(createPlatformInjector(platformProviders, desc));
      }
    }
    return assertPlatform(marker);
  };
}
/**
 * Helper function to create an instance of a platform injector (that maintains the 'platform'
 * scope).
 */
function createPlatformInjector(providers = [], name) {
  return Injector.create({
    name,
    providers: [{
      provide: INJECTOR_SCOPE,
      useValue: 'platform'
    }, {
      provide: PLATFORM_DESTROY_LISTENERS,
      useValue: new Set([() => _platformInjector = null])
    }, ...providers]
  });
}
/**
 * Checks that there is currently a platform that contains the given token as a provider.
 *
 * @publicApi
 */
function assertPlatform(requiredToken) {
  const platform = getPlatform();
  if (!platform) {
    throw new RuntimeError(401 /* RuntimeErrorCode.PLATFORM_NOT_FOUND */, ngDevMode && 'No platform exists!');
  }
  if ((typeof ngDevMode === 'undefined' || ngDevMode) && !platform.injector.get(requiredToken, null)) {
    throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, 'A platform with a different configuration has been created. Please destroy it first.');
  }
  return platform;
}
/**
 * Returns the current platform.
 *
 * @publicApi
 */
function getPlatform() {
  return _platformInjector?.get(PlatformRef) ?? null;
}
/**
 * Destroys the current Angular platform and all Angular applications on the page.
 * Destroys all modules and listeners registered with the platform.
 *
 * @publicApi
 */
function destroyPlatform() {
  getPlatform()?.destroy();
}
/**
 * The goal of this function is to bootstrap a platform injector,
 * but avoid referencing `PlatformRef` class.
 * This function is needed for bootstrapping a Standalone Component.
 */
function createOrReusePlatformInjector(providers = []) {
  // If a platform injector already exists, it means that the platform
  // is already bootstrapped and no additional actions are required.
  if (_platformInjector) return _platformInjector;
  publishDefaultGlobalUtils();
  // Otherwise, setup a new platform injector and run platform initializers.
  const injector = createPlatformInjector(providers);
  _platformInjector = injector;
  publishSignalConfiguration();
  runPlatformInitializers(injector);
  return injector;
}
/**
 * @description
 * This function is used to provide initialization functions that will be executed upon
 * initialization of the platform injector.
 *
 * Note that the provided initializer is run in the injection context.
 *
 * Previously, this was achieved using the `PLATFORM_INITIALIZER` token which is now deprecated.
 *
 * @see {@link PLATFORM_INITIALIZER}
 *
 * @publicApi
 */
function providePlatformInitializer(initializerFn) {
  return makeEnvironmentProviders([{
    provide: PLATFORM_INITIALIZER,
    useValue: initializerFn,
    multi: true
  }]);
}
function runPlatformInitializers(injector) {
  const inits = injector.get(PLATFORM_INITIALIZER, null);
  runInInjectionContext(injector, () => {
    inits?.forEach(init => init());
  });
}

/**
 * Used to periodically verify no expressions have changed after they were checked.
 *
 * @param options Used to configure when the check will execute.
 *   - `interval` will periodically run exhaustive `checkNoChanges` on application views
 *   - `useNgZoneOnStable` will use ZoneJS to determine when change detection might have run
 *      in an application using ZoneJS to drive change detection. When the `NgZone.onStable` would
 *      have emitted, all views attached to the `ApplicationRef` are checked for changes.
 *   - 'exhaustive' means that all views attached to `ApplicationRef` and all the descendants of those views will be
 *     checked for changes (excluding those subtrees which are detached via `ChangeDetectorRef.detach()`).
 *     This is useful because the check that runs after regular change detection does not work for components using `ChangeDetectionStrategy.OnPush`.
 *     This check is will surface any existing errors hidden by `OnPush` components. By default, this check is exhaustive
 *     and will always check all views, regardless of their "dirty" state and `ChangeDetectionStrategy`.
 *
 * When the `useNgZoneOnStable` option is `true`, this function will provide its own `NgZone` implementation and needs
 * to come after any other `NgZone` provider, including `provideZoneChangeDetection()` and `provideExperimentalZonelessChangeDetection()`.
 *
 * @experimental
 * @publicApi
 */
function provideExperimentalCheckNoChangesForDebug(options) {
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (options.interval === undefined && !options.useNgZoneOnStable) {
      throw new Error('Must provide one of `useNgZoneOnStable` or `interval`');
    }
    const checkNoChangesMode = options?.exhaustive === false ? CheckNoChangesMode.OnlyDirtyViews : CheckNoChangesMode.Exhaustive;
    return makeEnvironmentProviders([options?.useNgZoneOnStable ? {
      provide: NgZone,
      useFactory: () => new DebugNgZoneForCheckNoChanges(checkNoChangesMode)
    } : [], options?.interval !== undefined ? exhaustiveCheckNoChangesInterval(options.interval, checkNoChangesMode) : [], {
      provide: ENVIRONMENT_INITIALIZER,
      multi: true,
      useValue: () => {
        if (options?.useNgZoneOnStable && !(inject(NgZone) instanceof DebugNgZoneForCheckNoChanges)) {
          throw new Error('`provideExperimentalCheckNoChangesForDebug` with `useNgZoneOnStable` must be after any other provider for `NgZone`.');
        }
      }
    }]);
  } else {
    return makeEnvironmentProviders([]);
  }
}
class DebugNgZoneForCheckNoChanges extends NgZone {
  checkNoChangesMode;
  applicationRef;
  scheduler;
  errorHandler;
  injector = /*#__PURE__*/(() => inject(EnvironmentInjector))();
  constructor(checkNoChangesMode) {
    const zonelessEnabled = inject(ZONELESS_ENABLED);
    // Use coalescing to ensure we aren't ever running this check synchronously
    super({
      shouldCoalesceEventChangeDetection: true,
      shouldCoalesceRunChangeDetection: zonelessEnabled
    });
    this.checkNoChangesMode = checkNoChangesMode;
    if (zonelessEnabled) {
      // prevent emits to ensure code doesn't rely on these
      this.onMicrotaskEmpty.emit = () => {};
      this.onStable.emit = () => {
        this.scheduler ||= this.injector.get(ChangeDetectionSchedulerImpl);
        if (this.scheduler.pendingRenderTaskId || this.scheduler.runningTick) {
          return;
        }
        this.checkApplicationViews();
      };
      this.onUnstable.emit = () => {};
    } else {
      this.runOutsideAngular(() => {
        this.onStable.subscribe(() => {
          this.checkApplicationViews();
        });
      });
    }
  }
  checkApplicationViews() {
    this.applicationRef ||= this.injector.get(ApplicationRef);
    for (const view of this.applicationRef.allViews) {
      try {
        checkNoChangesInternal(view._lView, this.checkNoChangesMode, view.notifyErrorHandler);
      } catch (e) {
        this.errorHandler ||= this.injector.get(ErrorHandler);
        this.errorHandler.handleError(e);
      }
    }
  }
}
function exhaustiveCheckNoChangesInterval(interval, checkNoChangesMode) {
  return {
    provide: ENVIRONMENT_INITIALIZER,
    multi: true,
    useFactory: () => {
      const applicationRef = inject(ApplicationRef);
      const errorHandler = inject(ErrorHandler);
      const scheduler = inject(ChangeDetectionSchedulerImpl);
      const ngZone = inject(NgZone);
      return () => {
        function scheduleCheckNoChanges() {
          ngZone.runOutsideAngular(() => {
            setTimeout(() => {
              if (applicationRef.destroyed) {
                return;
              }
              if (scheduler.pendingRenderTaskId || scheduler.runningTick) {
                scheduleCheckNoChanges();
                return;
              }
              for (const view of applicationRef.allViews) {
                try {
                  checkNoChangesInternal(view._lView, checkNoChangesMode, view.notifyErrorHandler);
                } catch (e) {
                  errorHandler.handleError(e);
                }
              }
              scheduleCheckNoChanges();
            }, interval);
          });
        }
        scheduleCheckNoChanges();
      };
    }
  };
}

/**
 * Returns whether Angular is in development mode.
 *
 * By default, this is true, unless `enableProdMode` is invoked prior to calling this method or the
 * application is built using the Angular CLI with the `optimization` option.
 * @see {@link cli/build ng build}
 *
 * @publicApi
 */
function isDevMode() {
  return typeof ngDevMode === 'undefined' || !!ngDevMode;
}
/**
 * Disable Angular's development mode, which turns off assertions and other
 * checks within the framework.
 *
 * One important assertion this disables verifies that a change detection pass
 * does not result in additional changes to any bindings (also known as
 * unidirectional data flow).
 *
 * Using this method is discouraged as the Angular CLI will set production mode when using the
 * `optimization` option.
 * @see {@link cli/build ng build}
 *
 * @publicApi
 */
function enableProdMode() {
  // The below check is there so when ngDevMode is set via terser
  // `global['ngDevMode'] = false;` is also dropped.
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    _global['ngDevMode'] = false;
  }
}

// Public API for render

/**
 * Returns the NgModuleFactory with the given id (specified using [@NgModule.id
 * field](api/core/NgModule#id)), if it exists and has been loaded. Factories for NgModules that do
 * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
 * @publicApi
 * @deprecated Use `getNgModuleById` instead.
 */
function getModuleFactory(id) {
  const type = getRegisteredNgModuleType(id);
  if (!type) throw noModuleError(id);
  return new NgModuleFactory(type);
}
/**
 * Returns the NgModule class with the given id (specified using [@NgModule.id
 * field](api/core/NgModule#id)), if it exists and has been loaded. Classes for NgModules that do
 * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
 * @publicApi
 */
function getNgModuleById(id) {
  const type = getRegisteredNgModuleType(id);
  if (!type) throw noModuleError(id);
  return type;
}
function noModuleError(id) {
  return new Error(`No module with ID ${id} loaded`);
}

/**
 * Base class that provides change detection functionality.
 * A change-detection tree collects all views that are to be checked for changes.
 * Use the methods to add and remove views from the tree, initiate change-detection,
 * and explicitly mark views as _dirty_, meaning that they have changed and need to be re-rendered.
 *
 * @see [Using change detection hooks](guide/components/lifecycle#using-change-detection-hooks)
 * @see [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection)
 *
 * @usageNotes
 *
 * The following examples demonstrate how to modify default change-detection behavior
 * to perform explicit detection when needed.
 *
 * ### Use `markForCheck()` with `CheckOnce` strategy
 *
 * The following example sets the `OnPush` change-detection strategy for a component
 * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
 * after an interval.
 *
 * <code-example path="core/ts/change_detect/change-detection.ts"
 * region="mark-for-check"></code-example>
 *
 * ### Detach change detector to limit how often check occurs
 *
 * The following example defines a component with a large list of read-only data
 * that is expected to change constantly, many times per second.
 * To improve performance, we want to check and update the list
 * less often than the changes actually occur. To do that, we detach
 * the component's change detector and perform an explicit local check every five seconds.
 *
 * <code-example path="core/ts/change_detect/change-detection.ts" region="detach"></code-example>
 *
 *
 * ### Reattaching a detached component
 *
 * The following example creates a component displaying live data.
 * The component detaches its change detector from the main change detector tree
 * when the `live` property is set to false, and reattaches it when the property
 * becomes true.
 *
 * <code-example path="core/ts/change_detect/change-detection.ts" region="reattach"></code-example>
 *
 * @publicApi
 */
let ChangeDetectorRef = /*#__PURE__*/(() => {
  class ChangeDetectorRef {
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectChangeDetectorRef)();
  }
  return ChangeDetectorRef;
})();
/** Returns a ChangeDetectorRef (a.k.a. a ViewRef) */
function injectChangeDetectorRef(flags) {
  return createViewRef(getCurrentTNode(), getLView(), (flags & 16 /* InternalInjectFlags.ForPipe */) === 16 /* InternalInjectFlags.ForPipe */);
}
/**
 * Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias).
 *
 * @param tNode The node that is requesting a ChangeDetectorRef
 * @param lView The view to which the node belongs
 * @param isPipe Whether the view is being injected into a pipe.
 * @returns The ChangeDetectorRef to use
 */
function createViewRef(tNode, lView, isPipe) {
  if (isComponentHost(tNode) && !isPipe) {
    // The LView represents the location where the component is declared.
    // Instead we want the LView for the component View and so we need to look it up.
    const componentView = getComponentLViewByIndex(tNode.index, lView); // look down
    return new ViewRef$1(componentView, componentView);
  } else if (tNode.type & (3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
    // The LView represents the location where the injection is requested from.
    // We need to locate the containing LView (in case where the `lView` is an embedded view)
    const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up
    return new ViewRef$1(hostComponentView, lView);
  }
  return null;
}

/**
 * Represents an Angular view.
 *
 * @see [Change detection usage](/api/core/ChangeDetectorRef?tab=usage-notes)
 *
 * @publicApi
 */
class ViewRef extends ChangeDetectorRef {}
/**
 * Represents an Angular view in a view container.
 * An embedded view can be referenced from a component
 * other than the hosting component whose template defines it, or it can be defined
 * independently by a `TemplateRef`.
 *
 * Properties of elements in a view can change, but the structure (number and order) of elements in
 * a view cannot. Change the structure of elements by inserting, moving, or
 * removing nested views in a view container.
 *
 * @see {@link ViewContainerRef}
 *
 * @usageNotes
 *
 * The following template breaks down into two separate `TemplateRef` instances,
 * an outer one and an inner one.
 *
 * ```
 * Count: {{items.length}}
 * <ul>
 *   <li *ngFor="let  item of items">{{item}}</li>
 * </ul>
 * ```
 *
 * This is the outer `TemplateRef`:
 *
 * ```
 * Count: {{items.length}}
 * <ul>
 *   <ng-template ngFor let-item [ngForOf]="items"></ng-template>
 * </ul>
 * ```
 *
 * This is the inner `TemplateRef`:
 *
 * ```
 *   <li>{{item}}</li>
 * ```
 *
 * The outer and inner `TemplateRef` instances are assembled into views as follows:
 *
 * ```
 * <!-- ViewRef: outer-0 -->
 * Count: 2
 * <ul>
 *   <ng-template view-container-ref></ng-template>
 *   <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
 *   <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
 * </ul>
 * <!-- /ViewRef: outer-0 -->
 * ```
 * @publicApi
 */
class EmbeddedViewRef extends ViewRef {}

// Public API for compiler

// This file exists for easily patching NgModuleFactoryLoader in g3
var ng_module_factory_loader_impl = {};

/**
 * @publicApi
 */
class DebugEventListener {
  name;
  callback;
  constructor(name, callback) {
    this.name = name;
    this.callback = callback;
  }
}
/**
 * @publicApi
 */
function asNativeElements(debugEls) {
  return debugEls.map(el => el.nativeElement);
}
/**
 * @publicApi
 */
class DebugNode {
  /**
   * The underlying DOM node.
   */
  nativeNode;
  constructor(nativeNode) {
    this.nativeNode = nativeNode;
  }
  /**
   * The `DebugElement` parent. Will be `null` if this is the root element.
   */
  get parent() {
    const parent = this.nativeNode.parentNode;
    return parent ? new DebugElement(parent) : null;
  }
  /**
   * The host dependency injector. For example, the root element's component instance injector.
   */
  get injector() {
    return getInjector(this.nativeNode);
  }
  /**
   * The element's own component instance, if it has one.
   */
  get componentInstance() {
    const nativeElement = this.nativeNode;
    return nativeElement && (getComponent(nativeElement) || getOwningComponent(nativeElement));
  }
  /**
   * An object that provides parent context for this element. Often an ancestor component instance
   * that governs this element.
   *
   * When an element is repeated within *ngFor, the context is an `NgForOf` whose `$implicit`
   * property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero
   * of heroes"`.
   */
  get context() {
    return getComponent(this.nativeNode) || getContext(this.nativeNode);
  }
  /**
   * The callbacks attached to the component's @Output properties and/or the element's event
   * properties.
   */
  get listeners() {
    return getListeners(this.nativeNode).filter(listener => listener.type === 'dom');
  }
  /**
   * Dictionary of objects associated with template local variables (e.g. #foo), keyed by the local
   * variable name.
   */
  get references() {
    return getLocalRefs(this.nativeNode);
  }
  /**
   * This component's injector lookup tokens. Includes the component itself plus the tokens that the
   * component lists in its providers metadata.
   */
  get providerTokens() {
    return getInjectionTokens(this.nativeNode);
  }
}
/**
 * @publicApi
 *
 * @see [Component testing scenarios](guide/testing/components-scenarios)
 * @see [Basics of testing components](guide/testing/components-basics)
 * @see [Testing utility APIs](guide/testing/utility-apis)
 */
class DebugElement extends DebugNode {
  constructor(nativeNode) {
    ngDevMode && assertDomNode(nativeNode);
    super(nativeNode);
  }
  /**
   * The underlying DOM element at the root of the component.
   */
  get nativeElement() {
    return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;
  }
  /**
   * The element tag name, if it is an element.
   */
  get name() {
    const context = getLContext(this.nativeNode);
    const lView = context ? context.lView : null;
    if (lView !== null) {
      const tData = lView[TVIEW].data;
      const tNode = tData[context.nodeIndex];
      return tNode.value;
    } else {
      return this.nativeNode.nodeName;
    }
  }
  /**
   *  Gets a map of property names to property values for an element.
   *
   *  This map includes:
   *  - Regular property bindings (e.g. `[id]="id"`)
   *  - Host property bindings (e.g. `host: { '[id]': "id" }`)
   *  - Interpolated property bindings (e.g. `id="{{ value }}")
   *
   *  It does not include:
   *  - input property bindings (e.g. `[myCustomInput]="value"`)
   *  - attribute bindings (e.g. `[attr.role]="menu"`)
   */
  get properties() {
    const context = getLContext(this.nativeNode);
    const lView = context ? context.lView : null;
    if (lView === null) {
      return {};
    }
    const tData = lView[TVIEW].data;
    const tNode = tData[context.nodeIndex];
    const properties = {};
    // Collect properties from the DOM.
    copyDomProperties(this.nativeElement, properties);
    // Collect properties from the bindings. This is needed for animation renderer which has
    // synthetic properties which don't get reflected into the DOM.
    collectPropertyBindings(properties, tNode, lView, tData);
    return properties;
  }
  /**
   *  A map of attribute names to attribute values for an element.
   */
  // TODO: replace null by undefined in the return type
  get attributes() {
    const attributes = {};
    const element = this.nativeElement;
    if (!element) {
      return attributes;
    }
    const context = getLContext(element);
    const lView = context ? context.lView : null;
    if (lView === null) {
      return {};
    }
    const tNodeAttrs = lView[TVIEW].data[context.nodeIndex].attrs;
    const lowercaseTNodeAttrs = [];
    // For debug nodes we take the element's attribute directly from the DOM since it allows us
    // to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
    // that are set through `Renderer2`). The problem is that the browser will lowercase all names,
    // however since we have the attributes already on the TNode, we can preserve the case by going
    // through them once, adding them to the `attributes` map and putting their lower-cased name
    // into an array. Afterwards when we're going through the native DOM attributes, we can check
    // whether we haven't run into an attribute already through the TNode.
    if (tNodeAttrs) {
      let i = 0;
      while (i < tNodeAttrs.length) {
        const attrName = tNodeAttrs[i];
        // Stop as soon as we hit a marker. We only care about the regular attributes. Everything
        // else will be handled below when we read the final attributes off the DOM.
        if (typeof attrName !== 'string') break;
        const attrValue = tNodeAttrs[i + 1];
        attributes[attrName] = attrValue;
        lowercaseTNodeAttrs.push(attrName.toLowerCase());
        i += 2;
      }
    }
    for (const attr of element.attributes) {
      // Make sure that we don't assign the same attribute both in its
      // case-sensitive form and the lower-cased one from the browser.
      if (!lowercaseTNodeAttrs.includes(attr.name)) {
        attributes[attr.name] = attr.value;
      }
    }
    return attributes;
  }
  /**
   * The inline styles of the DOM element.
   */
  // TODO: replace null by undefined in the return type
  get styles() {
    const element = this.nativeElement;
    return element?.style ?? {};
  }
  /**
   * A map containing the class names on the element as keys.
   *
   * This map is derived from the `className` property of the DOM element.
   *
   * Note: The values of this object will always be `true`. The class key will not appear in the KV
   * object if it does not exist on the element.
   *
   * @see [Element.className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)
   */
  get classes() {
    const result = {};
    const element = this.nativeElement;
    // SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
    const className = element.className;
    const classes = typeof className !== 'string' ? className.baseVal.split(' ') : className.split(' ');
    classes.forEach(value => result[value] = true);
    return result;
  }
  /**
   * The `childNodes` of the DOM element as a `DebugNode` array.
   *
   * @see [Node.childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)
   */
  get childNodes() {
    const childNodes = this.nativeNode.childNodes;
    const children = [];
    for (let i = 0; i < childNodes.length; i++) {
      const element = childNodes[i];
      children.push(getDebugNode(element));
    }
    return children;
  }
  /**
   * The immediate `DebugElement` children. Walk the tree by descending through `children`.
   */
  get children() {
    const nativeElement = this.nativeElement;
    if (!nativeElement) return [];
    const childNodes = nativeElement.children;
    const children = [];
    for (let i = 0; i < childNodes.length; i++) {
      const element = childNodes[i];
      children.push(getDebugNode(element));
    }
    return children;
  }
  /**
   * @returns the first `DebugElement` that matches the predicate at any depth in the subtree.
   */
  query(predicate) {
    const results = this.queryAll(predicate);
    return results[0] || null;
  }
  /**
   * @returns All `DebugElement` matches for the predicate at any depth in the subtree.
   */
  queryAll(predicate) {
    const matches = [];
    _queryAll(this, predicate, matches, true);
    return matches;
  }
  /**
   * @returns All `DebugNode` matches for the predicate at any depth in the subtree.
   */
  queryAllNodes(predicate) {
    const matches = [];
    _queryAll(this, predicate, matches, false);
    return matches;
  }
  /**
   * Triggers the event by its name if there is a corresponding listener in the element's
   * `listeners` collection.
   *
   * If the event lacks a listener or there's some other problem, consider
   * calling `nativeElement.dispatchEvent(eventObject)`.
   *
   * @param eventName The name of the event to trigger
   * @param eventObj The _event object_ expected by the handler
   *
   * @see [Testing components scenarios](guide/testing/components-scenarios#trigger-event-handler)
   */
  triggerEventHandler(eventName, eventObj) {
    const node = this.nativeNode;
    const invokedListeners = [];
    this.listeners.forEach(listener => {
      if (listener.name === eventName) {
        const callback = listener.callback;
        callback.call(node, eventObj);
        invokedListeners.push(callback);
      }
    });
    // We need to check whether `eventListeners` exists, because it's something
    // that Zone.js only adds to `EventTarget` in browser environments.
    if (typeof node.eventListeners === 'function') {
      // Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
      // cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
      // listener.
      node.eventListeners(eventName).forEach(listener => {
        // In order to ensure that we can detect the special __ngUnwrap__ token described above, we
        // use `toString` on the listener and see if it contains the token. We use this approach to
        // ensure that it still worked with compiled code since it cannot remove or rename string
        // literals. We also considered using a special function name (i.e. if(listener.name ===
        // special)) but that was more cumbersome and we were also concerned the compiled code could
        // strip the name, turning the condition in to ("" === "") and always returning true.
        if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
          const unwrappedListener = listener('__ngUnwrap__');
          return invokedListeners.indexOf(unwrappedListener) === -1 && unwrappedListener.call(node, eventObj);
        }
      });
    }
  }
}
function copyDomProperties(element, properties) {
  if (element) {
    // Skip own properties (as those are patched)
    let obj = Object.getPrototypeOf(element);
    const NodePrototype = Node.prototype;
    while (obj !== null && obj !== NodePrototype) {
      const descriptors = Object.getOwnPropertyDescriptors(obj);
      for (let key in descriptors) {
        if (!key.startsWith('__') && !key.startsWith('on')) {
          // don't include properties starting with `__` and `on`.
          // `__` are patched values which should not be included.
          // `on` are listeners which also should not be included.
          const value = element[key];
          if (isPrimitiveValue(value)) {
            properties[key] = value;
          }
        }
      }
      obj = Object.getPrototypeOf(obj);
    }
  }
}
function isPrimitiveValue(value) {
  return typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' || value === null;
}
function _queryAll(parentElement, predicate, matches, elementsOnly) {
  const context = getLContext(parentElement.nativeNode);
  const lView = context ? context.lView : null;
  if (lView !== null) {
    const parentTNode = lView[TVIEW].data[context.nodeIndex];
    _queryNodeChildren(parentTNode, lView, predicate, matches, elementsOnly, parentElement.nativeNode);
  } else {
    // If the context is null, then `parentElement` was either created with Renderer2 or native DOM
    // APIs.
    _queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
  }
}
/**
 * Recursively match the current TNode against the predicate, and goes on with the next ones.
 *
 * @param tNode the current TNode
 * @param lView the LView of this TNode
 * @param predicate the predicate to match
 * @param matches the list of positive matches
 * @param elementsOnly whether only elements should be searched
 * @param rootNativeNode the root native node on which predicate should not be matched
 */
function _queryNodeChildren(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
  ngDevMode && assertTNodeForLView(tNode, lView);
  const nativeNode = getNativeByTNodeOrNull(tNode, lView);
  // For each type of TNode, specific logic is executed.
  if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
    // Case 1: the TNode is an element
    // The native node has to be checked.
    _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
    if (isComponentHost(tNode)) {
      // If the element is the host of a component, then all nodes in its view have to be processed.
      // Note: the component's content (tNode.child) will be processed from the insertion points.
      const componentView = getComponentLViewByIndex(tNode.index, lView);
      if (componentView && componentView[TVIEW].firstChild) {
        _queryNodeChildren(componentView[TVIEW].firstChild, componentView, predicate, matches, elementsOnly, rootNativeNode);
      }
    } else {
      if (tNode.child) {
        // Otherwise, its children have to be processed.
        _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
      }
      // We also have to query the DOM directly in order to catch elements inserted through
      // Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
      // times. ViewEngine could do it more efficiently, because all the insertions go through
      // Renderer2, however that's not the case in Ivy. This approach is being used because:
      // 1. Matching the ViewEngine behavior would mean potentially introducing a dependency
      //    from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
      // 2. It allows us to capture nodes that were inserted directly via the DOM.
      nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
    }
    // In all cases, if a dynamic container exists for this node, each view inside it has to be
    // processed.
    const nodeOrContainer = lView[tNode.index];
    if (isLContainer(nodeOrContainer)) {
      _queryNodeChildrenInContainer(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
    }
  } else if (tNode.type & 4 /* TNodeType.Container */) {
    // Case 2: the TNode is a container
    // The native node has to be checked.
    const lContainer = lView[tNode.index];
    _addQueryMatch(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
    // Each view inside the container has to be processed.
    _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode);
  } else if (tNode.type & 16 /* TNodeType.Projection */) {
    // Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
    // The nodes projected at this location all need to be processed.
    const componentView = lView[DECLARATION_COMPONENT_VIEW];
    const componentHost = componentView[T_HOST];
    const head = componentHost.projection[tNode.projection];
    if (Array.isArray(head)) {
      for (let nativeNode of head) {
        _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
      }
    } else if (head) {
      const nextLView = componentView[PARENT];
      const nextTNode = nextLView[TVIEW].data[head.index];
      _queryNodeChildren(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
    }
  } else if (tNode.child) {
    // Case 4: the TNode is a view.
    _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  }
  // We don't want to go to the next sibling of the root node.
  if (rootNativeNode !== nativeNode) {
    // To determine the next node to be processed, we need to use the next or the projectionNext
    // link, depending on whether the current node has been projected.
    const nextTNode = tNode.flags & 2 /* TNodeFlags.isProjected */ ? tNode.projectionNext : tNode.next;
    if (nextTNode) {
      _queryNodeChildren(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
    }
  }
}
/**
 * Process all TNodes in a given container.
 *
 * @param lContainer the container to be processed
 * @param predicate the predicate to match
 * @param matches the list of positive matches
 * @param elementsOnly whether only elements should be searched
 * @param rootNativeNode the root native node on which predicate should not be matched
 */
function _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
  for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
    const childView = lContainer[i];
    const firstChild = childView[TVIEW].firstChild;
    if (firstChild) {
      _queryNodeChildren(firstChild, childView, predicate, matches, elementsOnly, rootNativeNode);
    }
  }
}
/**
 * Match the current native node against the predicate.
 *
 * @param nativeNode the current native node
 * @param predicate the predicate to match
 * @param matches the list of positive matches
 * @param elementsOnly whether only elements should be searched
 * @param rootNativeNode the root native node on which predicate should not be matched
 */
function _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
  if (rootNativeNode !== nativeNode) {
    const debugNode = getDebugNode(nativeNode);
    if (!debugNode) {
      return;
    }
    // Type of the "predicate and "matches" array are set based on the value of
    // the "elementsOnly" parameter. TypeScript is not able to properly infer these
    // types with generics, so we manually cast the parameters accordingly.
    if (elementsOnly && debugNode instanceof DebugElement && predicate(debugNode) && matches.indexOf(debugNode) === -1) {
      matches.push(debugNode);
    } else if (!elementsOnly && predicate(debugNode) && matches.indexOf(debugNode) === -1) {
      matches.push(debugNode);
    }
  }
}
/**
 * Match all the descendants of a DOM node against a predicate.
 *
 * @param nativeNode the current native node
 * @param predicate the predicate to match
 * @param matches the list where matches are stored
 * @param elementsOnly whether only elements should be searched
 */
function _queryNativeNodeDescendants(parentNode, predicate, matches, elementsOnly) {
  const nodes = parentNode.childNodes;
  const length = nodes.length;
  for (let i = 0; i < length; i++) {
    const node = nodes[i];
    const debugNode = getDebugNode(node);
    if (debugNode) {
      if (elementsOnly && debugNode instanceof DebugElement && predicate(debugNode) && matches.indexOf(debugNode) === -1) {
        matches.push(debugNode);
      } else if (!elementsOnly && predicate(debugNode) && matches.indexOf(debugNode) === -1) {
        matches.push(debugNode);
      }
      _queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
    }
  }
}
/**
 * Iterates through the property bindings for a given node and generates
 * a map of property names to values. This map only contains property bindings
 * defined in templates, not in host bindings.
 */
function collectPropertyBindings(properties, tNode, lView, tData) {
  let bindingIndexes = tNode.propertyBindings;
  if (bindingIndexes !== null) {
    for (let i = 0; i < bindingIndexes.length; i++) {
      const bindingIndex = bindingIndexes[i];
      const propMetadata = tData[bindingIndex];
      const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
      const propertyName = metadataParts[0];
      if (metadataParts.length > 1) {
        let value = metadataParts[1];
        for (let j = 1; j < metadataParts.length - 1; j++) {
          value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
        }
        properties[propertyName] = value;
      } else {
        properties[propertyName] = lView[bindingIndex];
      }
    }
  }
}
// Need to keep the nodes in a global Map so that multiple angular apps are supported.
const _nativeNodeToDebugNode = /*#__PURE__*/new Map();
const NG_DEBUG_PROPERTY = '__ng_debug__';
/**
 * @publicApi
 */
function getDebugNode(nativeNode) {
  if (nativeNode instanceof Node) {
    if (!nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY)) {
      nativeNode[NG_DEBUG_PROPERTY] = nativeNode.nodeType == Node.ELEMENT_NODE ? new DebugElement(nativeNode) : new DebugNode(nativeNode);
    }
    return nativeNode[NG_DEBUG_PROPERTY];
  }
  return null;
}
function getAllDebugNodes() {
  return Array.from(_nativeNodeToDebugNode.values());
}
function indexDebugNode(node) {
  _nativeNodeToDebugNode.set(node.nativeNode, node);
}
function removeDebugNodeFromIndex(node) {
  _nativeNodeToDebugNode.delete(node.nativeNode);
}
class DefaultIterableDifferFactory {
  constructor() {}
  supports(obj) {
    return isListLikeIterable(obj);
  }
  create(trackByFn) {
    return new DefaultIterableDiffer(trackByFn);
  }
}
const trackByIdentity = (index, item) => item;
/**
 * @deprecated v4.0.0 - Should not be part of public API.
 * @publicApi
 */
class DefaultIterableDiffer {
  length = 0;
  // TODO: confirm the usage of `collection` as it's unused, readonly and on a non public API.
  collection;
  // Keeps track of the used records at any point in time (during & across `_check()` calls)
  _linkedRecords = null;
  // Keeps track of the removed records at any point in time during `_check()` calls.
  _unlinkedRecords = null;
  _previousItHead = null;
  _itHead = null;
  _itTail = null;
  _additionsHead = null;
  _additionsTail = null;
  _movesHead = null;
  _movesTail = null;
  _removalsHead = null;
  _removalsTail = null;
  // Keeps track of records where custom track by is the same, but item identity has changed
  _identityChangesHead = null;
  _identityChangesTail = null;
  _trackByFn;
  constructor(trackByFn) {
    this._trackByFn = trackByFn || trackByIdentity;
  }
  forEachItem(fn) {
    let record;
    for (record = this._itHead; record !== null; record = record._next) {
      fn(record);
    }
  }
  forEachOperation(fn) {
    let nextIt = this._itHead;
    let nextRemove = this._removalsHead;
    let addRemoveOffset = 0;
    let moveOffsets = null;
    while (nextIt || nextRemove) {
      // Figure out which is the next record to process
      // Order: remove, add, move
      const record = !nextRemove || nextIt && nextIt.currentIndex < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ? nextIt : nextRemove;
      const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
      const currentIndex = record.currentIndex;
      // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
      if (record === nextRemove) {
        addRemoveOffset--;
        nextRemove = nextRemove._nextRemoved;
      } else {
        nextIt = nextIt._next;
        if (record.previousIndex == null) {
          addRemoveOffset++;
        } else {
          // INVARIANT:  currentIndex < previousIndex
          if (!moveOffsets) moveOffsets = [];
          const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
          const localCurrentIndex = currentIndex - addRemoveOffset;
          if (localMovePreviousIndex != localCurrentIndex) {
            for (let i = 0; i < localMovePreviousIndex; i++) {
              const offset = i < moveOffsets.length ? moveOffsets[i] : moveOffsets[i] = 0;
              const index = offset + i;
              if (localCurrentIndex <= index && index < localMovePreviousIndex) {
                moveOffsets[i] = offset + 1;
              }
            }
            const previousIndex = record.previousIndex;
            moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
          }
        }
      }
      if (adjPreviousIndex !== currentIndex) {
        fn(record, adjPreviousIndex, currentIndex);
      }
    }
  }
  forEachPreviousItem(fn) {
    let record;
    for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
      fn(record);
    }
  }
  forEachAddedItem(fn) {
    let record;
    for (record = this._additionsHead; record !== null; record = record._nextAdded) {
      fn(record);
    }
  }
  forEachMovedItem(fn) {
    let record;
    for (record = this._movesHead; record !== null; record = record._nextMoved) {
      fn(record);
    }
  }
  forEachRemovedItem(fn) {
    let record;
    for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
      fn(record);
    }
  }
  forEachIdentityChange(fn) {
    let record;
    for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
      fn(record);
    }
  }
  diff(collection) {
    if (collection == null) collection = [];
    if (!isListLikeIterable(collection)) {
      throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && `Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`);
    }
    if (this.check(collection)) {
      return this;
    } else {
      return null;
    }
  }
  onDestroy() {}
  check(collection) {
    this._reset();
    let record = this._itHead;
    let mayBeDirty = false;
    let index;
    let item;
    let itemTrackBy;
    if (Array.isArray(collection)) {
      this.length = collection.length;
      for (let index = 0; index < this.length; index++) {
        item = collection[index];
        itemTrackBy = this._trackByFn(index, item);
        if (record === null || !Object.is(record.trackById, itemTrackBy)) {
          record = this._mismatch(record, item, itemTrackBy, index);
          mayBeDirty = true;
        } else {
          if (mayBeDirty) {
            // TODO(misko): can we limit this to duplicates only?
            record = this._verifyReinsertion(record, item, itemTrackBy, index);
          }
          if (!Object.is(record.item, item)) this._addIdentityChange(record, item);
        }
        record = record._next;
      }
    } else {
      index = 0;
      iterateListLike(collection, item => {
        itemTrackBy = this._trackByFn(index, item);
        if (record === null || !Object.is(record.trackById, itemTrackBy)) {
          record = this._mismatch(record, item, itemTrackBy, index);
          mayBeDirty = true;
        } else {
          if (mayBeDirty) {
            // TODO(misko): can we limit this to duplicates only?
            record = this._verifyReinsertion(record, item, itemTrackBy, index);
          }
          if (!Object.is(record.item, item)) this._addIdentityChange(record, item);
        }
        record = record._next;
        index++;
      });
      this.length = index;
    }
    this._truncate(record);
    this.collection = collection;
    return this.isDirty;
  }
  /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
   * changes.
   */
  get isDirty() {
    return this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null || this._identityChangesHead !== null;
  }
  /**
   * Reset the state of the change objects to show no changes. This means set previousKey to
   * currentKey, and clear all of the queues (additions, moves, removals).
   * Set the previousIndexes of moved and added items to their currentIndexes
   * Reset the list of additions, moves and removals
   *
   * @internal
   */
  _reset() {
    if (this.isDirty) {
      let record;
      for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
        record._nextPrevious = record._next;
      }
      for (record = this._additionsHead; record !== null; record = record._nextAdded) {
        record.previousIndex = record.currentIndex;
      }
      this._additionsHead = this._additionsTail = null;
      for (record = this._movesHead; record !== null; record = record._nextMoved) {
        record.previousIndex = record.currentIndex;
      }
      this._movesHead = this._movesTail = null;
      this._removalsHead = this._removalsTail = null;
      this._identityChangesHead = this._identityChangesTail = null;
      // TODO(vicb): when assert gets supported
      // assert(!this.isDirty);
    }
  }
  /**
   * This is the core function which handles differences between collections.
   *
   * - `record` is the record which we saw at this position last time. If null then it is a new
   *   item.
   * - `item` is the current item in the collection
   * - `index` is the position of the item in the collection
   *
   * @internal
   */
  _mismatch(record, item, itemTrackBy, index) {
    // The previous record after which we will append the current one.
    let previousRecord;
    if (record === null) {
      previousRecord = this._itTail;
    } else {
      previousRecord = record._prev;
      // Remove the record from the collection since we know it does not match the item.
      this._remove(record);
    }
    // See if we have evicted the item, which used to be at some anterior position of _itHead list.
    record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
    if (record !== null) {
      // It is an item which we have evicted earlier: reinsert it back into the list.
      // But first we need to check if identity changed, so we can update in view if necessary.
      if (!Object.is(record.item, item)) this._addIdentityChange(record, item);
      this._reinsertAfter(record, previousRecord, index);
    } else {
      // Attempt to see if the item is at some posterior position of _itHead list.
      record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
      if (record !== null) {
        // We have the item in _itHead at/after `index` position. We need to move it forward in the
        // collection.
        // But first we need to check if identity changed, so we can update in view if necessary.
        if (!Object.is(record.item, item)) this._addIdentityChange(record, item);
        this._moveAfter(record, previousRecord, index);
      } else {
        // It is a new item: add it.
        record = this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
      }
    }
    return record;
  }
  /**
   * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
   *
   * Use case: `[a, a]` => `[b, a, a]`
   *
   * If we did not have this check then the insertion of `b` would:
   *   1) evict first `a`
   *   2) insert `b` at `0` index.
   *   3) leave `a` at index `1` as is. <-- this is wrong!
   *   3) reinsert `a` at index 2. <-- this is wrong!
   *
   * The correct behavior is:
   *   1) evict first `a`
   *   2) insert `b` at `0` index.
   *   3) reinsert `a` at index 1.
   *   3) move `a` at from `1` to `2`.
   *
   *
   * Double check that we have not evicted a duplicate item. We need to check if the item type may
   * have already been removed:
   * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
   * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
   * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
   * at the end.
   *
   * @internal
   */
  _verifyReinsertion(record, item, itemTrackBy, index) {
    let reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
    if (reinsertRecord !== null) {
      record = this._reinsertAfter(reinsertRecord, record._prev, index);
    } else if (record.currentIndex != index) {
      record.currentIndex = index;
      this._addToMoves(record, index);
    }
    return record;
  }
  /**
   * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection
   *
   * - `record` The first excess {@link IterableChangeRecord_}.
   *
   * @internal
   */
  _truncate(record) {
    // Anything after that needs to be removed;
    while (record !== null) {
      const nextRecord = record._next;
      this._addToRemovals(this._unlink(record));
      record = nextRecord;
    }
    if (this._unlinkedRecords !== null) {
      this._unlinkedRecords.clear();
    }
    if (this._additionsTail !== null) {
      this._additionsTail._nextAdded = null;
    }
    if (this._movesTail !== null) {
      this._movesTail._nextMoved = null;
    }
    if (this._itTail !== null) {
      this._itTail._next = null;
    }
    if (this._removalsTail !== null) {
      this._removalsTail._nextRemoved = null;
    }
    if (this._identityChangesTail !== null) {
      this._identityChangesTail._nextIdentityChange = null;
    }
  }
  /** @internal */
  _reinsertAfter(record, prevRecord, index) {
    if (this._unlinkedRecords !== null) {
      this._unlinkedRecords.remove(record);
    }
    const prev = record._prevRemoved;
    const next = record._nextRemoved;
    if (prev === null) {
      this._removalsHead = next;
    } else {
      prev._nextRemoved = next;
    }
    if (next === null) {
      this._removalsTail = prev;
    } else {
      next._prevRemoved = prev;
    }
    this._insertAfter(record, prevRecord, index);
    this._addToMoves(record, index);
    return record;
  }
  /** @internal */
  _moveAfter(record, prevRecord, index) {
    this._unlink(record);
    this._insertAfter(record, prevRecord, index);
    this._addToMoves(record, index);
    return record;
  }
  /** @internal */
  _addAfter(record, prevRecord, index) {
    this._insertAfter(record, prevRecord, index);
    if (this._additionsTail === null) {
      // TODO(vicb):
      // assert(this._additionsHead === null);
      this._additionsTail = this._additionsHead = record;
    } else {
      // TODO(vicb):
      // assert(_additionsTail._nextAdded === null);
      // assert(record._nextAdded === null);
      this._additionsTail = this._additionsTail._nextAdded = record;
    }
    return record;
  }
  /** @internal */
  _insertAfter(record, prevRecord, index) {
    // TODO(vicb):
    // assert(record != prevRecord);
    // assert(record._next === null);
    // assert(record._prev === null);
    const next = prevRecord === null ? this._itHead : prevRecord._next;
    // TODO(vicb):
    // assert(next != record);
    // assert(prevRecord != record);
    record._next = next;
    record._prev = prevRecord;
    if (next === null) {
      this._itTail = record;
    } else {
      next._prev = record;
    }
    if (prevRecord === null) {
      this._itHead = record;
    } else {
      prevRecord._next = record;
    }
    if (this._linkedRecords === null) {
      this._linkedRecords = new _DuplicateMap();
    }
    this._linkedRecords.put(record);
    record.currentIndex = index;
    return record;
  }
  /** @internal */
  _remove(record) {
    return this._addToRemovals(this._unlink(record));
  }
  /** @internal */
  _unlink(record) {
    if (this._linkedRecords !== null) {
      this._linkedRecords.remove(record);
    }
    const prev = record._prev;
    const next = record._next;
    // TODO(vicb):
    // assert((record._prev = null) === null);
    // assert((record._next = null) === null);
    if (prev === null) {
      this._itHead = next;
    } else {
      prev._next = next;
    }
    if (next === null) {
      this._itTail = prev;
    } else {
      next._prev = prev;
    }
    return record;
  }
  /** @internal */
  _addToMoves(record, toIndex) {
    // TODO(vicb):
    // assert(record._nextMoved === null);
    if (record.previousIndex === toIndex) {
      return record;
    }
    if (this._movesTail === null) {
      // TODO(vicb):
      // assert(_movesHead === null);
      this._movesTail = this._movesHead = record;
    } else {
      // TODO(vicb):
      // assert(_movesTail._nextMoved === null);
      this._movesTail = this._movesTail._nextMoved = record;
    }
    return record;
  }
  _addToRemovals(record) {
    if (this._unlinkedRecords === null) {
      this._unlinkedRecords = new _DuplicateMap();
    }
    this._unlinkedRecords.put(record);
    record.currentIndex = null;
    record._nextRemoved = null;
    if (this._removalsTail === null) {
      // TODO(vicb):
      // assert(_removalsHead === null);
      this._removalsTail = this._removalsHead = record;
      record._prevRemoved = null;
    } else {
      // TODO(vicb):
      // assert(_removalsTail._nextRemoved === null);
      // assert(record._nextRemoved === null);
      record._prevRemoved = this._removalsTail;
      this._removalsTail = this._removalsTail._nextRemoved = record;
    }
    return record;
  }
  /** @internal */
  _addIdentityChange(record, item) {
    record.item = item;
    if (this._identityChangesTail === null) {
      this._identityChangesTail = this._identityChangesHead = record;
    } else {
      this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
    }
    return record;
  }
}
class IterableChangeRecord_ {
  item;
  trackById;
  currentIndex = null;
  previousIndex = null;
  /** @internal */
  _nextPrevious = null;
  /** @internal */
  _prev = null;
  /** @internal */
  _next = null;
  /** @internal */
  _prevDup = null;
  /** @internal */
  _nextDup = null;
  /** @internal */
  _prevRemoved = null;
  /** @internal */
  _nextRemoved = null;
  /** @internal */
  _nextAdded = null;
  /** @internal */
  _nextMoved = null;
  /** @internal */
  _nextIdentityChange = null;
  constructor(item, trackById) {
    this.item = item;
    this.trackById = trackById;
  }
}
// A linked list of IterableChangeRecords with the same IterableChangeRecord_.item
class _DuplicateItemRecordList {
  /** @internal */
  _head = null;
  /** @internal */
  _tail = null;
  /**
   * Append the record to the list of duplicates.
   *
   * Note: by design all records in the list of duplicates hold the same value in record.item.
   */
  add(record) {
    if (this._head === null) {
      this._head = this._tail = record;
      record._nextDup = null;
      record._prevDup = null;
    } else {
      // TODO(vicb):
      // assert(record.item ==  _head.item ||
      //       record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
      this._tail._nextDup = record;
      record._prevDup = this._tail;
      record._nextDup = null;
      this._tail = record;
    }
  }
  // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
  // IterableChangeRecord_.currentIndex >= atOrAfterIndex
  get(trackById, atOrAfterIndex) {
    let record;
    for (record = this._head; record !== null; record = record._nextDup) {
      if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex) && Object.is(record.trackById, trackById)) {
        return record;
      }
    }
    return null;
  }
  /**
   * Remove one {@link IterableChangeRecord_} from the list of duplicates.
   *
   * Returns whether the list of duplicates is empty.
   */
  remove(record) {
    // TODO(vicb):
    // assert(() {
    //  // verify that the record being removed is in the list.
    //  for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
    //    if (identical(cursor, record)) return true;
    //  }
    //  return false;
    //});
    const prev = record._prevDup;
    const next = record._nextDup;
    if (prev === null) {
      this._head = next;
    } else {
      prev._nextDup = next;
    }
    if (next === null) {
      this._tail = prev;
    } else {
      next._prevDup = prev;
    }
    return this._head === null;
  }
}
class _DuplicateMap {
  map = /*#__PURE__*/(() => new Map())();
  put(record) {
    const key = record.trackById;
    let duplicates = this.map.get(key);
    if (!duplicates) {
      duplicates = new _DuplicateItemRecordList();
      this.map.set(key, duplicates);
    }
    duplicates.add(record);
  }
  /**
   * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
   * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
   *
   * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
   * have any more `a`s needs to return the second `a`.
   */
  get(trackById, atOrAfterIndex) {
    const key = trackById;
    const recordList = this.map.get(key);
    return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
  }
  /**
   * Removes a {@link IterableChangeRecord_} from the list of duplicates.
   *
   * The list of duplicates also is removed from the map if it gets empty.
   */
  remove(record) {
    const key = record.trackById;
    const recordList = this.map.get(key);
    // Remove the list of duplicates when it gets empty
    if (recordList.remove(record)) {
      this.map.delete(key);
    }
    return record;
  }
  get isEmpty() {
    return this.map.size === 0;
  }
  clear() {
    this.map.clear();
  }
}
function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
  const previousIndex = item.previousIndex;
  if (previousIndex === null) return previousIndex;
  let moveOffset = 0;
  if (moveOffsets && previousIndex < moveOffsets.length) {
    moveOffset = moveOffsets[previousIndex];
  }
  return previousIndex + addRemoveOffset + moveOffset;
}
class DefaultKeyValueDifferFactory {
  constructor() {}
  supports(obj) {
    return obj instanceof Map || isJsObject(obj);
  }
  create() {
    return new DefaultKeyValueDiffer();
  }
}
class DefaultKeyValueDiffer {
  _records = /*#__PURE__*/(() => new Map())();
  _mapHead = null;
  // _appendAfter is used in the check loop
  _appendAfter = null;
  _previousMapHead = null;
  _changesHead = null;
  _changesTail = null;
  _additionsHead = null;
  _additionsTail = null;
  _removalsHead = null;
  _removalsTail = null;
  get isDirty() {
    return this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null;
  }
  forEachItem(fn) {
    let record;
    for (record = this._mapHead; record !== null; record = record._next) {
      fn(record);
    }
  }
  forEachPreviousItem(fn) {
    let record;
    for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
      fn(record);
    }
  }
  forEachChangedItem(fn) {
    let record;
    for (record = this._changesHead; record !== null; record = record._nextChanged) {
      fn(record);
    }
  }
  forEachAddedItem(fn) {
    let record;
    for (record = this._additionsHead; record !== null; record = record._nextAdded) {
      fn(record);
    }
  }
  forEachRemovedItem(fn) {
    let record;
    for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
      fn(record);
    }
  }
  diff(map) {
    if (!map) {
      map = new Map();
    } else if (!(map instanceof Map || isJsObject(map))) {
      throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && `Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`);
    }
    return this.check(map) ? this : null;
  }
  onDestroy() {}
  /**
   * Check the current state of the map vs the previous.
   * The algorithm is optimised for when the keys do no change.
   */
  check(map) {
    this._reset();
    let insertBefore = this._mapHead;
    this._appendAfter = null;
    this._forEach(map, (value, key) => {
      if (insertBefore && insertBefore.key === key) {
        this._maybeAddToChanges(insertBefore, value);
        this._appendAfter = insertBefore;
        insertBefore = insertBefore._next;
      } else {
        const record = this._getOrCreateRecordForKey(key, value);
        insertBefore = this._insertBeforeOrAppend(insertBefore, record);
      }
    });
    // Items remaining at the end of the list have been deleted
    if (insertBefore) {
      if (insertBefore._prev) {
        insertBefore._prev._next = null;
      }
      this._removalsHead = insertBefore;
      for (let record = insertBefore; record !== null; record = record._nextRemoved) {
        if (record === this._mapHead) {
          this._mapHead = null;
        }
        this._records.delete(record.key);
        record._nextRemoved = record._next;
        record.previousValue = record.currentValue;
        record.currentValue = null;
        record._prev = null;
        record._next = null;
      }
    }
    // Make sure tails have no next records from previous runs
    if (this._changesTail) this._changesTail._nextChanged = null;
    if (this._additionsTail) this._additionsTail._nextAdded = null;
    return this.isDirty;
  }
  /**
   * Inserts a record before `before` or append at the end of the list when `before` is null.
   *
   * Notes:
   * - This method appends at `this._appendAfter`,
   * - This method updates `this._appendAfter`,
   * - The return value is the new value for the insertion pointer.
   */
  _insertBeforeOrAppend(before, record) {
    if (before) {
      const prev = before._prev;
      record._next = before;
      record._prev = prev;
      before._prev = record;
      if (prev) {
        prev._next = record;
      }
      if (before === this._mapHead) {
        this._mapHead = record;
      }
      this._appendAfter = before;
      return before;
    }
    if (this._appendAfter) {
      this._appendAfter._next = record;
      record._prev = this._appendAfter;
    } else {
      this._mapHead = record;
    }
    this._appendAfter = record;
    return null;
  }
  _getOrCreateRecordForKey(key, value) {
    if (this._records.has(key)) {
      const record = this._records.get(key);
      this._maybeAddToChanges(record, value);
      const prev = record._prev;
      const next = record._next;
      if (prev) {
        prev._next = next;
      }
      if (next) {
        next._prev = prev;
      }
      record._next = null;
      record._prev = null;
      return record;
    }
    const record = new KeyValueChangeRecord_(key);
    this._records.set(key, record);
    record.currentValue = value;
    this._addToAdditions(record);
    return record;
  }
  /** @internal */
  _reset() {
    if (this.isDirty) {
      let record;
      // let `_previousMapHead` contain the state of the map before the changes
      this._previousMapHead = this._mapHead;
      for (record = this._previousMapHead; record !== null; record = record._next) {
        record._nextPrevious = record._next;
      }
      // Update `record.previousValue` with the value of the item before the changes
      // We need to update all changed items (that's those which have been added and changed)
      for (record = this._changesHead; record !== null; record = record._nextChanged) {
        record.previousValue = record.currentValue;
      }
      for (record = this._additionsHead; record != null; record = record._nextAdded) {
        record.previousValue = record.currentValue;
      }
      this._changesHead = this._changesTail = null;
      this._additionsHead = this._additionsTail = null;
      this._removalsHead = null;
    }
  }
  // Add the record or a given key to the list of changes only when the value has actually changed
  _maybeAddToChanges(record, newValue) {
    if (!Object.is(newValue, record.currentValue)) {
      record.previousValue = record.currentValue;
      record.currentValue = newValue;
      this._addToChanges(record);
    }
  }
  _addToAdditions(record) {
    if (this._additionsHead === null) {
      this._additionsHead = this._additionsTail = record;
    } else {
      this._additionsTail._nextAdded = record;
      this._additionsTail = record;
    }
  }
  _addToChanges(record) {
    if (this._changesHead === null) {
      this._changesHead = this._changesTail = record;
    } else {
      this._changesTail._nextChanged = record;
      this._changesTail = record;
    }
  }
  /** @internal */
  _forEach(obj, fn) {
    if (obj instanceof Map) {
      obj.forEach(fn);
    } else {
      Object.keys(obj).forEach(k => fn(obj[k], k));
    }
  }
}
class KeyValueChangeRecord_ {
  key;
  previousValue = null;
  currentValue = null;
  /** @internal */
  _nextPrevious = null;
  /** @internal */
  _next = null;
  /** @internal */
  _prev = null;
  /** @internal */
  _nextAdded = null;
  /** @internal */
  _nextRemoved = null;
  /** @internal */
  _nextChanged = null;
  constructor(key) {
    this.key = key;
  }
}
function defaultIterableDiffersFactory() {
  return new IterableDiffers([new DefaultIterableDifferFactory()]);
}
/**
 * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
 *
 * @publicApi
 */
let IterableDiffers = /*#__PURE__*/(() => {
  class IterableDiffers {
    factories;
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: IterableDiffers,
      providedIn: 'root',
      factory: defaultIterableDiffersFactory
    }))();
    constructor(factories) {
      this.factories = factories;
    }
    static create(factories, parent) {
      if (parent != null) {
        const copied = parent.factories.slice();
        factories = factories.concat(copied);
      }
      return new IterableDiffers(factories);
    }
    /**
     * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
     * inherited {@link IterableDiffers} instance with the provided factories and return a new
     * {@link IterableDiffers} instance.
     *
     * @usageNotes
     * ### Example
     *
     * The following example shows how to extend an existing list of factories,
     * which will only be applied to the injector for this component and its children.
     * This step is all that's required to make a new {@link IterableDiffer} available.
     *
     * ```
     * @Component({
     *   viewProviders: [
     *     IterableDiffers.extend([new ImmutableListDiffer()])
     *   ]
     * })
     * ```
     */
    static extend(factories) {
      return {
        provide: IterableDiffers,
        useFactory: parent => {
          // if parent is null, it means that we are in the root injector and we have just overridden
          // the default injection mechanism for IterableDiffers, in such a case just assume
          // `defaultIterableDiffersFactory`.
          return IterableDiffers.create(factories, parent || defaultIterableDiffersFactory());
        },
        // Dependency technically isn't optional, but we can provide a better error message this way.
        deps: [[IterableDiffers, new SkipSelf(), new Optional()]]
      };
    }
    find(iterable) {
      const factory = this.factories.find(f => f.supports(iterable));
      if (factory != null) {
        return factory;
      } else {
        throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode && `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
      }
    }
  }
  return IterableDiffers;
})();
function getTypeNameForDebugging(type) {
  return type['name'] || typeof type;
}
function defaultKeyValueDiffersFactory() {
  return new KeyValueDiffers([new DefaultKeyValueDifferFactory()]);
}
/**
 * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
 *
 * @publicApi
 */
let KeyValueDiffers = /*#__PURE__*/(() => {
  class KeyValueDiffers {
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: KeyValueDiffers,
      providedIn: 'root',
      factory: defaultKeyValueDiffersFactory
    }))();
    factories;
    constructor(factories) {
      this.factories = factories;
    }
    static create(factories, parent) {
      if (parent) {
        const copied = parent.factories.slice();
        factories = factories.concat(copied);
      }
      return new KeyValueDiffers(factories);
    }
    /**
     * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
     * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
     * {@link KeyValueDiffers} instance.
     *
     * @usageNotes
     * ### Example
     *
     * The following example shows how to extend an existing list of factories,
     * which will only be applied to the injector for this component and its children.
     * This step is all that's required to make a new {@link KeyValueDiffer} available.
     *
     * ```
     * @Component({
     *   viewProviders: [
     *     KeyValueDiffers.extend([new ImmutableMapDiffer()])
     *   ]
     * })
     * ```
     */
    static extend(factories) {
      return {
        provide: KeyValueDiffers,
        useFactory: parent => {
          // if parent is null, it means that we are in the root injector and we have just overridden
          // the default injection mechanism for KeyValueDiffers, in such a case just assume
          // `defaultKeyValueDiffersFactory`.
          return KeyValueDiffers.create(factories, parent || defaultKeyValueDiffersFactory());
        },
        // Dependency technically isn't optional, but we can provide a better error message this way.
        deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]]
      };
    }
    find(kv) {
      const factory = this.factories.find(f => f.supports(kv));
      if (factory) {
        return factory;
      }
      throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode && `Cannot find a differ supporting object '${kv}'`);
    }
  }
  return KeyValueDiffers;
})();
/**
 * Structural diffing for `Object`s and `Map`s.
 */
const keyValDiff = [/*#__PURE__*/new DefaultKeyValueDifferFactory()];
/**
 * Structural diffing for `Iterable` types such as `Array`s.
 */
const iterableDiff = [/*#__PURE__*/new DefaultIterableDifferFactory()];
const defaultIterableDiffers = /*#__PURE__*/new IterableDiffers(iterableDiff);
const defaultKeyValueDiffers = /*#__PURE__*/new KeyValueDiffers(keyValDiff);

/**
 * @module
 * @description
 * Change detection enables data binding in Angular.
 */

/**
 * This platform has to be included in any other platform
 *
 * @publicApi
 */
const platformCore = /*#__PURE__*/createPlatformFactory(null, 'core', []);

/**
 * Re-exported by `BrowserModule`, which is included automatically in the root
 * `AppModule` when you create a new app with the CLI `new` command. Eagerly injects
 * `ApplicationRef` to instantiate it.
 *
 * @publicApi
 */
let ApplicationModule = /*#__PURE__*/(() => {
  class ApplicationModule {
    // Inject ApplicationRef to make it eager...
    constructor(appRef) {}
    static ɵfac = function ApplicationModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ApplicationModule)(ɵɵinject(ApplicationRef));
    };
    static ɵmod = (() => /*@__PURE__*/ɵɵdefineNgModule({
      type: ApplicationModule
    }))();
    static ɵinj = (() => /*@__PURE__*/ɵɵdefineInjector({}))();
  }
  return ApplicationModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationModule, [{
    type: NgModule
  }], () => [{
    type: ApplicationRef
  }], null);
})();

/**
 * The default equality function used for `signal` and `computed`, which uses referential equality.
 */
function defaultEquals(a, b) {
  return Object.is(a, b);
}

/**
 * The currently active consumer `ReactiveNode`, if running code in a reactive context.
 *
 * Change this via `setActiveConsumer`.
 */
let activeConsumer = null;
let inNotificationPhase = false;
/**
 * Global epoch counter. Incremented whenever a source signal is set.
 */
let epoch = 1;
/**
 * Symbol used to tell `Signal`s apart from other functions.
 *
 * This can be used to auto-unwrap signals in various cases, or to auto-wrap non-signal values.
 */
const SIGNAL = /* @__PURE__ */Symbol('SIGNAL');
function setActiveConsumer(consumer) {
  const prev = activeConsumer;
  activeConsumer = consumer;
  return prev;
}
function getActiveConsumer() {
  return activeConsumer;
}
function isInNotificationPhase() {
  return inNotificationPhase;
}
function isReactive(value) {
  return value[SIGNAL] !== undefined;
}
const REACTIVE_NODE = {
  version: 0,
  lastCleanEpoch: 0,
  dirty: false,
  producerNode: undefined,
  producerLastReadVersion: undefined,
  producerIndexOfThis: undefined,
  nextProducerIndex: 0,
  liveConsumerNode: undefined,
  liveConsumerIndexOfThis: undefined,
  consumerAllowSignalWrites: false,
  consumerIsAlwaysLive: false,
  producerMustRecompute: () => false,
  producerRecomputeValue: () => {},
  consumerMarkedDirty: () => {},
  consumerOnSignalRead: () => {}
};
/**
 * Called by implementations when a producer's signal is read.
 */
function producerAccessed(node) {
  if (inNotificationPhase) {
    throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? `Assertion error: signal read during notification phase` : '');
  }
  if (activeConsumer === null) {
    // Accessed outside of a reactive context, so nothing to record.
    return;
  }
  activeConsumer.consumerOnSignalRead(node);
  // This producer is the `idx`th dependency of `activeConsumer`.
  const idx = activeConsumer.nextProducerIndex++;
  assertConsumerNode(activeConsumer);
  if (idx < activeConsumer.producerNode.length && activeConsumer.producerNode[idx] !== node) {
    // There's been a change in producers since the last execution of `activeConsumer`.
    // `activeConsumer.producerNode[idx]` holds a stale dependency which will be be removed and
    // replaced with `this`.
    //
    // If `activeConsumer` isn't live, then this is a no-op, since we can replace the producer in
    // `activeConsumer.producerNode` directly. However, if `activeConsumer` is live, then we need
    // to remove it from the stale producer's `liveConsumer`s.
    if (consumerIsLive(activeConsumer)) {
      const staleProducer = activeConsumer.producerNode[idx];
      producerRemoveLiveConsumerAtIndex(staleProducer, activeConsumer.producerIndexOfThis[idx]);
      // At this point, the only record of `staleProducer` is the reference at
      // `activeConsumer.producerNode[idx]` which will be overwritten below.
    }
  }
  if (activeConsumer.producerNode[idx] !== node) {
    // We're a new dependency of the consumer (at `idx`).
    activeConsumer.producerNode[idx] = node;
    // If the active consumer is live, then add it as a live consumer. If not, then use 0 as a
    // placeholder value.
    activeConsumer.producerIndexOfThis[idx] = consumerIsLive(activeConsumer) ? producerAddLiveConsumer(node, activeConsumer, idx) : 0;
  }
  activeConsumer.producerLastReadVersion[idx] = node.version;
}
/**
 * Increment the global epoch counter.
 *
 * Called by source producers (that is, not computeds) whenever their values change.
 */
function producerIncrementEpoch() {
  epoch++;
}
/**
 * Ensure this producer's `version` is up-to-date.
 */
function producerUpdateValueVersion(node) {
  if (consumerIsLive(node) && !node.dirty) {
    // A live consumer will be marked dirty by producers, so a clean state means that its version
    // is guaranteed to be up-to-date.
    return;
  }
  if (!node.dirty && node.lastCleanEpoch === epoch) {
    // Even non-live consumers can skip polling if they previously found themselves to be clean at
    // the current epoch, since their dependencies could not possibly have changed (such a change
    // would've increased the epoch).
    return;
  }
  if (!node.producerMustRecompute(node) && !consumerPollProducersForChange(node)) {
    // None of our producers report a change since the last time they were read, so no
    // recomputation of our value is necessary, and we can consider ourselves clean.
    producerMarkClean(node);
    return;
  }
  node.producerRecomputeValue(node);
  // After recomputing the value, we're no longer dirty.
  producerMarkClean(node);
}
/**
 * Propagate a dirty notification to live consumers of this producer.
 */
function producerNotifyConsumers(node) {
  if (node.liveConsumerNode === undefined) {
    return;
  }
  // Prevent signal reads when we're updating the graph
  const prev = inNotificationPhase;
  inNotificationPhase = true;
  try {
    for (const consumer of node.liveConsumerNode) {
      if (!consumer.dirty) {
        consumerMarkDirty(consumer);
      }
    }
  } finally {
    inNotificationPhase = prev;
  }
}
/**
 * Whether this `ReactiveNode` in its producer capacity is currently allowed to initiate updates,
 * based on the current consumer context.
 */
function producerUpdatesAllowed() {
  return activeConsumer?.consumerAllowSignalWrites !== false;
}
function consumerMarkDirty(node) {
  node.dirty = true;
  producerNotifyConsumers(node);
  node.consumerMarkedDirty?.(node);
}
function producerMarkClean(node) {
  node.dirty = false;
  node.lastCleanEpoch = epoch;
}
/**
 * Prepare this consumer to run a computation in its reactive context.
 *
 * Must be called by subclasses which represent reactive computations, before those computations
 * begin.
 */
function consumerBeforeComputation(node) {
  node && (node.nextProducerIndex = 0);
  return setActiveConsumer(node);
}
/**
 * Finalize this consumer's state after a reactive computation has run.
 *
 * Must be called by subclasses which represent reactive computations, after those computations
 * have finished.
 */
function consumerAfterComputation(node, prevConsumer) {
  setActiveConsumer(prevConsumer);
  if (!node || node.producerNode === undefined || node.producerIndexOfThis === undefined || node.producerLastReadVersion === undefined) {
    return;
  }
  if (consumerIsLive(node)) {
    // For live consumers, we need to remove the producer -> consumer edge for any stale producers
    // which weren't dependencies after the recomputation.
    for (let i = node.nextProducerIndex; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Truncate the producer tracking arrays.
  // Perf note: this is essentially truncating the length to `node.nextProducerIndex`, but
  // benchmarking has shown that individual pop operations are faster.
  while (node.producerNode.length > node.nextProducerIndex) {
    node.producerNode.pop();
    node.producerLastReadVersion.pop();
    node.producerIndexOfThis.pop();
  }
}
/**
 * Determine whether this consumer has any dependencies which have changed since the last time
 * they were read.
 */
function consumerPollProducersForChange(node) {
  assertConsumerNode(node);
  // Poll producers for change.
  for (let i = 0; i < node.producerNode.length; i++) {
    const producer = node.producerNode[i];
    const seenVersion = node.producerLastReadVersion[i];
    // First check the versions. A mismatch means that the producer's value is known to have
    // changed since the last time we read it.
    if (seenVersion !== producer.version) {
      return true;
    }
    // The producer's version is the same as the last time we read it, but it might itself be
    // stale. Force the producer to recompute its version (calculating a new value if necessary).
    producerUpdateValueVersion(producer);
    // Now when we do this check, `producer.version` is guaranteed to be up to date, so if the
    // versions still match then it has not changed since the last time we read it.
    if (seenVersion !== producer.version) {
      return true;
    }
  }
  return false;
}
/**
 * Disconnect this consumer from the graph.
 */
function consumerDestroy(node) {
  assertConsumerNode(node);
  if (consumerIsLive(node)) {
    // Drop all connections from the graph to this node.
    for (let i = 0; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Truncate all the arrays to drop all connection from this node to the graph.
  node.producerNode.length = node.producerLastReadVersion.length = node.producerIndexOfThis.length = 0;
  if (node.liveConsumerNode) {
    node.liveConsumerNode.length = node.liveConsumerIndexOfThis.length = 0;
  }
}
/**
 * Add `consumer` as a live consumer of this node.
 *
 * Note that this operation is potentially transitive. If this node becomes live, then it becomes
 * a live consumer of all of its current producers.
 */
function producerAddLiveConsumer(node, consumer, indexOfThis) {
  assertProducerNode(node);
  if (node.liveConsumerNode.length === 0 && isConsumerNode(node)) {
    // When going from 0 to 1 live consumers, we become a live consumer to our producers.
    for (let i = 0; i < node.producerNode.length; i++) {
      node.producerIndexOfThis[i] = producerAddLiveConsumer(node.producerNode[i], node, i);
    }
  }
  node.liveConsumerIndexOfThis.push(indexOfThis);
  return node.liveConsumerNode.push(consumer) - 1;
}
/**
 * Remove the live consumer at `idx`.
 */
function producerRemoveLiveConsumerAtIndex(node, idx) {
  assertProducerNode(node);
  if (typeof ngDevMode !== 'undefined' && ngDevMode && idx >= node.liveConsumerNode.length) {
    throw new Error(`Assertion error: active consumer index ${idx} is out of bounds of ${node.liveConsumerNode.length} consumers)`);
  }
  if (node.liveConsumerNode.length === 1 && isConsumerNode(node)) {
    // When removing the last live consumer, we will no longer be live. We need to remove
    // ourselves from our producers' tracking (which may cause consumer-producers to lose
    // liveness as well).
    for (let i = 0; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Move the last value of `liveConsumers` into `idx`. Note that if there's only a single
  // live consumer, this is a no-op.
  const lastIdx = node.liveConsumerNode.length - 1;
  node.liveConsumerNode[idx] = node.liveConsumerNode[lastIdx];
  node.liveConsumerIndexOfThis[idx] = node.liveConsumerIndexOfThis[lastIdx];
  // Truncate the array.
  node.liveConsumerNode.length--;
  node.liveConsumerIndexOfThis.length--;
  // If the index is still valid, then we need to fix the index pointer from the producer to this
  // consumer, and update it from `lastIdx` to `idx` (accounting for the move above).
  if (idx < node.liveConsumerNode.length) {
    const idxProducer = node.liveConsumerIndexOfThis[idx];
    const consumer = node.liveConsumerNode[idx];
    assertConsumerNode(consumer);
    consumer.producerIndexOfThis[idxProducer] = idx;
  }
}
function consumerIsLive(node) {
  return node.consumerIsAlwaysLive || (node?.liveConsumerNode?.length ?? 0) > 0;
}
function assertConsumerNode(node) {
  node.producerNode ??= [];
  node.producerIndexOfThis ??= [];
  node.producerLastReadVersion ??= [];
}
function assertProducerNode(node) {
  node.liveConsumerNode ??= [];
  node.liveConsumerIndexOfThis ??= [];
}
function isConsumerNode(node) {
  return node.producerNode !== undefined;
}

/**
 * Create a computed signal which derives a reactive value from an expression.
 */
function createComputed(computation) {
  const node = Object.create(COMPUTED_NODE);
  node.computation = computation;
  const computed = () => {
    // Check if the value needs updating before returning it.
    producerUpdateValueVersion(node);
    // Record that someone looked at this signal.
    producerAccessed(node);
    if (node.value === ERRORED$1) {
      throw node.error;
    }
    return node.value;
  };
  computed[SIGNAL] = node;
  return computed;
}
/**
 * A dedicated symbol used before a computed value has been calculated for the first time.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const UNSET$1 = /* @__PURE__ */Symbol('UNSET');
/**
 * A dedicated symbol used in place of a computed signal value to indicate that a given computation
 * is in progress. Used to detect cycles in computation chains.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const COMPUTING$1 = /* @__PURE__ */Symbol('COMPUTING');
/**
 * A dedicated symbol used in place of a computed signal value to indicate that a given computation
 * failed. The thrown error is cached until the computation gets dirty again.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const ERRORED$1 = /* @__PURE__ */Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const COMPUTED_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    value: UNSET$1,
    dirty: true,
    error: null,
    equal: defaultEquals,
    producerMustRecompute(node) {
      // Force a recomputation if there's no current value, or if the current value is in the
      // process of being calculated (which should throw an error).
      return node.value === UNSET$1 || node.value === COMPUTING$1;
    },
    producerRecomputeValue(node) {
      if (node.value === COMPUTING$1) {
        // Our computation somehow led to a cyclic read of itself.
        throw new Error('Detected cycle in computations.');
      }
      const oldValue = node.value;
      node.value = COMPUTING$1;
      const prevConsumer = consumerBeforeComputation(node);
      let newValue;
      try {
        newValue = node.computation();
      } catch (err) {
        newValue = ERRORED$1;
        node.error = err;
      } finally {
        consumerAfterComputation(node, prevConsumer);
      }
      if (oldValue !== UNSET$1 && oldValue !== ERRORED$1 && newValue !== ERRORED$1 && node.equal(oldValue, newValue)) {
        // No change to `valueVersion` - old and new values are
        // semantically equivalent.
        node.value = oldValue;
        return;
      }
      node.value = newValue;
      node.version++;
    }
  };
})();
function defaultThrowError() {
  throw new Error();
}
let throwInvalidWriteToSignalErrorFn = defaultThrowError;
function throwInvalidWriteToSignalError() {
  throwInvalidWriteToSignalErrorFn();
}
function setThrowInvalidWriteToSignalError(fn) {
  throwInvalidWriteToSignalErrorFn = fn;
}

/**
 * If set, called after `WritableSignal`s are updated.
 *
 * This hook can be used to achieve various effects, such as running effects synchronously as part
 * of setting a signal.
 */
let postSignalSetFn = null;
/**
 * Create a `Signal` that can be set or updated directly.
 */
function createSignal(initialValue) {
  const node = Object.create(SIGNAL_NODE);
  node.value = initialValue;
  const getter = () => {
    producerAccessed(node);
    return node.value;
  };
  getter[SIGNAL] = node;
  return getter;
}
function setPostSignalSetFn(fn) {
  const prev = postSignalSetFn;
  postSignalSetFn = fn;
  return prev;
}
function signalGetFn() {
  producerAccessed(this);
  return this.value;
}
function signalSetFn(node, newValue) {
  if (!producerUpdatesAllowed()) {
    throwInvalidWriteToSignalError();
  }
  if (!node.equal(node.value, newValue)) {
    node.value = newValue;
    signalValueChanged(node);
  }
}
function signalUpdateFn(node, updater) {
  if (!producerUpdatesAllowed()) {
    throwInvalidWriteToSignalError();
  }
  signalSetFn(node, updater(node.value));
}
function runPostSignalSetFn() {
  postSignalSetFn?.();
}
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const SIGNAL_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    equal: defaultEquals,
    value: undefined
  };
})();
function signalValueChanged(node) {
  node.version++;
  producerIncrementEpoch();
  producerNotifyConsumers(node);
  postSignalSetFn?.();
}
function createWatch(fn, schedule, allowSignalWrites) {
  const node = Object.create(WATCH_NODE);
  if (allowSignalWrites) {
    node.consumerAllowSignalWrites = true;
  }
  node.fn = fn;
  node.schedule = schedule;
  const registerOnCleanup = cleanupFn => {
    node.cleanupFn = cleanupFn;
  };
  function isWatchNodeDestroyed(node) {
    return node.fn === null && node.schedule === null;
  }
  function destroyWatchNode(node) {
    if (!isWatchNodeDestroyed(node)) {
      consumerDestroy(node); // disconnect watcher from the reactive graph
      node.cleanupFn();
      // nullify references to the integration functions to mark node as destroyed
      node.fn = null;
      node.schedule = null;
      node.cleanupFn = NOOP_CLEANUP_FN;
    }
  }
  const run = () => {
    if (node.fn === null) {
      // trying to run a destroyed watch is noop
      return;
    }
    if (isInNotificationPhase()) {
      throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
    }
    node.dirty = false;
    if (node.hasRun && !consumerPollProducersForChange(node)) {
      return;
    }
    node.hasRun = true;
    const prevConsumer = consumerBeforeComputation(node);
    try {
      node.cleanupFn();
      node.cleanupFn = NOOP_CLEANUP_FN;
      node.fn(registerOnCleanup);
    } finally {
      consumerAfterComputation(node, prevConsumer);
    }
  };
  node.ref = {
    notify: () => consumerMarkDirty(node),
    run,
    cleanup: () => node.cleanupFn(),
    destroy: () => destroyWatchNode(node),
    [SIGNAL]: node
  };
  return node.ref;
}
const NOOP_CLEANUP_FN = () => {};
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const WATCH_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    consumerIsAlwaysLive: true,
    consumerAllowSignalWrites: false,
    consumerMarkedDirty: node => {
      if (node.schedule !== null) {
        node.schedule(node.ref);
      }
    },
    hasRun: false,
    cleanupFn: NOOP_CLEANUP_FN
  };
})();
function setAlternateWeakRefImpl(impl) {
  // TODO: remove this function
}

/**
 * Internal create application API that implements the core application creation logic and optional
 * bootstrap logic.
 *
 * Platforms (such as `platform-browser`) may require different set of application and platform
 * providers for an application to function correctly. As a result, platforms may use this function
 * internally and supply the necessary providers during the bootstrap, while exposing
 * platform-specific APIs as a part of their public API.
 *
 * @returns A promise that returns an `ApplicationRef` instance once resolved.
 */
function internalCreateApplication(config) {
  try {
    const {
      rootComponent,
      appProviders,
      platformProviders
    } = config;
    if ((typeof ngDevMode === 'undefined' || ngDevMode) && rootComponent !== undefined) {
      assertStandaloneComponentType(rootComponent);
    }
    const platformInjector = createOrReusePlatformInjector(platformProviders);
    // Create root application injector based on a set of providers configured at the platform
    // bootstrap level as well as providers passed to the bootstrap call by a user.
    const allAppProviders = [internalProvideZoneChangeDetection({}), {
      provide: ChangeDetectionScheduler,
      useExisting: ChangeDetectionSchedulerImpl
    }, ...(appProviders || [])];
    const adapter = new EnvironmentNgModuleRefAdapter({
      providers: allAppProviders,
      parent: platformInjector,
      debugName: typeof ngDevMode === 'undefined' || ngDevMode ? 'Environment Injector' : '',
      // We skip environment initializers because we need to run them inside the NgZone, which
      // happens after we get the NgZone instance from the Injector.
      runEnvironmentInitializers: false
    });
    return bootstrap({
      r3Injector: adapter.injector,
      platformInjector,
      rootComponent
    });
  } catch (e) {
    return Promise.reject(e);
  }
}

/**
 * Retrieves all defer blocks in a given LView.
 *
 * @param lView lView with defer blocks
 * @param deferBlocks defer block aggregator array
 */
function getDeferBlocks(lView, deferBlocks) {
  const tView = lView[TVIEW];
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    if (isLContainer(lView[i])) {
      const lContainer = lView[i];
      // An LContainer may represent an instance of a defer block, in which case
      // we store it as a result. Otherwise, keep iterating over LContainer views and
      // look for defer blocks.
      const isLast = i === tView.bindingStartIndex - 1;
      if (!isLast) {
        const tNode = tView.data[i];
        const tDetails = getTDeferBlockDetails(tView, tNode);
        if (isTDeferBlockDetails(tDetails)) {
          deferBlocks.push({
            lContainer,
            lView,
            tNode,
            tDetails
          });
          // This LContainer represents a defer block, so we exit
          // this iteration and don't inspect views in this LContainer.
          continue;
        }
      }
      for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
        getDeferBlocks(lContainer[i], deferBlocks);
      }
    } else if (isLView(lView[i])) {
      // This is a component, enter the `getDeferBlocks` recursively.
      getDeferBlocks(lView[i], deferBlocks);
    }
  }
}

/** Apps in which we've enabled event replay.
 *  This is to prevent initializing event replay more than once per app.
 */
const appsWithEventReplay = /*#__PURE__*/new WeakSet();
/**
 * The key that represents all replayable elements that are not in defer blocks.
 */
const EAGER_CONTENT_LISTENERS_KEY = '';
/**
 * A list of block events that need to be replayed
 */
let blockEventQueue = [];
/**
 * Determines whether Event Replay feature should be activated on the client.
 */
function shouldEnableEventReplay(injector) {
  return injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
}
/**
 * Returns a set of providers required to setup support for event replay.
 * Requires hydration to be enabled separately.
 */
function withEventReplay() {
  const providers = [{
    provide: IS_EVENT_REPLAY_ENABLED,
    useFactory: () => {
      let isEnabled = true;
      if (typeof ngServerMode === 'undefined' || !ngServerMode) {
        // Note: globalThis[CONTRACT_PROPERTY] may be undefined in case Event Replay feature
        // is enabled, but there are no events configured in this application, in which case
        // we don't activate this feature, since there are no events to replay.
        const appId = inject(APP_ID);
        isEnabled = !!window._ejsas?.[appId];
      }
      if (isEnabled) {
        performanceMarkFeature('NgEventReplay');
      }
      return isEnabled;
    }
  }];
  if (typeof ngServerMode === 'undefined' || !ngServerMode) {
    providers.push({
      provide: ENVIRONMENT_INITIALIZER,
      useValue: () => {
        const injector = inject(Injector);
        const appRef = injector.get(ApplicationRef);
        // We have to check for the appRef here due to the possibility of multiple apps
        // being present on the same page. We only want to enable event replay for the
        // apps that actually want it.
        if (!appsWithEventReplay.has(appRef)) {
          const jsActionMap = inject(JSACTION_BLOCK_ELEMENT_MAP);
          if (shouldEnableEventReplay(injector)) {
            setStashFn((rEl, eventName, listenerFn) => {
              sharedStashFunction(rEl, eventName, listenerFn);
              sharedMapFunction(rEl, jsActionMap);
            });
          }
        }
      },
      multi: true
    }, {
      provide: APP_BOOTSTRAP_LISTENER,
      useFactory: () => {
        const injector = inject(Injector);
        const appRef = inject(ApplicationRef);
        return () => {
          // We have to check for the appRef here due to the possibility of multiple apps
          // being present on the same page. We only want to enable event replay for the
          // apps that actually want it.
          if (!shouldEnableEventReplay(injector) || appsWithEventReplay.has(appRef)) {
            return;
          }
          appsWithEventReplay.add(appRef);
          appRef.onDestroy(() => appsWithEventReplay.delete(appRef));
          // Kick off event replay logic once hydration for the initial part
          // of the application is completed. This timing is similar to the unclaimed
          // dehydrated views cleanup timing.
          whenStable(appRef).then(() => {
            const eventContractDetails = injector.get(JSACTION_EVENT_CONTRACT);
            initEventReplay(eventContractDetails, injector);
            const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
            jsActionMap.get(EAGER_CONTENT_LISTENERS_KEY)?.forEach(removeListeners);
            jsActionMap.delete(EAGER_CONTENT_LISTENERS_KEY);
            const eventContract = eventContractDetails.instance;
            // This removes event listeners registered through the container manager,
            // as listeners registered on `document.body` might never be removed if we
            // don't clean up the contract.
            if (isIncrementalHydrationEnabled(injector)) {
              // When incremental hydration is enabled, we cannot clean up the event
              // contract immediately because we're unaware if there are any deferred
              // blocks to hydrate. We can only schedule a contract cleanup when the
              // app is destroyed.
              appRef.onDestroy(() => eventContract.cleanUp());
            } else {
              eventContract.cleanUp();
            }
          });
        };
      },
      multi: true
    });
  }
  return providers;
}
const initEventReplay = (eventDelegation, injector) => {
  const appId = injector.get(APP_ID);
  // This is set in packages/platform-server/src/utils.ts
  const earlyJsactionData = window._ejsas[appId];
  const eventContract = eventDelegation.instance = new _angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.EventContract(new _angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.EventContractContainer(earlyJsactionData.c));
  for (const et of earlyJsactionData.et) {
    eventContract.addEvent(et);
  }
  for (const et of earlyJsactionData.etc) {
    eventContract.addEvent(et);
  }
  const eventInfos = (0,_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.getAppScopedQueuedEventInfos)(appId);
  eventContract.replayEarlyEventInfos(eventInfos);
  (0,_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.clearAppScopedEarlyEventContract)(appId);
  const dispatcher = new _angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.EventDispatcher(event => {
    invokeRegisteredReplayListeners(injector, event, event.currentTarget);
  });
  (0,_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.registerDispatcher)(eventContract, dispatcher);
};
/**
 * Extracts information about all DOM events (added in a template) registered on elements in a give
 * LView. Maps collected events to a corresponding DOM element (an element is used as a key).
 */
function collectDomEventsInfo(tView, lView, eventTypesToReplay) {
  const domEventsInfo = new Map();
  const lCleanup = lView[CLEANUP];
  const tCleanup = tView.cleanup;
  if (!tCleanup || !lCleanup) {
    return domEventsInfo;
  }
  for (let i = 0; i < tCleanup.length;) {
    const firstParam = tCleanup[i++];
    const secondParam = tCleanup[i++];
    if (typeof firstParam !== 'string') {
      continue;
    }
    const eventType = firstParam;
    if (!(0,_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.isEarlyEventType)(eventType)) {
      continue;
    }
    if ((0,_angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.isCaptureEventType)(eventType)) {
      eventTypesToReplay.capture.add(eventType);
    } else {
      eventTypesToReplay.regular.add(eventType);
    }
    const listenerElement = unwrapRNode(lView[secondParam]);
    i++; // move the cursor to the next position (location of the listener idx)
    const useCaptureOrIndx = tCleanup[i++];
    // if useCaptureOrIndx is boolean then report it as is.
    // if useCaptureOrIndx is positive number then it in unsubscribe method
    // if useCaptureOrIndx is negative number then it is a Subscription
    const isDomEvent = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0;
    if (!isDomEvent) {
      continue;
    }
    if (!domEventsInfo.has(listenerElement)) {
      domEventsInfo.set(listenerElement, [eventType]);
    } else {
      domEventsInfo.get(listenerElement).push(eventType);
    }
  }
  return domEventsInfo;
}
function invokeRegisteredReplayListeners(injector, event, currentTarget) {
  const blockName = (currentTarget && currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE)) ?? '';
  if (/d\d+/.test(blockName)) {
    hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget);
  } else if (event.eventPhase === _angular_core_primitives_event_dispatch__WEBPACK_IMPORTED_MODULE_5__.EventPhase.REPLAY) {
    invokeListeners(event, currentTarget);
  }
}
function hydrateAndInvokeBlockListeners(_x16, _x17, _x18, _x19) {
  return _hydrateAndInvokeBlockListeners.apply(this, arguments);
}
function _hydrateAndInvokeBlockListeners() {
  _hydrateAndInvokeBlockListeners = (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* (blockName, injector, event, currentTarget) {
    blockEventQueue.push({
      event,
      currentTarget
    });
    yield triggerHydrationFromBlockName(injector, blockName, replayQueuedBlockEvents);
  });
  return _hydrateAndInvokeBlockListeners.apply(this, arguments);
}
function replayQueuedBlockEvents(hydratedBlocks) {
  // clone the queue
  const queue = [...blockEventQueue];
  // empty it
  blockEventQueue = [];
  for (let {
    event,
    currentTarget
  } of queue) {
    const blockName = currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
    if (hydratedBlocks.has(blockName)) {
      invokeListeners(event, currentTarget);
    } else {
      // requeue events that weren't yet hydrated
      blockEventQueue.push({
        event,
        currentTarget
      });
    }
  }
}

/**
 * A collection that tracks all serialized views (`ngh` DOM annotations)
 * to avoid duplication. An attempt to add a duplicate view results in the
 * collection returning the index of the previously collected serialized view.
 * This reduces the number of annotations needed for a given page.
 */
class SerializedViewCollection {
  views = [];
  indexByContent = /*#__PURE__*/(() => new Map())();
  add(serializedView) {
    const viewAsString = JSON.stringify(serializedView);
    if (!this.indexByContent.has(viewAsString)) {
      const index = this.views.length;
      this.views.push(serializedView);
      this.indexByContent.set(viewAsString, index);
      return index;
    }
    return this.indexByContent.get(viewAsString);
  }
  getAll() {
    return this.views;
  }
}
/**
 * Global counter that is used to generate a unique id for TViews
 * during the serialization process.
 */
let tViewSsrId = 0;
/**
 * Generates a unique id for a given TView and returns this id.
 * The id is also stored on this instance of a TView and reused in
 * subsequent calls.
 *
 * This id is needed to uniquely identify and pick up dehydrated views
 * at runtime.
 */
function getSsrId(tView) {
  if (!tView.ssrId) {
    tView.ssrId = `t${tViewSsrId++}`;
  }
  return tView.ssrId;
}
/**
 * Computes the number of root nodes in a given view
 * (or child nodes in a given container if a tNode is provided).
 */
function calcNumRootNodes(tView, lView, tNode) {
  const rootNodes = [];
  collectNativeNodes(tView, lView, tNode, rootNodes);
  return rootNodes.length;
}
/**
 * Computes the number of root nodes in all views in a given LContainer.
 */
function calcNumRootNodesInLContainer(lContainer) {
  const rootNodes = [];
  collectNativeNodesInLContainer(lContainer, rootNodes);
  return rootNodes.length;
}
/**
 * Annotates root level component's LView for hydration,
 * see `annotateHostElementForHydration` for additional information.
 */
function annotateComponentLViewForHydration(lView, context, injector) {
  const hostElement = lView[HOST];
  // Root elements might also be annotated with the `ngSkipHydration` attribute,
  // check if it's present before starting the serialization process.
  if (hostElement && !hostElement.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
    return annotateHostElementForHydration(hostElement, lView, null, context);
  }
  return null;
}
/**
 * Annotates root level LContainer for hydration. This happens when a root component
 * injects ViewContainerRef, thus making the component an anchor for a view container.
 * This function serializes the component itself as well as all views from the view
 * container.
 */
function annotateLContainerForHydration(lContainer, context, injector) {
  const componentLView = unwrapLView(lContainer[HOST]);
  // Serialize the root component itself.
  const componentLViewNghIndex = annotateComponentLViewForHydration(componentLView, context, injector);
  if (componentLViewNghIndex === null) {
    // Component was not serialized (for example, if hydration was skipped by adding
    // the `ngSkipHydration` attribute or this component uses i18n blocks in the template,
    // but `withI18nSupport()` was not added), avoid annotating host element with the `ngh`
    // attribute.
    return;
  }
  const hostElement = unwrapRNode(componentLView[HOST]);
  // Serialize all views within this view container.
  const rootLView = lContainer[PARENT];
  const rootLViewNghIndex = annotateHostElementForHydration(hostElement, rootLView, null, context);
  const renderer = componentLView[RENDERER];
  // For cases when a root component also acts as an anchor node for a ViewContainerRef
  // (for example, when ViewContainerRef is injected in a root component), there is a need
  // to serialize information about the component itself, as well as an LContainer that
  // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  // (1) hydration info for the root component itself and (2) hydration info for the
  // ViewContainerRef instance (an LContainer). Each piece of information is included into
  // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  // Since we only have 1 root element, we encode both bits of info into a single string:
  // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  // and 25 is the `ngh` for a root view which holds LContainer).
  const finalIndex = `${componentLViewNghIndex}|${rootLViewNghIndex}`;
  renderer.setAttribute(hostElement, NGH_ATTR_NAME, finalIndex);
}
/**
 * Annotates all components bootstrapped in a given ApplicationRef
 * with info needed for hydration.
 *
 * @param appRef An instance of an ApplicationRef.
 * @param doc A reference to the current Document instance.
 * @return event types that need to be replayed
 */
function annotateForHydration(appRef, doc) {
  const injector = appRef.injector;
  const isI18nHydrationEnabledVal = isI18nHydrationEnabled(injector);
  const isIncrementalHydrationEnabledVal = isIncrementalHydrationEnabled(injector);
  const serializedViewCollection = new SerializedViewCollection();
  const corruptedTextNodes = new Map();
  const viewRefs = appRef._views;
  const shouldReplayEvents = injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
  const eventTypesToReplay = {
    regular: new Set(),
    capture: new Set()
  };
  const deferBlocks = new Map();
  const appId = appRef.injector.get(APP_ID);
  for (const viewRef of viewRefs) {
    const lNode = getLNodeForHydration(viewRef);
    // An `lView` might be `null` if a `ViewRef` represents
    // an embedded view (not a component view).
    if (lNode !== null) {
      const context = {
        serializedViewCollection,
        corruptedTextNodes,
        isI18nHydrationEnabled: isI18nHydrationEnabledVal,
        isIncrementalHydrationEnabled: isIncrementalHydrationEnabledVal,
        i18nChildren: new Map(),
        eventTypesToReplay,
        shouldReplayEvents,
        appId,
        deferBlocks
      };
      if (isLContainer(lNode)) {
        annotateLContainerForHydration(lNode, context, injector);
      } else {
        annotateComponentLViewForHydration(lNode, context, injector);
      }
      insertCorruptedTextNodeMarkers(corruptedTextNodes, doc);
    }
  }
  // Note: we *always* include hydration info key and a corresponding value
  // into the TransferState, even if the list of serialized views is empty.
  // This is needed as a signal to the client that the server part of the
  // hydration logic was setup and enabled correctly. Otherwise, if a client
  // hydration doesn't find a key in the transfer state - an error is produced.
  const serializedViews = serializedViewCollection.getAll();
  const transferState = injector.get(TransferState);
  transferState.set(NGH_DATA_KEY, serializedViews);
  if (deferBlocks.size > 0) {
    const blocks = {};
    // TODO(incremental-hydration): we should probably have an object here instead of a Map?
    for (const [id, info] of deferBlocks.entries()) {
      blocks[id] = info;
    }
    transferState.set(NGH_DEFER_BLOCKS_KEY, blocks);
  }
  return eventTypesToReplay;
}
/**
 * Serializes the lContainer data into a list of SerializedView objects,
 * that represent views within this lContainer.
 *
 * @param lContainer the lContainer we are serializing
 * @param tNode the TNode that contains info about this LContainer
 * @param lView that hosts this LContainer
 * @param parentDeferBlockId the defer block id of the parent if it exists
 * @param context the hydration context
 * @returns an array of the `SerializedView` objects
 */
function serializeLContainer(lContainer, tNode, lView, parentDeferBlockId, context) {
  const views = [];
  let lastViewAsString = '';
  for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
    let childLView = lContainer[i];
    let template;
    let numRootNodes;
    let serializedView;
    if (isRootView(childLView)) {
      // If this is a root view, get an LView for the underlying component,
      // because it contains information about the view to serialize.
      childLView = childLView[HEADER_OFFSET];
      // If we have an LContainer at this position, this indicates that the
      // host element was used as a ViewContainerRef anchor (e.g. a `ViewContainerRef`
      // was injected within the component class). This case requires special handling.
      if (isLContainer(childLView)) {
        // Calculate the number of root nodes in all views in a given container
        // and increment by one to account for an anchor node itself, i.e. in this
        // scenario we'll have a layout that would look like this:
        // `<app-root /><#VIEW1><#VIEW2>...<!--container-->`
        // The `+1` is to capture the `<app-root />` element.
        numRootNodes = calcNumRootNodesInLContainer(childLView) + 1;
        annotateLContainerForHydration(childLView, context, lView[INJECTOR]);
        const componentLView = unwrapLView(childLView[HOST]);
        serializedView = {
          [TEMPLATE_ID]: componentLView[TVIEW].ssrId,
          [NUM_ROOT_NODES]: numRootNodes
        };
      }
    }
    if (!serializedView) {
      const childTView = childLView[TVIEW];
      if (childTView.type === 1 /* TViewType.Component */) {
        template = childTView.ssrId;
        // This is a component view, thus it has only 1 root node: the component
        // host node itself (other nodes would be inside that host node).
        numRootNodes = 1;
      } else {
        template = getSsrId(childTView);
        numRootNodes = calcNumRootNodes(childTView, childLView, childTView.firstChild);
      }
      serializedView = {
        [TEMPLATE_ID]: template,
        [NUM_ROOT_NODES]: numRootNodes
      };
      let isHydrateNeverBlock = false;
      // If this is a defer block, serialize extra info.
      if (isDeferBlock(lView[TVIEW], tNode)) {
        const lDetails = getLDeferBlockDetails(lView, tNode);
        if (context.isIncrementalHydrationEnabled) {
          const deferBlockId = `d${context.deferBlocks.size}`;
          const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
          if (tDetails.hydrateTriggers?.has(7 /* DeferBlockTrigger.Never */)) {
            isHydrateNeverBlock = true;
          }
          let rootNodes = [];
          collectNativeNodesInLContainer(lContainer, rootNodes);
          // Add defer block into info context.deferBlocks
          const deferBlockInfo = {
            [DEFER_PARENT_BLOCK_ID]: parentDeferBlockId,
            [NUM_ROOT_NODES]: rootNodes.length,
            [DEFER_BLOCK_STATE$1]: lDetails[DEFER_BLOCK_STATE],
            [DEFER_HYDRATE_TRIGGERS]: serializeHydrateTriggers(tDetails.hydrateTriggers)
          };
          context.deferBlocks.set(deferBlockId, deferBlockInfo);
          const node = unwrapRNode(lContainer);
          if (node !== undefined) {
            if (node.nodeType === Node.COMMENT_NODE) {
              annotateDeferBlockAnchorForHydration(node, deferBlockId);
            }
          } else {
            ngDevMode && validateNodeExists(node, childLView, tNode);
            ngDevMode && validateMatchingNode(node, Node.COMMENT_NODE, null, childLView, tNode, true);
            annotateDeferBlockAnchorForHydration(node, deferBlockId);
          }
          if (!isHydrateNeverBlock) {
            // Add JSAction attributes for root nodes that use some hydration triggers
            annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, deferBlockId, context);
          }
          // Use current block id as parent for nested routes.
          parentDeferBlockId = deferBlockId;
          // Serialize extra info into the view object.
          // TODO(incremental-hydration): this should be serialized and included at a different level
          // (not at the view level).
          serializedView[DEFER_BLOCK_ID] = deferBlockId;
        }
        // DEFER_BLOCK_STATE is used for reconciliation in hydration, both regular and incremental.
        // We need to know which template is rendered when hydrating. So we serialize this state
        // regardless of hydration type.
        serializedView[DEFER_BLOCK_STATE$1] = lDetails[DEFER_BLOCK_STATE];
      }
      if (!isHydrateNeverBlock) {
        // TODO(incremental-hydration): avoid copying of an object here
        serializedView = {
          ...serializedView,
          ...serializeLView(lContainer[i], parentDeferBlockId, context)
        };
      }
    }
    // Check if the previous view has the same shape (for example, it was
    // produced by the *ngFor), in which case bump the counter on the previous
    // view instead of including the same information again.
    const currentViewAsString = JSON.stringify(serializedView);
    if (views.length > 0 && currentViewAsString === lastViewAsString) {
      const previousView = views[views.length - 1];
      previousView[MULTIPLIER] ??= 1;
      previousView[MULTIPLIER]++;
    } else {
      // Record this view as most recently added.
      lastViewAsString = currentViewAsString;
      views.push(serializedView);
    }
  }
  return views;
}
function serializeHydrateTriggers(triggerMap) {
  if (triggerMap === null) {
    return null;
  }
  const serializableDeferBlockTrigger = new Set([0 /* DeferBlockTrigger.Idle */, 1 /* DeferBlockTrigger.Immediate */, 2 /* DeferBlockTrigger.Viewport */, 5 /* DeferBlockTrigger.Timer */]);
  let triggers = [];
  for (let [trigger, details] of triggerMap) {
    if (serializableDeferBlockTrigger.has(trigger)) {
      if (details === null) {
        triggers.push(trigger);
      } else {
        triggers.push({
          trigger,
          details
        });
      }
    }
  }
  return triggers;
}
/**
 * Helper function to produce a node path (which navigation steps runtime logic
 * needs to take to locate a node) and stores it in the `NODES` section of the
 * current serialized view.
 */
function appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes) {
  const noOffsetIndex = tNode.index - HEADER_OFFSET;
  ngh[NODES] ??= {};
  // Ensure we don't calculate the path multiple times.
  ngh[NODES][noOffsetIndex] ??= calcPathForNode(tNode, lView, excludedParentNodes);
}
/**
 * Helper function to append information about a disconnected node.
 * This info is needed at runtime to avoid DOM lookups for this element
 * and instead, the element would be created from scratch.
 */
function appendDisconnectedNodeIndex(ngh, tNodeOrNoOffsetIndex) {
  const noOffsetIndex = typeof tNodeOrNoOffsetIndex === 'number' ? tNodeOrNoOffsetIndex : tNodeOrNoOffsetIndex.index - HEADER_OFFSET;
  ngh[DISCONNECTED_NODES] ??= [];
  if (!ngh[DISCONNECTED_NODES].includes(noOffsetIndex)) {
    ngh[DISCONNECTED_NODES].push(noOffsetIndex);
  }
}
/**
 * Serializes the lView data into a SerializedView object that will later be added
 * to the TransferState storage and referenced using the `ngh` attribute on a host
 * element.
 *
 * @param lView the lView we are serializing
 * @param context the hydration context
 * @returns the `SerializedView` object containing the data to be added to the host node
 */
function serializeLView(lView, parentDeferBlockId = null, context) {
  const ngh = {};
  const tView = lView[TVIEW];
  const i18nChildren = getOrComputeI18nChildren(tView, context);
  const nativeElementsToEventTypes = context.shouldReplayEvents ? collectDomEventsInfo(tView, lView, context.eventTypesToReplay) : null;
  // Iterate over DOM element references in an LView.
  for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
    const tNode = tView.data[i];
    const noOffsetIndex = i - HEADER_OFFSET;
    // Attempt to serialize any i18n data for the given slot. We do this first, as i18n
    // has its own process for serialization.
    const i18nData = trySerializeI18nBlock(lView, i, context);
    if (i18nData) {
      ngh[I18N_DATA] ??= {};
      ngh[I18N_DATA][noOffsetIndex] = i18nData.caseQueue;
      for (const nodeNoOffsetIndex of i18nData.disconnectedNodes) {
        appendDisconnectedNodeIndex(ngh, nodeNoOffsetIndex);
      }
      for (const nodeNoOffsetIndex of i18nData.disjointNodes) {
        const tNode = tView.data[nodeNoOffsetIndex + HEADER_OFFSET];
        ngDevMode && assertTNode(tNode);
        appendSerializedNodePath(ngh, tNode, lView, i18nChildren);
      }
      continue;
    }
    // Skip processing of a given slot in the following cases:
    // - Local refs (e.g. <div #localRef>) take up an extra slot in LViews
    //   to store the same element. In this case, there is no information in
    //   a corresponding slot in TNode data structure.
    // - When a slot contains something other than a TNode. For example, there
    //   might be some metadata information about a defer block or a control flow block.
    if (!isTNodeShape(tNode)) {
      continue;
    }
    // Skip any nodes that are in an i18n block but are considered detached (i.e. not
    // present in the template). These nodes are disconnected from the DOM tree, and
    // so we don't want to serialize any information about them.
    if (isDetachedByI18n(tNode)) {
      continue;
    }
    // Check if a native node that represents a given TNode is disconnected from the DOM tree.
    // Such nodes must be excluded from the hydration (since the hydration won't be able to
    // find them), so the TNode ids are collected and used at runtime to skip the hydration.
    //
    // This situation may happen during the content projection, when some nodes don't make it
    // into one of the content projection slots (for example, when there is no default
    // <ng-content /> slot in projector component's template).
    if (isDisconnectedNode(tNode, lView) && isContentProjectedNode(tNode)) {
      appendDisconnectedNodeIndex(ngh, tNode);
      continue;
    }
    if (Array.isArray(tNode.projection)) {
      for (const projectionHeadTNode of tNode.projection) {
        // We may have `null`s in slots with no projected content.
        if (!projectionHeadTNode) continue;
        if (!Array.isArray(projectionHeadTNode)) {
          // If we process re-projected content (i.e. `<ng-content>`
          // appears at projection location), skip annotations for this content
          // since all DOM nodes in this projection were handled while processing
          // a parent lView, which contains those nodes.
          if (!isProjectionTNode(projectionHeadTNode) && !isInSkipHydrationBlock(projectionHeadTNode)) {
            if (isDisconnectedNode(projectionHeadTNode, lView)) {
              // Check whether this node is connected, since we may have a TNode
              // in the data structure as a projection segment head, but the
              // content projection slot might be disabled (e.g.
              // <ng-content *ngIf="false" />).
              appendDisconnectedNodeIndex(ngh, projectionHeadTNode);
            } else {
              appendSerializedNodePath(ngh, projectionHeadTNode, lView, i18nChildren);
            }
          }
        } else {
          // If a value is an array, it means that we are processing a projection
          // where projectable nodes were passed in as DOM nodes (for example, when
          // calling `ViewContainerRef.createComponent(CmpA, {projectableNodes: [...]})`).
          //
          // In this scenario, nodes can come from anywhere (either created manually,
          // accessed via `document.querySelector`, etc) and may be in any state
          // (attached or detached from the DOM tree). As a result, we can not reliably
          // restore the state for such cases during hydration.
          throw unsupportedProjectionOfDomNodes(unwrapRNode(lView[i]));
        }
      }
    }
    conditionallyAnnotateNodePath(ngh, tNode, lView, i18nChildren);
    if (isLContainer(lView[i])) {
      // Serialize information about a template.
      const embeddedTView = tNode.tView;
      if (embeddedTView !== null) {
        ngh[TEMPLATES] ??= {};
        ngh[TEMPLATES][noOffsetIndex] = getSsrId(embeddedTView);
      }
      // Serialize views within this LContainer.
      const hostNode = lView[i][HOST]; // host node of this container
      // LView[i][HOST] can be of 2 different types:
      // - either a DOM node
      // - or an array that represents an LView of a component
      if (Array.isArray(hostNode)) {
        // This is a component, serialize info about it.
        const targetNode = unwrapRNode(hostNode);
        if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
          annotateHostElementForHydration(targetNode, hostNode, parentDeferBlockId, context);
        }
      }
      ngh[CONTAINERS] ??= {};
      ngh[CONTAINERS][noOffsetIndex] = serializeLContainer(lView[i], tNode, lView, parentDeferBlockId, context);
    } else if (Array.isArray(lView[i]) && !isLetDeclaration(tNode)) {
      // This is a component, annotate the host node with an `ngh` attribute.
      // Note: Let declarations that return an array are also storing an array in the LView,
      // we need to exclude them.
      const targetNode = unwrapRNode(lView[i][HOST]);
      if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
        annotateHostElementForHydration(targetNode, lView[i], parentDeferBlockId, context);
      }
    } else {
      // <ng-container> case
      if (tNode.type & 8 /* TNodeType.ElementContainer */) {
        // An <ng-container> is represented by the number of
        // top-level nodes. This information is needed to skip over
        // those nodes to reach a corresponding anchor node (comment node).
        ngh[ELEMENT_CONTAINERS] ??= {};
        ngh[ELEMENT_CONTAINERS][noOffsetIndex] = calcNumRootNodes(tView, lView, tNode.child);
      } else if (tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
        // Current TNode represents an `<ng-content>` slot or `@let` declaration,
        // thus it has no DOM elements associated with it, so the **next sibling**
        // node would not be able to find an anchor. In this case, use full path instead.
        let nextTNode = tNode.next;
        // Skip over all `<ng-content>` slots and `@let` declarations in a row.
        while (nextTNode !== null && nextTNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
          nextTNode = nextTNode.next;
        }
        if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {
          // Handle a tNode after the `<ng-content>` slot.
          appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren);
        }
      } else if (tNode.type & 1 /* TNodeType.Text */) {
        const rNode = unwrapRNode(lView[i]);
        processTextNodeBeforeSerialization(context, rNode);
      }
    }
    // Attach `jsaction` attribute to elements that have registered listeners,
    // thus potentially having a need to do an event replay.
    if (nativeElementsToEventTypes && tNode.type & 2 /* TNodeType.Element */) {
      const nativeElement = unwrapRNode(lView[i]);
      if (nativeElementsToEventTypes.has(nativeElement)) {
        setJSActionAttributes(nativeElement, nativeElementsToEventTypes.get(nativeElement), parentDeferBlockId);
      }
    }
  }
  return ngh;
}
/**
 * Serializes node location in cases when it's needed, specifically:
 *
 *  1. If `tNode.projectionNext` is different from `tNode.next` - it means that
 *     the next `tNode` after projection is different from the one in the original
 *     template. Since hydration relies on `tNode.next`, this serialized info
 *     is required to help runtime code find the node at the correct location.
 *  2. In certain content projection-based use-cases, it's possible that only
 *     a content of a projected element is rendered. In this case, content nodes
 *     require an extra annotation, since runtime logic can't rely on parent-child
 *     connection to identify the location of a node.
 */
function conditionallyAnnotateNodePath(ngh, tNode, lView, excludedParentNodes) {
  if (isProjectionTNode(tNode)) {
    // Do not annotate projection nodes (<ng-content />), since
    // they don't have a corresponding DOM node representing them.
    return;
  }
  // Handle case #1 described above.
  if (tNode.projectionNext && tNode.projectionNext !== tNode.next && !isInSkipHydrationBlock(tNode.projectionNext)) {
    appendSerializedNodePath(ngh, tNode.projectionNext, lView, excludedParentNodes);
  }
  // Handle case #2 described above.
  // Note: we only do that for the first node (i.e. when `tNode.prev === null`),
  // the rest of the nodes would rely on the current node location, so no extra
  // annotation is needed.
  if (tNode.prev === null && tNode.parent !== null && isDisconnectedNode(tNode.parent, lView) && !isDisconnectedNode(tNode, lView)) {
    appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes);
  }
}
/**
 * Determines whether a component instance that is represented
 * by a given LView uses `ViewEncapsulation.ShadowDom`.
 */
function componentUsesShadowDomEncapsulation(lView) {
  const instance = lView[CONTEXT];
  return instance?.constructor ? getComponentDef(instance.constructor)?.encapsulation === ViewEncapsulation.ShadowDom : false;
}
/**
 * Annotates component host element for hydration:
 * - by either adding the `ngh` attribute and collecting hydration-related info
 *   for the serialization and transferring to the client
 * - or by adding the `ngSkipHydration` attribute in case Angular detects that
 *   component contents is not compatible with hydration.
 *
 * @param element The Host element to be annotated
 * @param lView The associated LView
 * @param context The hydration context
 * @returns An index of serialized view from the transfer state object
 *          or `null` when a given component can not be serialized.
 */
function annotateHostElementForHydration(element, lView, parentDeferBlockId, context) {
  const renderer = lView[RENDERER];
  if (hasI18n(lView) && !isI18nHydrationSupportEnabled() || componentUsesShadowDomEncapsulation(lView)) {
    // Attach the skip hydration attribute if this component:
    // - either has i18n blocks, since hydrating such blocks is not yet supported
    // - or uses ShadowDom view encapsulation, since Domino doesn't support
    //   shadow DOM, so we can not guarantee that client and server representations
    //   would exactly match
    renderer.setAttribute(element, SKIP_HYDRATION_ATTR_NAME, '');
    return null;
  } else {
    const ngh = serializeLView(lView, parentDeferBlockId, context);
    const index = context.serializedViewCollection.add(ngh);
    renderer.setAttribute(element, NGH_ATTR_NAME, index.toString());
    return index;
  }
}
/**
 * Annotates defer block comment node for hydration:
 *
 * @param comment The Host element to be annotated
 * @param deferBlockId the id of the target defer block
 */
function annotateDeferBlockAnchorForHydration(comment, deferBlockId) {
  comment.textContent = `ngh=${deferBlockId}`;
}
/**
 * Physically inserts the comment nodes to ensure empty text nodes and adjacent
 * text node separators are preserved after server serialization of the DOM.
 * These get swapped back for empty text nodes or separators once hydration happens
 * on the client.
 *
 * @param corruptedTextNodes The Map of text nodes to be replaced with comments
 * @param doc The document
 */
function insertCorruptedTextNodeMarkers(corruptedTextNodes, doc) {
  for (const [textNode, marker] of corruptedTextNodes) {
    textNode.after(doc.createComment(marker));
  }
}
/**
 * Detects whether a given TNode represents a node that
 * is being content projected.
 */
function isContentProjectedNode(tNode) {
  let currentTNode = tNode;
  while (currentTNode != null) {
    // If we come across a component host node in parent nodes -
    // this TNode is in the content projection section.
    if (isComponentHost(currentTNode)) {
      return true;
    }
    currentTNode = currentTNode.parent;
  }
  return false;
}
/**
 * Incremental hydration requires that any defer block root node
 * with interaction or hover triggers have all of their root nodes
 * trigger hydration with those events. So we need to make sure all
 * the root nodes of that block have the proper jsaction attribute
 * to ensure hydration is triggered, since the content is dehydrated
 */
function annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, parentDeferBlockId, context) {
  const actionList = convertHydrateTriggersToJsAction(tDetails.hydrateTriggers);
  for (let et of actionList) {
    context.eventTypesToReplay.regular.add(et);
  }
  if (actionList.length > 0) {
    const elementNodes = rootNodes.filter(rn => rn.nodeType === Node.ELEMENT_NODE);
    for (let rNode of elementNodes) {
      setJSActionAttributes(rNode, actionList, parentDeferBlockId);
    }
  }
}

/**
 * Indicates whether the hydration-related code was added,
 * prevents adding it multiple times.
 */
let isHydrationSupportEnabled = false;
/**
 * Indicates whether the i18n-related code was added,
 * prevents adding it multiple times.
 *
 * Note: This merely controls whether the code is loaded,
 * while `setIsI18nHydrationSupportEnabled` determines
 * whether i18n blocks are serialized or hydrated.
 */
let isI18nHydrationRuntimeSupportEnabled = false;
/**
 * Indicates whether the incremental hydration code was added,
 * prevents adding it multiple times.
 */
let isIncrementalHydrationRuntimeSupportEnabled = false;
/**
 * Defines a period of time that Angular waits for the `ApplicationRef.isStable` to emit `true`.
 * If there was no event with the `true` value during this time, Angular reports a warning.
 */
const APPLICATION_IS_STABLE_TIMEOUT = 10_000;
/**
 * Brings the necessary hydration code in tree-shakable manner.
 * The code is only present when the `provideClientHydration` is
 * invoked. Otherwise, this code is tree-shaken away during the
 * build optimization step.
 *
 * This technique allows us to swap implementations of methods so
 * tree shaking works appropriately when hydration is disabled or
 * enabled. It brings in the appropriate version of the method that
 * supports hydration only when enabled.
 */
function enableHydrationRuntimeSupport() {
  if (!isHydrationSupportEnabled) {
    isHydrationSupportEnabled = true;
    enableRetrieveHydrationInfoImpl();
    enableLocateOrCreateElementNodeImpl();
    enableLocateOrCreateTextNodeImpl();
    enableLocateOrCreateElementContainerNodeImpl();
    enableLocateOrCreateContainerAnchorImpl();
    enableLocateOrCreateContainerRefImpl();
    enableFindMatchingDehydratedViewImpl();
    enableApplyRootElementTransformImpl();
  }
}
/**
 * Brings the necessary i18n hydration code in tree-shakable manner.
 * Similar to `enableHydrationRuntimeSupport`, the code is only
 * present when `withI18nSupport` is invoked.
 */
function enableI18nHydrationRuntimeSupport() {
  if (!isI18nHydrationRuntimeSupportEnabled) {
    isI18nHydrationRuntimeSupportEnabled = true;
    enableLocateOrCreateI18nNodeImpl();
    enablePrepareI18nBlockForHydrationImpl();
    enableClaimDehydratedIcuCaseImpl();
  }
}
/**
 * Brings the necessary incremental hydration code in tree-shakable manner.
 * Similar to `enableHydrationRuntimeSupport`, the code is only
 * present when `enableIncrementalHydrationRuntimeSupport` is invoked.
 */
function enableIncrementalHydrationRuntimeSupport() {
  if (!isIncrementalHydrationRuntimeSupportEnabled) {
    isIncrementalHydrationRuntimeSupportEnabled = true;
    enableRetrieveDeferBlockDataImpl();
  }
}
/**
 * Outputs a message with hydration stats into a console.
 */
function printHydrationStats(injector) {
  const console = injector.get(Console);
  const message = `Angular hydrated ${ngDevMode.hydratedComponents} component(s) ` + `and ${ngDevMode.hydratedNodes} node(s), ` + `${ngDevMode.componentsSkippedHydration} component(s) were skipped. ` + `Learn more at https://angular.dev/guide/hydration.`;
  // tslint:disable-next-line:no-console
  console.log(message);
}
/**
 * Returns a Promise that is resolved when an application becomes stable.
 */
function whenStableWithTimeout(appRef, injector) {
  const whenStablePromise = whenStable(appRef);
  if (typeof ngDevMode !== 'undefined' && ngDevMode) {
    const timeoutTime = APPLICATION_IS_STABLE_TIMEOUT;
    const console = injector.get(Console);
    const ngZone = injector.get(NgZone);
    // The following call should not and does not prevent the app to become stable
    // We cannot use RxJS timer here because the app would remain unstable.
    // This also avoids an extra change detection cycle.
    const timeoutId = ngZone.runOutsideAngular(() => {
      return setTimeout(() => logWarningOnStableTimedout(timeoutTime, console), timeoutTime);
    });
    whenStablePromise.finally(() => clearTimeout(timeoutId));
  }
  return whenStablePromise;
}
/**
 * Defines a name of an attribute that is added to the <body> tag
 * in the `index.html` file in case a given route was configured
 * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode".
 */
const CLIENT_RENDER_MODE_FLAG = 'ngcm';
/**
 * Checks whether the `RenderMode.Client` was defined for the current route.
 */
function isClientRenderModeEnabled() {
  const doc = getDocument();
  return (typeof ngServerMode === 'undefined' || !ngServerMode) && doc.body.hasAttribute(CLIENT_RENDER_MODE_FLAG);
}
/**
 * Returns a set of providers required to setup hydration support
 * for an application that is server side rendered. This function is
 * included into the `provideClientHydration` public API function from
 * the `platform-browser` package.
 *
 * The function sets up an internal flag that would be recognized during
 * the server side rendering time as well, so there is no need to
 * configure or change anything in NgUniversal to enable the feature.
 */
function withDomHydration() {
  const providers = [{
    provide: IS_HYDRATION_DOM_REUSE_ENABLED,
    useFactory: () => {
      let isEnabled = true;
      if (typeof ngServerMode === 'undefined' || !ngServerMode) {
        // On the client, verify that the server response contains
        // hydration annotations. Otherwise, keep hydration disabled.
        const transferState = inject(TransferState, {
          optional: true
        });
        isEnabled = !!transferState?.get(NGH_DATA_KEY, null);
      }
      if (isEnabled) {
        performanceMarkFeature('NgHydration');
      }
      return isEnabled;
    }
  }, {
    provide: ENVIRONMENT_INITIALIZER,
    useValue: () => {
      // i18n support is enabled by calling withI18nSupport(), but there's
      // no way to turn it off (e.g. for tests), so we turn it off by default.
      setIsI18nHydrationSupportEnabled(false);
      if (typeof ngServerMode !== 'undefined' && ngServerMode) {
        // Since this function is used across both server and client,
        // make sure that the runtime code is only added when invoked
        // on the client (see the `enableHydrationRuntimeSupport` function
        // call below).
        return;
      }
      if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
        verifySsrContentsIntegrity();
        enableHydrationRuntimeSupport();
      } else if (typeof ngDevMode !== 'undefined' && ngDevMode && !isClientRenderModeEnabled()) {
        const console = inject(Console);
        const message = formatRuntimeError(-505 /* RuntimeErrorCode.MISSING_HYDRATION_ANNOTATIONS */, 'Angular hydration was requested on the client, but there was no ' + 'serialized information present in the server response, ' + 'thus hydration was not enabled. ' + 'Make sure the `provideClientHydration()` is included into the list ' + 'of providers in the server part of the application configuration.');
        // tslint:disable-next-line:no-console
        console.warn(message);
      }
    },
    multi: true
  }];
  if (typeof ngServerMode === 'undefined' || !ngServerMode) {
    providers.push({
      provide: PRESERVE_HOST_CONTENT,
      useFactory: () => {
        // Preserve host element content only in a browser
        // environment and when hydration is configured properly.
        // On a server, an application is rendered from scratch,
        // so the host content needs to be empty.
        return inject(IS_HYDRATION_DOM_REUSE_ENABLED);
      }
    }, {
      provide: APP_BOOTSTRAP_LISTENER,
      useFactory: () => {
        if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
          const appRef = inject(ApplicationRef);
          const injector = inject(Injector);
          return () => {
            // Wait until an app becomes stable and cleanup all views that
            // were not claimed during the application bootstrap process.
            // The timing is similar to when we start the serialization process
            // on the server.
            //
            // Note: the cleanup task *MUST* be scheduled within the Angular zone in Zone apps
            // to ensure that change detection is properly run afterward.
            whenStableWithTimeout(appRef, injector).then(() => {
              cleanupDehydratedViews(appRef);
              if (typeof ngDevMode !== 'undefined' && ngDevMode) {
                printHydrationStats(injector);
              }
            });
          };
        }
        return () => {}; // noop
      },
      multi: true
    });
  }
  return makeEnvironmentProviders(providers);
}
/**
 * Returns a set of providers required to setup support for i18n hydration.
 * Requires hydration to be enabled separately.
 */
function withI18nSupport() {
  return [{
    provide: IS_I18N_HYDRATION_ENABLED,
    useFactory: () => inject(IS_HYDRATION_DOM_REUSE_ENABLED)
  }, {
    provide: ENVIRONMENT_INITIALIZER,
    useValue: () => {
      if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
        enableI18nHydrationRuntimeSupport();
        setIsI18nHydrationSupportEnabled(true);
        performanceMarkFeature('NgI18nHydration');
      }
    },
    multi: true
  }];
}
/**
 * Returns a set of providers required to setup support for incremental hydration.
 * Requires hydration to be enabled separately.
 * Enabling incremental hydration also enables event replay for the entire app.
 *
 * @developerPreview
 */
function withIncrementalHydration() {
  const providers = [withEventReplay(), {
    provide: IS_INCREMENTAL_HYDRATION_ENABLED,
    useValue: true
  }, {
    provide: DEHYDRATED_BLOCK_REGISTRY,
    useClass: DehydratedBlockRegistry
  }, {
    provide: ENVIRONMENT_INITIALIZER,
    useValue: () => {
      enableIncrementalHydrationRuntimeSupport();
      performanceMarkFeature('NgIncrementalHydration');
    },
    multi: true
  }];
  if (typeof ngServerMode === 'undefined' || !ngServerMode) {
    providers.push({
      provide: APP_BOOTSTRAP_LISTENER,
      useFactory: () => {
        const injector = inject(Injector);
        const doc = getDocument();
        return () => {
          const deferBlockData = processBlockData(injector);
          const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body);
          processAndInitTriggers(injector, deferBlockData, commentsByBlockId);
          appendDeferBlocksToJSActionMap(doc, injector);
        };
      },
      multi: true
    });
  }
  return providers;
}
/**
 *
 * @param time The time in ms until the stable timedout warning message is logged
 */
function logWarningOnStableTimedout(time, console) {
  const message = `Angular hydration expected the ApplicationRef.isStable() to emit \`true\`, but it ` + `didn't happen within ${time}ms. Angular hydration logic depends on the application becoming stable ` + `as a signal to complete hydration process.`;
  console.warn(formatRuntimeError(-506 /* RuntimeErrorCode.HYDRATION_STABLE_TIMEDOUT */, message));
}
/**
 * Verifies whether the DOM contains a special marker added during SSR time to make sure
 * there is no SSR'ed contents transformations happen after SSR is completed. Typically that
 * happens either by CDN or during the build process as an optimization to remove comment nodes.
 * Hydration process requires comment nodes produced by Angular to locate correct DOM segments.
 * When this special marker is *not* present - throw an error and do not proceed with hydration,
 * since it will not be able to function correctly.
 *
 * Note: this function is invoked only on the client, so it's safe to use DOM APIs.
 */
function verifySsrContentsIntegrity() {
  const doc = getDocument();
  let hydrationMarker;
  for (const node of doc.body.childNodes) {
    if (node.nodeType === Node.COMMENT_NODE && node.textContent?.trim() === SSR_CONTENT_INTEGRITY_MARKER) {
      hydrationMarker = node;
      break;
    }
  }
  if (!hydrationMarker) {
    throw new RuntimeError(-507 /* RuntimeErrorCode.MISSING_SSR_CONTENT_INTEGRITY_MARKER */, typeof ngDevMode !== 'undefined' && ngDevMode && 'Angular hydration logic detected that HTML content of this page was modified after it ' + 'was produced during server side rendering. Make sure that there are no optimizations ' + 'that remove comment nodes from HTML enabled on your CDN. Angular hydration ' + 'relies on HTML produced by the server, including whitespaces and comment nodes.');
  }
}

/**
 * Transforms a value (typically a string) to a boolean.
 * Intended to be used as a transform function of an input.
 *
 *  @usageNotes
 *  ```typescript
 *  @Input({ transform: booleanAttribute }) status!: boolean;
 *  ```
 * @param value Value to be transformed.
 *
 * @publicApi
 */
function booleanAttribute(value) {
  return typeof value === 'boolean' ? value : value != null && value !== 'false';
}
/**
 * Transforms a value (typically a string) to a number.
 * Intended to be used as a transform function of an input.
 * @param value Value to be transformed.
 * @param fallbackValue Value to use if the provided value can't be parsed as a number.
 *
 *  @usageNotes
 *  ```typescript
 *  @Input({ transform: numberAttribute }) id!: number;
 *  ```
 *
 * @publicApi
 */
function numberAttribute(value, fallbackValue = NaN) {
  // parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,
  // and other non-number values as NaN, where Number just uses 0) but it considers the string
  // '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.
  const isNumberValue = !isNaN(parseFloat(value)) && !isNaN(Number(value));
  return isNumberValue ? Number(value) : fallbackValue;
}
const PERFORMANCE_MARK_PREFIX = '🅰️';
let enablePerfLogging = false;
/**
 * Function that will start measuring against the performance API
 * Should be used in pair with stopMeasuring
 */
function startMeasuring(label) {
  if (!enablePerfLogging) {
    return;
  }
  const {
    startLabel
  } = labels(label);
  /* tslint:disable:ban */
  performance.mark(startLabel);
  /* tslint:enable:ban */
}
/**
 * Function that will stop measuring against the performance API
 * Should be used in pair with stopMeasuring
 */
function stopMeasuring(label) {
  if (!enablePerfLogging) {
    return;
  }
  const {
    startLabel,
    labelName,
    endLabel
  } = labels(label);
  /* tslint:disable:ban */
  performance.mark(endLabel);
  performance.measure(labelName, startLabel, endLabel);
  performance.clearMarks(startLabel);
  performance.clearMarks(endLabel);
  /* tslint:enable:ban */
}
function labels(label) {
  const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
  return {
    labelName,
    startLabel: `start:${labelName}`,
    endLabel: `end:${labelName}`
  };
}
let warningLogged = false;
/**
 * This enables an internal performance profiler
 *
 * It should not be imported in application code
 */
function enableProfiling() {
  if (!warningLogged && (typeof performance === 'undefined' || !performance.mark || !performance.measure)) {
    warningLogged = true;
    console.warn('Performance API is not supported on this platform');
    return;
  }
  enablePerfLogging = true;
}
function disableProfiling() {
  enablePerfLogging = false;
}

/*!
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */
/**
 * Gets the class name of the closest component to a node.
 * Warning! this function will return minified names if the name of the component is minified. The
 * consumer of the function is responsible for resolving the minified name to its original name.
 * @param node Node from which to start the search.
 */
function getClosestComponentName(node) {
  let currentNode = node;
  while (currentNode) {
    const lView = readPatchedLView(currentNode);
    if (lView !== null) {
      for (let i = HEADER_OFFSET; i < lView.length; i++) {
        const current = lView[i];
        if (!isLView(current) && !isLContainer(current) || current[HOST] !== currentNode) {
          continue;
        }
        const tView = lView[TVIEW];
        const tNode = getTNode(tView, i);
        if (isComponentHost(tNode)) {
          const def = tView.data[tNode.directiveStart + tNode.componentOffset];
          const name = def.debugInfo?.className || def.type.name;
          // Note: the name may be an empty string if the class name is
          // dropped due to minification. In such cases keep going up the tree.
          if (name) {
            return name;
          } else {
            break;
          }
        }
      }
    }
    currentNode = currentNode.parentNode;
  }
  return null;
}

/**
 * Compiles a partial directive declaration object into a full directive definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareDirective(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'directive',
    type: decl.type
  });
  return compiler.compileDirectiveDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
}
/**
 * Evaluates the class metadata declaration.
 *
 * @codeGenApi
 */
function ɵɵngDeclareClassMetadata(decl) {
  setClassMetadata(decl.type, decl.decorators, decl.ctorParameters ?? null, decl.propDecorators ?? null);
}
/**
 * Evaluates the class metadata of a component that contains deferred blocks.
 *
 * @codeGenApi
 */
function ɵɵngDeclareClassMetadataAsync(decl) {
  setClassMetadataAsync(decl.type, decl.resolveDeferredDeps, (...types) => {
    const meta = decl.resolveMetadata(...types);
    setClassMetadata(decl.type, meta.decorators, meta.ctorParameters, meta.propDecorators);
  });
}
/**
 * Compiles a partial component declaration object into a full component definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareComponent(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'component',
    type: decl.type
  });
  return compiler.compileComponentDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵcmp.js`, decl);
}
/**
 * Compiles a partial pipe declaration object into a full pipe definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareFactory(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: getFactoryKind(decl.target),
    type: decl.type
  });
  return compiler.compileFactoryDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
}
function getFactoryKind(target) {
  switch (target) {
    case FactoryTarget.Directive:
      return 'directive';
    case FactoryTarget.Component:
      return 'component';
    case FactoryTarget.Injectable:
      return 'injectable';
    case FactoryTarget.Pipe:
      return 'pipe';
    case FactoryTarget.NgModule:
      return 'NgModule';
  }
}
/**
 * Compiles a partial injectable declaration object into a full injectable definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareInjectable(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'injectable',
    type: decl.type
  });
  return compiler.compileInjectableDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵprov.js`, decl);
}
/**
 * Compiles a partial injector declaration object into a full injector definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareInjector(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'NgModule',
    type: decl.type
  });
  return compiler.compileInjectorDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵinj.js`, decl);
}
/**
 * Compiles a partial NgModule declaration object into a full NgModule definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclareNgModule(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'NgModule',
    type: decl.type
  });
  return compiler.compileNgModuleDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵmod.js`, decl);
}
/**
 * Compiles a partial pipe declaration object into a full pipe definition object.
 *
 * @codeGenApi
 */
function ɵɵngDeclarePipe(decl) {
  const compiler = getCompilerFacade({
    usage: 1 /* JitCompilerUsage.PartialDeclaration */,
    kind: 'pipe',
    type: decl.type
  });
  return compiler.compilePipeDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵpipe.js`, decl);
}

// we reexport these symbols just so that they are retained during the dead code elimination

/**
 * Create a computed `Signal` which derives a reactive value from an expression.
 */
function computed(computation, options) {
  performanceMarkFeature('NgSignals');
  const getter = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.createComputed)(computation);
  if (options?.equal) {
    getter[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL].equal = options.equal;
  }
  if (ngDevMode) {
    getter.toString = () => `[Computed: ${getter()}]`;
    getter[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL].debugName = options?.debugName;
  }
  return getter;
}
const identityFn = v => v;
/**
 * Create a linked signal which represents state that is (re)set from a linked reactive expression.
 */
function createLinkedSignal(node) {
  const linkedSignalGetter = () => {
    // Check if the value needs updating before returning it.
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerUpdateValueVersion)(node);
    // Record that someone looked at this signal.
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerAccessed)(node);
    if (node.value === ERRORED) {
      throw node.error;
    }
    return node.value;
  };
  const getter = linkedSignalGetter;
  getter[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
  if (ngDevMode) {
    getter.toString = () => `[LinkedSignal: ${getter()}]`;
  }
  getter.set = newValue => {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerUpdateValueVersion)(node);
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalSetFn)(node, newValue);
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerMarkClean)(node);
  };
  getter.update = updateFn => {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerUpdateValueVersion)(node);
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.signalUpdateFn)(node, updateFn);
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerMarkClean)(node);
  };
  getter.asReadonly = signalAsReadonlyFn.bind(getter);
  return getter;
}
function linkedSignal(optionsOrComputation, options) {
  performanceMarkFeature('NgSignals');
  const isShorthand = typeof optionsOrComputation === 'function';
  const node = Object.create(LINKED_SIGNAL_NODE);
  node.source = isShorthand ? optionsOrComputation : optionsOrComputation.source;
  if (!isShorthand) {
    node.computation = optionsOrComputation.computation;
  }
  const equal = isShorthand ? options?.equal : optionsOrComputation.equal;
  if (equal) {
    node.equal = equal;
  }
  return createLinkedSignal(node);
}
/**
 * A dedicated symbol used before a state value has been set / calculated for the first time.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const UNSET = /* @__PURE__ */Symbol('UNSET');
/**
 * A dedicated symbol used in place of a linked signal value to indicate that a given computation
 * is in progress. Used to detect cycles in computation chains.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const COMPUTING = /* @__PURE__ */Symbol('COMPUTING');
/**
 * A dedicated symbol used in place of a linked signal value to indicate that a given computation
 * failed. The thrown error is cached until the computation gets dirty again or the state is set.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const ERRORED = /* @__PURE__ */Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `LINKED_SIGNAL_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const LINKED_SIGNAL_NODE = /* @__PURE__ */(() => {
  return {
    ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.REACTIVE_NODE,
    value: UNSET,
    dirty: true,
    error: null,
    equal: _angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.defaultEquals,
    computation: identityFn,
    producerMustRecompute(node) {
      // Force a recomputation if there's no current value, or if the current value is in the
      // process of being calculated (which should throw an error).
      return node.value === UNSET || node.value === COMPUTING;
    },
    producerRecomputeValue(node) {
      if (node.value === COMPUTING) {
        // Our computation somehow led to a cyclic read of itself.
        throw new Error('Detected cycle in computations.');
      }
      const oldValue = node.value;
      node.value = COMPUTING;
      const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerBeforeComputation)(node);
      let newValue;
      try {
        const newSourceValue = node.source();
        const prev = oldValue === UNSET || oldValue === ERRORED ? undefined : {
          source: node.sourceValue,
          value: oldValue
        };
        newValue = node.computation(newSourceValue, prev);
        node.sourceValue = newSourceValue;
      } catch (err) {
        newValue = ERRORED;
        node.error = err;
      } finally {
        (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerAfterComputation)(node, prevConsumer);
      }
      if (oldValue !== UNSET && newValue !== ERRORED && node.equal(oldValue, newValue)) {
        // No change to `valueVersion` - old and new values are
        // semantically equivalent.
        node.value = oldValue;
        return;
      }
      node.value = newValue;
      node.version++;
    }
  };
})();

/**
 * Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function
 * can, optionally, return a value.
 */
function untracked(nonReactiveReadsFn) {
  const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(null);
  // We are not trying to catch any particular errors here, just making sure that the consumers
  // stack is restored in case of errors.
  try {
    return nonReactiveReadsFn();
  } finally {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.setActiveConsumer)(prevConsumer);
  }
}
let ViewContext = /*#__PURE__*/(() => {
  class ViewContext {
    view;
    node;
    constructor(view, node) {
      this.view = view;
      this.node = node;
    }
    /**
     * @internal
     * @nocollapse
     */
    static __NG_ELEMENT_ID__ = (() => injectViewContext)();
  }
  return ViewContext;
})();
function injectViewContext() {
  return new ViewContext(getLView(), getCurrentTNode());
}

/**
 * Controls whether effects use the legacy `microtaskEffect` by default.
 */
const USE_MICROTASK_EFFECT_BY_DEFAULT = false;
let MicrotaskEffectScheduler = /*#__PURE__*/(() => {
  class MicrotaskEffectScheduler extends ZoneAwareEffectScheduler {
    pendingTasks = (() => inject(PendingTasksInternal))();
    taskId = null;
    schedule(effect) {
      // Check whether there are any pending effects _before_ queueing in the base class.
      super.schedule(effect);
      if (this.taskId === null) {
        this.taskId = this.pendingTasks.add();
        queueMicrotask(() => this.flush());
      }
    }
    flush() {
      try {
        super.flush();
      } finally {
        if (this.taskId !== null) {
          this.pendingTasks.remove(this.taskId);
          this.taskId = null;
        }
      }
    }
    /** @nocollapse */
    static ɵprov = (() => /** @pureOrBreakMyCode */ /* @__PURE__ */ɵɵdefineInjectable({
      token: MicrotaskEffectScheduler,
      providedIn: 'root',
      factory: () => new MicrotaskEffectScheduler()
    }))();
  }
  return MicrotaskEffectScheduler;
})();
/**
 * Core reactive node for an Angular effect.
 *
 * `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
 * scheduling abstraction (`MicrotaskEffectScheduler`) as well as automatic cleanup via `DestroyRef`
 * if available/requested.
 */
class EffectHandle {
  scheduler;
  effectFn;
  zone;
  injector;
  unregisterOnDestroy;
  watcher;
  constructor(scheduler, effectFn, zone, destroyRef, injector, allowSignalWrites) {
    this.scheduler = scheduler;
    this.effectFn = effectFn;
    this.zone = zone;
    this.injector = injector;
    this.watcher = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.createWatch)(onCleanup => this.runEffect(onCleanup), () => this.schedule(), allowSignalWrites);
    this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  }
  runEffect(onCleanup) {
    try {
      this.effectFn(onCleanup);
    } catch (err) {
      // Inject the `ErrorHandler` here in order to avoid circular DI error
      // if the effect is used inside of a custom `ErrorHandler`.
      const errorHandler = this.injector.get(ErrorHandler, null, {
        optional: true
      });
      errorHandler?.handleError(err);
    }
  }
  run() {
    this.watcher.run();
  }
  schedule() {
    this.scheduler.schedule(this);
  }
  destroy() {
    this.watcher.destroy();
    this.unregisterOnDestroy?.();
    // Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
    // retain a reference to it. Attempting to execute it will be a no-op.
  }
}
// Just used for the name for the debug error below.
function effect$1() {}
/**
 * Create a global `Effect` for the given reactive function.
 */
function microtaskEffect(effectFn, options) {
  performanceMarkFeature('NgSignals');
  ngDevMode && assertNotInReactiveContext(effect$1, 'Call `effect` outside of a reactive context. For example, schedule the ' + 'effect inside the component constructor.');
  !options?.injector && assertInInjectionContext(effect$1);
  const injector = options?.injector ?? inject(Injector);
  const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  const handle = new EffectHandle(injector.get(MicrotaskEffectScheduler), effectFn, typeof Zone === 'undefined' ? null : Zone.current, destroyRef, injector, options?.allowSignalWrites ?? false);
  // Effects need to be marked dirty manually to trigger their initial run. The timing of this
  // marking matters, because the effects may read signals that track component inputs, which are
  // only available after those components have had their first update pass.
  //
  // We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
  // the context of a component or not. If it is, then we check whether the component has already
  // run its update pass, and defer the effect's initial scheduling until the update pass if it
  // hasn't already run.
  const cdr = injector.get(ChangeDetectorRef, null, {
    optional: true
  });
  if (!cdr || !(cdr._lView[FLAGS] & 8 /* LViewFlags.FirstLViewPass */)) {
    // This effect is either not running in a view injector, or the view has already
    // undergone its first change detection pass, which is necessary for any required inputs to be
    // set.
    handle.watcher.notify();
  } else {
    // Delay the initialization of the effect until the view is fully initialized.
    (cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
  }
  return handle;
}
let useMicrotaskEffectsByDefault = USE_MICROTASK_EFFECT_BY_DEFAULT;
/**
 * Toggle the flag on whether to use microtask effects (for testing).
 */
function setUseMicrotaskEffectsByDefault(value) {
  const prev = useMicrotaskEffectsByDefault;
  useMicrotaskEffectsByDefault = value;
  return prev;
}
class EffectRefImpl {
  [_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL];
  constructor(node) {
    this[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
  }
  destroy() {
    this[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL].destroy();
  }
}
/**
 * Registers an "effect" that will be scheduled & executed whenever the signals that it reads
 * changes.
 *
 * Angular has two different kinds of effect: component effects and root effects. Component effects
 * are created when `effect()` is called from a component, directive, or within a service of a
 * component/directive. Root effects are created when `effect()` is called from outside the
 * component tree, such as in a root service, or when the `forceRoot` option is provided.
 *
 * The two effect types differ in their timing. Component effects run as a component lifecycle
 * event during Angular's synchronization (change detection) process, and can safely read input
 * signals or create/destroy views that depend on component state. Root effects run as microtasks
 * and have no connection to the component tree or change detection.
 *
 * `effect()` must be run in injection context, unless the `injector` option is manually specified.
 *
 * @developerPreview
 */
function effect(effectFn, options) {
  if (useMicrotaskEffectsByDefault) {
    if (ngDevMode && options?.forceRoot) {
      throw new Error(`Cannot use 'forceRoot' option with microtask effects on`);
    }
    return microtaskEffect(effectFn, options);
  }
  performanceMarkFeature('NgSignals');
  ngDevMode && assertNotInReactiveContext(effect, 'Call `effect` outside of a reactive context. For example, schedule the ' + 'effect inside the component constructor.');
  !options?.injector && assertInInjectionContext(effect);
  if (ngDevMode && options?.allowSignalWrites !== undefined) {
    console.warn(`The 'allowSignalWrites' flag is deprecated & longer required for effect() (writes are allowed by default)`);
  }
  const injector = options?.injector ?? inject(Injector);
  let destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  let node;
  const viewContext = injector.get(ViewContext, null, {
    optional: true
  });
  const notifier = injector.get(ChangeDetectionScheduler);
  if (viewContext !== null && !options?.forceRoot) {
    // This effect was created in the context of a view, and will be associated with the view.
    node = createViewEffect(viewContext.view, notifier, effectFn);
    if (destroyRef instanceof NodeInjectorDestroyRef && destroyRef._lView === viewContext.view) {
      // The effect is being created in the same view as the `DestroyRef` references, so it will be
      // automatically destroyed without the need for an explicit `DestroyRef` registration.
      destroyRef = null;
    }
  } else {
    // This effect was created outside the context of a view, and will be scheduled independently.
    node = createRootEffect(effectFn, injector.get(EffectScheduler), notifier);
  }
  node.injector = injector;
  if (destroyRef !== null) {
    // If we need to register for cleanup, do that here.
    node.onDestroyFn = destroyRef.onDestroy(() => node.destroy());
  }
  if (ngDevMode) {
    node.debugName = options?.debugName ?? '';
  }
  return new EffectRefImpl(node);
}
/**
 * Not public API, which guarantees `EffectScheduler` only ever comes from the application root
 * injector.
 */
const APP_EFFECT_SCHEDULER = /* @__PURE__ */new InjectionToken('', {
  providedIn: 'root',
  factory: () => inject(EffectScheduler)
});
const BASE_EFFECT_NODE = /* @__PURE__ */(() => ({
  ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.REACTIVE_NODE,
  consumerIsAlwaysLive: true,
  consumerAllowSignalWrites: true,
  dirty: true,
  hasRun: false,
  cleanupFns: undefined,
  zone: null,
  onDestroyFn: noop,
  run() {
    this.dirty = false;
    if (ngDevMode && (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.isInNotificationPhase)()) {
      throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
    }
    if (this.hasRun && !(0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerPollProducersForChange)(this)) {
      return;
    }
    this.hasRun = true;
    const registerCleanupFn = cleanupFn => (this.cleanupFns ??= []).push(cleanupFn);
    const prevNode = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerBeforeComputation)(this);
    // We clear `setIsRefreshingViews` so that `markForCheck()` within the body of an effect will
    // cause CD to reach the component in question.
    const prevRefreshingViews = setIsRefreshingViews(false);
    try {
      this.maybeCleanup();
      this.fn(registerCleanupFn);
    } finally {
      setIsRefreshingViews(prevRefreshingViews);
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerAfterComputation)(this, prevNode);
    }
  },
  maybeCleanup() {
    if (!this.cleanupFns?.length) {
      return;
    }
    try {
      // Attempt to run the cleanup functions. Regardless of failure or success, we consider
      // cleanup "completed" and clear the list for the next run of the effect. Note that an error
      // from the cleanup function will still crash the current run of the effect.
      while (this.cleanupFns.length) {
        this.cleanupFns.pop()();
      }
    } finally {
      this.cleanupFns = [];
    }
  }
}))();
const ROOT_EFFECT_NODE = /* @__PURE__ */(() => ({
  ...BASE_EFFECT_NODE,
  consumerMarkedDirty() {
    this.scheduler.schedule(this);
    this.notifier.notify(13 /* NotificationSource.RootEffect */);
  },
  destroy() {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerDestroy)(this);
    this.onDestroyFn();
    this.maybeCleanup();
  }
}))();
const VIEW_EFFECT_NODE = /* @__PURE__ */(() => ({
  ...BASE_EFFECT_NODE,
  consumerMarkedDirty() {
    this.view[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
    markAncestorsForTraversal(this.view);
    this.notifier.notify(14 /* NotificationSource.ViewEffect */);
  },
  destroy() {
    (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerDestroy)(this);
    this.onDestroyFn();
    this.maybeCleanup();
    this.view[EFFECTS]?.delete(this);
  }
}))();
function createViewEffect(view, notifier, fn) {
  const node = Object.create(VIEW_EFFECT_NODE);
  node.view = view;
  node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  node.notifier = notifier;
  node.fn = fn;
  view[EFFECTS] ??= new Set();
  view[EFFECTS].add(node);
  node.consumerMarkedDirty(node);
  return node;
}
function createRootEffect(fn, scheduler, notifier) {
  const node = Object.create(ROOT_EFFECT_NODE);
  node.fn = fn;
  node.scheduler = scheduler;
  node.notifier = notifier;
  node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  node.scheduler.schedule(node);
  node.notifier.notify(13 /* NotificationSource.RootEffect */);
  return node;
}
const NOT_SET = /*#__PURE__*/Symbol('NOT_SET');
const EMPTY_CLEANUP_SET = /*#__PURE__*/new Set();
const AFTER_RENDER_PHASE_EFFECT_NODE = /* @__PURE__ */(() => ({
  ..._angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL_NODE,
  consumerIsAlwaysLive: true,
  consumerAllowSignalWrites: true,
  value: NOT_SET,
  cleanup: null,
  /** Called when the effect becomes dirty */
  consumerMarkedDirty() {
    if (this.sequence.impl.executing) {
      // If hooks are in the middle of executing, then it matters whether this node has yet been
      // executed within its sequence. If not, then we don't want to notify the scheduler since
      // this node will be reached naturally.
      if (this.sequence.lastPhase === null || this.sequence.lastPhase < this.phase) {
        return;
      }
      // If during the execution of a later phase an earlier phase became dirty, then we should not
      // run any further phases until the earlier one reruns.
      this.sequence.erroredOrDestroyed = true;
    }
    // Either hooks are not running, or we're marking a node dirty that has already run within its
    // sequence.
    this.sequence.scheduler.notify(7 /* NotificationSource.RenderHook */);
  },
  phaseFn(previousValue) {
    this.sequence.lastPhase = this.phase;
    if (!this.dirty) {
      return this.signal;
    }
    this.dirty = false;
    if (this.value !== NOT_SET && !(0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerPollProducersForChange)(this)) {
      // None of our producers report a change since the last time they were read, so no
      // recomputation of our value is necessary.
      return this.signal;
    }
    // Run any needed cleanup functions.
    try {
      for (const cleanupFn of this.cleanup ?? EMPTY_CLEANUP_SET) {
        cleanupFn();
      }
    } finally {
      // Even if a cleanup function errors, ensure it's cleared.
      this.cleanup?.clear();
    }
    // Prepare to call the user's effect callback. If there was a previous phase, then it gave us
    // its value as a `Signal`, otherwise `previousValue` will be `undefined`.
    const args = [];
    if (previousValue !== undefined) {
      args.push(previousValue);
    }
    args.push(this.registerCleanupFn);
    // Call the user's callback in our reactive context.
    const prevConsumer = (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerBeforeComputation)(this);
    let newValue;
    try {
      newValue = this.userFn.apply(null, args);
    } finally {
      (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.consumerAfterComputation)(this, prevConsumer);
    }
    if (this.value === NOT_SET || !this.equal(this.value, newValue)) {
      this.value = newValue;
      this.version++;
    }
    return this.signal;
  }
}))();
/**
 * An `AfterRenderSequence` that manages an `afterRenderEffect`'s phase effects.
 */
class AfterRenderEffectSequence extends AfterRenderSequence {
  scheduler;
  /**
   * While this sequence is executing, this tracks the last phase which was called by the
   * `afterRender` machinery.
   *
   * When a phase effect is marked dirty, this is used to determine whether it's already run or not.
   */
  lastPhase = null;
  /**
   * The reactive nodes for each phase, if a phase effect is defined for that phase.
   *
   * These are initialized to `undefined` but set in the constructor.
   */
  nodes = /*#__PURE__*/(() => [undefined, undefined, undefined, undefined])();
  constructor(impl, effectHooks, scheduler, destroyRef) {
    // Note that we also initialize the underlying `AfterRenderSequence` hooks to `undefined` and
    // populate them as we create reactive nodes below.
    super(impl, [undefined, undefined, undefined, undefined], false, destroyRef);
    this.scheduler = scheduler;
    // Setup a reactive node for each phase.
    for (const phase of AFTER_RENDER_PHASES) {
      const effectHook = effectHooks[phase];
      if (effectHook === undefined) {
        continue;
      }
      const node = Object.create(AFTER_RENDER_PHASE_EFFECT_NODE);
      node.sequence = this;
      node.phase = phase;
      node.userFn = effectHook;
      node.dirty = true;
      node.signal = () => {
        (0,_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.producerAccessed)(node);
        return node.value;
      };
      node.signal[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL] = node;
      node.registerCleanupFn = fn => (node.cleanup ??= new Set()).add(fn);
      this.nodes[phase] = node;
      // Install the upstream hook which runs the `phaseFn` for this phase.
      this.hooks[phase] = value => node.phaseFn(value);
    }
  }
  afterRun() {
    super.afterRun();
    // We're done running this sequence, so reset `lastPhase`.
    this.lastPhase = null;
  }
  destroy() {
    super.destroy();
    // Run the cleanup functions for each node.
    for (const node of this.nodes) {
      for (const fn of node?.cleanup ?? EMPTY_CLEANUP_SET) {
        fn();
      }
    }
  }
}
/**
 * @experimental
 */
function afterRenderEffect(callbackOrSpec, options) {
  ngDevMode && assertNotInReactiveContext(afterRenderEffect, 'Call `afterRenderEffect` outside of a reactive context. For example, create the render ' + 'effect inside the component constructor`.');
  !options?.injector && assertInInjectionContext(afterRenderEffect);
  if (typeof ngServerMode !== 'undefined' && ngServerMode) {
    return NOOP_AFTER_RENDER_REF;
  }
  const injector = options?.injector ?? inject(Injector);
  const scheduler = injector.get(ChangeDetectionScheduler);
  const manager = injector.get(AfterRenderManager);
  manager.impl ??= injector.get(AfterRenderImpl);
  let spec = callbackOrSpec;
  if (typeof spec === 'function') {
    spec = {
      mixedReadWrite: callbackOrSpec
    };
  }
  const sequence = new AfterRenderEffectSequence(manager.impl, [spec.earlyRead, spec.write, spec.mixedReadWrite, spec.read], scheduler, injector.get(DestroyRef));
  manager.impl.register(sequence);
  return sequence;
}

// This file exists to allow the set of reactivity exports to be modified in g3, as these APIs are

/**
 * Status of a `Resource`.
 *
 * @experimental
 */
var ResourceStatus = /*#__PURE__*/function (ResourceStatus) {
  /**
   * The resource has no valid request and will not perform any loading.
   *
   * `value()` will be `undefined`.
   */
  ResourceStatus[ResourceStatus["Idle"] = 0] = "Idle";
  /**
   * Loading failed with an error.
   *
   * `value()` will be `undefined`.
   */
  ResourceStatus[ResourceStatus["Error"] = 1] = "Error";
  /**
   * The resource is currently loading a new value as a result of a change in its `request`.
   *
   * `value()` will be `undefined`.
   */
  ResourceStatus[ResourceStatus["Loading"] = 2] = "Loading";
  /**
   * The resource is currently reloading a fresh value for the same request.
   *
   * `value()` will continue to return the previously fetched value during the reloading operation.
   */
  ResourceStatus[ResourceStatus["Reloading"] = 3] = "Reloading";
  /**
   * Loading has completed and the resource has the value returned from the loader.
   */
  ResourceStatus[ResourceStatus["Resolved"] = 4] = "Resolved";
  /**
   * The resource's value was set locally via `.set()` or `.update()`.
   */
  ResourceStatus[ResourceStatus["Local"] = 5] = "Local";
  return ResourceStatus;
}(ResourceStatus || {});
/**
 * Constructs a `Resource` that projects a reactive request to an asynchronous operation defined by
 * a loader function, which exposes the result of the loading operation via signals.
 *
 * Note that `resource` is intended for _read_ operations, not operations which perform mutations.
 * `resource` will cancel in-progress loads via the `AbortSignal` when destroyed or when a new
 * request object becomes available, which could prematurely abort mutations.
 *
 * @experimental
 */
function resource(options) {
  options?.injector || assertInInjectionContext(resource);
  const request = options.request ?? (() => null);
  return new WritableResourceImpl(request, options.loader, options.equal, options.injector);
}
/**
 * Base class for `WritableResource` which handles the state operations and is unopinionated on the
 * actual async operation.
 *
 * Mainly factored out for better readability.
 */
class BaseWritableResource {
  value;
  status = /*#__PURE__*/(() => signal(ResourceStatus.Idle))();
  error = /*#__PURE__*/(() => signal(undefined))();
  rawSetValue;
  constructor(equal) {
    this.value = signal(undefined, {
      equal: equal ? wrapEqualityFn(equal) : undefined
    });
    this.rawSetValue = this.value.set;
    this.value.set = value => this.set(value);
    this.value.update = fn => this.set(fn(untracked(this.value)));
  }
  set(value) {
    // Set the value signal and check whether its `version` changes. This will tell us
    // if the value signal actually updated or not.
    const prevVersion = this.value[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL].version;
    this.rawSetValue(value);
    if (this.value[_angular_core_primitives_signals__WEBPACK_IMPORTED_MODULE_1__.SIGNAL].version === prevVersion) {
      // The value must've been equal to the previous, so no need to change states.
      return;
    }
    // We're departing from whatever state the resource was in previously, and entering
    // Local state.
    this.onLocalValue();
    this.status.set(ResourceStatus.Local);
    this.error.set(undefined);
  }
  update(updater) {
    this.value.update(updater);
  }
  isLoading = /*#__PURE__*/(() => computed(() => this.status() === ResourceStatus.Loading || this.status() === ResourceStatus.Reloading))();
  hasValue() {
    return this.status() === ResourceStatus.Resolved || this.status() === ResourceStatus.Local || this.status() === ResourceStatus.Reloading;
  }
  asReadonly() {
    return this;
  }
  /**
   * Put the resource in a state with a given value.
   */
  setValueState(status, value = undefined) {
    this.status.set(status);
    this.rawSetValue(value);
    this.error.set(undefined);
  }
  /**
   * Put the resource into the error state.
   */
  setErrorState(err) {
    this.status.set(ResourceStatus.Error);
    this.value.set(undefined);
    this.error.set(err);
  }
}
class WritableResourceImpl extends BaseWritableResource {
  loaderFn;
  request;
  pendingTasks;
  effectRef;
  pendingController;
  resolvePendingTask = /*#__PURE__*/(() => undefined)();
  constructor(requestFn, loaderFn, equal, injector) {
    super(equal);
    this.loaderFn = loaderFn;
    injector = injector ?? inject(Injector);
    this.pendingTasks = injector.get(PendingTasks);
    this.request = computed(() => ({
      // The current request as defined for this resource.
      request: requestFn(),
      // A counter signal which increments from 0, re-initialized for each request (similar to the
      // `linkedSignal` pattern). A value other than 0 indicates a refresh operation.
      reload: signal(0)
    }));
    // The actual data-fetching effect.
    this.effectRef = effect(this.loadEffect.bind(this), {
      injector,
      manualCleanup: true
    });
    // Cancel any pending request when the resource itself is destroyed.
    injector.get(DestroyRef).onDestroy(() => this.destroy());
  }
  reload() {
    // We don't want to restart in-progress loads.
    const status = untracked(this.status);
    if (status === ResourceStatus.Idle || status === ResourceStatus.Loading || status === ResourceStatus.Reloading) {
      return false;
    }
    untracked(this.request).reload.update(v => v + 1);
    return true;
  }
  destroy() {
    this.effectRef.destroy();
    this.abortInProgressLoad();
    this.setValueState(ResourceStatus.Idle);
  }
  loadEffect() {
    var _this2 = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      // Capture the status before any state transitions.
      const previousStatus = untracked(_this2.status);
      // Cancel any previous loading attempts.
      _this2.abortInProgressLoad();
      const request = _this2.request();
      if (request.request === undefined) {
        // An undefined request means there's nothing to load.
        _this2.setValueState(ResourceStatus.Idle);
        return;
      }
      // Subscribing here allows us to refresh the load later by updating the refresh signal. At the
      // same time, we update the status according to whether we're reloading or loading.
      if (request.reload() === 0) {
        _this2.setValueState(ResourceStatus.Loading); // value becomes undefined
      } else {
        _this2.status.set(ResourceStatus.Reloading); // value persists
      }
      // Capturing _this_ load's pending task in a local variable is important here. We may attempt to
      // resolve it twice:
      //
      //  1. when the loading function promise resolves/rejects
      //  2. when cancelling the loading operation
      //
      // After the loading operation is cancelled, `this.resolvePendingTask` no longer represents this
      // particular task, but this `await` may eventually resolve/reject. Thus, when we cancel in
      // response to (1) below, we need to cancel the locally saved task.
      const resolvePendingTask = _this2.resolvePendingTask = _this2.pendingTasks.add();
      const {
        signal: abortSignal
      } = _this2.pendingController = new AbortController();
      try {
        // The actual loading is run through `untracked` - only the request side of `resource` is
        // reactive. This avoids any confusion with signals tracking or not tracking depending on
        // which side of the `await` they are.
        const result = yield untracked(() => _this2.loaderFn({
          abortSignal,
          request: request.request,
          previous: {
            status: previousStatus
          }
        }));
        if (abortSignal.aborted) {
          // This load operation was cancelled.
          return;
        }
        // Success :)
        _this2.setValueState(ResourceStatus.Resolved, result);
      } catch (err) {
        if (abortSignal.aborted) {
          // This load operation was cancelled.
          return;
        }
        // Fail :(
        _this2.setErrorState(err);
      } finally {
        // Resolve the pending task now that loading is done.
        resolvePendingTask();
      }
    })();
  }
  abortInProgressLoad() {
    this.pendingController?.abort();
    this.pendingController = undefined;
    // Once the load is aborted, we no longer want to block stability on its resolution.
    this.resolvePendingTask?.();
    this.resolvePendingTask = undefined;
  }
  onLocalValue() {
    this.abortInProgressLoad();
  }
}
/**
 * Wraps an equality function to handle either value being `undefined`.
 */
function wrapEqualityFn(equal) {
  return (a, b) => a === undefined || b === undefined ? a === b : equal(a, b);
}

/**
 * Creates a `ComponentRef` instance based on provided component type and a set of options.
 *
 * @usageNotes
 *
 * The example below demonstrates how the `createComponent` function can be used
 * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
 * so that it gets included into change detection cycles.
 *
 * Note: the example uses standalone components, but the function can also be used for
 * non-standalone components (declared in an NgModule) as well.
 *
 * ```typescript
 * @Component({
 *   standalone: true,
 *   template: `Hello {{ name }}!`
 * })
 * class HelloComponent {
 *   name = 'Angular';
 * }
 *
 * @Component({
 *   standalone: true,
 *   template: `<div id="hello-component-host"></div>`
 * })
 * class RootComponent {}
 *
 * // Bootstrap an application.
 * const applicationRef = await bootstrapApplication(RootComponent);
 *
 * // Locate a DOM node that would be used as a host.
 * const hostElement = document.getElementById('hello-component-host');
 *
 * // Get an `EnvironmentInjector` instance from the `ApplicationRef`.
 * const environmentInjector = applicationRef.injector;
 *
 * // We can now create a `ComponentRef` instance.
 * const componentRef = createComponent(HelloComponent, {hostElement, environmentInjector});
 *
 * // Last step is to register the newly created ref using the `ApplicationRef` instance
 * // to include the component view into change detection cycles.
 * applicationRef.attachView(componentRef.hostView);
 * componentRef.changeDetectorRef.detectChanges();
 * ```
 *
 * @param component Component class reference.
 * @param options Set of options to use:
 *  * `environmentInjector`: An `EnvironmentInjector` instance to be used for the component.
 *  * `hostElement` (optional): A DOM node that should act as a host node for the component. If not
 * provided, Angular creates one based on the tag name used in the component selector (and falls
 * back to using `div` if selector doesn't have tag name info).
 *  * `elementInjector` (optional): An `ElementInjector` instance, see additional info about it
 * [here](guide/di/hierarchical-dependency-injection#elementinjector).
 *  * `projectableNodes` (optional): A list of DOM nodes that should be projected through
 *                      [`<ng-content>`](api/core/ng-content) of the new component instance.
 * @returns ComponentRef instance that represents a given Component.
 *
 * @publicApi
 */
function createComponent(component, options) {
  ngDevMode && assertComponentDef(component);
  const componentDef = getComponentDef(component);
  const elementInjector = options.elementInjector || getNullInjector();
  const factory = new ComponentFactory(componentDef);
  return factory.create(elementInjector, options.projectableNodes, options.hostElement, options.environmentInjector);
}
/**
 * Creates an object that allows to retrieve component metadata.
 *
 * @usageNotes
 *
 * The example below demonstrates how to use the function and how the fields
 * of the returned object map to the component metadata.
 *
 * ```typescript
 * @Component({
 *   standalone: true,
 *   selector: 'foo-component',
 *   template: `
 *     <ng-content></ng-content>
 *     <ng-content select="content-selector-a"></ng-content>
 *   `,
 * })
 * class FooComponent {
 *   @Input('inputName') inputPropName: string;
 *   @Output('outputName') outputPropName = new EventEmitter<void>();
 * }
 *
 * const mirror = reflectComponentType(FooComponent);
 * expect(mirror.type).toBe(FooComponent);
 * expect(mirror.selector).toBe('foo-component');
 * expect(mirror.isStandalone).toBe(true);
 * expect(mirror.inputs).toEqual([{propName: 'inputName', templateName: 'inputPropName'}]);
 * expect(mirror.outputs).toEqual([{propName: 'outputName', templateName: 'outputPropName'}]);
 * expect(mirror.ngContentSelectors).toEqual([
 *   '*',                 // first `<ng-content>` in a template, the selector defaults to `*`
 *   'content-selector-a' // second `<ng-content>` in a template
 * ]);
 * ```
 *
 * @param component Component class reference.
 * @returns An object that allows to retrieve component metadata.
 *
 * @publicApi
 */
function reflectComponentType(component) {
  const componentDef = getComponentDef(component);
  if (!componentDef) return null;
  const factory = new ComponentFactory(componentDef);
  return {
    get selector() {
      return factory.selector;
    },
    get type() {
      return factory.componentType;
    },
    get inputs() {
      return factory.inputs;
    },
    get outputs() {
      return factory.outputs;
    },
    get ngContentSelectors() {
      return factory.ngContentSelectors;
    },
    get isStandalone() {
      return componentDef.standalone;
    },
    get isSignal() {
      return componentDef.signals;
    }
  };
}

/**
 * Merge multiple application configurations from left to right.
 *
 * @param configs Two or more configurations to be merged.
 * @returns A merged [ApplicationConfig](api/core/ApplicationConfig).
 *
 * @publicApi
 */
function mergeApplicationConfig(...configs) {
  return configs.reduce((prev, curr) => {
    return Object.assign(prev, curr, {
      providers: [...prev.providers, ...curr.providers]
    });
  }, {
    providers: []
  });
}

/**
 * Injection token representing the current HTTP request object.
 *
 * Use this token to access the current request when handling server-side
 * rendering (SSR).
 *
 * @remarks
 * This token may be `null` in the following scenarios:
 *
 * * During the build processes.
 * * When the application is rendered in the browser (client-side rendering).
 * * When performing static site generation (SSG).
 * * During route extraction in development (at the time of the request).
 *
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | `Request` on MDN}
 *
 * @developerPreview
 */
const REQUEST = /*#__PURE__*/new InjectionToken('REQUEST', {
  providedIn: 'platform',
  factory: () => null
});
/**
 * Injection token for response initialization options.
 *
 * Use this token to provide response options for configuring or initializing
 * HTTP responses in server-side rendering or API endpoints.
 *
 * @remarks
 * This token may be `null` in the following scenarios:
 *
 * * During the build processes.
 * * When the application is rendered in the browser (client-side rendering).
 * * When performing static site generation (SSG).
 * * During route extraction in development (at the time of the request).
 *
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response | `ResponseInit` on MDN}
 *
 * @developerPreview
 */
const RESPONSE_INIT = /*#__PURE__*/new InjectionToken('RESPONSE_INIT', {
  providedIn: 'platform',
  factory: () => null
});
/**
 * Injection token for additional request context.
 *
 * Use this token to pass custom metadata or context related to the current request in server-side rendering.
 *
 * @remarks
 * This token is only available during server-side rendering and will be `null` in other contexts.
 *
 * @developerPreview
 */
const REQUEST_CONTEXT = /*#__PURE__*/new InjectionToken('REQUEST_CONTEXT', {
  providedIn: 'platform',
  factory: () => null
});

/**
 * @module
 * @description
 * Entry point from which you should import all public core APIs.
 */
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  // This helper is to give a reasonable error message to people upgrading to v9 that have not yet
  // installed `@angular/localize` in their app.
  // tslint:disable-next-line: no-toplevel-property-access
  _global.$localize ??= function () {
    throw new Error('It looks like your application or one of its dependencies is using i18n.\n' + 'Angular 9 introduced a global `$localize()` function that needs to be loaded.\n' + 'Please run `ng add @angular/localize` from the Angular CLI.\n' + "(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.\n" + 'For server-side rendering applications add the import to your `main.server.ts` file.)');
  };
}

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
// This file only reexports content of the `src` folder. Keep it that way.

/* This file is not used to build this module. It is only used during editing
 * by the TypeScript language service and during build for verification. `ngc`
 * replaces this file with production index.ts when it rewrites private symbol
 * names.
 */

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 4281:
/*!*********************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0/node_modules/@angular/core/fesm2022/primitives/event-dispatch.mjs ***!
  \*********************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Attribute: () => (/* binding */ Attribute),
/* harmony export */   EventContract: () => (/* binding */ EventContract),
/* harmony export */   EventContractContainer: () => (/* binding */ EventContractContainer),
/* harmony export */   EventDispatcher: () => (/* binding */ EventDispatcher),
/* harmony export */   EventInfoWrapper: () => (/* binding */ EventInfoWrapper),
/* harmony export */   EventPhase: () => (/* binding */ EventPhase),
/* harmony export */   bootstrapAppScopedEarlyEventContract: () => (/* binding */ bootstrapAppScopedEarlyEventContract),
/* harmony export */   clearAppScopedEarlyEventContract: () => (/* binding */ clearAppScopedEarlyEventContract),
/* harmony export */   getActionCache: () => (/* binding */ getDefaulted),
/* harmony export */   getAppScopedQueuedEventInfos: () => (/* binding */ getAppScopedQueuedEventInfos),
/* harmony export */   isCaptureEventType: () => (/* binding */ isCaptureEventType),
/* harmony export */   isEarlyEventType: () => (/* binding */ isEarlyEventType),
/* harmony export */   registerAppScopedDispatcher: () => (/* binding */ registerAppScopedDispatcher),
/* harmony export */   registerDispatcher: () => (/* binding */ registerDispatcher$1),
/* harmony export */   removeAllAppScopedEventListeners: () => (/* binding */ removeAllAppScopedEventListeners)
/* harmony export */ });
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */

const Attribute = {
  /**
   * The jsaction attribute defines a mapping of a DOM event to a
   * generic event (aka jsaction), to which the actual event handlers
   * that implement the behavior of the application are bound. The
   * value is a semicolon separated list of colon separated pairs of
   * an optional DOM event name and a jsaction name. If the optional
   * DOM event name is omitted, 'click' is assumed. The jsaction names
   * are dot separated pairs of a namespace and a simple jsaction
   * name.
   *
   * See grammar in README.md for expected syntax in the attribute value.
   */
  JSACTION: 'jsaction'
};

/** All properties that are used by jsaction. */
const Property = {
  /**
   * The parsed value of the jsaction attribute is stored in this
   * property on the DOM node. The parsed value is an Object. The
   * property names of the object are the events; the values are the
   * names of the actions. This property is attached even on nodes
   * that don't have a jsaction attribute as an optimization, because
   * property lookup is faster than attribute access.
   */
  JSACTION: '__jsaction',
  /**
   * The owner property references an a logical owner for a DOM node. JSAction
   * will follow this reference instead of parentNode when traversing the DOM
   * to find jsaction attributes. This allows overlaying a logical structure
   * over a document where the DOM structure can't reflect that structure.
   */
  OWNER: '__owner'
};

/**
 * Map from jsaction annotation to a parsed map from event name to action name.
 */
const parseCache = {};
/**
 * Reads the jsaction parser cache from the given DOM Element.
 */
function get(element) {
  return element[Property.JSACTION];
}
/**
 * Reads the jsaction parser cache for the given DOM element. If no cache is yet present,
 * creates an empty one.
 */
function getDefaulted(element) {
  const cache = get(element) ?? {};
  set(element, cache);
  return cache;
}
/**
 * Writes the jsaction parser cache to the given DOM Element.
 */
function set(element, actionMap) {
  element[Property.JSACTION] = actionMap;
}
/**
 * Looks up the parsed action map from the source jsaction attribute value.
 *
 * @param text Unparsed jsaction attribute value.
 * @return Parsed jsaction attribute value, if already present in the cache.
 */
function getParsed(text) {
  return parseCache[text];
}
/**
 * Inserts the parse result for the given source jsaction value into the cache.
 *
 * @param text Unparsed jsaction attribute value.
 * @param parsed Attribute value parsed into the action map.
 */
function setParsed(text, parsed) {
  parseCache[text] = parsed;
}
/**
 * Clears the jsaction parser cache from the given DOM Element.
 *
 * @param element .
 */
function clear(element) {
  if (Property.JSACTION in element) {
    delete element[Property.JSACTION];
  }
}

/*
 * Names of events that are special to jsaction. These are not all
 * event types that are legal to use in either HTML or the addEvent()
 * API, but these are the ones that are treated specially. All other
 * DOM events can be used in either addEvent() or in the value of the
 * jsaction attribute. Beware of browser specific events or events
 * that don't bubble though: If they are not mentioned here, then
 * event contract doesn't work around their peculiarities.
 */
const EventType = {
  /**
   * Mouse middle click, introduced in Chrome 55 and not yet supported on
   * other browsers.
   */
  AUXCLICK: 'auxclick',
  /**
   * The change event fired by browsers when the `value` attribute of input,
   * select, and textarea elements are changed.
   */
  CHANGE: 'change',
  /**
   * The click event. In addEvent() refers to all click events, in the
   * jsaction attribute it refers to the unmodified click and Enter/Space
   * keypress events.  In the latter case, a jsaction click will be triggered,
   * for accessibility reasons.  See clickmod and clickonly, below.
   */
  CLICK: 'click',
  /**
   * Specifies the jsaction for a modified click event (i.e. a mouse
   * click with the modifier key Cmd/Ctrl pressed). This event isn't
   * separately enabled in addEvent(), because in the DOM, it's just a
   * click event.
   */
  CLICKMOD: 'clickmod',
  /**
   * Specifies the jsaction for a click-only event.  Click-only doesn't take
   * into account the case where an element with focus receives an Enter/Space
   * keypress.  This event isn't separately enabled in addEvent().
   */
  CLICKONLY: 'clickonly',
  /**
   * The dblclick event.
   */
  DBLCLICK: 'dblclick',
  /**
   * Focus doesn't bubble, but you can use it in addEvent() and
   * jsaction anyway. EventContract does the right thing under the
   * hood.
   */
  FOCUS: 'focus',
  /**
   * This event only exists in IE. For addEvent() and jsaction, use
   * focus instead; EventContract does the right thing even though
   * focus doesn't bubble.
   */
  FOCUSIN: 'focusin',
  /**
   * Analog to focus.
   */
  BLUR: 'blur',
  /**
   * Analog to focusin.
   */
  FOCUSOUT: 'focusout',
  /**
   * Submit doesn't bubble, so it cannot be used with event
   * contract. However, the browser helpfully fires a click event on
   * the submit button of a form (even if the form is not submitted by
   * a click on the submit button). So you should handle click on the
   * submit button instead.
   */
  SUBMIT: 'submit',
  /**
   * The keydown event. In addEvent() and non-click jsaction it represents the
   * regular DOM keydown event. It represents click actions in non-Gecko
   * browsers.
   */
  KEYDOWN: 'keydown',
  /**
   * The keypress event. In addEvent() and non-click jsaction it represents the
   * regular DOM keypress event. It represents click actions in Gecko browsers.
   */
  KEYPRESS: 'keypress',
  /**
   * The keyup event. In addEvent() and non-click jsaction it represents the
   * regular DOM keyup event. It represents click actions in non-Gecko
   * browsers.
   */
  KEYUP: 'keyup',
  /**
   * The mouseup event. Can either be used directly or used implicitly to
   * capture mouseup events. In addEvent(), it represents a regular DOM
   * mouseup event.
   */
  MOUSEUP: 'mouseup',
  /**
   * The mousedown event. Can either be used directly or used implicitly to
   * capture mouseenter events. In addEvent(), it represents a regular DOM
   * mouseover event.
   */
  MOUSEDOWN: 'mousedown',
  /**
   * The mouseover event. Can either be used directly or used implicitly to
   * capture mouseenter events. In addEvent(), it represents a regular DOM
   * mouseover event.
   */
  MOUSEOVER: 'mouseover',
  /**
   * The mouseout event. Can either be used directly or used implicitly to
   * capture mouseover events. In addEvent(), it represents a regular DOM
   * mouseout event.
   */
  MOUSEOUT: 'mouseout',
  /**
   * The mouseenter event. Does not bubble and fires individually on each
   * element being entered within a DOM tree.
   */
  MOUSEENTER: 'mouseenter',
  /**
   * The mouseleave event. Does not bubble and fires individually on each
   * element being entered within a DOM tree.
   */
  MOUSELEAVE: 'mouseleave',
  /**
   * The mousemove event.
   */
  MOUSEMOVE: 'mousemove',
  /**
   * The pointerup event. Can either be used directly or used implicitly to
   * capture pointerup events. In addEvent(), it represents a regular DOM
   * pointerup event.
   */
  POINTERUP: 'pointerup',
  /**
   * The pointerdown event. Can either be used directly or used implicitly to
   * capture pointerenter events. In addEvent(), it represents a regular DOM
   * mouseover event.
   */
  POINTERDOWN: 'pointerdown',
  /**
   * The pointerover event. Can either be used directly or used implicitly to
   * capture pointerenter events. In addEvent(), it represents a regular DOM
   * pointerover event.
   */
  POINTEROVER: 'pointerover',
  /**
   * The pointerout event. Can either be used directly or used implicitly to
   * capture pointerover events. In addEvent(), it represents a regular DOM
   * pointerout event.
   */
  POINTEROUT: 'pointerout',
  /**
   * The pointerenter event. Does not bubble and fires individually on each
   * element being entered within a DOM tree.
   */
  POINTERENTER: 'pointerenter',
  /**
   * The pointerleave event. Does not bubble and fires individually on each
   * element being entered within a DOM tree.
   */
  POINTERLEAVE: 'pointerleave',
  /**
   * The pointermove event.
   */
  POINTERMOVE: 'pointermove',
  /**
   * The pointercancel event.
   */
  POINTERCANCEL: 'pointercancel',
  /**
   * The gotpointercapture event is fired when
   * Element.setPointerCapture(pointerId) is called on a mouse input, or
   * implicitly when a touch input begins.
   */
  GOTPOINTERCAPTURE: 'gotpointercapture',
  /**
   * The lostpointercapture event is fired when
   * Element.releasePointerCapture(pointerId) is called, or implicitly after a
   * touch input ends.
   */
  LOSTPOINTERCAPTURE: 'lostpointercapture',
  /**
   * The error event. The error event doesn't bubble, but you can use it in
   * addEvent() and jsaction anyway. EventContract does the right thing under
   * the hood (except in IE8 which does not use error events).
   */
  ERROR: 'error',
  /**
   * The load event. The load event doesn't bubble, but you can use it in
   * addEvent() and jsaction anyway. EventContract does the right thing
   * under the hood.
   */
  LOAD: 'load',
  /**
   * The unload event.
   */
  UNLOAD: 'unload',
  /**
   * The touchstart event. Bubbles, will only ever fire in browsers with
   * touch support.
   */
  TOUCHSTART: 'touchstart',
  /**
   * The touchend event. Bubbles, will only ever fire in browsers with
   * touch support.
   */
  TOUCHEND: 'touchend',
  /**
   * The touchmove event. Bubbles, will only ever fire in browsers with
   * touch support.
   */
  TOUCHMOVE: 'touchmove',
  /**
   * The input event.
   */
  INPUT: 'input',
  /**
   * The scroll event.
   */
  SCROLL: 'scroll',
  /**
   * The toggle event. The toggle event doesn't bubble, but you can use it in
   * addEvent() and jsaction anyway. EventContract does the right thing
   * under the hood.
   */
  TOGGLE: 'toggle',
  /**
   * A custom event. The actual custom event type is declared as the 'type'
   * field in the event details. Supported in Firefox 6+, IE 9+, and all Chrome
   * versions.
   *
   * This is an internal name. Users should use jsaction's fireCustomEvent to
   * fire custom events instead of relying on this type to create them.
   */
  CUSTOM: '_custom'
};
/** All event types that do not bubble or capture and need a polyfill. */
const MOUSE_SPECIAL_EVENT_TYPES = [EventType.MOUSEENTER, EventType.MOUSELEAVE, 'pointerenter', 'pointerleave'];
/** All event types that are registered in the bubble phase. */
const BUBBLE_EVENT_TYPES = [EventType.CLICK, EventType.DBLCLICK, EventType.FOCUSIN, EventType.FOCUSOUT, EventType.KEYDOWN, EventType.KEYUP, EventType.KEYPRESS, EventType.MOUSEOVER, EventType.MOUSEOUT, EventType.SUBMIT, EventType.TOUCHSTART, EventType.TOUCHEND, EventType.TOUCHMOVE, 'touchcancel', 'auxclick', 'change', 'compositionstart', 'compositionupdate', 'compositionend', 'beforeinput', 'input', 'select', 'copy', 'cut', 'paste', 'mousedown', 'mouseup', 'wheel', 'contextmenu', 'dragover', 'dragenter', 'dragleave', 'drop', 'dragstart', 'dragend', 'pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'pointerover', 'pointerout', 'gotpointercapture', 'lostpointercapture',
// Video events.
'ended', 'loadedmetadata',
// Page visibility events.
'pagehide', 'pageshow', 'visibilitychange',
// Content visibility events.
'beforematch'];
/** All event types that are registered in the capture phase. */
const CAPTURE_EVENT_TYPES = [EventType.FOCUS, EventType.BLUR, EventType.ERROR, EventType.LOAD, EventType.TOGGLE];
/**
 * Whether or not an event type should be registered in the capture phase.
 * @param eventType
 * @returns bool
 */
const isCaptureEventType = eventType => CAPTURE_EVENT_TYPES.indexOf(eventType) >= 0;
/** All event types that are registered early.  */
const EARLY_EVENT_TYPES = /*#__PURE__*/BUBBLE_EVENT_TYPES.concat(CAPTURE_EVENT_TYPES);
/**
 * Whether or not an event type is registered in the early contract.
 */
const isEarlyEventType = eventType => EARLY_EVENT_TYPES.indexOf(eventType) >= 0;

/**
 * If on a Macintosh with an extended keyboard, the Enter key located in the
 * numeric pad has a different ASCII code.
 */
const MAC_ENTER = 3;
/** The Enter key. */
const ENTER = 13;
/** The Space key. */
const SPACE = 32;
/** Special keycodes used by jsaction for the generic click action. */
const KeyCode = {
  MAC_ENTER,
  ENTER,
  SPACE
};

/**
 * Gets a browser event type, if it would differ from the JSAction event type.
 */
function getBrowserEventType(eventType) {
  // Mouseenter and mouseleave events are not handled directly because they
  // are not available everywhere. In browsers where they are available, they
  // don't bubble and aren't visible at the container boundary. Instead, we
  // synthesize the mouseenter and mouseleave events from mouseover and
  // mouseout events, respectively. Cf. eventcontract.js.
  if (eventType === EventType.MOUSEENTER) {
    return EventType.MOUSEOVER;
  } else if (eventType === EventType.MOUSELEAVE) {
    return EventType.MOUSEOUT;
  } else if (eventType === EventType.POINTERENTER) {
    return EventType.POINTEROVER;
  } else if (eventType === EventType.POINTERLEAVE) {
    return EventType.POINTEROUT;
  }
  return eventType;
}
/**
 * Registers the event handler function with the given DOM element for
 * the given event type.
 *
 * @param element The element.
 * @param eventType The event type.
 * @param handler The handler function to install.
 * @param passive A boolean value that, if `true`, indicates that the function
 *     specified by `handler` will never call `preventDefault()`.
 * @return Information needed to uninstall the event handler eventually.
 */
function addEventListener(element, eventType, handler, passive) {
  // All event handlers are registered in the bubbling
  // phase.
  //
  // All browsers support focus and blur, but these events only are propagated
  // in the capture phase. Very legacy browsers do not support focusin or
  // focusout.
  //
  // It would be a bad idea to register all event handlers in the
  // capture phase because then regular onclick handlers would not be
  // executed at all on events that trigger a jsaction. That's not
  // entirely what we want, at least for now.
  //
  // Error and load events (i.e. on images) do not bubble so they are also
  // handled in the capture phase.
  let capture = false;
  if (isCaptureEventType(eventType)) {
    capture = true;
  }
  const options = typeof passive === 'boolean' ? {
    capture,
    passive
  } : capture;
  element.addEventListener(eventType, handler, options);
  return {
    eventType,
    handler,
    capture,
    passive
  };
}
/**
 * Removes the event handler for the given event from the element.
 * the given event type.
 *
 * @param element The element.
 * @param info The information needed to deregister the handler, as returned by
 *     addEventListener(), above.
 */
function removeEventListener(element, info) {
  if (element.removeEventListener) {
    // It's worth noting that some browser releases have been inconsistent on this, and unless
    // you have specific reasons otherwise, it's probably wise to use the same values used for
    // the call to addEventListener() when calling removeEventListener().
    const options = typeof info.passive === 'boolean' ? {
      capture: info.capture
    } : info.capture;
    element.removeEventListener(info.eventType, info.handler, options);
    // `detachEvent` is an old DOM API.
    // tslint:disable-next-line:no-any
  } else if (element.detachEvent) {
    // `detachEvent` is an old DOM API.
    // tslint:disable-next-line:no-any
    element.detachEvent(`on${info.eventType}`, info.handler);
  }
}
/**
 * Cancels propagation of an event.
 * @param e The event to cancel propagation for.
 */
function stopPropagation(e) {
  e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}
/**
 * Prevents the default action of an event.
 * @param e The event to prevent the default action for.
 */
function preventDefault(e) {
  e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
/**
 * Gets the target Element of the event. In Firefox, a text node may appear as
 * the target of the event, in which case we return the parent element of the
 * text node.
 * @param e The event to get the target of.
 * @return The target element.
 */
function getTarget(e) {
  let el = e.target;
  // In Firefox, the event may have a text node as its target. We always
  // want the parent Element the text node belongs to, however.
  if (!el.getAttribute && el.parentNode) {
    el = el.parentNode;
  }
  return el;
}
/**
 * Whether we are on a Mac. Not pulling in useragent just for this.
 */
let isMac = typeof navigator !== 'undefined' && /*#__PURE__*//Macintosh/.test(navigator.userAgent);
/**
 * Determines and returns whether the given event (which is assumed to be a
 * click event) is a middle click.
 * NOTE: There is not a consistent way to identify middle click
 * http://www.unixpapa.com/js/mouse.html
 */
function isMiddleClick(e) {
  return (
    // `which` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.which === 2 ||
    // `which` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.which == null &&
    // `button` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.button === 4 // middle click for IE
  );
}
/**
 * Determines and returns whether the given event (which is assumed
 * to be a click event) is modified. A middle click is considered a modified
 * click to retain the default browser action, which opens a link in a new tab.
 * @param e The event.
 * @return Whether the given event is modified.
 */
function isModifiedClickEvent(e) {
  return (
    // `metaKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    isMac && e.metaKey ||
    // `ctrlKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    !isMac && e.ctrlKey || isMiddleClick(e) ||
    // `shiftKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.shiftKey
  );
}
/** Whether we are on WebKit (e.g., Chrome). */
const isWebKit = typeof navigator !== 'undefined' && ! /*#__PURE__*//Opera/.test(navigator.userAgent) && /*#__PURE__*//WebKit/.test(navigator.userAgent);
/** Whether we are on IE. */
const isIe = typeof navigator !== 'undefined' && (/*#__PURE__*//MSIE/.test(navigator.userAgent) || /*#__PURE__*//Trident/.test(navigator.userAgent));
/** Whether we are on Gecko (e.g., Firefox). */
const isGecko = typeof navigator !== 'undefined' && ! /*#__PURE__*//Opera|WebKit/.test(navigator.userAgent) && /*#__PURE__*//Gecko/.test(navigator.product);
/**
 * Determines and returns whether the given element is a valid target for
 * keypress/keydown DOM events that act like regular DOM clicks.
 * @param el The element.
 * @return Whether the given element is a valid action key target.
 */
function isValidActionKeyTarget(el) {
  if (!('getAttribute' in el)) {
    return false;
  }
  if (isTextControl(el)) {
    return false;
  }
  if (isNativelyActivatable(el)) {
    return false;
  }
  // `isContentEditable` is an old DOM API.
  // tslint:disable-next-line:no-any
  if (el.isContentEditable) {
    return false;
  }
  return true;
}
/**
 * Whether an event has a modifier key activated.
 * @param e The event.
 * @return True, if a modifier key is activated.
 */
function hasModifierKey(e) {
  return (
    // `ctrlKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.ctrlKey ||
    // `shiftKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.shiftKey ||
    // `altKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.altKey ||
    // `metaKey` is an old DOM API.
    // tslint:disable-next-line:no-any
    e.metaKey
  );
}
/**
 * Determines and returns whether the given event has a target that already
 * has event handlers attached because it is a native HTML control. Used to
 * determine if preventDefault should be called when isActionKeyEvent is true.
 * @param e The event.
 * @return If preventDefault should be called.
 */
function shouldCallPreventDefaultOnNativeHtmlControl(e) {
  const el = getTarget(e);
  const tagName = el.tagName.toUpperCase();
  const role = (el.getAttribute('role') || '').toUpperCase();
  if (tagName === 'BUTTON' || role === 'BUTTON') {
    return true;
  }
  if (!isNativeHTMLControl(el)) {
    return false;
  }
  if (tagName === 'A') {
    return false;
  }
  /**
   * Fix for physical d-pads on feature phone platforms; the native event
   * (ie. isTrusted: true) needs to fire to show the OPTION list. See
   * b/135288469 for more info.
   */
  if (tagName === 'SELECT') {
    return false;
  }
  if (processSpace(el)) {
    return false;
  }
  if (isTextControl(el)) {
    return false;
  }
  return true;
}
/**
 * Determines and returns whether the given event acts like a regular DOM click,
 * and should be handled instead of the click.  If this returns true, the caller
 * will call preventDefault() to prevent a possible duplicate event.
 * This is represented by a keypress (keydown on Gecko browsers) on Enter or
 * Space key.
 * @param e The event.
 * @return True, if the event emulates a DOM click.
 */
function isActionKeyEvent(e) {
  let key =
  // `which` is an old DOM API.
  // tslint:disable-next-line:no-any
  e.which ||
  // `keyCode` is an old DOM API.
  // tslint:disable-next-line:no-any
  e.keyCode;
  if (!key && e.key) {
    key = ACTION_KEY_TO_KEYCODE[e.key];
  }
  if (isWebKit && key === KeyCode.MAC_ENTER) {
    key = KeyCode.ENTER;
  }
  if (key !== KeyCode.ENTER && key !== KeyCode.SPACE) {
    return false;
  }
  const el = getTarget(e);
  if (e.type !== EventType.KEYDOWN || !isValidActionKeyTarget(el) || hasModifierKey(e)) {
    return false;
  }
  // For <input type="checkbox">, we must only handle the browser's native click
  // event, so that the browser can toggle the checkbox.
  if (processSpace(el) && key === KeyCode.SPACE) {
    return false;
  }
  // If this element is non-focusable, ignore stray keystrokes (b/18337209)
  // Sscreen readers can move without tab focus, so any tabIndex is focusable.
  // See B/21809604
  if (!isFocusable(el)) {
    return false;
  }
  const type = (el.getAttribute('role') || el.type || el.tagName).toUpperCase();
  const isSpecificTriggerKey = IDENTIFIER_TO_KEY_TRIGGER_MAPPING[type] % key === 0;
  const isDefaultTriggerKey = !(type in IDENTIFIER_TO_KEY_TRIGGER_MAPPING) && key === KeyCode.ENTER;
  const hasType = el.tagName.toUpperCase() !== 'INPUT' || !!el.type;
  return (isSpecificTriggerKey || isDefaultTriggerKey) && hasType;
}
/**
 * Checks whether a DOM element can receive keyboard focus.
 * This code is based on goog.dom.isFocusable, but simplified since we shouldn't
 * care about visibility if we're already handling a keyboard event.
 */
function isFocusable(el) {
  return (el.tagName in NATIVELY_FOCUSABLE_ELEMENTS || hasSpecifiedTabIndex(el)) && !el.disabled;
}
/**
 * @param element Element to check.
 * @return Whether the element has a specified tab index.
 */
function hasSpecifiedTabIndex(element) {
  // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),
  // which returns an object with a 'specified' property if tabIndex is
  // specified.  This works on other browsers, too.
  const attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
  return attrNode != null && attrNode.specified;
}
/** Element tagnames that are focusable by default. */
const NATIVELY_FOCUSABLE_ELEMENTS = {
  'A': 1,
  'INPUT': 1,
  'TEXTAREA': 1,
  'SELECT': 1,
  'BUTTON': 1
};
/** @return True, if the Space key was pressed. */
function isSpaceKeyEvent(e) {
  const key =
  // `which` is an old DOM API.
  // tslint:disable-next-line:no-any
  e.which ||
  // `keyCode` is an old DOM API.
  // tslint:disable-next-line:no-any
  e.keyCode;
  const el = getTarget(e);
  const elementName = (el.type || el.tagName).toUpperCase();
  return key === KeyCode.SPACE && elementName !== 'CHECKBOX';
}
/**
 * Determines whether the event corresponds to a non-bubbling mouse
 * event type (mouseenter, mouseleave, pointerenter, and pointerleave).
 *
 * During mouseover (mouseenter) and pointerover (pointerenter), the
 * relatedTarget is the element being entered from. During mouseout (mouseleave)
 * and pointerout (pointerleave), the relatedTarget is the element being exited
 * to.
 *
 * In both cases, if relatedTarget is outside target, then the corresponding
 * special event has occurred, otherwise it hasn't.
 *
 * @param e The mouseover/mouseout event.
 * @param type The type of the mouse special event.
 * @param element The element on which the jsaction for the
 *     mouseenter/mouseleave event is defined.
 * @return True if the event is a mouseenter/mouseleave event.
 */
function isMouseSpecialEvent(e, type, element) {
  // `relatedTarget` is an old DOM API.
  // tslint:disable-next-line:no-any
  const related = e.relatedTarget;
  return (e.type === EventType.MOUSEOVER && type === EventType.MOUSEENTER || e.type === EventType.MOUSEOUT && type === EventType.MOUSELEAVE || e.type === EventType.POINTEROVER && type === EventType.POINTERENTER || e.type === EventType.POINTEROUT && type === EventType.POINTERLEAVE) && (!related || related !== element && !element.contains(related));
}
/**
 * Creates a new EventLike object for a mouseenter/mouseleave event that's
 * derived from the original corresponding mouseover/mouseout event.
 * @param e The event.
 * @param target The element on which the jsaction for the mouseenter/mouseleave
 *     event is defined.
 * @return A modified event-like object copied from the event object passed into
 *     this function.
 */
function createMouseSpecialEvent(e, target) {
  // We have to create a copy of the event object because we need to mutate
  // its fields. We do this for the special mouse events because the event
  // target needs to be retargeted to the action element rather than the real
  // element (since we are simulating the special mouse events with mouseover/
  // mouseout).
  //
  // Since we're making a copy anyways, we might as well attempt to convert
  // this event into a pseudo-real mouseenter/mouseleave event by adjusting
  // its type.
  //
  // tslint:disable-next-line:no-any
  const copy = {};
  for (const property in e) {
    if (property === 'srcElement' || property === 'target') {
      continue;
    }
    const key = property;
    // Making a copy requires iterating through all properties of `Event`.
    // tslint:disable-next-line:no-dict-access-on-struct-type
    const value = e[key];
    if (typeof value === 'function') {
      continue;
    }
    // Value should be the expected type, but the value of `key` is not known
    // statically.
    // tslint:disable-next-line:no-any
    copy[key] = value;
  }
  if (e.type === EventType.MOUSEOVER) {
    copy['type'] = EventType.MOUSEENTER;
  } else if (e.type === EventType.MOUSEOUT) {
    copy['type'] = EventType.MOUSELEAVE;
  } else if (e.type === EventType.POINTEROVER) {
    copy['type'] = EventType.POINTERENTER;
  } else {
    copy['type'] = EventType.POINTERLEAVE;
  }
  copy['target'] = copy['srcElement'] = target;
  copy['bubbles'] = false;
  return copy;
}
/**
 * Returns touch data extracted from the touch event: clientX, clientY, screenX
 * and screenY. If the event has no touch information at all, the returned
 * value is null.
 *
 * The fields of this Object are unquoted.
 *
 * @param event A touch event.
 */
function getTouchData(event) {
  const touch = event.changedTouches && event.changedTouches[0] || event.touches && event.touches[0];
  if (!touch) {
    return null;
  }
  return {
    clientX: touch.clientX,
    clientY: touch.clientY,
    screenX: touch.screenX,
    screenY: touch.screenY
  };
}
/**
 * Creates a new EventLike object for a "click" event that's derived from the
 * original corresponding "touchend" event for a fast-click implementation.
 *
 * It takes a touch event, adds common fields found in a click event and
 * changes the type to 'click', so that the resulting event looks more like
 * a real click event.
 *
 * @param event A touch event.
 * @return A modified event-like object copied from the event object passed into
 *     this function.
 */
function recreateTouchEventAsClick(event) {
  const click = {};
  click['originalEventType'] = event.type;
  click['type'] = EventType.CLICK;
  for (const property in event) {
    if (property === 'type' || property === 'srcElement') {
      continue;
    }
    const key = property;
    // Making a copy requires iterating through all properties of `TouchEvent`.
    // tslint:disable-next-line:no-dict-access-on-struct-type
    const value = event[key];
    if (typeof value === 'function') {
      continue;
    }
    // Value should be the expected type, but the value of `key` is not known
    // statically.
    // tslint:disable-next-line:no-any
    click[key] = value;
  }
  // Ensure that the event has the most recent timestamp. This timestamp
  // may be used in the future to validate or cancel subsequent click events.
  click['timeStamp'] = Date.now();
  // Emulate preventDefault and stopPropagation behavior
  click['defaultPrevented'] = false;
  click['preventDefault'] = syntheticPreventDefault;
  click['_propagationStopped'] = false;
  click['stopPropagation'] = syntheticStopPropagation;
  // Emulate click coordinates using touch info
  const touch = getTouchData(event);
  if (touch) {
    click['clientX'] = touch.clientX;
    click['clientY'] = touch.clientY;
    click['screenX'] = touch.screenX;
    click['screenY'] = touch.screenY;
  }
  return click;
}
/**
 * An implementation of "preventDefault" for a synthesized event. Simply
 * sets "defaultPrevented" property to true.
 */
function syntheticPreventDefault() {
  this.defaultPrevented = true;
}
/**
 * An implementation of "stopPropagation" for a synthesized event. It simply
 * sets a synthetic non-standard "_propagationStopped" property to true.
 */
function syntheticStopPropagation() {
  this._propagationStopped = true;
}
/**
 * Mapping of KeyboardEvent.key values to
 * KeyCode values.
 */
const ACTION_KEY_TO_KEYCODE = {
  'Enter': KeyCode.ENTER,
  ' ': KeyCode.SPACE
};
/**
 * Mapping of HTML element identifiers (ARIA role, type, or tagName) to the
 * keys (enter and/or space) that should activate them. A value of zero means
 * that both should activate them.
 */
const IDENTIFIER_TO_KEY_TRIGGER_MAPPING = {
  'A': KeyCode.ENTER,
  'BUTTON': 0,
  'CHECKBOX': KeyCode.SPACE,
  'COMBOBOX': KeyCode.ENTER,
  'FILE': 0,
  'GRIDCELL': KeyCode.ENTER,
  'LINK': KeyCode.ENTER,
  'LISTBOX': KeyCode.ENTER,
  'MENU': 0,
  'MENUBAR': 0,
  'MENUITEM': 0,
  'MENUITEMCHECKBOX': 0,
  'MENUITEMRADIO': 0,
  'OPTION': 0,
  'RADIO': KeyCode.SPACE,
  'RADIOGROUP': KeyCode.SPACE,
  'RESET': 0,
  'SUBMIT': 0,
  'SWITCH': KeyCode.SPACE,
  'TAB': 0,
  'TREE': KeyCode.ENTER,
  'TREEITEM': KeyCode.ENTER
};
/**
 * Returns whether or not to process space based on the type of the element;
 * checks to make sure that type is not null.
 * @param element The element.
 * @return Whether or not to process space based on type.
 */
function processSpace(element) {
  const type = (element.getAttribute('type') || element.tagName).toUpperCase();
  return type in PROCESS_SPACE;
}
/**
 * Returns whether or not the given element is a text control.
 * @param el The element.
 * @return Whether or not the given element is a text control.
 */
function isTextControl(el) {
  const type = (el.getAttribute('type') || el.tagName).toUpperCase();
  return type in TEXT_CONTROLS;
}
/**
 * Returns if the given element is a native HTML control.
 * @param el The element.
 * @return If the given element is a native HTML control.
 */
function isNativeHTMLControl(el) {
  return el.tagName.toUpperCase() in NATIVE_HTML_CONTROLS;
}
/**
 * Returns if the given element is natively activatable. Browsers emit click
 * events for natively activatable elements, even when activated via keyboard.
 * For these elements, we don't need to raise a11y click events.
 * @param el The element.
 * @return If the given element is a native HTML control.
 */
function isNativelyActivatable(el) {
  return el.tagName.toUpperCase() === 'BUTTON' || !!el.type && el.type.toUpperCase() === 'FILE';
}
/**
 * HTML <input> types (not ARIA roles) which will auto-trigger a click event for
 * the Space key, with side-effects. We will not call preventDefault if space is
 * pressed, nor will we raise a11y click events.  For all other elements, we can
 * suppress the default event (which has no desired side-effects) and handle the
 * keydown ourselves.
 */
const PROCESS_SPACE = {
  'CHECKBOX': true,
  'FILE': true,
  'OPTION': true,
  'RADIO': true
};
/** TagNames and Input types for which to not process enter/space as click. */
const TEXT_CONTROLS = {
  'COLOR': true,
  'DATE': true,
  'DATETIME': true,
  'DATETIME-LOCAL': true,
  'EMAIL': true,
  'MONTH': true,
  'NUMBER': true,
  'PASSWORD': true,
  'RANGE': true,
  'SEARCH': true,
  'TEL': true,
  'TEXT': true,
  'TEXTAREA': true,
  'TIME': true,
  'URL': true,
  'WEEK': true
};
/** TagNames that are native HTML controls. */
const NATIVE_HTML_CONTROLS = {
  'A': true,
  'AREA': true,
  'BUTTON': true,
  'DIALOG': true,
  'IMG': true,
  'INPUT': true,
  'LINK': true,
  'MENU': true,
  'OPTGROUP': true,
  'OPTION': true,
  'PROGRESS': true,
  'SELECT': true,
  'TEXTAREA': true
};
/** Exported for testing. */
const testing = {
  setIsMac(value) {
    isMac = value;
  }
};

/**
 * Whether the user agent is running on iOS.
 */
const isIos = typeof navigator !== 'undefined' && /*#__PURE__*//iPhone|iPad|iPod/.test(navigator.userAgent);
/**
 * A class representing a container node and all the event handlers
 * installed on it. Used so that handlers can be cleaned up if the
 * container is removed from the contract.
 */
class EventContractContainer {
  element;
  /**
   * Array of event handlers and their corresponding event types that are
   * installed on this container.
   *
   */
  handlerInfos = [];
  /**
   * @param element The container Element.
   */
  constructor(element) {
    this.element = element;
  }
  /**
   * Installs the provided installer on the element owned by this container,
   * and maintains a reference to resulting handler in order to remove it
   * later if desired.
   */
  addEventListener(eventType, getHandler, passive) {
    // In iOS, event bubbling doesn't happen automatically in any DOM element,
    // unless it has an onclick attribute or DOM event handler attached to it.
    // This breaks JsAction in some cases. See "Making Elements Clickable"
    // section at http://goo.gl/2VoGnB.
    //
    // A workaround for this issue is to change the CSS cursor style to 'pointer'
    // for the container element, which magically turns on event bubbling. This
    // solution is described in the comments section at http://goo.gl/6pEO1z.
    //
    // We use a navigator.userAgent check here as this problem is present both
    // on Mobile Safari and thin WebKit wrappers, such as Chrome for iOS.
    if (isIos) {
      this.element.style.cursor = 'pointer';
    }
    this.handlerInfos.push(addEventListener(this.element, eventType, getHandler(this.element), passive));
  }
  /**
   * Removes all the handlers installed on this container.
   */
  cleanUp() {
    for (let i = 0; i < this.handlerInfos.length; i++) {
      removeEventListener(this.element, this.handlerInfos[i]);
    }
    this.handlerInfos = [];
  }
}
const Char = {
  /**
   * The separator between the namespace and the action name in the
   * jsaction attribute value.
   */
  NAMESPACE_ACTION_SEPARATOR: '.',
  /**
   * The separator between the event name and action in the jsaction
   * attribute value.
   */
  EVENT_ACTION_SEPARATOR: ':'
};

/** Added for readability when accessing stable property names. */
function getEventType(eventInfo) {
  return eventInfo.eventType;
}
/** Added for readability when accessing stable property names. */
function setEventType(eventInfo, eventType) {
  eventInfo.eventType = eventType;
}
/** Added for readability when accessing stable property names. */
function getEvent(eventInfo) {
  return eventInfo.event;
}
/** Added for readability when accessing stable property names. */
function setEvent(eventInfo, event) {
  eventInfo.event = event;
}
/** Added for readability when accessing stable property names. */
function getTargetElement(eventInfo) {
  return eventInfo.targetElement;
}
/** Added for readability when accessing stable property names. */
function setTargetElement(eventInfo, targetElement) {
  eventInfo.targetElement = targetElement;
}
/** Added for readability when accessing stable property names. */
function getContainer(eventInfo) {
  return eventInfo.eic;
}
/** Added for readability when accessing stable property names. */
function setContainer(eventInfo, container) {
  eventInfo.eic = container;
}
/** Added for readability when accessing stable property names. */
function getTimestamp(eventInfo) {
  return eventInfo.timeStamp;
}
/** Added for readability when accessing stable property names. */
function setTimestamp(eventInfo, timestamp) {
  eventInfo.timeStamp = timestamp;
}
/** Added for readability when accessing stable property names. */
function getAction(eventInfo) {
  return eventInfo.eia;
}
/** Added for readability when accessing stable property names. */
function setAction(eventInfo, actionName, actionElement) {
  eventInfo.eia = [actionName, actionElement];
}
/** Added for readability when accessing stable property names. */
function unsetAction(eventInfo) {
  eventInfo.eia = undefined;
}
/** Added for readability when accessing stable property names. */
function getActionName(actionInfo) {
  return actionInfo[0];
}
/** Added for readability when accessing stable property names. */
function getActionElement(actionInfo) {
  return actionInfo[1];
}
/** Added for readability when accessing stable property names. */
function getIsReplay(eventInfo) {
  return eventInfo.eirp;
}
/** Added for readability when accessing stable property names. */
function setIsReplay(eventInfo, replay) {
  eventInfo.eirp = replay;
}
/** Added for readability when accessing stable property names. */
function getA11yClickKey(eventInfo) {
  return eventInfo.eiack;
}
/** Added for readability when accessing stable property names. */
function setA11yClickKey(eventInfo, a11yClickKey) {
  eventInfo.eiack = a11yClickKey;
}
/** Added for readability when accessing stable property names. */
function getResolved(eventInfo) {
  return eventInfo.eir;
}
/** Added for readability when accessing stable property names. */
function setResolved(eventInfo, resolved) {
  eventInfo.eir = resolved;
}
/** Clones an `EventInfo` */
function cloneEventInfo(eventInfo) {
  return {
    eventType: eventInfo.eventType,
    event: eventInfo.event,
    targetElement: eventInfo.targetElement,
    eic: eventInfo.eic,
    eia: eventInfo.eia,
    timeStamp: eventInfo.timeStamp,
    eirp: eventInfo.eirp,
    eiack: eventInfo.eiack,
    eir: eventInfo.eir
  };
}
/**
 * Utility function for creating an `EventInfo`.
 *
 * This can be used from code-size sensitive compilation units, as taking
 * parameters vs. an `Object` literal reduces code size.
 */
function createEventInfoFromParameters(eventType, event, targetElement, container, timestamp, action, isReplay, a11yClickKey) {
  return {
    eventType,
    event,
    targetElement,
    eic: container,
    timeStamp: timestamp,
    eia: action,
    eirp: isReplay,
    eiack: a11yClickKey
  };
}
/**
 * Utility function for creating an `EventInfo`.
 *
 * This should be used in compilation units that are less sensitive to code
 * size.
 */
function createEventInfo({
  eventType,
  event,
  targetElement,
  container,
  timestamp,
  action,
  isReplay,
  a11yClickKey
}) {
  return {
    eventType,
    event,
    targetElement,
    eic: container,
    timeStamp: timestamp,
    eia: action ? [action.name, action.element] : undefined,
    eirp: isReplay,
    eiack: a11yClickKey
  };
}
/**
 * Utility class around an `EventInfo`.
 *
 * This should be used in compilation units that are less sensitive to code
 * size.
 */
class EventInfoWrapper {
  eventInfo;
  constructor(eventInfo) {
    this.eventInfo = eventInfo;
  }
  getEventType() {
    return getEventType(this.eventInfo);
  }
  setEventType(eventType) {
    setEventType(this.eventInfo, eventType);
  }
  getEvent() {
    return getEvent(this.eventInfo);
  }
  setEvent(event) {
    setEvent(this.eventInfo, event);
  }
  getTargetElement() {
    return getTargetElement(this.eventInfo);
  }
  setTargetElement(targetElement) {
    setTargetElement(this.eventInfo, targetElement);
  }
  getContainer() {
    return getContainer(this.eventInfo);
  }
  setContainer(container) {
    setContainer(this.eventInfo, container);
  }
  getTimestamp() {
    return getTimestamp(this.eventInfo);
  }
  setTimestamp(timestamp) {
    setTimestamp(this.eventInfo, timestamp);
  }
  getAction() {
    const action = getAction(this.eventInfo);
    if (!action) return undefined;
    return {
      name: action[0],
      element: action[1]
    };
  }
  setAction(action) {
    if (!action) {
      unsetAction(this.eventInfo);
      return;
    }
    setAction(this.eventInfo, action.name, action.element);
  }
  getIsReplay() {
    return getIsReplay(this.eventInfo);
  }
  setIsReplay(replay) {
    setIsReplay(this.eventInfo, replay);
  }
  getResolved() {
    return getResolved(this.eventInfo);
  }
  setResolved(resolved) {
    setResolved(this.eventInfo, resolved);
  }
  clone() {
    return new EventInfoWrapper(cloneEventInfo(this.eventInfo));
  }
}

/**
 * Since maps from event to action are immutable we can use a single map
 * to represent the empty map.
 */
const EMPTY_ACTION_MAP = {};
/**
 * This regular expression matches a semicolon.
 */
const REGEXP_SEMICOLON = /\s*;\s*/;
/** If no event type is defined, defaults to `click`. */
const DEFAULT_EVENT_TYPE = EventType.CLICK;
/** Resolves actions for Events. */
class ActionResolver {
  a11yClickSupport = false;
  clickModSupport = true;
  syntheticMouseEventSupport;
  updateEventInfoForA11yClick = /*#__PURE__*/(() => undefined)();
  preventDefaultForA11yClick = /*#__PURE__*/(() => undefined)();
  populateClickOnlyAction = /*#__PURE__*/(() => undefined)();
  constructor({
    syntheticMouseEventSupport = false,
    clickModSupport = true
  } = {}) {
    this.syntheticMouseEventSupport = syntheticMouseEventSupport;
    this.clickModSupport = clickModSupport;
  }
  resolveEventType(eventInfo) {
    // We distinguish modified and plain clicks in order to support the
    // default browser behavior of modified clicks on links; usually to
    // open the URL of the link in new tab or new window on ctrl/cmd
    // click. A DOM 'click' event is mapped to the jsaction 'click'
    // event iff there is no modifier present on the event. If there is
    // a modifier, it's mapped to 'clickmod' instead.
    //
    // It's allowed to omit the event in the jsaction attribute. In that
    // case, 'click' is assumed. Thus the following two are equivalent:
    //
    //   <a href="someurl" jsaction="gna.fu">
    //   <a href="someurl" jsaction="click:gna.fu">
    //
    // For unmodified clicks, EventContract invokes the jsaction
    // 'gna.fu'. For modified clicks, EventContract won't find a
    // suitable action and leave the event to be handled by the
    // browser.
    //
    // In order to also invoke a jsaction handler for a modifier click,
    // 'clickmod' needs to be used:
    //
    //   <a href="someurl" jsaction="clickmod:gna.fu">
    //
    // EventContract invokes the jsaction 'gna.fu' for modified
    // clicks. Unmodified clicks are left to the browser.
    //
    // In order to set up the event contract to handle both clickonly and
    // clickmod, only addEvent(EventType.CLICK) is necessary.
    //
    // In order to set up the event contract to handle click,
    // addEvent() is necessary for CLICK, KEYDOWN, and KEYPRESS event types.  If
    // a11y click support is enabled, addEvent() will set up the appropriate key
    // event handler automatically.
    if (this.clickModSupport && getEventType(eventInfo) === EventType.CLICK && isModifiedClickEvent(getEvent(eventInfo))) {
      setEventType(eventInfo, EventType.CLICKMOD);
    } else if (this.a11yClickSupport) {
      this.updateEventInfoForA11yClick(eventInfo);
    }
  }
  resolveAction(eventInfo) {
    if (getResolved(eventInfo)) {
      return;
    }
    this.populateAction(eventInfo, getTargetElement(eventInfo));
    setResolved(eventInfo, true);
  }
  resolveParentAction(eventInfo) {
    const action = getAction(eventInfo);
    const actionElement = action && getActionElement(action);
    unsetAction(eventInfo);
    const parentNode = actionElement && this.getParentNode(actionElement);
    if (!parentNode) {
      return;
    }
    this.populateAction(eventInfo, parentNode);
  }
  /**
   * Searches for a jsaction that the DOM event maps to and creates an
   * object containing event information used for dispatching by
   * jsaction.Dispatcher. This method populates the `action` and `actionElement`
   * fields of the EventInfo object passed in by finding the first
   * jsaction attribute above the target Node of the event, and below
   * the container Node, that specifies a jsaction for the event
   * type. If no such jsaction is found, then action is undefined.
   *
   * @param eventInfo `EventInfo` to set `action` and `actionElement` if an
   *    action is found on any `Element` in the path of the `Event`.
   */
  populateAction(eventInfo, currentTarget) {
    let actionElement = currentTarget;
    while (actionElement && actionElement !== getContainer(eventInfo)) {
      if (actionElement.nodeType === Node.ELEMENT_NODE) {
        this.populateActionOnElement(actionElement, eventInfo);
      }
      if (getAction(eventInfo)) {
        // An event is handled by at most one jsaction. Thus we stop at the
        // first matching jsaction specified in a jsaction attribute up the
        // ancestor chain of the event target node.
        break;
      }
      actionElement = this.getParentNode(actionElement);
    }
    const action = getAction(eventInfo);
    if (!action) {
      // No action found.
      return;
    }
    if (this.a11yClickSupport) {
      this.preventDefaultForA11yClick(eventInfo);
    }
    // We attempt to handle the mouseenter/mouseleave events here by
    // detecting whether the mouseover/mouseout events correspond to
    // entering/leaving an element.
    if (this.syntheticMouseEventSupport) {
      if (getEventType(eventInfo) === EventType.MOUSEENTER || getEventType(eventInfo) === EventType.MOUSELEAVE || getEventType(eventInfo) === EventType.POINTERENTER || getEventType(eventInfo) === EventType.POINTERLEAVE) {
        // We attempt to handle the mouseenter/mouseleave events here by
        // detecting whether the mouseover/mouseout events correspond to
        // entering/leaving an element.
        if (isMouseSpecialEvent(getEvent(eventInfo), getEventType(eventInfo), getActionElement(action))) {
          // If both mouseover/mouseout and mouseenter/mouseleave events are
          // enabled, two separate handlers for mouseover/mouseout are
          // registered. Both handlers will see the same event instance
          // so we create a copy to avoid interfering with the dispatching of
          // the mouseover/mouseout event.
          const copiedEvent = createMouseSpecialEvent(getEvent(eventInfo), getActionElement(action));
          setEvent(eventInfo, copiedEvent);
          // Since the mouseenter/mouseleave events do not bubble, the target
          // of the event is technically the `actionElement` (the node with the
          // `jsaction` attribute)
          setTargetElement(eventInfo, getActionElement(action));
        } else {
          unsetAction(eventInfo);
        }
      }
    }
  }
  /**
   * Walk to the parent node, unless the node has a different owner in
   * which case we walk to the owner. Attempt to walk to host of a
   * shadow root if needed.
   */
  getParentNode(element) {
    const owner = element[Property.OWNER];
    if (owner) {
      return owner;
    }
    const parentNode = element.parentNode;
    if (parentNode?.nodeName === '#document-fragment') {
      return parentNode?.host ?? null;
    }
    return parentNode;
  }
  /**
   * Accesses the jsaction map on a node and retrieves the name of the
   * action the given event is mapped to, if any. It parses the
   * attribute value and stores it in a property on the node for
   * subsequent retrieval without re-parsing and re-accessing the
   * attribute.
   *
   * @param actionElement The DOM node to retrieve the jsaction map from.
   * @param eventInfo `EventInfo` to set `action` and `actionElement` if an
   *    action is found on the `actionElement`.
   */
  populateActionOnElement(actionElement, eventInfo) {
    const actionMap = this.parseActions(actionElement);
    const actionName = actionMap[getEventType(eventInfo)];
    if (actionName !== undefined) {
      setAction(eventInfo, actionName, actionElement);
    }
    if (this.a11yClickSupport) {
      this.populateClickOnlyAction(actionElement, eventInfo, actionMap);
    }
  }
  /**
   * Parses and caches an element's jsaction element into a map.
   *
   * This is primarily for internal use.
   *
   * @param actionElement The DOM node to retrieve the jsaction map from.
   * @return Map from event to qualified name of the jsaction bound to it.
   */
  parseActions(actionElement) {
    let actionMap = get(actionElement);
    if (!actionMap) {
      const jsactionAttribute = actionElement.getAttribute(Attribute.JSACTION);
      if (!jsactionAttribute) {
        actionMap = EMPTY_ACTION_MAP;
        set(actionElement, actionMap);
      } else {
        actionMap = getParsed(jsactionAttribute);
        if (!actionMap) {
          actionMap = {};
          const values = jsactionAttribute.split(REGEXP_SEMICOLON);
          for (let idx = 0; idx < values.length; idx++) {
            const value = values[idx];
            if (!value) {
              continue;
            }
            const colon = value.indexOf(Char.EVENT_ACTION_SEPARATOR);
            const hasColon = colon !== -1;
            const type = hasColon ? value.substr(0, colon).trim() : DEFAULT_EVENT_TYPE;
            const action = hasColon ? value.substr(colon + 1).trim() : value;
            actionMap[type] = action;
          }
          setParsed(jsactionAttribute, actionMap);
        }
        set(actionElement, actionMap);
      }
    }
    return actionMap;
  }
  addA11yClickSupport(updateEventInfoForA11yClick, preventDefaultForA11yClick, populateClickOnlyAction) {
    this.a11yClickSupport = true;
    this.updateEventInfoForA11yClick = updateEventInfoForA11yClick;
    this.preventDefaultForA11yClick = preventDefaultForA11yClick;
    this.populateClickOnlyAction = populateClickOnlyAction;
  }
}

/**
 * @fileoverview An enum to control who can call certain jsaction APIs.
 */
var Restriction = /*#__PURE__*/function (Restriction) {
  Restriction[Restriction["I_AM_THE_JSACTION_FRAMEWORK"] = 0] = "I_AM_THE_JSACTION_FRAMEWORK";
  return Restriction;
}(Restriction || {});
/**
 * Receives a DOM event, determines the jsaction associated with the source
 * element of the DOM event, and invokes the handler associated with the
 * jsaction.
 */
class Dispatcher {
  dispatchDelegate;
  // The ActionResolver to use to resolve actions.
  actionResolver;
  /** The replayer function to be called when there are queued events. */
  eventReplayer;
  /** Whether the event replay is scheduled. */
  eventReplayScheduled = false;
  /** The queue of events. */
  replayEventInfoWrappers = [];
  /**
   * Options are:
   *   - `eventReplayer`: When the event contract dispatches replay events
   *      to the Dispatcher, the Dispatcher collects them and in the next tick
   *      dispatches them to the `eventReplayer`. Defaults to dispatching to `dispatchDelegate`.
   * @param dispatchDelegate A function that should handle dispatching an `EventInfoWrapper` to handlers.
   */
  constructor(dispatchDelegate, {
    actionResolver,
    eventReplayer
  } = {}) {
    this.dispatchDelegate = dispatchDelegate;
    this.actionResolver = actionResolver;
    this.eventReplayer = eventReplayer;
  }
  /**
   * Receives an event or the event queue from the EventContract. The event
   * queue is copied and it attempts to replay.
   * If event info is passed in it looks for an action handler that can handle
   * the given event.  If there is no handler registered queues the event and
   * checks if a loader is registered for the given namespace. If so, calls it.
   *
   * Alternatively, if in global dispatch mode, calls all registered global
   * handlers for the appropriate event type.
   *
   * The three functionalities of this call are deliberately not split into
   * three methods (and then declared as an abstract interface), because the
   * interface is used by EventContract, which lives in a different jsbinary.
   * Therefore the interface between the three is defined entirely in terms that
   * are invariant under jscompiler processing (Function and Array, as opposed
   * to a custom type with method names).
   *
   * @param eventInfo The info for the event that triggered this call or the
   *     queue of events from EventContract.
   */
  dispatch(eventInfo) {
    const eventInfoWrapper = new EventInfoWrapper(eventInfo);
    this.actionResolver?.resolveEventType(eventInfo);
    this.actionResolver?.resolveAction(eventInfo);
    const action = eventInfoWrapper.getAction();
    if (action && shouldPreventDefaultBeforeDispatching(action.element, eventInfoWrapper)) {
      preventDefault(eventInfoWrapper.getEvent());
    }
    if (this.eventReplayer && eventInfoWrapper.getIsReplay()) {
      this.scheduleEventInfoWrapperReplay(eventInfoWrapper);
      return;
    }
    this.dispatchDelegate(eventInfoWrapper);
  }
  /**
   * Schedules an `EventInfoWrapper` for replay. The replaying will happen in its own
   * stack once the current flow cedes control. This is done to mimic
   * browser event handling.
   */
  scheduleEventInfoWrapperReplay(eventInfoWrapper) {
    this.replayEventInfoWrappers.push(eventInfoWrapper);
    if (this.eventReplayScheduled) {
      return;
    }
    this.eventReplayScheduled = true;
    Promise.resolve().then(() => {
      this.eventReplayScheduled = false;
      this.eventReplayer(this.replayEventInfoWrappers);
    });
  }
}
/**
 * Creates an `EventReplayer` that calls the `replay` function for every `eventInfoWrapper` in
 * the queue.
 */
function createEventReplayer(replay) {
  return eventInfoWrappers => {
    for (const eventInfoWrapper of eventInfoWrappers) {
      replay(eventInfoWrapper);
    }
  };
}
/**
 * Returns true if the default action of this event should be prevented before
 * this event is dispatched.
 */
function shouldPreventDefaultBeforeDispatching(actionElement, eventInfoWrapper) {
  // Prevent browser from following <a> node links if a jsaction is present
  // and we are dispatching the action now. Note that the targetElement may be
  // a child of an anchor that has a jsaction attached. For that reason, we
  // need to check the actionElement rather than the targetElement.
  return actionElement.tagName === 'A' && (eventInfoWrapper.getEventType() === EventType.CLICK || eventInfoWrapper.getEventType() === EventType.CLICKMOD);
}
/**
 * Registers deferred functionality for an EventContract and a Jsaction
 * Dispatcher.
 */
function registerDispatcher$2(eventContract, dispatcher) {
  eventContract.ecrd(eventInfo => {
    dispatcher.dispatch(eventInfo);
  }, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
}

/** An internal symbol used to indicate whether propagation should be stopped or not. */
const PROPAGATION_STOPPED_SYMBOL = /*#__PURE__*/Symbol.for('propagationStopped');
/** Extra event phases beyond what the browser provides. */
const EventPhase = {
  REPLAY: 101
};
const PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser dispatch, `preventDefault` would have no ' + 'effect. You can check whether an event is being replayed by accessing the event phase: ' + '`event.eventPhase === EventPhase.REPLAY`.';
const PREVENT_DEFAULT_ERROR_MESSAGE = `\`preventDefault\` called during event replay.`;
const COMPOSED_PATH_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser ' + 'dispatch, `composedPath()` will be empty. Iterate parent nodes from `event.target` or ' + '`event.currentTarget` if you need to check elements in the event path.';
const COMPOSED_PATH_ERROR_MESSAGE = `\`composedPath\` called during event replay.`;
/**
 * A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`,
 * `currentTarget`, etc.
 */
class EventDispatcher {
  dispatchDelegate;
  clickModSupport;
  actionResolver;
  dispatcher;
  constructor(dispatchDelegate, clickModSupport = true) {
    this.dispatchDelegate = dispatchDelegate;
    this.clickModSupport = clickModSupport;
    this.actionResolver = new ActionResolver({
      clickModSupport
    });
    this.dispatcher = new Dispatcher(eventInfoWrapper => {
      this.dispatchToDelegate(eventInfoWrapper);
    }, {
      actionResolver: this.actionResolver
    });
  }
  /**
   * The entrypoint for the `EventContract` dispatch.
   */
  dispatch(eventInfo) {
    this.dispatcher.dispatch(eventInfo);
  }
  /** Internal method that does basic disaptching. */
  dispatchToDelegate(eventInfoWrapper) {
    if (eventInfoWrapper.getIsReplay()) {
      prepareEventForReplay(eventInfoWrapper);
    }
    prepareEventForBubbling(eventInfoWrapper);
    while (eventInfoWrapper.getAction()) {
      prepareEventForDispatch(eventInfoWrapper);
      // If this is a capture event, ONLY dispatch if the action element is the target.
      if (isCaptureEventType(eventInfoWrapper.getEventType()) && eventInfoWrapper.getAction().element !== eventInfoWrapper.getTargetElement()) {
        return;
      }
      this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction().name);
      if (propagationStopped(eventInfoWrapper)) {
        return;
      }
      this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo);
    }
  }
}
function prepareEventForBubbling(eventInfoWrapper) {
  const event = eventInfoWrapper.getEvent();
  const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event);
  const stopPropagation = () => {
    event[PROPAGATION_STOPPED_SYMBOL] = true;
    originalStopPropagation();
  };
  patchEventInstance(event, 'stopPropagation', stopPropagation);
  patchEventInstance(event, 'stopImmediatePropagation', stopPropagation);
}
function propagationStopped(eventInfoWrapper) {
  const event = eventInfoWrapper.getEvent();
  return !!event[PROPAGATION_STOPPED_SYMBOL];
}
function prepareEventForReplay(eventInfoWrapper) {
  const event = eventInfoWrapper.getEvent();
  const target = eventInfoWrapper.getTargetElement();
  const originalPreventDefault = event.preventDefault.bind(event);
  patchEventInstance(event, 'target', target);
  patchEventInstance(event, 'eventPhase', EventPhase.REPLAY);
  patchEventInstance(event, 'preventDefault', () => {
    originalPreventDefault();
    throw new Error(PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''));
  });
  patchEventInstance(event, 'composedPath', () => {
    throw new Error(COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''));
  });
}
function prepareEventForDispatch(eventInfoWrapper) {
  const event = eventInfoWrapper.getEvent();
  const currentTarget = eventInfoWrapper.getAction()?.element;
  if (currentTarget) {
    patchEventInstance(event, 'currentTarget', currentTarget, {
      // `currentTarget` is going to get reassigned every dispatch.
      configurable: true
    });
  }
}
/**
 * Patch `Event` instance during non-standard `Event` dispatch. This patches just the `Event`
 * instance that the browser created, it does not patch global properties or methods.
 *
 * This is necessary because dispatching an `Event` outside of browser dispatch results in
 * incorrect properties and methods that need to be polyfilled or do not work.
 *
 * JSAction dispatch adds two extra "phases" to event dispatch:
 * 1. Event delegation - the event is being dispatched by a delegating event handler on a container
 *    (typically `window.document.documentElement`), to a delegated event handler on some child
 *    element. Certain `Event` properties will be unintuitive, such as `currentTarget`, which would
 *    be the container rather than the child element. Bubbling would also not work. In order to
 *    emulate the browser, these properties and methods on the `Event` are patched.
 * 2. Event replay - the event is being dispatched by the framework once the handlers have been
 *    loaded (during hydration, or late-loaded). Certain `Event` properties can be unset by the
 *    browser because the `Event` is no longer actively being dispatched, such as `target`. Other
 *    methods have no effect because the `Event` has already been dispatched, such as
 *    `preventDefault`. Bubbling would also not work. These properties and methods are patched,
 *    either to fill in information that the browser may have removed, or to throw errors in methods
 *    that no longer behave as expected.
 */
function patchEventInstance(event, property, value, {
  configurable = false
} = {}) {
  Object.defineProperty(event, property, {
    value,
    configurable
  });
}
/**
 * Registers deferred functionality for an EventContract and a Jsaction
 * Dispatcher.
 */
function registerDispatcher$1(eventContract, dispatcher) {
  eventContract.ecrd(eventInfo => {
    dispatcher.dispatch(eventInfo);
  }, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
}

/**
 * EarlyEventContract intercepts events in the bubbling phase at the
 * boundary of the document body. This mapping will be passed to the
 * late-loaded EventContract.
 */
class EarlyEventContract {
  dataContainer;
  constructor(dataContainer = window, container = window.document.documentElement) {
    this.dataContainer = dataContainer;
    dataContainer._ejsa = createEarlyJsactionData(container);
  }
  /**
   * Installs a list of event types for container .
   */
  addEvents(types, capture) {
    addEvents(this.dataContainer._ejsa, types, capture);
  }
}
/** Creates an `EarlyJsactionData` object. */
function createEarlyJsactionData(container) {
  const q = [];
  const d = eventInfo => {
    q.push(eventInfo);
  };
  const h = event => {
    d(createEventInfoFromParameters(event.type, event, event.target, container, Date.now()));
  };
  return {
    c: container,
    q,
    et: [],
    etc: [],
    d,
    h
  };
}
/** Add all the events to the container stored in the `EarlyJsactionData`. */
function addEvents(earlyJsactionData, types, capture) {
  for (let i = 0; i < types.length; i++) {
    const eventType = types[i];
    const eventTypes = capture ? earlyJsactionData.etc : earlyJsactionData.et;
    eventTypes.push(eventType);
    earlyJsactionData.c.addEventListener(eventType, earlyJsactionData.h, capture);
  }
}
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
function getQueuedEventInfos(earlyJsactionData) {
  return earlyJsactionData?.q ?? [];
}
/** Register a different dispatcher function on the `EarlyJsactionData`. */
function registerDispatcher(earlyJsactionData, dispatcher) {
  if (!earlyJsactionData) {
    return;
  }
  earlyJsactionData.d = dispatcher;
}
/** Removes all event listener handlers. */
function removeAllEventListeners(earlyJsactionData) {
  if (!earlyJsactionData) {
    return;
  }
  removeEventListeners(earlyJsactionData.c, earlyJsactionData.et, earlyJsactionData.h);
  removeEventListeners(earlyJsactionData.c, earlyJsactionData.etc, earlyJsactionData.h, true);
}
function removeEventListeners(container, eventTypes, earlyEventHandler, capture) {
  for (let i = 0; i < eventTypes.length; i++) {
    container.removeEventListener(eventTypes[i], earlyEventHandler, /* useCapture */capture);
  }
}

/**
 * @define Support for the non-bubbling mouseenter and mouseleave events.  This
 * flag can be overridden in a build rule.
 */
const MOUSE_SPECIAL_SUPPORT = false;

/**
 * @fileoverview Implements the local event handling contract. This
 * allows DOM objects in a container that enters into this contract to
 * define event handlers which are executed in a local context.
 *
 * One EventContract instance can manage the contract for multiple
 * containers, which are added using the addContainer() method.
 *
 * Events can be registered using the addEvent() method.
 *
 * A Dispatcher is added using the registerDispatcher() method. Until there is
 * a dispatcher, events are queued. The idea is that the EventContract
 * class is inlined in the HTML of the top level page and instantiated
 * right after the start of <body>. The Dispatcher class is contained
 * in the external deferred js, and instantiated and registered with
 * EventContract when the external javascript in the page loads. The
 * external javascript will also register the jsaction handlers, which
 * then pick up the queued events at the time of registration.
 *
 * Since this class is meant to be inlined in the main page HTML, the
 * size of the binary compiled from this file MUST be kept as small as
 * possible and thus its dependencies to a minimum.
 */
/**
 * EventContract intercepts events in the bubbling phase at the
 * boundary of a container element, and maps them to generic actions
 * which are specified using the custom jsaction attribute in
 * HTML. Behavior of the application is then specified in terms of
 * handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.
 *
 * This has several benefits: (1) No DOM event handlers need to be
 * registered on the specific elements in the UI. (2) The set of
 * events that the application has to handle can be specified in terms
 * of the semantics of the application, rather than in terms of DOM
 * events. (3) Invocation of handlers can be delayed and handlers can
 * be delay loaded in a generic way.
 */
let EventContract = /*#__PURE__*/(() => {
  class EventContract {
    static MOUSE_SPECIAL_SUPPORT = (() => MOUSE_SPECIAL_SUPPORT)();
    containerManager;
    /**
     * The DOM events which this contract covers. Used to prevent double
     * registration of event types. The value of the map is the
     * internally created DOM event handler function that handles the
     * DOM events. See addEvent().
     *
     */
    eventHandlers = {};
    browserEventTypeToExtraEventTypes = {};
    /**
     * The dispatcher function. Events are passed to this function for
     * handling once it was set using the registerDispatcher() method. This is
     * done because the function is passed from another jsbinary, so passing the
     * instance and invoking the method here would require to leave the method
     * unobfuscated.
     */
    dispatcher = null;
    /**
     * The list of suspended `EventInfo` that will be dispatched
     * as soon as the `Dispatcher` is registered.
     */
    queuedEventInfos = [];
    constructor(containerManager) {
      this.containerManager = containerManager;
    }
    handleEvent(eventType, event, container) {
      const eventInfo = createEventInfoFromParameters(/* eventType= */eventType, /* event= */event, /* targetElement= */event.target, /* container= */container, /* timestamp= */Date.now());
      this.handleEventInfo(eventInfo);
    }
    /**
     * Handle an `EventInfo`.
     */
    handleEventInfo(eventInfo) {
      if (!this.dispatcher) {
        // All events are queued when the dispatcher isn't yet loaded.
        setIsReplay(eventInfo, true);
        this.queuedEventInfos?.push(eventInfo);
        return;
      }
      this.dispatcher(eventInfo);
    }
    /**
     * Enables jsaction handlers to be called for the event type given by
     * name.
     *
     * If the event is already registered, this does nothing.
     *
     * @param prefixedEventType If supplied, this event is used in
     *     the actual browser event registration instead of the name that is
     *     exposed to jsaction. Use this if you e.g. want users to be able
     *     to subscribe to jsaction="transitionEnd:foo" while the underlying
     *     event is webkitTransitionEnd in one browser and mozTransitionEnd
     *     in another.
     *
     * @param passive A boolean value that, if `true`, indicates that the event
     *     handler will never call `preventDefault()`.
     */
    addEvent(eventType, prefixedEventType, passive) {
      if (eventType in this.eventHandlers || !this.containerManager) {
        return;
      }
      if (!EventContract.MOUSE_SPECIAL_SUPPORT && MOUSE_SPECIAL_EVENT_TYPES.indexOf(eventType) >= 0) {
        return;
      }
      const eventHandler = (eventType, event, container) => {
        this.handleEvent(eventType, event, container);
      };
      // Store the callback to allow us to replay events.
      this.eventHandlers[eventType] = eventHandler;
      const browserEventType = getBrowserEventType(prefixedEventType || eventType);
      if (browserEventType !== eventType) {
        const eventTypes = this.browserEventTypeToExtraEventTypes[browserEventType] || [];
        eventTypes.push(eventType);
        this.browserEventTypeToExtraEventTypes[browserEventType] = eventTypes;
      }
      this.containerManager.addEventListener(browserEventType, element => {
        return event => {
          eventHandler(eventType, event, element);
        };
      }, passive);
    }
    /**
     * Gets the queued early events and replay them using the appropriate handler
     * in the provided event contract. Once all the events are replayed, it cleans
     * up the early contract.
     */
    replayEarlyEvents(earlyJsactionData = window._ejsa) {
      // Check if the early contract is present and prevent calling this function
      // more than once.
      if (!earlyJsactionData) {
        return;
      }
      // Replay the early contract events.
      this.replayEarlyEventInfos(earlyJsactionData.q);
      // Clean up the early contract.
      removeAllEventListeners(earlyJsactionData);
      delete window._ejsa;
    }
    /**
     * Replays all the early `EventInfo` objects, dispatching them through the normal
     * `EventContract` flow.
     */
    replayEarlyEventInfos(earlyEventInfos) {
      for (let i = 0; i < earlyEventInfos.length; i++) {
        const earlyEventInfo = earlyEventInfos[i];
        const eventTypes = this.getEventTypesForBrowserEventType(earlyEventInfo.eventType);
        for (let j = 0; j < eventTypes.length; j++) {
          const eventInfo = cloneEventInfo(earlyEventInfo);
          // EventInfo eventType maps to JSAction's internal event type,
          // rather than the browser event type.
          setEventType(eventInfo, eventTypes[j]);
          this.handleEventInfo(eventInfo);
        }
      }
    }
    /**
     * Returns all JSAction event types that have been registered for a given
     * browser event type.
     */
    getEventTypesForBrowserEventType(browserEventType) {
      const eventTypes = [];
      if (this.eventHandlers[browserEventType]) {
        eventTypes.push(browserEventType);
      }
      if (this.browserEventTypeToExtraEventTypes[browserEventType]) {
        eventTypes.push(...this.browserEventTypeToExtraEventTypes[browserEventType]);
      }
      return eventTypes;
    }
    /**
     * Returns the event handler function for a given event type.
     */
    handler(eventType) {
      return this.eventHandlers[eventType];
    }
    /**
     * Cleans up the event contract. This resets all of the `EventContract`'s
     * internal state. Users are responsible for not using this `EventContract`
     * after it has been cleaned up.
     */
    cleanUp() {
      this.containerManager?.cleanUp();
      this.containerManager = null;
      this.eventHandlers = {};
      this.browserEventTypeToExtraEventTypes = {};
      this.dispatcher = null;
      this.queuedEventInfos = [];
    }
    /**
     * Register a dispatcher function. Event info of each event mapped to
     * a jsaction is passed for handling to this callback. The queued
     * events are passed as well to the dispatcher for later replaying
     * once the dispatcher is registered. Clears the event queue to null.
     *
     * @param dispatcher The dispatcher function.
     * @param restriction
     */
    registerDispatcher(dispatcher, restriction) {
      this.ecrd(dispatcher, restriction);
    }
    /**
     * Unrenamed alias for registerDispatcher. Necessary for any codebases that
     * split the `EventContract` and `Dispatcher` code into different compilation
     * units.
     */
    ecrd(dispatcher, restriction) {
      this.dispatcher = dispatcher;
      if (this.queuedEventInfos?.length) {
        for (let i = 0; i < this.queuedEventInfos.length; i++) {
          this.handleEventInfo(this.queuedEventInfos[i]);
        }
        this.queuedEventInfos = null;
      }
    }
  }
  return EventContract;
})();
/**
 * Creates an `EarlyJsactionData`, adds events to it, and populates it on a nested object on
 * the window.
 */
function bootstrapAppScopedEarlyEventContract(container, appId, bubbleEventTypes, captureEventTypes, dataContainer = window) {
  const earlyJsactionData = createEarlyJsactionData(container);
  if (!dataContainer._ejsas) {
    dataContainer._ejsas = {};
  }
  dataContainer._ejsas[appId] = earlyJsactionData;
  addEvents(earlyJsactionData, bubbleEventTypes);
  addEvents(earlyJsactionData, captureEventTypes, /* capture= */true);
}
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
function getAppScopedQueuedEventInfos(appId, dataContainer = window) {
  return getQueuedEventInfos(dataContainer._ejsas?.[appId]);
}
/**
 * Registers a dispatcher function on the `EarlyJsactionData` present on the nested object on the
 * window.
 */
function registerAppScopedDispatcher(restriction, appId, dispatcher, dataContainer = window) {
  registerDispatcher(dataContainer._ejsas?.[appId], dispatcher);
}
/** Removes all event listener handlers. */
function removeAllAppScopedEventListeners(appId, dataContainer = window) {
  removeAllEventListeners(dataContainer._ejsas?.[appId]);
}
/** Clear the early event contract. */
function clearAppScopedEarlyEventContract(appId, dataContainer = window) {
  if (!dataContainer._ejsas) {
    return;
  }
  dataContainer._ejsas[appId] = undefined;
}


/***/ }),

/***/ 2665:
/*!**************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+core@19.0.0_rxjs@7.8.1_zone.js@0.15.0/node_modules/@angular/core/fesm2022/primitives/signals.mjs ***!
  \**************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   REACTIVE_NODE: () => (/* binding */ REACTIVE_NODE),
/* harmony export */   SIGNAL: () => (/* binding */ SIGNAL),
/* harmony export */   SIGNAL_NODE: () => (/* binding */ SIGNAL_NODE),
/* harmony export */   consumerAfterComputation: () => (/* binding */ consumerAfterComputation),
/* harmony export */   consumerBeforeComputation: () => (/* binding */ consumerBeforeComputation),
/* harmony export */   consumerDestroy: () => (/* binding */ consumerDestroy),
/* harmony export */   consumerMarkDirty: () => (/* binding */ consumerMarkDirty),
/* harmony export */   consumerPollProducersForChange: () => (/* binding */ consumerPollProducersForChange),
/* harmony export */   createComputed: () => (/* binding */ createComputed),
/* harmony export */   createSignal: () => (/* binding */ createSignal),
/* harmony export */   createWatch: () => (/* binding */ createWatch),
/* harmony export */   defaultEquals: () => (/* binding */ defaultEquals),
/* harmony export */   getActiveConsumer: () => (/* binding */ getActiveConsumer),
/* harmony export */   isInNotificationPhase: () => (/* binding */ isInNotificationPhase),
/* harmony export */   isReactive: () => (/* binding */ isReactive),
/* harmony export */   producerAccessed: () => (/* binding */ producerAccessed),
/* harmony export */   producerIncrementEpoch: () => (/* binding */ producerIncrementEpoch),
/* harmony export */   producerMarkClean: () => (/* binding */ producerMarkClean),
/* harmony export */   producerNotifyConsumers: () => (/* binding */ producerNotifyConsumers),
/* harmony export */   producerUpdateValueVersion: () => (/* binding */ producerUpdateValueVersion),
/* harmony export */   producerUpdatesAllowed: () => (/* binding */ producerUpdatesAllowed),
/* harmony export */   runPostSignalSetFn: () => (/* binding */ runPostSignalSetFn),
/* harmony export */   setActiveConsumer: () => (/* binding */ setActiveConsumer),
/* harmony export */   setAlternateWeakRefImpl: () => (/* binding */ setAlternateWeakRefImpl),
/* harmony export */   setPostSignalSetFn: () => (/* binding */ setPostSignalSetFn),
/* harmony export */   setThrowInvalidWriteToSignalError: () => (/* binding */ setThrowInvalidWriteToSignalError),
/* harmony export */   signalSetFn: () => (/* binding */ signalSetFn),
/* harmony export */   signalUpdateFn: () => (/* binding */ signalUpdateFn)
/* harmony export */ });
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */

/**
 * The default equality function used for `signal` and `computed`, which uses referential equality.
 */
function defaultEquals(a, b) {
  return Object.is(a, b);
}

/**
 * The currently active consumer `ReactiveNode`, if running code in a reactive context.
 *
 * Change this via `setActiveConsumer`.
 */
let activeConsumer = null;
let inNotificationPhase = false;
/**
 * Global epoch counter. Incremented whenever a source signal is set.
 */
let epoch = 1;
/**
 * Symbol used to tell `Signal`s apart from other functions.
 *
 * This can be used to auto-unwrap signals in various cases, or to auto-wrap non-signal values.
 */
const SIGNAL = /* @__PURE__ */Symbol('SIGNAL');
function setActiveConsumer(consumer) {
  const prev = activeConsumer;
  activeConsumer = consumer;
  return prev;
}
function getActiveConsumer() {
  return activeConsumer;
}
function isInNotificationPhase() {
  return inNotificationPhase;
}
function isReactive(value) {
  return value[SIGNAL] !== undefined;
}
const REACTIVE_NODE = {
  version: 0,
  lastCleanEpoch: 0,
  dirty: false,
  producerNode: undefined,
  producerLastReadVersion: undefined,
  producerIndexOfThis: undefined,
  nextProducerIndex: 0,
  liveConsumerNode: undefined,
  liveConsumerIndexOfThis: undefined,
  consumerAllowSignalWrites: false,
  consumerIsAlwaysLive: false,
  producerMustRecompute: () => false,
  producerRecomputeValue: () => {},
  consumerMarkedDirty: () => {},
  consumerOnSignalRead: () => {}
};
/**
 * Called by implementations when a producer's signal is read.
 */
function producerAccessed(node) {
  if (inNotificationPhase) {
    throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? `Assertion error: signal read during notification phase` : '');
  }
  if (activeConsumer === null) {
    // Accessed outside of a reactive context, so nothing to record.
    return;
  }
  activeConsumer.consumerOnSignalRead(node);
  // This producer is the `idx`th dependency of `activeConsumer`.
  const idx = activeConsumer.nextProducerIndex++;
  assertConsumerNode(activeConsumer);
  if (idx < activeConsumer.producerNode.length && activeConsumer.producerNode[idx] !== node) {
    // There's been a change in producers since the last execution of `activeConsumer`.
    // `activeConsumer.producerNode[idx]` holds a stale dependency which will be be removed and
    // replaced with `this`.
    //
    // If `activeConsumer` isn't live, then this is a no-op, since we can replace the producer in
    // `activeConsumer.producerNode` directly. However, if `activeConsumer` is live, then we need
    // to remove it from the stale producer's `liveConsumer`s.
    if (consumerIsLive(activeConsumer)) {
      const staleProducer = activeConsumer.producerNode[idx];
      producerRemoveLiveConsumerAtIndex(staleProducer, activeConsumer.producerIndexOfThis[idx]);
      // At this point, the only record of `staleProducer` is the reference at
      // `activeConsumer.producerNode[idx]` which will be overwritten below.
    }
  }
  if (activeConsumer.producerNode[idx] !== node) {
    // We're a new dependency of the consumer (at `idx`).
    activeConsumer.producerNode[idx] = node;
    // If the active consumer is live, then add it as a live consumer. If not, then use 0 as a
    // placeholder value.
    activeConsumer.producerIndexOfThis[idx] = consumerIsLive(activeConsumer) ? producerAddLiveConsumer(node, activeConsumer, idx) : 0;
  }
  activeConsumer.producerLastReadVersion[idx] = node.version;
}
/**
 * Increment the global epoch counter.
 *
 * Called by source producers (that is, not computeds) whenever their values change.
 */
function producerIncrementEpoch() {
  epoch++;
}
/**
 * Ensure this producer's `version` is up-to-date.
 */
function producerUpdateValueVersion(node) {
  if (consumerIsLive(node) && !node.dirty) {
    // A live consumer will be marked dirty by producers, so a clean state means that its version
    // is guaranteed to be up-to-date.
    return;
  }
  if (!node.dirty && node.lastCleanEpoch === epoch) {
    // Even non-live consumers can skip polling if they previously found themselves to be clean at
    // the current epoch, since their dependencies could not possibly have changed (such a change
    // would've increased the epoch).
    return;
  }
  if (!node.producerMustRecompute(node) && !consumerPollProducersForChange(node)) {
    // None of our producers report a change since the last time they were read, so no
    // recomputation of our value is necessary, and we can consider ourselves clean.
    producerMarkClean(node);
    return;
  }
  node.producerRecomputeValue(node);
  // After recomputing the value, we're no longer dirty.
  producerMarkClean(node);
}
/**
 * Propagate a dirty notification to live consumers of this producer.
 */
function producerNotifyConsumers(node) {
  if (node.liveConsumerNode === undefined) {
    return;
  }
  // Prevent signal reads when we're updating the graph
  const prev = inNotificationPhase;
  inNotificationPhase = true;
  try {
    for (const consumer of node.liveConsumerNode) {
      if (!consumer.dirty) {
        consumerMarkDirty(consumer);
      }
    }
  } finally {
    inNotificationPhase = prev;
  }
}
/**
 * Whether this `ReactiveNode` in its producer capacity is currently allowed to initiate updates,
 * based on the current consumer context.
 */
function producerUpdatesAllowed() {
  return activeConsumer?.consumerAllowSignalWrites !== false;
}
function consumerMarkDirty(node) {
  node.dirty = true;
  producerNotifyConsumers(node);
  node.consumerMarkedDirty?.(node);
}
function producerMarkClean(node) {
  node.dirty = false;
  node.lastCleanEpoch = epoch;
}
/**
 * Prepare this consumer to run a computation in its reactive context.
 *
 * Must be called by subclasses which represent reactive computations, before those computations
 * begin.
 */
function consumerBeforeComputation(node) {
  node && (node.nextProducerIndex = 0);
  return setActiveConsumer(node);
}
/**
 * Finalize this consumer's state after a reactive computation has run.
 *
 * Must be called by subclasses which represent reactive computations, after those computations
 * have finished.
 */
function consumerAfterComputation(node, prevConsumer) {
  setActiveConsumer(prevConsumer);
  if (!node || node.producerNode === undefined || node.producerIndexOfThis === undefined || node.producerLastReadVersion === undefined) {
    return;
  }
  if (consumerIsLive(node)) {
    // For live consumers, we need to remove the producer -> consumer edge for any stale producers
    // which weren't dependencies after the recomputation.
    for (let i = node.nextProducerIndex; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Truncate the producer tracking arrays.
  // Perf note: this is essentially truncating the length to `node.nextProducerIndex`, but
  // benchmarking has shown that individual pop operations are faster.
  while (node.producerNode.length > node.nextProducerIndex) {
    node.producerNode.pop();
    node.producerLastReadVersion.pop();
    node.producerIndexOfThis.pop();
  }
}
/**
 * Determine whether this consumer has any dependencies which have changed since the last time
 * they were read.
 */
function consumerPollProducersForChange(node) {
  assertConsumerNode(node);
  // Poll producers for change.
  for (let i = 0; i < node.producerNode.length; i++) {
    const producer = node.producerNode[i];
    const seenVersion = node.producerLastReadVersion[i];
    // First check the versions. A mismatch means that the producer's value is known to have
    // changed since the last time we read it.
    if (seenVersion !== producer.version) {
      return true;
    }
    // The producer's version is the same as the last time we read it, but it might itself be
    // stale. Force the producer to recompute its version (calculating a new value if necessary).
    producerUpdateValueVersion(producer);
    // Now when we do this check, `producer.version` is guaranteed to be up to date, so if the
    // versions still match then it has not changed since the last time we read it.
    if (seenVersion !== producer.version) {
      return true;
    }
  }
  return false;
}
/**
 * Disconnect this consumer from the graph.
 */
function consumerDestroy(node) {
  assertConsumerNode(node);
  if (consumerIsLive(node)) {
    // Drop all connections from the graph to this node.
    for (let i = 0; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Truncate all the arrays to drop all connection from this node to the graph.
  node.producerNode.length = node.producerLastReadVersion.length = node.producerIndexOfThis.length = 0;
  if (node.liveConsumerNode) {
    node.liveConsumerNode.length = node.liveConsumerIndexOfThis.length = 0;
  }
}
/**
 * Add `consumer` as a live consumer of this node.
 *
 * Note that this operation is potentially transitive. If this node becomes live, then it becomes
 * a live consumer of all of its current producers.
 */
function producerAddLiveConsumer(node, consumer, indexOfThis) {
  assertProducerNode(node);
  if (node.liveConsumerNode.length === 0 && isConsumerNode(node)) {
    // When going from 0 to 1 live consumers, we become a live consumer to our producers.
    for (let i = 0; i < node.producerNode.length; i++) {
      node.producerIndexOfThis[i] = producerAddLiveConsumer(node.producerNode[i], node, i);
    }
  }
  node.liveConsumerIndexOfThis.push(indexOfThis);
  return node.liveConsumerNode.push(consumer) - 1;
}
/**
 * Remove the live consumer at `idx`.
 */
function producerRemoveLiveConsumerAtIndex(node, idx) {
  assertProducerNode(node);
  if (typeof ngDevMode !== 'undefined' && ngDevMode && idx >= node.liveConsumerNode.length) {
    throw new Error(`Assertion error: active consumer index ${idx} is out of bounds of ${node.liveConsumerNode.length} consumers)`);
  }
  if (node.liveConsumerNode.length === 1 && isConsumerNode(node)) {
    // When removing the last live consumer, we will no longer be live. We need to remove
    // ourselves from our producers' tracking (which may cause consumer-producers to lose
    // liveness as well).
    for (let i = 0; i < node.producerNode.length; i++) {
      producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
    }
  }
  // Move the last value of `liveConsumers` into `idx`. Note that if there's only a single
  // live consumer, this is a no-op.
  const lastIdx = node.liveConsumerNode.length - 1;
  node.liveConsumerNode[idx] = node.liveConsumerNode[lastIdx];
  node.liveConsumerIndexOfThis[idx] = node.liveConsumerIndexOfThis[lastIdx];
  // Truncate the array.
  node.liveConsumerNode.length--;
  node.liveConsumerIndexOfThis.length--;
  // If the index is still valid, then we need to fix the index pointer from the producer to this
  // consumer, and update it from `lastIdx` to `idx` (accounting for the move above).
  if (idx < node.liveConsumerNode.length) {
    const idxProducer = node.liveConsumerIndexOfThis[idx];
    const consumer = node.liveConsumerNode[idx];
    assertConsumerNode(consumer);
    consumer.producerIndexOfThis[idxProducer] = idx;
  }
}
function consumerIsLive(node) {
  return node.consumerIsAlwaysLive || (node?.liveConsumerNode?.length ?? 0) > 0;
}
function assertConsumerNode(node) {
  node.producerNode ??= [];
  node.producerIndexOfThis ??= [];
  node.producerLastReadVersion ??= [];
}
function assertProducerNode(node) {
  node.liveConsumerNode ??= [];
  node.liveConsumerIndexOfThis ??= [];
}
function isConsumerNode(node) {
  return node.producerNode !== undefined;
}

/**
 * Create a computed signal which derives a reactive value from an expression.
 */
function createComputed(computation) {
  const node = Object.create(COMPUTED_NODE);
  node.computation = computation;
  const computed = () => {
    // Check if the value needs updating before returning it.
    producerUpdateValueVersion(node);
    // Record that someone looked at this signal.
    producerAccessed(node);
    if (node.value === ERRORED) {
      throw node.error;
    }
    return node.value;
  };
  computed[SIGNAL] = node;
  return computed;
}
/**
 * A dedicated symbol used before a computed value has been calculated for the first time.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const UNSET = /* @__PURE__ */Symbol('UNSET');
/**
 * A dedicated symbol used in place of a computed signal value to indicate that a given computation
 * is in progress. Used to detect cycles in computation chains.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const COMPUTING = /* @__PURE__ */Symbol('COMPUTING');
/**
 * A dedicated symbol used in place of a computed signal value to indicate that a given computation
 * failed. The thrown error is cached until the computation gets dirty again.
 * Explicitly typed as `any` so we can use it as signal's value.
 */
const ERRORED = /* @__PURE__ */Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const COMPUTED_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    value: UNSET,
    dirty: true,
    error: null,
    equal: defaultEquals,
    producerMustRecompute(node) {
      // Force a recomputation if there's no current value, or if the current value is in the
      // process of being calculated (which should throw an error).
      return node.value === UNSET || node.value === COMPUTING;
    },
    producerRecomputeValue(node) {
      if (node.value === COMPUTING) {
        // Our computation somehow led to a cyclic read of itself.
        throw new Error('Detected cycle in computations.');
      }
      const oldValue = node.value;
      node.value = COMPUTING;
      const prevConsumer = consumerBeforeComputation(node);
      let newValue;
      try {
        newValue = node.computation();
      } catch (err) {
        newValue = ERRORED;
        node.error = err;
      } finally {
        consumerAfterComputation(node, prevConsumer);
      }
      if (oldValue !== UNSET && oldValue !== ERRORED && newValue !== ERRORED && node.equal(oldValue, newValue)) {
        // No change to `valueVersion` - old and new values are
        // semantically equivalent.
        node.value = oldValue;
        return;
      }
      node.value = newValue;
      node.version++;
    }
  };
})();
function defaultThrowError() {
  throw new Error();
}
let throwInvalidWriteToSignalErrorFn = defaultThrowError;
function throwInvalidWriteToSignalError() {
  throwInvalidWriteToSignalErrorFn();
}
function setThrowInvalidWriteToSignalError(fn) {
  throwInvalidWriteToSignalErrorFn = fn;
}

/**
 * If set, called after `WritableSignal`s are updated.
 *
 * This hook can be used to achieve various effects, such as running effects synchronously as part
 * of setting a signal.
 */
let postSignalSetFn = null;
/**
 * Create a `Signal` that can be set or updated directly.
 */
function createSignal(initialValue) {
  const node = Object.create(SIGNAL_NODE);
  node.value = initialValue;
  const getter = () => {
    producerAccessed(node);
    return node.value;
  };
  getter[SIGNAL] = node;
  return getter;
}
function setPostSignalSetFn(fn) {
  const prev = postSignalSetFn;
  postSignalSetFn = fn;
  return prev;
}
function signalGetFn() {
  producerAccessed(this);
  return this.value;
}
function signalSetFn(node, newValue) {
  if (!producerUpdatesAllowed()) {
    throwInvalidWriteToSignalError();
  }
  if (!node.equal(node.value, newValue)) {
    node.value = newValue;
    signalValueChanged(node);
  }
}
function signalUpdateFn(node, updater) {
  if (!producerUpdatesAllowed()) {
    throwInvalidWriteToSignalError();
  }
  signalSetFn(node, updater(node.value));
}
function runPostSignalSetFn() {
  postSignalSetFn?.();
}
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const SIGNAL_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    equal: defaultEquals,
    value: undefined
  };
})();
function signalValueChanged(node) {
  node.version++;
  producerIncrementEpoch();
  producerNotifyConsumers(node);
  postSignalSetFn?.();
}
function createWatch(fn, schedule, allowSignalWrites) {
  const node = Object.create(WATCH_NODE);
  if (allowSignalWrites) {
    node.consumerAllowSignalWrites = true;
  }
  node.fn = fn;
  node.schedule = schedule;
  const registerOnCleanup = cleanupFn => {
    node.cleanupFn = cleanupFn;
  };
  function isWatchNodeDestroyed(node) {
    return node.fn === null && node.schedule === null;
  }
  function destroyWatchNode(node) {
    if (!isWatchNodeDestroyed(node)) {
      consumerDestroy(node); // disconnect watcher from the reactive graph
      node.cleanupFn();
      // nullify references to the integration functions to mark node as destroyed
      node.fn = null;
      node.schedule = null;
      node.cleanupFn = NOOP_CLEANUP_FN;
    }
  }
  const run = () => {
    if (node.fn === null) {
      // trying to run a destroyed watch is noop
      return;
    }
    if (isInNotificationPhase()) {
      throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
    }
    node.dirty = false;
    if (node.hasRun && !consumerPollProducersForChange(node)) {
      return;
    }
    node.hasRun = true;
    const prevConsumer = consumerBeforeComputation(node);
    try {
      node.cleanupFn();
      node.cleanupFn = NOOP_CLEANUP_FN;
      node.fn(registerOnCleanup);
    } finally {
      consumerAfterComputation(node, prevConsumer);
    }
  };
  node.ref = {
    notify: () => consumerMarkDirty(node),
    run,
    cleanup: () => node.cleanupFn(),
    destroy: () => destroyWatchNode(node),
    [SIGNAL]: node
  };
  return node.ref;
}
const NOOP_CLEANUP_FN = () => {};
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const WATCH_NODE = /* @__PURE__ */(() => {
  return {
    ...REACTIVE_NODE,
    consumerIsAlwaysLive: true,
    consumerAllowSignalWrites: false,
    consumerMarkedDirty: node => {
      if (node.schedule !== null) {
        node.schedule(node.ref);
      }
    },
    hasRun: false,
    cleanupFn: NOOP_CLEANUP_FN
  };
})();
function setAlternateWeakRefImpl(impl) {
  // TODO: remove this function
}


/***/ }),

/***/ 8335:
/*!****************************************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+forms@19.0.0_@angular+common@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0._4b1d9132accf771fd930ed2e586487b4/node_modules/@angular/forms/fesm2022/forms.mjs ***!
  \****************************************************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AbstractControl: () => (/* binding */ AbstractControl),
/* harmony export */   AbstractControlDirective: () => (/* binding */ AbstractControlDirective),
/* harmony export */   AbstractFormGroupDirective: () => (/* binding */ AbstractFormGroupDirective),
/* harmony export */   COMPOSITION_BUFFER_MODE: () => (/* binding */ COMPOSITION_BUFFER_MODE),
/* harmony export */   CheckboxControlValueAccessor: () => (/* binding */ CheckboxControlValueAccessor),
/* harmony export */   CheckboxRequiredValidator: () => (/* binding */ CheckboxRequiredValidator),
/* harmony export */   ControlContainer: () => (/* binding */ ControlContainer),
/* harmony export */   ControlEvent: () => (/* binding */ ControlEvent),
/* harmony export */   DefaultValueAccessor: () => (/* binding */ DefaultValueAccessor),
/* harmony export */   EmailValidator: () => (/* binding */ EmailValidator),
/* harmony export */   FormArray: () => (/* binding */ FormArray),
/* harmony export */   FormArrayName: () => (/* binding */ FormArrayName),
/* harmony export */   FormBuilder: () => (/* binding */ FormBuilder),
/* harmony export */   FormControl: () => (/* binding */ FormControl),
/* harmony export */   FormControlDirective: () => (/* binding */ FormControlDirective),
/* harmony export */   FormControlName: () => (/* binding */ FormControlName),
/* harmony export */   FormGroup: () => (/* binding */ FormGroup),
/* harmony export */   FormGroupDirective: () => (/* binding */ FormGroupDirective),
/* harmony export */   FormGroupName: () => (/* binding */ FormGroupName),
/* harmony export */   FormRecord: () => (/* binding */ FormRecord),
/* harmony export */   FormResetEvent: () => (/* binding */ FormResetEvent),
/* harmony export */   FormSubmittedEvent: () => (/* binding */ FormSubmittedEvent),
/* harmony export */   FormsModule: () => (/* binding */ FormsModule),
/* harmony export */   MaxLengthValidator: () => (/* binding */ MaxLengthValidator),
/* harmony export */   MaxValidator: () => (/* binding */ MaxValidator),
/* harmony export */   MinLengthValidator: () => (/* binding */ MinLengthValidator),
/* harmony export */   MinValidator: () => (/* binding */ MinValidator),
/* harmony export */   NG_ASYNC_VALIDATORS: () => (/* binding */ NG_ASYNC_VALIDATORS),
/* harmony export */   NG_VALIDATORS: () => (/* binding */ NG_VALIDATORS),
/* harmony export */   NG_VALUE_ACCESSOR: () => (/* binding */ NG_VALUE_ACCESSOR),
/* harmony export */   NgControl: () => (/* binding */ NgControl),
/* harmony export */   NgControlStatus: () => (/* binding */ NgControlStatus),
/* harmony export */   NgControlStatusGroup: () => (/* binding */ NgControlStatusGroup),
/* harmony export */   NgForm: () => (/* binding */ NgForm),
/* harmony export */   NgModel: () => (/* binding */ NgModel),
/* harmony export */   NgModelGroup: () => (/* binding */ NgModelGroup),
/* harmony export */   NgSelectOption: () => (/* binding */ NgSelectOption),
/* harmony export */   NonNullableFormBuilder: () => (/* binding */ NonNullableFormBuilder),
/* harmony export */   NumberValueAccessor: () => (/* binding */ NumberValueAccessor),
/* harmony export */   PatternValidator: () => (/* binding */ PatternValidator),
/* harmony export */   PristineChangeEvent: () => (/* binding */ PristineChangeEvent),
/* harmony export */   RadioControlValueAccessor: () => (/* binding */ RadioControlValueAccessor),
/* harmony export */   RangeValueAccessor: () => (/* binding */ RangeValueAccessor),
/* harmony export */   ReactiveFormsModule: () => (/* binding */ ReactiveFormsModule),
/* harmony export */   RequiredValidator: () => (/* binding */ RequiredValidator),
/* harmony export */   SelectControlValueAccessor: () => (/* binding */ SelectControlValueAccessor),
/* harmony export */   SelectMultipleControlValueAccessor: () => (/* binding */ SelectMultipleControlValueAccessor),
/* harmony export */   StatusChangeEvent: () => (/* binding */ StatusChangeEvent),
/* harmony export */   TouchedChangeEvent: () => (/* binding */ TouchedChangeEvent),
/* harmony export */   UntypedFormArray: () => (/* binding */ UntypedFormArray),
/* harmony export */   UntypedFormBuilder: () => (/* binding */ UntypedFormBuilder),
/* harmony export */   UntypedFormControl: () => (/* binding */ UntypedFormControl),
/* harmony export */   UntypedFormGroup: () => (/* binding */ UntypedFormGroup),
/* harmony export */   VERSION: () => (/* binding */ VERSION),
/* harmony export */   Validators: () => (/* binding */ Validators),
/* harmony export */   ValueChangeEvent: () => (/* binding */ ValueChangeEvent),
/* harmony export */   isFormArray: () => (/* binding */ isFormArray),
/* harmony export */   isFormControl: () => (/* binding */ isFormControl),
/* harmony export */   isFormGroup: () => (/* binding */ isFormGroup),
/* harmony export */   isFormRecord: () => (/* binding */ isFormRecord),
/* harmony export */   "ɵInternalFormsSharedModule": () => (/* binding */ ɵInternalFormsSharedModule),
/* harmony export */   "ɵNgNoValidate": () => (/* binding */ ɵNgNoValidate),
/* harmony export */   "ɵNgSelectMultipleOption": () => (/* binding */ ɵNgSelectMultipleOption)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 580);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs */ 3092);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs/operators */ 6634);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */







/**
 * Base class for all ControlValueAccessor classes defined in Forms package.
 * Contains common logic and utility functions.
 *
 * Note: this is an *internal-only* class and should not be extended or used directly in
 * applications code.
 */
let BaseControlValueAccessor = /*#__PURE__*/(() => {
  class BaseControlValueAccessor {
    _renderer;
    _elementRef;
    /**
     * The registered callback function called when a change or input event occurs on the input
     * element.
     * @nodoc
     */
    onChange = _ => {};
    /**
     * The registered callback function called when a blur event occurs on the input element.
     * @nodoc
     */
    onTouched = () => {};
    constructor(_renderer, _elementRef) {
      this._renderer = _renderer;
      this._elementRef = _elementRef;
    }
    /**
     * Helper method that sets a property on a target element using the current Renderer
     * implementation.
     * @nodoc
     */
    setProperty(key, value) {
      this._renderer.setProperty(this._elementRef.nativeElement, key, value);
    }
    /**
     * Registers a function called when the control is touched.
     * @nodoc
     */
    registerOnTouched(fn) {
      this.onTouched = fn;
    }
    /**
     * Registers a function called when the control value changes.
     * @nodoc
     */
    registerOnChange(fn) {
      this.onChange = fn;
    }
    /**
     * Sets the "disabled" property on the range input element.
     * @nodoc
     */
    setDisabledState(isDisabled) {
      this.setProperty('disabled', isDisabled);
    }
    static ɵfac = (() => function BaseControlValueAccessor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BaseControlValueAccessor)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: BaseControlValueAccessor
    }))();
  }
  return BaseControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Base class for all built-in ControlValueAccessor classes (except DefaultValueAccessor, which is
 * used in case no other CVAs can be found). We use this class to distinguish between default CVA,
 * built-in CVAs and custom CVAs, so that Forms logic can recognize built-in CVAs and treat custom
 * ones with higher priority (when both built-in and custom CVAs are present).
 *
 * Note: this is an *internal-only* class and should not be extended or used directly in
 * applications code.
 */
let BuiltInControlValueAccessor = /*#__PURE__*/(() => {
  class BuiltInControlValueAccessor extends BaseControlValueAccessor {
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵBuiltInControlValueAccessor_BaseFactory;
      return function BuiltInControlValueAccessor_Factory(__ngFactoryType__) {
        return (ɵBuiltInControlValueAccessor_BaseFactory || (ɵBuiltInControlValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](BuiltInControlValueAccessor)))(__ngFactoryType__ || BuiltInControlValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: BuiltInControlValueAccessor,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return BuiltInControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Used to provide a `ControlValueAccessor` for form controls.
 *
 * See `DefaultValueAccessor` for how to implement one.
 *
 * @publicApi
 */
const NG_VALUE_ACCESSOR = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken(ngDevMode ? 'NgValueAccessor' : '');
const CHECKBOX_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => CheckboxControlValueAccessor),
  multi: true
};
/**
 * @description
 * A `ControlValueAccessor` for writing a value and listening to changes on a checkbox input
 * element.
 *
 * @usageNotes
 *
 * ### Using a checkbox with a reactive form.
 *
 * The following example shows how to use a checkbox with a reactive form.
 *
 * ```ts
 * const rememberLoginControl = new FormControl();
 * ```
 *
 * ```
 * <input type="checkbox" [formControl]="rememberLoginControl">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let CheckboxControlValueAccessor = /*#__PURE__*/(() => {
  class CheckboxControlValueAccessor extends BuiltInControlValueAccessor {
    /**
     * Sets the "checked" property on the input element.
     * @nodoc
     */
    writeValue(value) {
      this.setProperty('checked', value);
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵCheckboxControlValueAccessor_BaseFactory;
      return function CheckboxControlValueAccessor_Factory(__ngFactoryType__) {
        return (ɵCheckboxControlValueAccessor_BaseFactory || (ɵCheckboxControlValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](CheckboxControlValueAccessor)))(__ngFactoryType__ || CheckboxControlValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: CheckboxControlValueAccessor,
      selectors: [["input", "type", "checkbox", "formControlName", ""], ["input", "type", "checkbox", "formControl", ""], ["input", "type", "checkbox", "ngModel", ""]],
      hostBindings: function CheckboxControlValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("change", function CheckboxControlValueAccessor_change_HostBindingHandler($event) {
            return ctx.onChange($event.target.checked);
          })("blur", function CheckboxControlValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([CHECKBOX_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return CheckboxControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const DEFAULT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => DefaultValueAccessor),
  multi: true
};
/**
 * We must check whether the agent is Android because composition events
 * behave differently between iOS and Android.
 */
function _isAndroid() {
  const userAgent = (0,_angular_common__WEBPACK_IMPORTED_MODULE_1__["ɵgetDOM"])() ? (0,_angular_common__WEBPACK_IMPORTED_MODULE_1__["ɵgetDOM"])().getUserAgent() : '';
  return /android (\d+)/.test(userAgent.toLowerCase());
}
/**
 * @description
 * Provide this token to control if form directives buffer IME input until
 * the "compositionend" event occurs.
 * @publicApi
 */
const COMPOSITION_BUFFER_MODE = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken(ngDevMode ? 'CompositionEventMode' : '');
/**
 * The default `ControlValueAccessor` for writing a value and listening to changes on input
 * elements. The accessor is used by the `FormControlDirective`, `FormControlName`, and
 * `NgModel` directives.
 *
 *
 * @usageNotes
 *
 * ### Using the default value accessor
 *
 * The following example shows how to use an input element that activates the default value accessor
 * (in this case, a text field).
 *
 * ```ts
 * const firstNameControl = new FormControl();
 * ```
 *
 * ```
 * <input type="text" [formControl]="firstNameControl">
 * ```
 *
 * This value accessor is used by default for `<input type="text">` and `<textarea>` elements, but
 * you could also use it for custom components that have similar behavior and do not require special
 * processing. In order to attach the default value accessor to a custom element, add the
 * `ngDefaultControl` attribute as shown below.
 *
 * ```
 * <custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let DefaultValueAccessor = /*#__PURE__*/(() => {
  class DefaultValueAccessor extends BaseControlValueAccessor {
    _compositionMode;
    /** Whether the user is creating a composition string (IME events). */
    _composing = false;
    constructor(renderer, elementRef, _compositionMode) {
      super(renderer, elementRef);
      this._compositionMode = _compositionMode;
      if (this._compositionMode == null) {
        this._compositionMode = !_isAndroid();
      }
    }
    /**
     * Sets the "value" property on the input element.
     * @nodoc
     */
    writeValue(value) {
      const normalizedValue = value == null ? '' : value;
      this.setProperty('value', normalizedValue);
    }
    /** @internal */
    _handleInput(value) {
      if (!this._compositionMode || this._compositionMode && !this._composing) {
        this.onChange(value);
      }
    }
    /** @internal */
    _compositionStart() {
      this._composing = true;
    }
    /** @internal */
    _compositionEnd(value) {
      this._composing = false;
      this._compositionMode && this.onChange(value);
    }
    static ɵfac = (() => function DefaultValueAccessor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DefaultValueAccessor)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](COMPOSITION_BUFFER_MODE, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: DefaultValueAccessor,
      selectors: [["input", "formControlName", "", 3, "type", "checkbox"], ["textarea", "formControlName", ""], ["input", "formControl", "", 3, "type", "checkbox"], ["textarea", "formControl", ""], ["input", "ngModel", "", 3, "type", "checkbox"], ["textarea", "ngModel", ""], ["", "ngDefaultControl", ""]],
      hostBindings: function DefaultValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("input", function DefaultValueAccessor_input_HostBindingHandler($event) {
            return ctx._handleInput($event.target.value);
          })("blur", function DefaultValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          })("compositionstart", function DefaultValueAccessor_compositionstart_HostBindingHandler() {
            return ctx._compositionStart();
          })("compositionend", function DefaultValueAccessor_compositionend_HostBindingHandler($event) {
            return ctx._compositionEnd($event.target.value);
          });
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([DEFAULT_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return DefaultValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function isEmptyInputValue(value) {
  /**
   * Check if the object is a string or array before evaluating the length attribute.
   * This avoids falsely rejecting objects that contain a custom length attribute.
   * For example, the object {id: 1, length: 0, width: 0} should not be returned as empty.
   */
  return value == null || (typeof value === 'string' || Array.isArray(value)) && value.length === 0;
}
function hasValidLength(value) {
  // non-strict comparison is intentional, to check for both `null` and `undefined` values
  return value != null && typeof value.length === 'number';
}
/**
 * @description
 * An `InjectionToken` for registering additional synchronous validators used with
 * `AbstractControl`s.
 *
 * @see {@link NG_ASYNC_VALIDATORS}
 *
 * @usageNotes
 *
 * ### Providing a custom validator
 *
 * The following example registers a custom validator directive. Adding the validator to the
 * existing collection of validators requires the `multi: true` option.
 *
 * ```typescript
 * @Directive({
 *   selector: '[customValidator]',
 *   providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
 * })
 * class CustomValidatorDirective implements Validator {
 *   validate(control: AbstractControl): ValidationErrors | null {
 *     return { 'custom': true };
 *   }
 * }
 * ```
 *
 * @publicApi
 */
const NG_VALIDATORS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken(ngDevMode ? 'NgValidators' : '');
/**
 * @description
 * An `InjectionToken` for registering additional asynchronous validators used with
 * `AbstractControl`s.
 *
 * @see {@link NG_VALIDATORS}
 *
 * @usageNotes
 *
 * ### Provide a custom async validator directive
 *
 * The following example implements the `AsyncValidator` interface to create an
 * async validator directive with a custom error key.
 *
 * ```typescript
 * @Directive({
 *   selector: '[customAsyncValidator]',
 *   providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:
 * true}]
 * })
 * class CustomAsyncValidatorDirective implements AsyncValidator {
 *   validate(control: AbstractControl): Promise<ValidationErrors|null> {
 *     return Promise.resolve({'custom': true});
 *   }
 * }
 * ```
 *
 * @publicApi
 */
const NG_ASYNC_VALIDATORS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken(ngDevMode ? 'NgAsyncValidators' : '');
/**
 * A regular expression that matches valid e-mail addresses.
 *
 * At a high level, this regexp matches e-mail addresses of the format `local-part@tld`, where:
 * - `local-part` consists of one or more of the allowed characters (alphanumeric and some
 *   punctuation symbols).
 * - `local-part` cannot begin or end with a period (`.`).
 * - `local-part` cannot be longer than 64 characters.
 * - `tld` consists of one or more `labels` separated by periods (`.`). For example `localhost` or
 *   `foo.com`.
 * - A `label` consists of one or more of the allowed characters (alphanumeric, dashes (`-`) and
 *   periods (`.`)).
 * - A `label` cannot begin or end with a dash (`-`) or a period (`.`).
 * - A `label` cannot be longer than 63 characters.
 * - The whole address cannot be longer than 254 characters.
 *
 * ## Implementation background
 *
 * This regexp was ported over from AngularJS (see there for git history):
 * https://github.com/angular/angular.js/blob/c133ef836/src/ng/directive/input.js#L27
 * It is based on the
 * [WHATWG version](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with
 * some enhancements to incorporate more RFC rules (such as rules related to domain names and the
 * lengths of different parts of the address). The main differences from the WHATWG version are:
 *   - Disallow `local-part` to begin or end with a period (`.`).
 *   - Disallow `local-part` length to exceed 64 characters.
 *   - Disallow total address length to exceed 254 characters.
 *
 * See [this commit](https://github.com/angular/angular.js/commit/f3f5cf72e) for more details.
 */
const EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
 * @description
 * Provides a set of built-in validators that can be used by form controls.
 *
 * A validator is a function that processes a `FormControl` or collection of
 * controls and returns an error map or null. A null map means that validation has passed.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @publicApi
 */
class Validators {
  /**
   * @description
   * Validator that requires the control's value to be greater than or equal to the provided number.
   *
   * @usageNotes
   *
   * ### Validate against a minimum of 3
   *
   * ```typescript
   * const control = new FormControl(2, Validators.min(3));
   *
   * console.log(control.errors); // {min: {min: 3, actual: 2}}
   * ```
   *
   * @returns A validator function that returns an error map with the
   * `min` property if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static min(min) {
    return minValidator(min);
  }
  /**
   * @description
   * Validator that requires the control's value to be less than or equal to the provided number.
   *
   * @usageNotes
   *
   * ### Validate against a maximum of 15
   *
   * ```typescript
   * const control = new FormControl(16, Validators.max(15));
   *
   * console.log(control.errors); // {max: {max: 15, actual: 16}}
   * ```
   *
   * @returns A validator function that returns an error map with the
   * `max` property if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static max(max) {
    return maxValidator(max);
  }
  /**
   * @description
   * Validator that requires the control have a non-empty value.
   *
   * @usageNotes
   *
   * ### Validate that the field is non-empty
   *
   * ```typescript
   * const control = new FormControl('', Validators.required);
   *
   * console.log(control.errors); // {required: true}
   * ```
   *
   * @returns An error map with the `required` property
   * if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static required(control) {
    return requiredValidator(control);
  }
  /**
   * @description
   * Validator that requires the control's value be true. This validator is commonly
   * used for required checkboxes.
   *
   * @usageNotes
   *
   * ### Validate that the field value is true
   *
   * ```typescript
   * const control = new FormControl('some value', Validators.requiredTrue);
   *
   * console.log(control.errors); // {required: true}
   * ```
   *
   * @returns An error map that contains the `required` property
   * set to `true` if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static requiredTrue(control) {
    return requiredTrueValidator(control);
  }
  /**
   * @description
   * Validator that requires the control's value pass an email validation test.
   *
   * Tests the value using a [regular
   * expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
   * pattern suitable for common use cases. The pattern is based on the definition of a valid email
   * address in the [WHATWG HTML
   * specification](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with
   * some enhancements to incorporate more RFC rules (such as rules related to domain names and the
   * lengths of different parts of the address).
   *
   * The differences from the WHATWG version include:
   * - Disallow `local-part` (the part before the `@` symbol) to begin or end with a period (`.`).
   * - Disallow `local-part` to be longer than 64 characters.
   * - Disallow the whole address to be longer than 254 characters.
   *
   * If this pattern does not satisfy your business needs, you can use `Validators.pattern()` to
   * validate the value against a different pattern.
   *
   * @usageNotes
   *
   * ### Validate that the field matches a valid email pattern
   *
   * ```typescript
   * const control = new FormControl('bad@', Validators.email);
   *
   * console.log(control.errors); // {email: true}
   * ```
   *
   * @returns An error map with the `email` property
   * if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static email(control) {
    return emailValidator(control);
  }
  /**
   * @description
   * Validator that requires the length of the control's value to be greater than or equal
   * to the provided minimum length. This validator is also provided by default if you use the
   * the HTML5 `minlength` attribute. Note that the `minLength` validator is intended to be used
   * only for types that have a numeric `length` property, such as strings or arrays. The
   * `minLength` validator logic is also not invoked for values when their `length` property is 0
   * (for example in case of an empty string or an empty array), to support optional controls. You
   * can use the standard `required` validator if empty values should not be considered valid.
   *
   * @usageNotes
   *
   * ### Validate that the field has a minimum of 3 characters
   *
   * ```typescript
   * const control = new FormControl('ng', Validators.minLength(3));
   *
   * console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}
   * ```
   *
   * ```html
   * <input minlength="5">
   * ```
   *
   * @returns A validator function that returns an error map with the
   * `minlength` property if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static minLength(minLength) {
    return minLengthValidator(minLength);
  }
  /**
   * @description
   * Validator that requires the length of the control's value to be less than or equal
   * to the provided maximum length. This validator is also provided by default if you use the
   * the HTML5 `maxlength` attribute. Note that the `maxLength` validator is intended to be used
   * only for types that have a numeric `length` property, such as strings or arrays.
   *
   * @usageNotes
   *
   * ### Validate that the field has maximum of 5 characters
   *
   * ```typescript
   * const control = new FormControl('Angular', Validators.maxLength(5));
   *
   * console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}
   * ```
   *
   * ```html
   * <input maxlength="5">
   * ```
   *
   * @returns A validator function that returns an error map with the
   * `maxlength` property if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static maxLength(maxLength) {
    return maxLengthValidator(maxLength);
  }
  /**
   * @description
   * Validator that requires the control's value to match a regex pattern. This validator is also
   * provided by default if you use the HTML5 `pattern` attribute.
   *
   * @usageNotes
   *
   * ### Validate that the field only contains letters or spaces
   *
   * ```typescript
   * const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));
   *
   * console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}
   * ```
   *
   * ```html
   * <input pattern="[a-zA-Z ]*">
   * ```
   *
   * ### Pattern matching with the global or sticky flag
   *
   * `RegExp` objects created with the `g` or `y` flags that are passed into `Validators.pattern`
   * can produce different results on the same input when validations are run consecutively. This is
   * due to how the behavior of `RegExp.prototype.test` is
   * specified in [ECMA-262](https://tc39.es/ecma262/#sec-regexpbuiltinexec)
   * (`RegExp` preserves the index of the last match when the global or sticky flag is used).
   * Due to this behavior, it is recommended that when using
   * `Validators.pattern` you **do not** pass in a `RegExp` object with either the global or sticky
   * flag enabled.
   *
   * ```typescript
   * // Not recommended (since the `g` flag is used)
   * const controlOne = new FormControl('1', Validators.pattern(/foo/g));
   *
   * // Good
   * const controlTwo = new FormControl('1', Validators.pattern(/foo/));
   * ```
   *
   * @param pattern A regular expression to be used as is to test the values, or a string.
   * If a string is passed, the `^` character is prepended and the `$` character is
   * appended to the provided string (if not already present), and the resulting regular
   * expression is used to test the values.
   *
   * @returns A validator function that returns an error map with the
   * `pattern` property if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static pattern(pattern) {
    return patternValidator(pattern);
  }
  /**
   * @description
   * Validator that performs no operation.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static nullValidator(control) {
    return nullValidator(control);
  }
  static compose(validators) {
    return compose(validators);
  }
  /**
   * @description
   * Compose multiple async validators into a single function that returns the union
   * of the individual error objects for the provided control.
   *
   * @returns A validator function that returns an error map with the
   * merged error objects of the async validators if the validation check fails, otherwise `null`.
   *
   * @see {@link updateValueAndValidity()}
   *
   */
  static composeAsync(validators) {
    return composeAsync(validators);
  }
}
/**
 * Validator that requires the control's value to be greater than or equal to the provided number.
 * See `Validators.min` for additional information.
 */
function minValidator(min) {
  return control => {
    if (isEmptyInputValue(control.value) || isEmptyInputValue(min)) {
      return null; // don't validate empty values to allow optional controls
    }
    const value = parseFloat(control.value);
    // Controls with NaN values after parsing should be treated as not having a
    // minimum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-min
    return !isNaN(value) && value < min ? {
      'min': {
        'min': min,
        'actual': control.value
      }
    } : null;
  };
}
/**
 * Validator that requires the control's value to be less than or equal to the provided number.
 * See `Validators.max` for additional information.
 */
function maxValidator(max) {
  return control => {
    if (isEmptyInputValue(control.value) || isEmptyInputValue(max)) {
      return null; // don't validate empty values to allow optional controls
    }
    const value = parseFloat(control.value);
    // Controls with NaN values after parsing should be treated as not having a
    // maximum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-max
    return !isNaN(value) && value > max ? {
      'max': {
        'max': max,
        'actual': control.value
      }
    } : null;
  };
}
/**
 * Validator that requires the control have a non-empty value.
 * See `Validators.required` for additional information.
 */
function requiredValidator(control) {
  return isEmptyInputValue(control.value) ? {
    'required': true
  } : null;
}
/**
 * Validator that requires the control's value be true. This validator is commonly
 * used for required checkboxes.
 * See `Validators.requiredTrue` for additional information.
 */
function requiredTrueValidator(control) {
  return control.value === true ? null : {
    'required': true
  };
}
/**
 * Validator that requires the control's value pass an email validation test.
 * See `Validators.email` for additional information.
 */
function emailValidator(control) {
  if (isEmptyInputValue(control.value)) {
    return null; // don't validate empty values to allow optional controls
  }
  return EMAIL_REGEXP.test(control.value) ? null : {
    'email': true
  };
}
/**
 * Validator that requires the length of the control's value to be greater than or equal
 * to the provided minimum length. See `Validators.minLength` for additional information.
 */
function minLengthValidator(minLength) {
  return control => {
    if (isEmptyInputValue(control.value) || !hasValidLength(control.value)) {
      // don't validate empty values to allow optional controls
      // don't validate values without `length` property
      return null;
    }
    return control.value.length < minLength ? {
      'minlength': {
        'requiredLength': minLength,
        'actualLength': control.value.length
      }
    } : null;
  };
}
/**
 * Validator that requires the length of the control's value to be less than or equal
 * to the provided maximum length. See `Validators.maxLength` for additional information.
 */
function maxLengthValidator(maxLength) {
  return control => {
    return hasValidLength(control.value) && control.value.length > maxLength ? {
      'maxlength': {
        'requiredLength': maxLength,
        'actualLength': control.value.length
      }
    } : null;
  };
}
/**
 * Validator that requires the control's value to match a regex pattern.
 * See `Validators.pattern` for additional information.
 */
function patternValidator(pattern) {
  if (!pattern) return nullValidator;
  let regex;
  let regexStr;
  if (typeof pattern === 'string') {
    regexStr = '';
    if (pattern.charAt(0) !== '^') regexStr += '^';
    regexStr += pattern;
    if (pattern.charAt(pattern.length - 1) !== '$') regexStr += '$';
    regex = new RegExp(regexStr);
  } else {
    regexStr = pattern.toString();
    regex = pattern;
  }
  return control => {
    if (isEmptyInputValue(control.value)) {
      return null; // don't validate empty values to allow optional controls
    }
    const value = control.value;
    return regex.test(value) ? null : {
      'pattern': {
        'requiredPattern': regexStr,
        'actualValue': value
      }
    };
  };
}
/**
 * Function that has `ValidatorFn` shape, but performs no operation.
 */
function nullValidator(control) {
  return null;
}
function isPresent(o) {
  return o != null;
}
function toObservable(value) {
  const obs = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisPromise"])(value) ? (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(value) : value;
  if ((typeof ngDevMode === 'undefined' || ngDevMode) && !(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisSubscribable"])(obs)) {
    let errorMessage = `Expected async validator to return Promise or Observable.`;
    // A synchronous validator will return object or null.
    if (typeof value === 'object') {
      errorMessage += ' Are you using a synchronous validator where an async validator is expected?';
    }
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](-1101 /* RuntimeErrorCode.WRONG_VALIDATOR_RETURN_TYPE */, errorMessage);
  }
  return obs;
}
function mergeErrors(arrayOfErrors) {
  let res = {};
  arrayOfErrors.forEach(errors => {
    res = errors != null ? {
      ...res,
      ...errors
    } : res;
  });
  return Object.keys(res).length === 0 ? null : res;
}
function executeValidators(control, validators) {
  return validators.map(validator => validator(control));
}
function isValidatorFn(validator) {
  return !validator.validate;
}
/**
 * Given the list of validators that may contain both functions as well as classes, return the list
 * of validator functions (convert validator classes into validator functions). This is needed to
 * have consistent structure in validators list before composing them.
 *
 * @param validators The set of validators that may contain validators both in plain function form
 *     as well as represented as a validator class.
 */
function normalizeValidators(validators) {
  return validators.map(validator => {
    return isValidatorFn(validator) ? validator : c => validator.validate(c);
  });
}
/**
 * Merges synchronous validators into a single validator function.
 * See `Validators.compose` for additional information.
 */
function compose(validators) {
  if (!validators) return null;
  const presentValidators = validators.filter(isPresent);
  if (presentValidators.length == 0) return null;
  return function (control) {
    return mergeErrors(executeValidators(control, presentValidators));
  };
}
/**
 * Accepts a list of validators of different possible shapes (`Validator` and `ValidatorFn`),
 * normalizes the list (converts everything to `ValidatorFn`) and merges them into a single
 * validator function.
 */
function composeValidators(validators) {
  return validators != null ? compose(normalizeValidators(validators)) : null;
}
/**
 * Merges asynchronous validators into a single validator function.
 * See `Validators.composeAsync` for additional information.
 */
function composeAsync(validators) {
  if (!validators) return null;
  const presentValidators = validators.filter(isPresent);
  if (presentValidators.length == 0) return null;
  return function (control) {
    const observables = executeValidators(control, presentValidators).map(toObservable);
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.forkJoin)(observables).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.map)(mergeErrors));
  };
}
/**
 * Accepts a list of async validators of different possible shapes (`AsyncValidator` and
 * `AsyncValidatorFn`), normalizes the list (converts everything to `AsyncValidatorFn`) and merges
 * them into a single validator function.
 */
function composeAsyncValidators(validators) {
  return validators != null ? composeAsync(normalizeValidators(validators)) : null;
}
/**
 * Merges raw control validators with a given directive validator and returns the combined list of
 * validators as an array.
 */
function mergeValidators(controlValidators, dirValidator) {
  if (controlValidators === null) return [dirValidator];
  return Array.isArray(controlValidators) ? [...controlValidators, dirValidator] : [controlValidators, dirValidator];
}
/**
 * Retrieves the list of raw synchronous validators attached to a given control.
 */
function getControlValidators(control) {
  return control._rawValidators;
}
/**
 * Retrieves the list of raw asynchronous validators attached to a given control.
 */
function getControlAsyncValidators(control) {
  return control._rawAsyncValidators;
}
/**
 * Accepts a singleton validator, an array, or null, and returns an array type with the provided
 * validators.
 *
 * @param validators A validator, validators, or null.
 * @returns A validators array.
 */
function makeValidatorsArray(validators) {
  if (!validators) return [];
  return Array.isArray(validators) ? validators : [validators];
}
/**
 * Determines whether a validator or validators array has a given validator.
 *
 * @param validators The validator or validators to compare against.
 * @param validator The validator to check.
 * @returns Whether the validator is present.
 */
function hasValidator(validators, validator) {
  return Array.isArray(validators) ? validators.includes(validator) : validators === validator;
}
/**
 * Combines two arrays of validators into one. If duplicates are provided, only one will be added.
 *
 * @param validators The new validators.
 * @param currentValidators The base array of current validators.
 * @returns An array of validators.
 */
function addValidators(validators, currentValidators) {
  const current = makeValidatorsArray(currentValidators);
  const validatorsToAdd = makeValidatorsArray(validators);
  validatorsToAdd.forEach(v => {
    // Note: if there are duplicate entries in the new validators array,
    // only the first one would be added to the current list of validators.
    // Duplicate ones would be ignored since `hasValidator` would detect
    // the presence of a validator function and we update the current list in place.
    if (!hasValidator(current, v)) {
      current.push(v);
    }
  });
  return current;
}
function removeValidators(validators, currentValidators) {
  return makeValidatorsArray(currentValidators).filter(v => !hasValidator(validators, v));
}

/**
 * @description
 * Base class for control directives.
 *
 * This class is only used internally in the `ReactiveFormsModule` and the `FormsModule`.
 *
 * @publicApi
 */
class AbstractControlDirective {
  /**
   * @description
   * Reports the value of the control if it is present, otherwise null.
   */
  get value() {
    return this.control ? this.control.value : null;
  }
  /**
   * @description
   * Reports whether the control is valid. A control is considered valid if no
   * validation errors exist with the current value.
   * If the control is not present, null is returned.
   */
  get valid() {
    return this.control ? this.control.valid : null;
  }
  /**
   * @description
   * Reports whether the control is invalid, meaning that an error exists in the input value.
   * If the control is not present, null is returned.
   */
  get invalid() {
    return this.control ? this.control.invalid : null;
  }
  /**
   * @description
   * Reports whether a control is pending, meaning that async validation is occurring and
   * errors are not yet available for the input value. If the control is not present, null is
   * returned.
   */
  get pending() {
    return this.control ? this.control.pending : null;
  }
  /**
   * @description
   * Reports whether the control is disabled, meaning that the control is disabled
   * in the UI and is exempt from validation checks and excluded from aggregate
   * values of ancestor controls. If the control is not present, null is returned.
   */
  get disabled() {
    return this.control ? this.control.disabled : null;
  }
  /**
   * @description
   * Reports whether the control is enabled, meaning that the control is included in ancestor
   * calculations of validity or value. If the control is not present, null is returned.
   */
  get enabled() {
    return this.control ? this.control.enabled : null;
  }
  /**
   * @description
   * Reports the control's validation errors. If the control is not present, null is returned.
   */
  get errors() {
    return this.control ? this.control.errors : null;
  }
  /**
   * @description
   * Reports whether the control is pristine, meaning that the user has not yet changed
   * the value in the UI. If the control is not present, null is returned.
   */
  get pristine() {
    return this.control ? this.control.pristine : null;
  }
  /**
   * @description
   * Reports whether the control is dirty, meaning that the user has changed
   * the value in the UI. If the control is not present, null is returned.
   */
  get dirty() {
    return this.control ? this.control.dirty : null;
  }
  /**
   * @description
   * Reports whether the control is touched, meaning that the user has triggered
   * a `blur` event on it. If the control is not present, null is returned.
   */
  get touched() {
    return this.control ? this.control.touched : null;
  }
  /**
   * @description
   * Reports the validation status of the control. Possible values include:
   * 'VALID', 'INVALID', 'DISABLED', and 'PENDING'.
   * If the control is not present, null is returned.
   */
  get status() {
    return this.control ? this.control.status : null;
  }
  /**
   * @description
   * Reports whether the control is untouched, meaning that the user has not yet triggered
   * a `blur` event on it. If the control is not present, null is returned.
   */
  get untouched() {
    return this.control ? this.control.untouched : null;
  }
  /**
   * @description
   * Returns a multicasting observable that emits a validation status whenever it is
   * calculated for the control. If the control is not present, null is returned.
   */
  get statusChanges() {
    return this.control ? this.control.statusChanges : null;
  }
  /**
   * @description
   * Returns a multicasting observable of value changes for the control that emits every time the
   * value of the control changes in the UI or programmatically.
   * If the control is not present, null is returned.
   */
  get valueChanges() {
    return this.control ? this.control.valueChanges : null;
  }
  /**
   * @description
   * Returns an array that represents the path from the top-level form to this control.
   * Each index is the string name of the control on that level.
   */
  get path() {
    return null;
  }
  /**
   * Contains the result of merging synchronous validators into a single validator function
   * (combined using `Validators.compose`).
   */
  _composedValidatorFn;
  /**
   * Contains the result of merging asynchronous validators into a single validator function
   * (combined using `Validators.composeAsync`).
   */
  _composedAsyncValidatorFn;
  /**
   * Set of synchronous validators as they were provided while calling `setValidators` function.
   * @internal
   */
  _rawValidators = [];
  /**
   * Set of asynchronous validators as they were provided while calling `setAsyncValidators`
   * function.
   * @internal
   */
  _rawAsyncValidators = [];
  /**
   * Sets synchronous validators for this directive.
   * @internal
   */
  _setValidators(validators) {
    this._rawValidators = validators || [];
    this._composedValidatorFn = composeValidators(this._rawValidators);
  }
  /**
   * Sets asynchronous validators for this directive.
   * @internal
   */
  _setAsyncValidators(validators) {
    this._rawAsyncValidators = validators || [];
    this._composedAsyncValidatorFn = composeAsyncValidators(this._rawAsyncValidators);
  }
  /**
   * @description
   * Synchronous validator function composed of all the synchronous validators registered with this
   * directive.
   */
  get validator() {
    return this._composedValidatorFn || null;
  }
  /**
   * @description
   * Asynchronous validator function composed of all the asynchronous validators registered with
   * this directive.
   */
  get asyncValidator() {
    return this._composedAsyncValidatorFn || null;
  }
  /*
   * The set of callbacks to be invoked when directive instance is being destroyed.
   */
  _onDestroyCallbacks = [];
  /**
   * Internal function to register callbacks that should be invoked
   * when directive instance is being destroyed.
   * @internal
   */
  _registerOnDestroy(fn) {
    this._onDestroyCallbacks.push(fn);
  }
  /**
   * Internal function to invoke all registered "on destroy" callbacks.
   * Note: calling this function also clears the list of callbacks.
   * @internal
   */
  _invokeOnDestroyCallbacks() {
    this._onDestroyCallbacks.forEach(fn => fn());
    this._onDestroyCallbacks = [];
  }
  /**
   * @description
   * Resets the control with the provided value if the control is present.
   */
  reset(value = undefined) {
    if (this.control) this.control.reset(value);
  }
  /**
   * @description
   * Reports whether the control with the given path has the error specified.
   *
   * @param errorCode The code of the error to check
   * @param path A list of control names that designates how to move from the current control
   * to the control that should be queried for errors.
   *
   * @usageNotes
   * For example, for the following `FormGroup`:
   *
   * ```
   * form = new FormGroup({
   *   address: new FormGroup({ street: new FormControl() })
   * });
   * ```
   *
   * The path to the 'street' control from the root form would be 'address' -> 'street'.
   *
   * It can be provided to this method in one of two formats:
   *
   * 1. An array of string control names, e.g. `['address', 'street']`
   * 1. A period-delimited list of control names in one string, e.g. `'address.street'`
   *
   * If no path is given, this method checks for the error on the current control.
   *
   * @returns whether the given error is present in the control at the given path.
   *
   * If the control is not present, false is returned.
   */
  hasError(errorCode, path) {
    return this.control ? this.control.hasError(errorCode, path) : false;
  }
  /**
   * @description
   * Reports error data for the control with the given path.
   *
   * @param errorCode The code of the error to check
   * @param path A list of control names that designates how to move from the current control
   * to the control that should be queried for errors.
   *
   * @usageNotes
   * For example, for the following `FormGroup`:
   *
   * ```
   * form = new FormGroup({
   *   address: new FormGroup({ street: new FormControl() })
   * });
   * ```
   *
   * The path to the 'street' control from the root form would be 'address' -> 'street'.
   *
   * It can be provided to this method in one of two formats:
   *
   * 1. An array of string control names, e.g. `['address', 'street']`
   * 1. A period-delimited list of control names in one string, e.g. `'address.street'`
   *
   * @returns error data for that particular error. If the control or error is not present,
   * null is returned.
   */
  getError(errorCode, path) {
    return this.control ? this.control.getError(errorCode, path) : null;
  }
}

/**
 * @description
 * A base class for directives that contain multiple registered instances of `NgControl`.
 * Only used by the forms module.
 *
 * @publicApi
 */
class ControlContainer extends AbstractControlDirective {
  /**
   * @description
   * The name for the control
   */
  // TODO(issue/24571): remove '!'.
  name;
  /**
   * @description
   * The top-level form directive for the control.
   */
  get formDirective() {
    return null;
  }
  /**
   * @description
   * The path to this group.
   */
  get path() {
    return null;
  }
}

/**
 * @description
 * A base class that all `FormControl`-based directives extend. It binds a `FormControl`
 * object to a DOM element.
 *
 * @publicApi
 */
class NgControl extends AbstractControlDirective {
  /**
   * @description
   * The parent form for the control.
   *
   * @internal
   */
  _parent = null;
  /**
   * @description
   * The name for the control
   */
  name = null;
  /**
   * @description
   * The value accessor for the control
   */
  valueAccessor = null;
}

// DO NOT REFACTOR!
// Each status is represented by a separate function to make sure that
// advanced Closure Compiler optimizations related to property renaming
// can work correctly.
class AbstractControlStatus {
  _cd;
  constructor(cd) {
    this._cd = cd;
  }
  get isTouched() {
    // track the touched signal
    this._cd?.control?._touched?.();
    return !!this._cd?.control?.touched;
  }
  get isUntouched() {
    return !!this._cd?.control?.untouched;
  }
  get isPristine() {
    // track the pristine signal
    this._cd?.control?._pristine?.();
    return !!this._cd?.control?.pristine;
  }
  get isDirty() {
    // pristine signal already tracked above
    return !!this._cd?.control?.dirty;
  }
  get isValid() {
    // track the status signal
    this._cd?.control?._status?.();
    return !!this._cd?.control?.valid;
  }
  get isInvalid() {
    // status signal already tracked above
    return !!this._cd?.control?.invalid;
  }
  get isPending() {
    // status signal already tracked above
    return !!this._cd?.control?.pending;
  }
  get isSubmitted() {
    // track the submitted signal
    this._cd?._submitted?.();
    // We check for the `submitted` field from `NgForm` and `FormGroupDirective` classes, but
    // we avoid instanceof checks to prevent non-tree-shakable references to those types.
    return !!this._cd?.submitted;
  }
}
const ngControlStatusHost = {
  '[class.ng-untouched]': 'isUntouched',
  '[class.ng-touched]': 'isTouched',
  '[class.ng-pristine]': 'isPristine',
  '[class.ng-dirty]': 'isDirty',
  '[class.ng-valid]': 'isValid',
  '[class.ng-invalid]': 'isInvalid',
  '[class.ng-pending]': 'isPending'
};
const ngGroupStatusHost = {
  ...ngControlStatusHost,
  '[class.ng-submitted]': 'isSubmitted'
};
/**
 * @description
 * Directive automatically applied to Angular form controls that sets CSS classes
 * based on control status.
 *
 * @usageNotes
 *
 * ### CSS classes applied
 *
 * The following classes are applied as the properties become true:
 *
 * * ng-valid
 * * ng-invalid
 * * ng-pending
 * * ng-pristine
 * * ng-dirty
 * * ng-untouched
 * * ng-touched
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let NgControlStatus = /*#__PURE__*/(() => {
  class NgControlStatus extends AbstractControlStatus {
    constructor(cd) {
      super(cd);
    }
    static ɵfac = (() => function NgControlStatus_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgControlStatus)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgControl, 2));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgControlStatus,
      selectors: [["", "formControlName", ""], ["", "ngModel", ""], ["", "formControl", ""]],
      hostVars: 14,
      hostBindings: function NgControlStatus_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵclassProp"]("ng-untouched", ctx.isUntouched)("ng-touched", ctx.isTouched)("ng-pristine", ctx.isPristine)("ng-dirty", ctx.isDirty)("ng-valid", ctx.isValid)("ng-invalid", ctx.isInvalid)("ng-pending", ctx.isPending);
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return NgControlStatus;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Directive automatically applied to Angular form groups that sets CSS classes
 * based on control status (valid/invalid/dirty/etc). On groups, this includes the additional
 * class ng-submitted.
 *
 * @see {@link NgControlStatus}
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let NgControlStatusGroup = /*#__PURE__*/(() => {
  class NgControlStatusGroup extends AbstractControlStatus {
    constructor(cd) {
      super(cd);
    }
    static ɵfac = (() => function NgControlStatusGroup_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgControlStatusGroup)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 10));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgControlStatusGroup,
      selectors: [["", "formGroupName", ""], ["", "formArrayName", ""], ["", "ngModelGroup", ""], ["", "formGroup", ""], ["form", 3, "ngNoForm", ""], ["", "ngForm", ""]],
      hostVars: 16,
      hostBindings: function NgControlStatusGroup_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵclassProp"]("ng-untouched", ctx.isUntouched)("ng-touched", ctx.isTouched)("ng-pristine", ctx.isPristine)("ng-dirty", ctx.isDirty)("ng-valid", ctx.isValid)("ng-invalid", ctx.isInvalid)("ng-pending", ctx.isPending)("ng-submitted", ctx.isSubmitted);
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return NgControlStatusGroup;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const formControlNameExample = `
  <div [formGroup]="myGroup">
    <input formControlName="firstName">
  </div>

  In your class:

  this.myGroup = new FormGroup({
      firstName: new FormControl()
  });`;
const formGroupNameExample = `
  <div [formGroup]="myGroup">
      <div formGroupName="person">
        <input formControlName="firstName">
      </div>
  </div>

  In your class:

  this.myGroup = new FormGroup({
      person: new FormGroup({ firstName: new FormControl() })
  });`;
const formArrayNameExample = `
  <div [formGroup]="myGroup">
    <div formArrayName="cities">
      <div *ngFor="let city of cityArray.controls; index as i">
        <input [formControlName]="i">
      </div>
    </div>
  </div>

  In your class:

  this.cityArray = new FormArray([new FormControl('SF')]);
  this.myGroup = new FormGroup({
    cities: this.cityArray
  });`;
const ngModelGroupExample = `
  <form>
      <div ngModelGroup="person">
        <input [(ngModel)]="person.name" name="firstName">
      </div>
  </form>`;
const ngModelWithFormGroupExample = `
  <div [formGroup]="myGroup">
      <input formControlName="firstName">
      <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
  </div>
`;
function controlParentException(nameOrIndex) {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1050 /* RuntimeErrorCode.FORM_CONTROL_NAME_MISSING_PARENT */, `formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
      directive and pass it an existing FormGroup instance (you can create one in your class).

      ${describeFormControl(nameOrIndex)}

    Example:

    ${formControlNameExample}`);
}
function describeFormControl(nameOrIndex) {
  if (nameOrIndex == null || nameOrIndex === '') {
    return '';
  }
  const valueType = typeof nameOrIndex === 'string' ? 'name' : 'index';
  return `Affected Form Control ${valueType}: "${nameOrIndex}"`;
}
function ngModelGroupException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1051 /* RuntimeErrorCode.FORM_CONTROL_NAME_INSIDE_MODEL_GROUP */, `formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents
      that also have a "form" prefix: formGroupName, formArrayName, or formGroup.

      Option 1:  Update the parent to be formGroupName (reactive form strategy)

      ${formGroupNameExample}

      Option 2: Use ngModel instead of formControlName (template-driven strategy)

      ${ngModelGroupExample}`);
}
function missingFormException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1052 /* RuntimeErrorCode.FORM_GROUP_MISSING_INSTANCE */, `formGroup expects a FormGroup instance. Please pass one in.

      Example:

      ${formControlNameExample}`);
}
function groupParentException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1053 /* RuntimeErrorCode.FORM_GROUP_NAME_MISSING_PARENT */, `formGroupName must be used with a parent formGroup directive.  You'll want to add a formGroup
    directive and pass it an existing FormGroup instance (you can create one in your class).

    Example:

    ${formGroupNameExample}`);
}
function arrayParentException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1054 /* RuntimeErrorCode.FORM_ARRAY_NAME_MISSING_PARENT */, `formArrayName must be used with a parent formGroup directive.  You'll want to add a formGroup
      directive and pass it an existing FormGroup instance (you can create one in your class).

      Example:

      ${formArrayNameExample}`);
}
const disabledAttrWarning = `
  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  // Specify the \`disabled\` property at control creation time:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

  // Controls can also be enabled/disabled after creation:
  form.get('first')?.enable();
  form.get('last')?.disable();
`;
const asyncValidatorsDroppedWithOptsWarning = `
  It looks like you're constructing using a FormControl with both an options argument and an
  async validators argument. Mixing these arguments will cause your async validators to be dropped.
  You should either put all your validators in the options object, or in separate validators
  arguments. For example:

  // Using validators arguments
  fc = new FormControl(42, Validators.required, myAsyncValidator);

  // Using AbstractControlOptions
  fc = new FormControl(42, {validators: Validators.required, asyncValidators: myAV});

  // Do NOT mix them: async validators will be dropped!
  fc = new FormControl(42, {validators: Validators.required}, /* Oops! */ myAsyncValidator);
`;
function ngModelWarning(directiveName) {
  return `
  It looks like you're using ngModel on the same form field as ${directiveName}.
  Support for using the ngModel input property and ngModelChange event with
  reactive form directives has been deprecated in Angular v6 and will be removed
  in a future version of Angular.

  For more information on this, see our API docs here:
  https://angular.io/api/forms/${directiveName === 'formControl' ? 'FormControlDirective' : 'FormControlName'}#use-with-ngmodel
  `;
}
function describeKey(isFormGroup, key) {
  return isFormGroup ? `with name: '${key}'` : `at index: ${key}`;
}
function noControlsError(isFormGroup) {
  return `
    There are no form controls registered with this ${isFormGroup ? 'group' : 'array'} yet. If you're using ngModel,
    you may want to check next tick (e.g. use setTimeout).
  `;
}
function missingControlError(isFormGroup, key) {
  return `Cannot find form control ${describeKey(isFormGroup, key)}`;
}
function missingControlValueError(isFormGroup, key) {
  return `Must supply a value for form control ${describeKey(isFormGroup, key)}`;
}

/**
 * Reports that a control is valid, meaning that no errors exist in the input value.
 *
 * @see {@link status}
 */
const VALID = 'VALID';
/**
 * Reports that a control is invalid, meaning that an error exists in the input value.
 *
 * @see {@link status}
 */
const INVALID = 'INVALID';
/**
 * Reports that a control is pending, meaning that async validation is occurring and
 * errors are not yet available for the input value.
 *
 * @see {@link markAsPending}
 * @see {@link status}
 */
const PENDING = 'PENDING';
/**
 * Reports that a control is disabled, meaning that the control is exempt from ancestor
 * calculations of validity or value.
 *
 * @see {@link markAsDisabled}
 * @see {@link status}
 */
const DISABLED = 'DISABLED';
/**
 * Base class for every event sent by `AbstractControl.events()`
 *
 * @publicApi
 */
class ControlEvent {}
/**
 * Event fired when the value of a control changes.
 *
 * @publicApi
 */
class ValueChangeEvent extends ControlEvent {
  value;
  source;
  constructor(value, source) {
    super();
    this.value = value;
    this.source = source;
  }
}
/**
 * Event fired when the control's pristine state changes (pristine <=> dirty).
 *
 * @publicApi */
class PristineChangeEvent extends ControlEvent {
  pristine;
  source;
  constructor(pristine, source) {
    super();
    this.pristine = pristine;
    this.source = source;
  }
}
/**
 * Event fired when the control's touched status changes (touched <=> untouched).
 *
 * @publicApi
 */
class TouchedChangeEvent extends ControlEvent {
  touched;
  source;
  constructor(touched, source) {
    super();
    this.touched = touched;
    this.source = source;
  }
}
/**
 * Event fired when the control's status changes.
 *
 * @publicApi
 */
class StatusChangeEvent extends ControlEvent {
  status;
  source;
  constructor(status, source) {
    super();
    this.status = status;
    this.source = source;
  }
}
/**
 * Event fired when a form is submitted
 *
 * @publicApi
 */
class FormSubmittedEvent extends ControlEvent {
  source;
  constructor(source) {
    super();
    this.source = source;
  }
}
/**
 * Event fired when a form is reset.
 *
 * @publicApi
 */
class FormResetEvent extends ControlEvent {
  source;
  constructor(source) {
    super();
    this.source = source;
  }
}
/**
 * Gets validators from either an options object or given validators.
 */
function pickValidators(validatorOrOpts) {
  return (isOptionsObj(validatorOrOpts) ? validatorOrOpts.validators : validatorOrOpts) || null;
}
/**
 * Creates validator function by combining provided validators.
 */
function coerceToValidator(validator) {
  return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
/**
 * Gets async validators from either an options object or given validators.
 */
function pickAsyncValidators(asyncValidator, validatorOrOpts) {
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (isOptionsObj(validatorOrOpts) && asyncValidator) {
      console.warn(asyncValidatorsDroppedWithOptsWarning);
    }
  }
  return (isOptionsObj(validatorOrOpts) ? validatorOrOpts.asyncValidators : asyncValidator) || null;
}
/**
 * Creates async validator function by combining provided async validators.
 */
function coerceToAsyncValidator(asyncValidator) {
  return Array.isArray(asyncValidator) ? composeAsyncValidators(asyncValidator) : asyncValidator || null;
}
function isOptionsObj(validatorOrOpts) {
  return validatorOrOpts != null && !Array.isArray(validatorOrOpts) && typeof validatorOrOpts === 'object';
}
function assertControlPresent(parent, isGroup, key) {
  const controls = parent.controls;
  const collection = isGroup ? Object.keys(controls) : controls;
  if (!collection.length) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1000 /* RuntimeErrorCode.NO_CONTROLS */, typeof ngDevMode === 'undefined' || ngDevMode ? noControlsError(isGroup) : '');
  }
  if (!controls[key]) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1001 /* RuntimeErrorCode.MISSING_CONTROL */, typeof ngDevMode === 'undefined' || ngDevMode ? missingControlError(isGroup, key) : '');
  }
}
function assertAllValuesPresent(control, isGroup, value) {
  control._forEachChild((_, key) => {
    if (value[key] === undefined) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1002 /* RuntimeErrorCode.MISSING_CONTROL_VALUE */, typeof ngDevMode === 'undefined' || ngDevMode ? missingControlValueError(isGroup, key) : '');
    }
  });
}
/**
 * This is the base class for `FormControl`, `FormGroup`, and `FormArray`.
 *
 * It provides some of the shared behavior that all controls and groups of controls have, like
 * running validators, calculating status, and resetting state. It also defines the properties
 * that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
 * instantiated directly.
 *
 * The first type parameter TValue represents the value type of the control (`control.value`).
 * The optional type parameter TRawValue  represents the raw value type (`control.getRawValue()`).
 *
 * @see [Forms Guide](guide/forms)
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 * @see [Dynamic Forms Guide](guide/forms/dynamic-forms)
 *
 * @publicApi
 */
class AbstractControl {
  /** @internal */
  _pendingDirty = false;
  /**
   * Indicates that a control has its own pending asynchronous validation in progress.
   * It also stores if the control should emit events when the validation status changes.
   *
   * @internal
   */
  _hasOwnPendingAsyncValidator = null;
  /** @internal */
  _pendingTouched = false;
  /** @internal */
  _onCollectionChange = () => {};
  /** @internal */
  _updateOn;
  _parent = null;
  _asyncValidationSubscription;
  /**
   * Contains the result of merging synchronous validators into a single validator function
   * (combined using `Validators.compose`).
   *
   * @internal
   */
  _composedValidatorFn;
  /**
   * Contains the result of merging asynchronous validators into a single validator function
   * (combined using `Validators.composeAsync`).
   *
   * @internal
   */
  _composedAsyncValidatorFn;
  /**
   * Synchronous validators as they were provided:
   *  - in `AbstractControl` constructor
   *  - as an argument while calling `setValidators` function
   *  - while calling the setter on the `validator` field (e.g. `control.validator = validatorFn`)
   *
   * @internal
   */
  _rawValidators;
  /**
   * Asynchronous validators as they were provided:
   *  - in `AbstractControl` constructor
   *  - as an argument while calling `setAsyncValidators` function
   *  - while calling the setter on the `asyncValidator` field (e.g. `control.asyncValidator =
   * asyncValidatorFn`)
   *
   * @internal
   */
  _rawAsyncValidators;
  /**
   * The current value of the control.
   *
   * * For a `FormControl`, the current value.
   * * For an enabled `FormGroup`, the values of enabled controls as an object
   * with a key-value pair for each member of the group.
   * * For a disabled `FormGroup`, the values of all controls as an object
   * with a key-value pair for each member of the group.
   * * For a `FormArray`, the values of enabled controls as an array.
   *
   */
  value;
  /**
   * Initialize the AbstractControl instance.
   *
   * @param validators The function or array of functions that is used to determine the validity of
   *     this control synchronously.
   * @param asyncValidators The function or array of functions that is used to determine validity of
   *     this control asynchronously.
   */
  constructor(validators, asyncValidators) {
    this._assignValidators(validators);
    this._assignAsyncValidators(asyncValidators);
  }
  /**
   * Returns the function that is used to determine the validity of this control synchronously.
   * If multiple validators have been added, this will be a single composed function.
   * See `Validators.compose()` for additional information.
   */
  get validator() {
    return this._composedValidatorFn;
  }
  set validator(validatorFn) {
    this._rawValidators = this._composedValidatorFn = validatorFn;
  }
  /**
   * Returns the function that is used to determine the validity of this control asynchronously.
   * If multiple validators have been added, this will be a single composed function.
   * See `Validators.compose()` for additional information.
   */
  get asyncValidator() {
    return this._composedAsyncValidatorFn;
  }
  set asyncValidator(asyncValidatorFn) {
    this._rawAsyncValidators = this._composedAsyncValidatorFn = asyncValidatorFn;
  }
  /**
   * The parent control.
   */
  get parent() {
    return this._parent;
  }
  /**
   * The validation status of the control.
   *
   * @see {@link FormControlStatus}
   *
   * These status values are mutually exclusive, so a control cannot be
   * both valid AND invalid or invalid AND disabled.
   */
  get status() {
    return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(this.statusReactive);
  }
  set status(v) {
    (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(() => this.statusReactive.set(v));
  }
  /** @internal */
  _status = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.computed)(() => this.statusReactive()))();
  statusReactive = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.signal)(undefined))();
  /**
   * A control is `valid` when its `status` is `VALID`.
   *
   * @see {@link AbstractControl.status}
   *
   * @returns True if the control has passed all of its validation tests,
   * false otherwise.
   */
  get valid() {
    return this.status === VALID;
  }
  /**
   * A control is `invalid` when its `status` is `INVALID`.
   *
   * @see {@link AbstractControl.status}
   *
   * @returns True if this control has failed one or more of its validation checks,
   * false otherwise.
   */
  get invalid() {
    return this.status === INVALID;
  }
  /**
   * A control is `pending` when its `status` is `PENDING`.
   *
   * @see {@link AbstractControl.status}
   *
   * @returns True if this control is in the process of conducting a validation check,
   * false otherwise.
   */
  get pending() {
    return this.status == PENDING;
  }
  /**
   * A control is `disabled` when its `status` is `DISABLED`.
   *
   * Disabled controls are exempt from validation checks and
   * are not included in the aggregate value of their ancestor
   * controls.
   *
   * @see {@link AbstractControl.status}
   *
   * @returns True if the control is disabled, false otherwise.
   */
  get disabled() {
    return this.status === DISABLED;
  }
  /**
   * A control is `enabled` as long as its `status` is not `DISABLED`.
   *
   * @returns True if the control has any status other than 'DISABLED',
   * false if the status is 'DISABLED'.
   *
   * @see {@link AbstractControl.status}
   *
   */
  get enabled() {
    return this.status !== DISABLED;
  }
  /**
   * An object containing any errors generated by failing validation,
   * or null if there are no errors.
   */
  errors;
  /**
   * A control is `pristine` if the user has not yet changed
   * the value in the UI.
   *
   * @returns True if the user has not yet changed the value in the UI; compare `dirty`.
   * Programmatic changes to a control's value do not mark it dirty.
   */
  get pristine() {
    return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(this.pristineReactive);
  }
  set pristine(v) {
    (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(() => this.pristineReactive.set(v));
  }
  /** @internal */
  _pristine = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.computed)(() => this.pristineReactive()))();
  pristineReactive = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.signal)(true))();
  /**
   * A control is `dirty` if the user has changed the value
   * in the UI.
   *
   * @returns True if the user has changed the value of this control in the UI; compare `pristine`.
   * Programmatic changes to a control's value do not mark it dirty.
   */
  get dirty() {
    return !this.pristine;
  }
  /**
   * True if the control is marked as `touched`.
   *
   * A control is marked `touched` once the user has triggered
   * a `blur` event on it.
   */
  get touched() {
    return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(this.touchedReactive);
  }
  set touched(v) {
    (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(() => this.touchedReactive.set(v));
  }
  /** @internal */
  _touched = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.computed)(() => this.touchedReactive()))();
  touchedReactive = /*#__PURE__*/(() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.signal)(false))();
  /**
   * True if the control has not been marked as touched
   *
   * A control is `untouched` if the user has not yet triggered
   * a `blur` event on it.
   */
  get untouched() {
    return !this.touched;
  }
  /**
   * Exposed as observable, see below.
   *
   * @internal
   */
  _events = /*#__PURE__*/(() => new rxjs__WEBPACK_IMPORTED_MODULE_5__.Subject())();
  /**
   * A multicasting observable that emits an event every time the state of the control changes.
   * It emits for value, status, pristine or touched changes.
   *
   * **Note**: On value change, the emit happens right after a value of this control is updated. The
   * value of a parent control (for example if this FormControl is a part of a FormGroup) is updated
   * later, so accessing a value of a parent control (using the `value` property) from the callback
   * of this event might result in getting a value that has not been updated yet. Subscribe to the
   * `events` of the parent control instead.
   * For other event types, the events are emitted after the parent control has been updated.
   *
   */
  events = /*#__PURE__*/this._events.asObservable();
  /**
   * A multicasting observable that emits an event every time the value of the control changes, in
   * the UI or programmatically. It also emits an event each time you call enable() or disable()
   * without passing along {emitEvent: false} as a function argument.
   *
   * **Note**: the emit happens right after a value of this control is updated. The value of a
   * parent control (for example if this FormControl is a part of a FormGroup) is updated later, so
   * accessing a value of a parent control (using the `value` property) from the callback of this
   * event might result in getting a value that has not been updated yet. Subscribe to the
   * `valueChanges` event of the parent control instead.
   *
   * TODO: this should be piped from events() but is breaking in G3
   */
  valueChanges;
  /**
   * A multicasting observable that emits an event every time the validation `status` of the control
   * recalculates.
   *
   * @see {@link FormControlStatus}
   * @see {@link AbstractControl.status}
   *
   * TODO: this should be piped from events() but is breaking in G3
   */
  statusChanges;
  /**
   * Reports the update strategy of the `AbstractControl` (meaning
   * the event on which the control updates itself).
   * Possible values: `'change'` | `'blur'` | `'submit'`
   * Default value: `'change'`
   */
  get updateOn() {
    return this._updateOn ? this._updateOn : this.parent ? this.parent.updateOn : 'change';
  }
  /**
   * Sets the synchronous validators that are active on this control.  Calling
   * this overwrites any existing synchronous validators.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * If you want to add a new validator without affecting existing ones, consider
   * using `addValidators()` method instead.
   */
  setValidators(validators) {
    this._assignValidators(validators);
  }
  /**
   * Sets the asynchronous validators that are active on this control. Calling this
   * overwrites any existing asynchronous validators.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * If you want to add a new validator without affecting existing ones, consider
   * using `addAsyncValidators()` method instead.
   */
  setAsyncValidators(validators) {
    this._assignAsyncValidators(validators);
  }
  /**
   * Add a synchronous validator or validators to this control, without affecting other validators.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * Adding a validator that already exists will have no effect. If duplicate validator functions
   * are present in the `validators` array, only the first instance would be added to a form
   * control.
   *
   * @param validators The new validator function or functions to add to this control.
   */
  addValidators(validators) {
    this.setValidators(addValidators(validators, this._rawValidators));
  }
  /**
   * Add an asynchronous validator or validators to this control, without affecting other
   * validators.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * Adding a validator that already exists will have no effect.
   *
   * @param validators The new asynchronous validator function or functions to add to this control.
   */
  addAsyncValidators(validators) {
    this.setAsyncValidators(addValidators(validators, this._rawAsyncValidators));
  }
  /**
   * Remove a synchronous validator from this control, without affecting other validators.
   * Validators are compared by function reference; you must pass a reference to the exact same
   * validator function as the one that was originally set. If a provided validator is not found,
   * it is ignored.
   *
   * @usageNotes
   *
   * ### Reference to a ValidatorFn
   *
   * ```
   * // Reference to the RequiredValidator
   * const ctrl = new FormControl<string | null>('', Validators.required);
   * ctrl.removeValidators(Validators.required);
   *
   * // Reference to anonymous function inside MinValidator
   * const minValidator = Validators.min(3);
   * const ctrl = new FormControl<string | null>('', minValidator);
   * expect(ctrl.hasValidator(minValidator)).toEqual(true)
   * expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
   *
   * ctrl.removeValidators(minValidator);
   * ```
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * @param validators The validator or validators to remove.
   */
  removeValidators(validators) {
    this.setValidators(removeValidators(validators, this._rawValidators));
  }
  /**
   * Remove an asynchronous validator from this control, without affecting other validators.
   * Validators are compared by function reference; you must pass a reference to the exact same
   * validator function as the one that was originally set. If a provided validator is not found, it
   * is ignored.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   * @param validators The asynchronous validator or validators to remove.
   */
  removeAsyncValidators(validators) {
    this.setAsyncValidators(removeValidators(validators, this._rawAsyncValidators));
  }
  /**
   * Check whether a synchronous validator function is present on this control. The provided
   * validator must be a reference to the exact same function that was provided.
   *
   * @usageNotes
   *
   * ### Reference to a ValidatorFn
   *
   * ```
   * // Reference to the RequiredValidator
   * const ctrl = new FormControl<number | null>(0, Validators.required);
   * expect(ctrl.hasValidator(Validators.required)).toEqual(true)
   *
   * // Reference to anonymous function inside MinValidator
   * const minValidator = Validators.min(3);
   * const ctrl = new FormControl<number | null>(0, minValidator);
   * expect(ctrl.hasValidator(minValidator)).toEqual(true)
   * expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
   * ```
   *
   * @param validator The validator to check for presence. Compared by function reference.
   * @returns Whether the provided validator was found on this control.
   */
  hasValidator(validator) {
    return hasValidator(this._rawValidators, validator);
  }
  /**
   * Check whether an asynchronous validator function is present on this control. The provided
   * validator must be a reference to the exact same function that was provided.
   *
   * @param validator The asynchronous validator to check for presence. Compared by function
   *     reference.
   * @returns Whether the provided asynchronous validator was found on this control.
   */
  hasAsyncValidator(validator) {
    return hasValidator(this._rawAsyncValidators, validator);
  }
  /**
   * Empties out the synchronous validator list.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   */
  clearValidators() {
    this.validator = null;
  }
  /**
   * Empties out the async validator list.
   *
   * When you add or remove a validator at run time, you must call
   * `updateValueAndValidity()` for the new validation to take effect.
   *
   */
  clearAsyncValidators() {
    this.asyncValidator = null;
  }
  markAsTouched(opts = {}) {
    const changed = this.touched === false;
    this.touched = true;
    const sourceControl = opts.sourceControl ?? this;
    if (this._parent && !opts.onlySelf) {
      this._parent.markAsTouched({
        ...opts,
        sourceControl
      });
    }
    if (changed && opts.emitEvent !== false) {
      this._events.next(new TouchedChangeEvent(true, sourceControl));
    }
  }
  /**
   * Marks the control and all its descendant controls as `touched`.
   * @see {@link markAsTouched()}
   *
   * @param opts Configuration options that determine how the control propagates changes
   * and emits events after marking is applied.
   * * `emitEvent`: When true or not supplied (the default), the `events`
   * observable emits a `TouchedChangeEvent` with the `touched` property being `true`.
   * When false, no events are emitted.
   */
  markAllAsTouched(opts = {}) {
    this.markAsTouched({
      onlySelf: true,
      emitEvent: opts.emitEvent,
      sourceControl: this
    });
    this._forEachChild(control => control.markAllAsTouched(opts));
  }
  markAsUntouched(opts = {}) {
    const changed = this.touched === true;
    this.touched = false;
    this._pendingTouched = false;
    const sourceControl = opts.sourceControl ?? this;
    this._forEachChild(control => {
      control.markAsUntouched({
        onlySelf: true,
        emitEvent: opts.emitEvent,
        sourceControl
      });
    });
    if (this._parent && !opts.onlySelf) {
      this._parent._updateTouched(opts, sourceControl);
    }
    if (changed && opts.emitEvent !== false) {
      this._events.next(new TouchedChangeEvent(false, sourceControl));
    }
  }
  markAsDirty(opts = {}) {
    const changed = this.pristine === true;
    this.pristine = false;
    const sourceControl = opts.sourceControl ?? this;
    if (this._parent && !opts.onlySelf) {
      this._parent.markAsDirty({
        ...opts,
        sourceControl
      });
    }
    if (changed && opts.emitEvent !== false) {
      this._events.next(new PristineChangeEvent(false, sourceControl));
    }
  }
  markAsPristine(opts = {}) {
    const changed = this.pristine === false;
    this.pristine = true;
    this._pendingDirty = false;
    const sourceControl = opts.sourceControl ?? this;
    this._forEachChild(control => {
      /** We don't propagate the source control downwards */
      control.markAsPristine({
        onlySelf: true,
        emitEvent: opts.emitEvent
      });
    });
    if (this._parent && !opts.onlySelf) {
      this._parent._updatePristine(opts, sourceControl);
    }
    if (changed && opts.emitEvent !== false) {
      this._events.next(new PristineChangeEvent(true, sourceControl));
    }
  }
  markAsPending(opts = {}) {
    this.status = PENDING;
    const sourceControl = opts.sourceControl ?? this;
    if (opts.emitEvent !== false) {
      this._events.next(new StatusChangeEvent(this.status, sourceControl));
      this.statusChanges.emit(this.status);
    }
    if (this._parent && !opts.onlySelf) {
      this._parent.markAsPending({
        ...opts,
        sourceControl
      });
    }
  }
  disable(opts = {}) {
    // If parent has been marked artificially dirty we don't want to re-calculate the
    // parent's dirtiness based on the children.
    const skipPristineCheck = this._parentMarkedDirty(opts.onlySelf);
    this.status = DISABLED;
    this.errors = null;
    this._forEachChild(control => {
      /** We don't propagate the source control downwards */
      control.disable({
        ...opts,
        onlySelf: true
      });
    });
    this._updateValue();
    const sourceControl = opts.sourceControl ?? this;
    if (opts.emitEvent !== false) {
      this._events.next(new ValueChangeEvent(this.value, sourceControl));
      this._events.next(new StatusChangeEvent(this.status, sourceControl));
      this.valueChanges.emit(this.value);
      this.statusChanges.emit(this.status);
    }
    this._updateAncestors({
      ...opts,
      skipPristineCheck
    }, this);
    this._onDisabledChange.forEach(changeFn => changeFn(true));
  }
  /**
   * Enables the control. This means the control is included in validation checks and
   * the aggregate value of its parent. Its status recalculates based on its value and
   * its validators.
   *
   * By default, if the control has children, all children are enabled.
   *
   * @see {@link AbstractControl.status}
   *
   * @param opts Configure options that control how the control propagates changes and
   * emits events when marked as untouched
   * * `onlySelf`: When true, mark only this control. When false or not supplied,
   * marks all direct ancestors. Default is false.
   * * `emitEvent`: When true or not supplied (the default), the `statusChanges`,
   * `valueChanges` and `events`
   * observables emit events with the latest status and value when the control is enabled.
   * When false, no events are emitted.
   */
  enable(opts = {}) {
    // If parent has been marked artificially dirty we don't want to re-calculate the
    // parent's dirtiness based on the children.
    const skipPristineCheck = this._parentMarkedDirty(opts.onlySelf);
    this.status = VALID;
    this._forEachChild(control => {
      control.enable({
        ...opts,
        onlySelf: true
      });
    });
    this.updateValueAndValidity({
      onlySelf: true,
      emitEvent: opts.emitEvent
    });
    this._updateAncestors({
      ...opts,
      skipPristineCheck
    }, this);
    this._onDisabledChange.forEach(changeFn => changeFn(false));
  }
  _updateAncestors(opts, sourceControl) {
    if (this._parent && !opts.onlySelf) {
      this._parent.updateValueAndValidity(opts);
      if (!opts.skipPristineCheck) {
        this._parent._updatePristine({}, sourceControl);
      }
      this._parent._updateTouched({}, sourceControl);
    }
  }
  /**
   * Sets the parent of the control
   *
   * @param parent The new parent.
   */
  setParent(parent) {
    this._parent = parent;
  }
  /**
   * The raw value of this control. For most control implementations, the raw value will include
   * disabled children.
   */
  getRawValue() {
    return this.value;
  }
  updateValueAndValidity(opts = {}) {
    this._setInitialStatus();
    this._updateValue();
    if (this.enabled) {
      const shouldHaveEmitted = this._cancelExistingSubscription();
      this.errors = this._runValidator();
      this.status = this._calculateStatus();
      if (this.status === VALID || this.status === PENDING) {
        // If the canceled subscription should have emitted
        // we make sure the async validator emits the status change on completion
        this._runAsyncValidator(shouldHaveEmitted, opts.emitEvent);
      }
    }
    const sourceControl = opts.sourceControl ?? this;
    if (opts.emitEvent !== false) {
      this._events.next(new ValueChangeEvent(this.value, sourceControl));
      this._events.next(new StatusChangeEvent(this.status, sourceControl));
      this.valueChanges.emit(this.value);
      this.statusChanges.emit(this.status);
    }
    if (this._parent && !opts.onlySelf) {
      this._parent.updateValueAndValidity({
        ...opts,
        sourceControl
      });
    }
  }
  /** @internal */
  _updateTreeValidity(opts = {
    emitEvent: true
  }) {
    this._forEachChild(ctrl => ctrl._updateTreeValidity(opts));
    this.updateValueAndValidity({
      onlySelf: true,
      emitEvent: opts.emitEvent
    });
  }
  _setInitialStatus() {
    this.status = this._allControlsDisabled() ? DISABLED : VALID;
  }
  _runValidator() {
    return this.validator ? this.validator(this) : null;
  }
  _runAsyncValidator(shouldHaveEmitted, emitEvent) {
    if (this.asyncValidator) {
      this.status = PENDING;
      this._hasOwnPendingAsyncValidator = {
        emitEvent: emitEvent !== false
      };
      const obs = toObservable(this.asyncValidator(this));
      this._asyncValidationSubscription = obs.subscribe(errors => {
        this._hasOwnPendingAsyncValidator = null;
        // This will trigger the recalculation of the validation status, which depends on
        // the state of the asynchronous validation (whether it is in progress or not). So, it is
        // necessary that we have updated the `_hasOwnPendingAsyncValidator` boolean flag first.
        this.setErrors(errors, {
          emitEvent,
          shouldHaveEmitted
        });
      });
    }
  }
  _cancelExistingSubscription() {
    if (this._asyncValidationSubscription) {
      this._asyncValidationSubscription.unsubscribe();
      // we're cancelling the validator subscribtion, we keep if it should have emitted
      // because we want to emit eventually if it was required at least once.
      const shouldHaveEmitted = this._hasOwnPendingAsyncValidator?.emitEvent ?? false;
      this._hasOwnPendingAsyncValidator = null;
      return shouldHaveEmitted;
    }
    return false;
  }
  setErrors(errors, opts = {}) {
    this.errors = errors;
    this._updateControlsErrors(opts.emitEvent !== false, this, opts.shouldHaveEmitted);
  }
  /**
   * Retrieves a child control given the control's name or path.
   *
   * @param path A dot-delimited string or array of string/number values that define the path to the
   * control. If a string is provided, passing it as a string literal will result in improved type
   * information. Likewise, if an array is provided, passing it `as const` will cause improved type
   * information to be available.
   *
   * @usageNotes
   * ### Retrieve a nested control
   *
   * For example, to get a `name` control nested within a `person` sub-group:
   *
   * * `this.form.get('person.name');`
   *
   * -OR-
   *
   * * `this.form.get(['person', 'name'] as const);` // `as const` gives improved typings
   *
   * ### Retrieve a control in a FormArray
   *
   * When accessing an element inside a FormArray, you can use an element index.
   * For example, to get a `price` control from the first element in an `items` array you can use:
   *
   * * `this.form.get('items.0.price');`
   *
   * -OR-
   *
   * * `this.form.get(['items', 0, 'price']);`
   */
  get(path) {
    let currPath = path;
    if (currPath == null) return null;
    if (!Array.isArray(currPath)) currPath = currPath.split('.');
    if (currPath.length === 0) return null;
    return currPath.reduce((control, name) => control && control._find(name), this);
  }
  /**
   * @description
   * Reports error data for the control with the given path.
   *
   * @param errorCode The code of the error to check
   * @param path A list of control names that designates how to move from the current control
   * to the control that should be queried for errors.
   *
   * @usageNotes
   * For example, for the following `FormGroup`:
   *
   * ```
   * form = new FormGroup({
   *   address: new FormGroup({ street: new FormControl() })
   * });
   * ```
   *
   * The path to the 'street' control from the root form would be 'address' -> 'street'.
   *
   * It can be provided to this method in one of two formats:
   *
   * 1. An array of string control names, e.g. `['address', 'street']`
   * 1. A period-delimited list of control names in one string, e.g. `'address.street'`
   *
   * @returns error data for that particular error. If the control or error is not present,
   * null is returned.
   */
  getError(errorCode, path) {
    const control = path ? this.get(path) : this;
    return control && control.errors ? control.errors[errorCode] : null;
  }
  /**
   * @description
   * Reports whether the control with the given path has the error specified.
   *
   * @param errorCode The code of the error to check
   * @param path A list of control names that designates how to move from the current control
   * to the control that should be queried for errors.
   *
   * @usageNotes
   * For example, for the following `FormGroup`:
   *
   * ```
   * form = new FormGroup({
   *   address: new FormGroup({ street: new FormControl() })
   * });
   * ```
   *
   * The path to the 'street' control from the root form would be 'address' -> 'street'.
   *
   * It can be provided to this method in one of two formats:
   *
   * 1. An array of string control names, e.g. `['address', 'street']`
   * 1. A period-delimited list of control names in one string, e.g. `'address.street'`
   *
   * If no path is given, this method checks for the error on the current control.
   *
   * @returns whether the given error is present in the control at the given path.
   *
   * If the control is not present, false is returned.
   */
  hasError(errorCode, path) {
    return !!this.getError(errorCode, path);
  }
  /**
   * Retrieves the top-level ancestor of this control.
   */
  get root() {
    let x = this;
    while (x._parent) {
      x = x._parent;
    }
    return x;
  }
  /** @internal */
  _updateControlsErrors(emitEvent, changedControl, shouldHaveEmitted) {
    this.status = this._calculateStatus();
    if (emitEvent) {
      this.statusChanges.emit(this.status);
    }
    // The Events Observable expose a slight different bevahior than the statusChanges obs
    // An async validator will still emit a StatusChangeEvent is a previously cancelled
    // async validator has emitEvent set to true
    if (emitEvent || shouldHaveEmitted) {
      this._events.next(new StatusChangeEvent(this.status, changedControl));
    }
    if (this._parent) {
      this._parent._updateControlsErrors(emitEvent, changedControl, shouldHaveEmitted);
    }
  }
  /** @internal */
  _initObservables() {
    this.valueChanges = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
    this.statusChanges = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  }
  _calculateStatus() {
    if (this._allControlsDisabled()) return DISABLED;
    if (this.errors) return INVALID;
    if (this._hasOwnPendingAsyncValidator || this._anyControlsHaveStatus(PENDING)) return PENDING;
    if (this._anyControlsHaveStatus(INVALID)) return INVALID;
    return VALID;
  }
  /** @internal */
  _anyControlsHaveStatus(status) {
    return this._anyControls(control => control.status === status);
  }
  /** @internal */
  _anyControlsDirty() {
    return this._anyControls(control => control.dirty);
  }
  /** @internal */
  _anyControlsTouched() {
    return this._anyControls(control => control.touched);
  }
  /** @internal */
  _updatePristine(opts, changedControl) {
    const newPristine = !this._anyControlsDirty();
    const changed = this.pristine !== newPristine;
    this.pristine = newPristine;
    if (this._parent && !opts.onlySelf) {
      this._parent._updatePristine(opts, changedControl);
    }
    if (changed) {
      this._events.next(new PristineChangeEvent(this.pristine, changedControl));
    }
  }
  /** @internal */
  _updateTouched(opts = {}, changedControl) {
    this.touched = this._anyControlsTouched();
    this._events.next(new TouchedChangeEvent(this.touched, changedControl));
    if (this._parent && !opts.onlySelf) {
      this._parent._updateTouched(opts, changedControl);
    }
  }
  /** @internal */
  _onDisabledChange = [];
  /** @internal */
  _registerOnCollectionChange(fn) {
    this._onCollectionChange = fn;
  }
  /** @internal */
  _setUpdateStrategy(opts) {
    if (isOptionsObj(opts) && opts.updateOn != null) {
      this._updateOn = opts.updateOn;
    }
  }
  /**
   * Check to see if parent has been marked artificially dirty.
   *
   * @internal
   */
  _parentMarkedDirty(onlySelf) {
    const parentDirty = this._parent && this._parent.dirty;
    return !onlySelf && !!parentDirty && !this._parent._anyControlsDirty();
  }
  /** @internal */
  _find(name) {
    return null;
  }
  /**
   * Internal implementation of the `setValidators` method. Needs to be separated out into a
   * different method, because it is called in the constructor and it can break cases where
   * a control is extended.
   */
  _assignValidators(validators) {
    this._rawValidators = Array.isArray(validators) ? validators.slice() : validators;
    this._composedValidatorFn = coerceToValidator(this._rawValidators);
  }
  /**
   * Internal implementation of the `setAsyncValidators` method. Needs to be separated out into a
   * different method, because it is called in the constructor and it can break cases where
   * a control is extended.
   */
  _assignAsyncValidators(validators) {
    this._rawAsyncValidators = Array.isArray(validators) ? validators.slice() : validators;
    this._composedAsyncValidatorFn = coerceToAsyncValidator(this._rawAsyncValidators);
  }
}

/**
 * Tracks the value and validity state of a group of `FormControl` instances.
 *
 * A `FormGroup` aggregates the values of each child `FormControl` into one object,
 * with each control name as the key.  It calculates its status by reducing the status values
 * of its children. For example, if one of the controls in a group is invalid, the entire
 * group becomes invalid.
 *
 * `FormGroup` is one of the four fundamental building blocks used to define forms in Angular,
 * along with `FormControl`, `FormArray`, and `FormRecord`.
 *
 * When instantiating a `FormGroup`, pass in a collection of child controls as the first
 * argument. The key for each child registers the name for the control.
 *
 * `FormGroup` is intended for use cases where the keys are known ahead of time.
 * If you need to dynamically add and remove controls, use {@link FormRecord} instead.
 *
 * `FormGroup` accepts an optional type parameter `TControl`, which is an object type with inner
 * control types as values.
 *
 * @usageNotes
 *
 * ### Create a form group with 2 controls
 *
 * ```
 * const form = new FormGroup({
 *   first: new FormControl('Nancy', Validators.minLength(2)),
 *   last: new FormControl('Drew'),
 * });
 *
 * console.log(form.value);   // {first: 'Nancy', last; 'Drew'}
 * console.log(form.status);  // 'VALID'
 * ```
 *
 * ### The type argument, and optional controls
 *
 * `FormGroup` accepts one generic argument, which is an object containing its inner controls.
 * This type will usually be inferred automatically, but you can always specify it explicitly if you
 * wish.
 *
 * If you have controls that are optional (i.e. they can be removed, you can use the `?` in the
 * type):
 *
 * ```
 * const form = new FormGroup<{
 *   first: FormControl<string|null>,
 *   middle?: FormControl<string|null>, // Middle name is optional.
 *   last: FormControl<string|null>,
 * }>({
 *   first: new FormControl('Nancy'),
 *   last: new FormControl('Drew'),
 * });
 * ```
 *
 * ### Create a form group with a group-level validator
 *
 * You include group-level validators as the second arg, or group-level async
 * validators as the third arg. These come in handy when you want to perform validation
 * that considers the value of more than one child control.
 *
 * ```
 * const form = new FormGroup({
 *   password: new FormControl('', Validators.minLength(2)),
 *   passwordConfirm: new FormControl('', Validators.minLength(2)),
 * }, passwordMatchValidator);
 *
 *
 * function passwordMatchValidator(g: FormGroup) {
 *    return g.get('password').value === g.get('passwordConfirm').value
 *       ? null : {'mismatch': true};
 * }
 * ```
 *
 * Like `FormControl` instances, you choose to pass in
 * validators and async validators as part of an options object.
 *
 * ```
 * const form = new FormGroup({
 *   password: new FormControl('')
 *   passwordConfirm: new FormControl('')
 * }, { validators: passwordMatchValidator, asyncValidators: otherValidator });
 * ```
 *
 * ### Set the updateOn property for all controls in a form group
 *
 * The options object is used to set a default value for each child
 * control's `updateOn` property. If you set `updateOn` to `'blur'` at the
 * group level, all child controls default to 'blur', unless the child
 * has explicitly specified a different `updateOn` value.
 *
 * ```ts
 * const c = new FormGroup({
 *   one: new FormControl()
 * }, { updateOn: 'blur' });
 * ```
 *
 * ### Using a FormGroup with optional controls
 *
 * It is possible to have optional controls in a FormGroup. An optional control can be removed later
 * using `removeControl`, and can be omitted when calling `reset`. Optional controls must be
 * declared optional in the group's type.
 *
 * ```ts
 * const c = new FormGroup<{one?: FormControl<string>}>({
 *   one: new FormControl('')
 * });
 * ```
 *
 * Notice that `c.value.one` has type `string|null|undefined`. This is because calling `c.reset({})`
 * without providing the optional key `one` will cause it to become `null`.
 *
 * @publicApi
 */
class FormGroup extends AbstractControl {
  /**
   * Creates a new `FormGroup` instance.
   *
   * @param controls A collection of child controls. The key for each child is the name
   * under which it is registered.
   *
   * @param validatorOrOpts A synchronous validator function, or an array of
   * such functions, or an `AbstractControlOptions` object that contains validation functions
   * and a validation trigger.
   *
   * @param asyncValidator A single async validator or array of async validator functions
   *
   */
  constructor(controls, validatorOrOpts, asyncValidator) {
    super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
    (typeof ngDevMode === 'undefined' || ngDevMode) && validateFormGroupControls(controls);
    this.controls = controls;
    this._initObservables();
    this._setUpdateStrategy(validatorOrOpts);
    this._setUpControls();
    this.updateValueAndValidity({
      onlySelf: true,
      // If `asyncValidator` is present, it will trigger control status change from `PENDING` to
      // `VALID` or `INVALID`. The status should be broadcasted via the `statusChanges` observable,
      // so we set `emitEvent` to `true` to allow that during the control creation process.
      emitEvent: !!this.asyncValidator
    });
  }
  controls;
  registerControl(name, control) {
    if (this.controls[name]) return this.controls[name];
    this.controls[name] = control;
    control.setParent(this);
    control._registerOnCollectionChange(this._onCollectionChange);
    return control;
  }
  addControl(name, control, options = {}) {
    this.registerControl(name, control);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
    this._onCollectionChange();
  }
  /**
   * Remove a control from this group. In a strongly-typed group, required controls cannot be
   * removed.
   *
   * This method also updates the value and validity of the control.
   *
   * @param name The control name to remove from the collection
   * @param options Specifies whether this FormGroup instance should emit events after a
   *     control is removed.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control is
   * removed. When false, no events are emitted.
   */
  removeControl(name, options = {}) {
    if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
    delete this.controls[name];
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
    this._onCollectionChange();
  }
  setControl(name, control, options = {}) {
    if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
    delete this.controls[name];
    if (control) this.registerControl(name, control);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
    this._onCollectionChange();
  }
  contains(controlName) {
    return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled;
  }
  /**
   * Sets the value of the `FormGroup`. It accepts an object that matches
   * the structure of the group, with control names as keys.
   *
   * @usageNotes
   * ### Set the complete value for the form group
   *
   * ```
   * const form = new FormGroup({
   *   first: new FormControl(),
   *   last: new FormControl()
   * });
   *
   * console.log(form.value);   // {first: null, last: null}
   *
   * form.setValue({first: 'Nancy', last: 'Drew'});
   * console.log(form.value);   // {first: 'Nancy', last: 'Drew'}
   * ```
   *
   * @throws When strict checks fail, such as setting the value of a control
   * that doesn't exist or if you exclude a value of a control that does exist.
   *
   * @param value The new value for the control that matches the structure of the group.
   * @param options Configuration options that determine how the control propagates changes
   * and emits events after the value changes.
   * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
   * updateValueAndValidity} method.
   *
   * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
   * false.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges`
   * observables emit events with the latest status and value when the control value is updated.
   * When false, no events are emitted.
   */
  setValue(value, options = {}) {
    assertAllValuesPresent(this, true, value);
    Object.keys(value).forEach(name => {
      assertControlPresent(this, true, name);
      this.controls[name].setValue(value[name], {
        onlySelf: true,
        emitEvent: options.emitEvent
      });
    });
    this.updateValueAndValidity(options);
  }
  /**
   * Patches the value of the `FormGroup`. It accepts an object with control
   * names as keys, and does its best to match the values to the correct controls
   * in the group.
   *
   * It accepts both super-sets and sub-sets of the group without throwing an error.
   *
   * @usageNotes
   * ### Patch the value for a form group
   *
   * ```
   * const form = new FormGroup({
   *    first: new FormControl(),
   *    last: new FormControl()
   * });
   * console.log(form.value);   // {first: null, last: null}
   *
   * form.patchValue({first: 'Nancy'});
   * console.log(form.value);   // {first: 'Nancy', last: null}
   * ```
   *
   * @param value The object that matches the structure of the group.
   * @param options Configuration options that determine how the control propagates changes and
   * emits events after the value is patched.
   * * `onlySelf`: When true, each change only affects this control and not its parent. Default is
   * true.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control value
   * is updated. When false, no events are emitted. The configuration options are passed to
   * the {@link AbstractControl#updateValueAndValidity updateValueAndValidity} method.
   */
  patchValue(value, options = {}) {
    // Even though the `value` argument type doesn't allow `null` and `undefined` values, the
    // `patchValue` can be called recursively and inner data structures might have these values, so
    // we just ignore such cases when a field containing FormGroup instance receives `null` or
    // `undefined` as a value.
    if (value == null /* both `null` and `undefined` */) return;
    Object.keys(value).forEach(name => {
      // The compiler cannot see through the uninstantiated conditional type of `this.controls`, so
      // `as any` is required.
      const control = this.controls[name];
      if (control) {
        control.patchValue(/* Guaranteed to be present, due to the outer forEach. */value[name], {
          onlySelf: true,
          emitEvent: options.emitEvent
        });
      }
    });
    this.updateValueAndValidity(options);
  }
  /**
   * Resets the `FormGroup`, marks all descendants `pristine` and `untouched` and sets
   * the value of all descendants to their default values, or null if no defaults were provided.
   *
   * You reset to a specific form state by passing in a map of states
   * that matches the structure of your form, with control names as keys. The state
   * is a standalone value or a form state object with both a value and a disabled
   * status.
   *
   * @param value Resets the control with an initial value,
   * or an object that defines the initial value and disabled state.
   *
   * @param options Configuration options that determine how the control propagates changes
   * and emits events when the group is reset.
   * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
   * false.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges`
   * observables emit events with the latest status and value when the control is reset.
   * When false, no events are emitted.
   * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
   * updateValueAndValidity} method.
   *
   * @usageNotes
   *
   * ### Reset the form group values
   *
   * ```ts
   * const form = new FormGroup({
   *   first: new FormControl('first name'),
   *   last: new FormControl('last name')
   * });
   *
   * console.log(form.value);  // {first: 'first name', last: 'last name'}
   *
   * form.reset({ first: 'name', last: 'last name' });
   *
   * console.log(form.value);  // {first: 'name', last: 'last name'}
   * ```
   *
   * ### Reset the form group values and disabled status
   *
   * ```
   * const form = new FormGroup({
   *   first: new FormControl('first name'),
   *   last: new FormControl('last name')
   * });
   *
   * form.reset({
   *   first: {value: 'name', disabled: true},
   *   last: 'last'
   * });
   *
   * console.log(form.value);  // {last: 'last'}
   * console.log(form.get('first').status);  // 'DISABLED'
   * ```
   */
  reset(value = {}, options = {}) {
    this._forEachChild((control, name) => {
      control.reset(value ? value[name] : null, {
        onlySelf: true,
        emitEvent: options.emitEvent
      });
    });
    this._updatePristine(options, this);
    this._updateTouched(options, this);
    this.updateValueAndValidity(options);
  }
  /**
   * The aggregate value of the `FormGroup`, including any disabled controls.
   *
   * Retrieves all values regardless of disabled status.
   */
  getRawValue() {
    return this._reduceChildren({}, (acc, control, name) => {
      acc[name] = control.getRawValue();
      return acc;
    });
  }
  /** @internal */
  _syncPendingControls() {
    let subtreeUpdated = this._reduceChildren(false, (updated, child) => {
      return child._syncPendingControls() ? true : updated;
    });
    if (subtreeUpdated) this.updateValueAndValidity({
      onlySelf: true
    });
    return subtreeUpdated;
  }
  /** @internal */
  _forEachChild(cb) {
    Object.keys(this.controls).forEach(key => {
      // The list of controls can change (for ex. controls might be removed) while the loop
      // is running (as a result of invoking Forms API in `valueChanges` subscription), so we
      // have to null check before invoking the callback.
      const control = this.controls[key];
      control && cb(control, key);
    });
  }
  /** @internal */
  _setUpControls() {
    this._forEachChild(control => {
      control.setParent(this);
      control._registerOnCollectionChange(this._onCollectionChange);
    });
  }
  /** @internal */
  _updateValue() {
    this.value = this._reduceValue();
  }
  /** @internal */
  _anyControls(condition) {
    for (const [controlName, control] of Object.entries(this.controls)) {
      if (this.contains(controlName) && condition(control)) {
        return true;
      }
    }
    return false;
  }
  /** @internal */
  _reduceValue() {
    let acc = {};
    return this._reduceChildren(acc, (acc, control, name) => {
      if (control.enabled || this.disabled) {
        acc[name] = control.value;
      }
      return acc;
    });
  }
  /** @internal */
  _reduceChildren(initValue, fn) {
    let res = initValue;
    this._forEachChild((control, name) => {
      res = fn(res, control, name);
    });
    return res;
  }
  /** @internal */
  _allControlsDisabled() {
    for (const controlName of Object.keys(this.controls)) {
      if (this.controls[controlName].enabled) {
        return false;
      }
    }
    return Object.keys(this.controls).length > 0 || this.disabled;
  }
  /** @internal */
  _find(name) {
    return this.controls.hasOwnProperty(name) ? this.controls[name] : null;
  }
}
/**
 * Will validate that none of the controls has a key with a dot
 * Throws other wise
 */
function validateFormGroupControls(controls) {
  const invalidKeys = Object.keys(controls).filter(key => key.includes('.'));
  if (invalidKeys.length > 0) {
    // TODO: make this an error once there are no more uses in G3
    console.warn(`FormGroup keys cannot include \`.\`, please replace the keys for: ${invalidKeys.join(',')}.`);
  }
}
const UntypedFormGroup = FormGroup;
/**
 * @description
 * Asserts that the given control is an instance of `FormGroup`
 *
 * @publicApi
 */
const isFormGroup = control => control instanceof FormGroup;
/**
 * Tracks the value and validity state of a collection of `FormControl` instances, each of which has
 * the same value type.
 *
 * `FormRecord` is very similar to {@link FormGroup}, except it can be used with a dynamic keys,
 * with controls added and removed as needed.
 *
 * `FormRecord` accepts one generic argument, which describes the type of the controls it contains.
 *
 * @usageNotes
 *
 * ```
 * let numbers = new FormRecord({bill: new FormControl('415-123-456')});
 * numbers.addControl('bob', new FormControl('415-234-567'));
 * numbers.removeControl('bill');
 * ```
 *
 * @publicApi
 */
class FormRecord extends FormGroup {}
/**
 * @description
 * Asserts that the given control is an instance of `FormRecord`
 *
 * @publicApi
 */
const isFormRecord = control => control instanceof FormRecord;

/**
 * Token to provide to allow SetDisabledState to always be called when a CVA is added, regardless of
 * whether the control is disabled or enabled.
 *
 * @see {@link FormsModule#withconfig}
 */
const CALL_SET_DISABLED_STATE = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken('CallSetDisabledState', {
  providedIn: 'root',
  factory: () => setDisabledStateDefault
});
/**
 * Whether to use the fixed setDisabledState behavior by default.
 */
const setDisabledStateDefault = 'always';
function controlPath(name, parent) {
  return [...parent.path, name];
}
/**
 * Links a Form control and a Form directive by setting up callbacks (such as `onChange`) on both
 * instances. This function is typically invoked when form directive is being initialized.
 *
 * @param control Form control instance that should be linked.
 * @param dir Directive that should be linked with a given control.
 */
function setUpControl(control, dir, callSetDisabledState = setDisabledStateDefault) {
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (!control) _throwError(dir, 'Cannot find control with');
    if (!dir.valueAccessor) _throwMissingValueAccessorError(dir);
  }
  setUpValidators(control, dir);
  dir.valueAccessor.writeValue(control.value);
  // The legacy behavior only calls the CVA's `setDisabledState` if the control is disabled.
  // If the `callSetDisabledState` option is set to `always`, then this bug is fixed and
  // the method is always called.
  if (control.disabled || callSetDisabledState === 'always') {
    dir.valueAccessor.setDisabledState?.(control.disabled);
  }
  setUpViewChangePipeline(control, dir);
  setUpModelChangePipeline(control, dir);
  setUpBlurPipeline(control, dir);
  setUpDisabledChangeHandler(control, dir);
}
/**
 * Reverts configuration performed by the `setUpControl` control function.
 * Effectively disconnects form control with a given form directive.
 * This function is typically invoked when corresponding form directive is being destroyed.
 *
 * @param control Form control which should be cleaned up.
 * @param dir Directive that should be disconnected from a given control.
 * @param validateControlPresenceOnChange Flag that indicates whether onChange handler should
 *     contain asserts to verify that it's not called once directive is destroyed. We need this flag
 *     to avoid potentially breaking changes caused by better control cleanup introduced in #39235.
 */
function cleanUpControl(control, dir, validateControlPresenceOnChange = true) {
  const noop = () => {
    if (validateControlPresenceOnChange && (typeof ngDevMode === 'undefined' || ngDevMode)) {
      _noControlError(dir);
    }
  };
  // The `valueAccessor` field is typically defined on FromControl and FormControlName directive
  // instances and there is a logic in `selectValueAccessor` function that throws if it's not the
  // case. We still check the presence of `valueAccessor` before invoking its methods to make sure
  // that cleanup works correctly if app code or tests are setup to ignore the error thrown from
  // `selectValueAccessor`. See https://github.com/angular/angular/issues/40521.
  if (dir.valueAccessor) {
    dir.valueAccessor.registerOnChange(noop);
    dir.valueAccessor.registerOnTouched(noop);
  }
  cleanUpValidators(control, dir);
  if (control) {
    dir._invokeOnDestroyCallbacks();
    control._registerOnCollectionChange(() => {});
  }
}
function registerOnValidatorChange(validators, onChange) {
  validators.forEach(validator => {
    if (validator.registerOnValidatorChange) validator.registerOnValidatorChange(onChange);
  });
}
/**
 * Sets up disabled change handler function on a given form control if ControlValueAccessor
 * associated with a given directive instance supports the `setDisabledState` call.
 *
 * @param control Form control where disabled change handler should be setup.
 * @param dir Corresponding directive instance associated with this control.
 */
function setUpDisabledChangeHandler(control, dir) {
  if (dir.valueAccessor.setDisabledState) {
    const onDisabledChange = isDisabled => {
      dir.valueAccessor.setDisabledState(isDisabled);
    };
    control.registerOnDisabledChange(onDisabledChange);
    // Register a callback function to cleanup disabled change handler
    // from a control instance when a directive is destroyed.
    dir._registerOnDestroy(() => {
      control._unregisterOnDisabledChange(onDisabledChange);
    });
  }
}
/**
 * Sets up sync and async directive validators on provided form control.
 * This function merges validators from the directive into the validators of the control.
 *
 * @param control Form control where directive validators should be setup.
 * @param dir Directive instance that contains validators to be setup.
 */
function setUpValidators(control, dir) {
  const validators = getControlValidators(control);
  if (dir.validator !== null) {
    control.setValidators(mergeValidators(validators, dir.validator));
  } else if (typeof validators === 'function') {
    // If sync validators are represented by a single validator function, we force the
    // `Validators.compose` call to happen by executing the `setValidators` function with
    // an array that contains that function. We need this to avoid possible discrepancies in
    // validators behavior, so sync validators are always processed by the `Validators.compose`.
    // Note: we should consider moving this logic inside the `setValidators` function itself, so we
    // have consistent behavior on AbstractControl API level. The same applies to the async
    // validators logic below.
    control.setValidators([validators]);
  }
  const asyncValidators = getControlAsyncValidators(control);
  if (dir.asyncValidator !== null) {
    control.setAsyncValidators(mergeValidators(asyncValidators, dir.asyncValidator));
  } else if (typeof asyncValidators === 'function') {
    control.setAsyncValidators([asyncValidators]);
  }
  // Re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4
  const onValidatorChange = () => control.updateValueAndValidity();
  registerOnValidatorChange(dir._rawValidators, onValidatorChange);
  registerOnValidatorChange(dir._rawAsyncValidators, onValidatorChange);
}
/**
 * Cleans up sync and async directive validators on provided form control.
 * This function reverts the setup performed by the `setUpValidators` function, i.e.
 * removes directive-specific validators from a given control instance.
 *
 * @param control Form control from where directive validators should be removed.
 * @param dir Directive instance that contains validators to be removed.
 * @returns true if a control was updated as a result of this action.
 */
function cleanUpValidators(control, dir) {
  let isControlUpdated = false;
  if (control !== null) {
    if (dir.validator !== null) {
      const validators = getControlValidators(control);
      if (Array.isArray(validators) && validators.length > 0) {
        // Filter out directive validator function.
        const updatedValidators = validators.filter(validator => validator !== dir.validator);
        if (updatedValidators.length !== validators.length) {
          isControlUpdated = true;
          control.setValidators(updatedValidators);
        }
      }
    }
    if (dir.asyncValidator !== null) {
      const asyncValidators = getControlAsyncValidators(control);
      if (Array.isArray(asyncValidators) && asyncValidators.length > 0) {
        // Filter out directive async validator function.
        const updatedAsyncValidators = asyncValidators.filter(asyncValidator => asyncValidator !== dir.asyncValidator);
        if (updatedAsyncValidators.length !== asyncValidators.length) {
          isControlUpdated = true;
          control.setAsyncValidators(updatedAsyncValidators);
        }
      }
    }
  }
  // Clear onValidatorChange callbacks by providing a noop function.
  const noop = () => {};
  registerOnValidatorChange(dir._rawValidators, noop);
  registerOnValidatorChange(dir._rawAsyncValidators, noop);
  return isControlUpdated;
}
function setUpViewChangePipeline(control, dir) {
  dir.valueAccessor.registerOnChange(newValue => {
    control._pendingValue = newValue;
    control._pendingChange = true;
    control._pendingDirty = true;
    if (control.updateOn === 'change') updateControl(control, dir);
  });
}
function setUpBlurPipeline(control, dir) {
  dir.valueAccessor.registerOnTouched(() => {
    control._pendingTouched = true;
    if (control.updateOn === 'blur' && control._pendingChange) updateControl(control, dir);
    if (control.updateOn !== 'submit') control.markAsTouched();
  });
}
function updateControl(control, dir) {
  if (control._pendingDirty) control.markAsDirty();
  control.setValue(control._pendingValue, {
    emitModelToViewChange: false
  });
  dir.viewToModelUpdate(control._pendingValue);
  control._pendingChange = false;
}
function setUpModelChangePipeline(control, dir) {
  const onChange = (newValue, emitModelEvent) => {
    // control -> view
    dir.valueAccessor.writeValue(newValue);
    // control -> ngModel
    if (emitModelEvent) dir.viewToModelUpdate(newValue);
  };
  control.registerOnChange(onChange);
  // Register a callback function to cleanup onChange handler
  // from a control instance when a directive is destroyed.
  dir._registerOnDestroy(() => {
    control._unregisterOnChange(onChange);
  });
}
/**
 * Links a FormGroup or FormArray instance and corresponding Form directive by setting up validators
 * present in the view.
 *
 * @param control FormGroup or FormArray instance that should be linked.
 * @param dir Directive that provides view validators.
 */
function setUpFormContainer(control, dir) {
  if (control == null && (typeof ngDevMode === 'undefined' || ngDevMode)) _throwError(dir, 'Cannot find control with');
  setUpValidators(control, dir);
}
/**
 * Reverts the setup performed by the `setUpFormContainer` function.
 *
 * @param control FormGroup or FormArray instance that should be cleaned up.
 * @param dir Directive that provided view validators.
 * @returns true if a control was updated as a result of this action.
 */
function cleanUpFormContainer(control, dir) {
  return cleanUpValidators(control, dir);
}
function _noControlError(dir) {
  return _throwError(dir, 'There is no FormControl instance attached to form control element with');
}
function _throwError(dir, message) {
  const messageEnd = _describeControlLocation(dir);
  throw new Error(`${message} ${messageEnd}`);
}
function _describeControlLocation(dir) {
  const path = dir.path;
  if (path && path.length > 1) return `path: '${path.join(' -> ')}'`;
  if (path?.[0]) return `name: '${path}'`;
  return 'unspecified name attribute';
}
function _throwMissingValueAccessorError(dir) {
  const loc = _describeControlLocation(dir);
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](-1203 /* RuntimeErrorCode.NG_MISSING_VALUE_ACCESSOR */, `No value accessor for form control ${loc}.`);
}
function _throwInvalidValueAccessorError(dir) {
  const loc = _describeControlLocation(dir);
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1200 /* RuntimeErrorCode.NG_VALUE_ACCESSOR_NOT_PROVIDED */, `Value accessor was not provided as an array for form control with ${loc}. ` + `Check that the \`NG_VALUE_ACCESSOR\` token is configured as a \`multi: true\` provider.`);
}
function isPropertyUpdated(changes, viewModel) {
  if (!changes.hasOwnProperty('model')) return false;
  const change = changes['model'];
  if (change.isFirstChange()) return true;
  return !Object.is(viewModel, change.currentValue);
}
function isBuiltInAccessor(valueAccessor) {
  // Check if a given value accessor is an instance of a class that directly extends
  // `BuiltInControlValueAccessor` one.
  return Object.getPrototypeOf(valueAccessor.constructor) === BuiltInControlValueAccessor;
}
function syncPendingControls(form, directives) {
  form._syncPendingControls();
  directives.forEach(dir => {
    const control = dir.control;
    if (control.updateOn === 'submit' && control._pendingChange) {
      dir.viewToModelUpdate(control._pendingValue);
      control._pendingChange = false;
    }
  });
}
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
function selectValueAccessor(dir, valueAccessors) {
  if (!valueAccessors) return null;
  if (!Array.isArray(valueAccessors) && (typeof ngDevMode === 'undefined' || ngDevMode)) _throwInvalidValueAccessorError(dir);
  let defaultAccessor = undefined;
  let builtinAccessor = undefined;
  let customAccessor = undefined;
  valueAccessors.forEach(v => {
    if (v.constructor === DefaultValueAccessor) {
      defaultAccessor = v;
    } else if (isBuiltInAccessor(v)) {
      if (builtinAccessor && (typeof ngDevMode === 'undefined' || ngDevMode)) _throwError(dir, 'More than one built-in value accessor matches form control with');
      builtinAccessor = v;
    } else {
      if (customAccessor && (typeof ngDevMode === 'undefined' || ngDevMode)) _throwError(dir, 'More than one custom value accessor matches form control with');
      customAccessor = v;
    }
  });
  if (customAccessor) return customAccessor;
  if (builtinAccessor) return builtinAccessor;
  if (defaultAccessor) return defaultAccessor;
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    _throwError(dir, 'No valid value accessor for form control with');
  }
  return null;
}
function removeListItem$1(list, el) {
  const index = list.indexOf(el);
  if (index > -1) list.splice(index, 1);
}
// TODO(kara): remove after deprecation period
function _ngModelWarning(name, type, instance, warningConfig) {
  if (warningConfig === 'never') return;
  if ((warningConfig === null || warningConfig === 'once') && !type._ngModelWarningSentOnce || warningConfig === 'always' && !instance._ngModelWarningSent) {
    console.warn(ngModelWarning(name));
    type._ngModelWarningSentOnce = true;
    instance._ngModelWarningSent = true;
  }
}
const formDirectiveProvider$1 = {
  provide: ControlContainer,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => NgForm)
};
const resolvedPromise$1 = /*#__PURE__*/(() => Promise.resolve())();
/**
 * @description
 * Creates a top-level `FormGroup` instance and binds it to a form
 * to track aggregate form value and validation status.
 *
 * As soon as you import the `FormsModule`, this directive becomes active by default on
 * all `<form>` tags.  You don't need to add a special selector.
 *
 * You optionally export the directive into a local template variable using `ngForm` as the key
 * (ex: `#myForm="ngForm"`). This is optional, but useful.  Many properties from the underlying
 * `FormGroup` instance are duplicated on the directive itself, so a reference to it
 * gives you access to the aggregate value and validity status of the form, as well as
 * user interaction properties like `dirty` and `touched`.
 *
 * To register child controls with the form, use `NgModel` with a `name`
 * attribute. You may use `NgModelGroup` to create sub-groups within the form.
 *
 * If necessary, listen to the directive's `ngSubmit` event to be notified when the user has
 * triggered a form submission. The `ngSubmit` event emits the original form
 * submission event.
 *
 * In template driven forms, all `<form>` tags are automatically tagged as `NgForm`.
 * To import the `FormsModule` but skip its usage in some forms,
 * for example, to use native HTML5 validation, add the `ngNoForm` and the `<form>`
 * tags won't create an `NgForm` directive. In reactive forms, using `ngNoForm` is
 * unnecessary because the `<form>` tags are inert. In that case, you would
 * refrain from using the `formGroup` directive.
 *
 * @usageNotes
 *
 * ### Listening for form submission
 *
 * The following example shows how to capture the form values from the "ngSubmit" event.
 *
 * {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
 *
 * ### Setting the update options
 *
 * The following example shows you how to change the "updateOn" option from its default using
 * ngFormOptions.
 *
 * ```html
 * <form [ngFormOptions]="{updateOn: 'blur'}">
 *    <input name="one" ngModel>  <!-- this ngModel will update on blur -->
 * </form>
 * ```
 *
 * ### Native DOM validation UI
 *
 * In order to prevent the native DOM form validation UI from interfering with Angular's form
 * validation, Angular automatically adds the `novalidate` attribute on any `<form>` whenever
 * `FormModule` or `ReactiveFormModule` are imported into the application.
 * If you want to explicitly enable native DOM validation UI with Angular forms, you can add the
 * `ngNativeValidate` attribute to the `<form>` element:
 *
 * ```html
 * <form ngNativeValidate>
 *   ...
 * </form>
 * ```
 *
 * @ngModule FormsModule
 * @publicApi
 */
let NgForm = /*#__PURE__*/(() => {
  class NgForm extends ControlContainer {
    callSetDisabledState;
    /**
     * @description
     * Returns whether the form submission has been triggered.
     */
    get submitted() {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(this.submittedReactive);
    }
    /** @internal */
    _submitted = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.computed)(() => this.submittedReactive()))();
    submittedReactive = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.signal)(false))();
    _directives = (() => new Set())();
    /**
     * @description
     * The `FormGroup` instance created for this form.
     */
    form;
    /**
     * @description
     * Event emitter for the "ngSubmit" event
     */
    ngSubmit = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter())();
    /**
     * @description
     * Tracks options for the `NgForm` instance.
     *
     * **updateOn**: Sets the default `updateOn` value for all child `NgModels` below it
     * unless explicitly set by a child `NgModel` using `ngModelOptions`). Defaults to 'change'.
     * Possible values: `'change'` | `'blur'` | `'submit'`.
     *
     */
    // TODO(issue/24571): remove '!'.
    options;
    constructor(validators, asyncValidators, callSetDisabledState) {
      super();
      this.callSetDisabledState = callSetDisabledState;
      this.form = new FormGroup({}, composeValidators(validators), composeAsyncValidators(asyncValidators));
    }
    /** @nodoc */
    ngAfterViewInit() {
      this._setUpdateStrategy();
    }
    /**
     * @description
     * The directive instance.
     */
    get formDirective() {
      return this;
    }
    /**
     * @description
     * The internal `FormGroup` instance.
     */
    get control() {
      return this.form;
    }
    /**
     * @description
     * Returns an array representing the path to this group. Because this directive
     * always lives at the top level of a form, it is always an empty array.
     */
    get path() {
      return [];
    }
    /**
     * @description
     * Returns a map of the controls in this group.
     */
    get controls() {
      return this.form.controls;
    }
    /**
     * @description
     * Method that sets up the control directive in this group, re-calculates its value
     * and validity, and adds the instance to the internal list of directives.
     *
     * @param dir The `NgModel` directive instance.
     */
    addControl(dir) {
      resolvedPromise$1.then(() => {
        const container = this._findContainer(dir.path);
        dir.control = container.registerControl(dir.name, dir.control);
        setUpControl(dir.control, dir, this.callSetDisabledState);
        dir.control.updateValueAndValidity({
          emitEvent: false
        });
        this._directives.add(dir);
      });
    }
    /**
     * @description
     * Retrieves the `FormControl` instance from the provided `NgModel` directive.
     *
     * @param dir The `NgModel` directive instance.
     */
    getControl(dir) {
      return this.form.get(dir.path);
    }
    /**
     * @description
     * Removes the `NgModel` instance from the internal list of directives
     *
     * @param dir The `NgModel` directive instance.
     */
    removeControl(dir) {
      resolvedPromise$1.then(() => {
        const container = this._findContainer(dir.path);
        if (container) {
          container.removeControl(dir.name);
        }
        this._directives.delete(dir);
      });
    }
    /**
     * @description
     * Adds a new `NgModelGroup` directive instance to the form.
     *
     * @param dir The `NgModelGroup` directive instance.
     */
    addFormGroup(dir) {
      resolvedPromise$1.then(() => {
        const container = this._findContainer(dir.path);
        const group = new FormGroup({});
        setUpFormContainer(group, dir);
        container.registerControl(dir.name, group);
        group.updateValueAndValidity({
          emitEvent: false
        });
      });
    }
    /**
     * @description
     * Removes the `NgModelGroup` directive instance from the form.
     *
     * @param dir The `NgModelGroup` directive instance.
     */
    removeFormGroup(dir) {
      resolvedPromise$1.then(() => {
        const container = this._findContainer(dir.path);
        if (container) {
          container.removeControl(dir.name);
        }
      });
    }
    /**
     * @description
     * Retrieves the `FormGroup` for a provided `NgModelGroup` directive instance
     *
     * @param dir The `NgModelGroup` directive instance.
     */
    getFormGroup(dir) {
      return this.form.get(dir.path);
    }
    /**
     * Sets the new value for the provided `NgControl` directive.
     *
     * @param dir The `NgControl` directive instance.
     * @param value The new value for the directive's control.
     */
    updateModel(dir, value) {
      resolvedPromise$1.then(() => {
        const ctrl = this.form.get(dir.path);
        ctrl.setValue(value);
      });
    }
    /**
     * @description
     * Sets the value for this `FormGroup`.
     *
     * @param value The new value
     */
    setValue(value) {
      this.control.setValue(value);
    }
    /**
     * @description
     * Method called when the "submit" event is triggered on the form.
     * Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
     *
     * @param $event The "submit" event object
     */
    onSubmit($event) {
      this.submittedReactive.set(true);
      syncPendingControls(this.form, this._directives);
      this.ngSubmit.emit($event);
      // Forms with `method="dialog"` have some special behavior
      // that won't reload the page and that shouldn't be prevented.
      return $event?.target?.method === 'dialog';
    }
    /**
     * @description
     * Method called when the "reset" event is triggered on the form.
     */
    onReset() {
      this.resetForm();
    }
    /**
     * @description
     * Resets the form to an initial value and resets its submitted status.
     *
     * @param value The new value for the form.
     */
    resetForm(value = undefined) {
      this.form.reset(value);
      this.submittedReactive.set(false);
    }
    _setUpdateStrategy() {
      if (this.options && this.options.updateOn != null) {
        this.form._updateOn = this.options.updateOn;
      }
    }
    _findContainer(path) {
      path.pop();
      return path.length ? this.form.get(path) : this.form;
    }
    static ɵfac = (() => function NgForm_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgForm)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](CALL_SET_DISABLED_STATE, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgForm,
      selectors: [["form", 3, "ngNoForm", "", 3, "formGroup", ""], ["ng-form"], ["", "ngForm", ""]],
      hostBindings: function NgForm_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("submit", function NgForm_submit_HostBindingHandler($event) {
            return ctx.onSubmit($event);
          })("reset", function NgForm_reset_HostBindingHandler() {
            return ctx.onReset();
          });
        }
      },
      inputs: {
        options: [0, "ngFormOptions", "options"]
      },
      outputs: {
        ngSubmit: "ngSubmit"
      },
      exportAs: ["ngForm"],
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formDirectiveProvider$1]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return NgForm;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function removeListItem(list, el) {
  const index = list.indexOf(el);
  if (index > -1) list.splice(index, 1);
}
function isFormControlState(formState) {
  return typeof formState === 'object' && formState !== null && Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
}
const FormControl = class FormControl extends AbstractControl {
  /** @publicApi */
  defaultValue = null;
  /** @internal */
  _onChange = [];
  /** @internal */
  _pendingValue;
  /** @internal */
  _pendingChange = false;
  constructor(
  // formState and defaultValue will only be null if T is nullable
  formState = null, validatorOrOpts, asyncValidator) {
    super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
    this._applyFormState(formState);
    this._setUpdateStrategy(validatorOrOpts);
    this._initObservables();
    this.updateValueAndValidity({
      onlySelf: true,
      // If `asyncValidator` is present, it will trigger control status change from `PENDING` to
      // `VALID` or `INVALID`.
      // The status should be broadcasted via the `statusChanges` observable, so we set
      // `emitEvent` to `true` to allow that during the control creation process.
      emitEvent: !!this.asyncValidator
    });
    if (isOptionsObj(validatorOrOpts) && (validatorOrOpts.nonNullable || validatorOrOpts.initialValueIsDefault)) {
      if (isFormControlState(formState)) {
        this.defaultValue = formState.value;
      } else {
        this.defaultValue = formState;
      }
    }
  }
  setValue(value, options = {}) {
    this.value = this._pendingValue = value;
    if (this._onChange.length && options.emitModelToViewChange !== false) {
      this._onChange.forEach(changeFn => changeFn(this.value, options.emitViewToModelChange !== false));
    }
    this.updateValueAndValidity(options);
  }
  patchValue(value, options = {}) {
    this.setValue(value, options);
  }
  reset(formState = this.defaultValue, options = {}) {
    this._applyFormState(formState);
    this.markAsPristine(options);
    this.markAsUntouched(options);
    this.setValue(this.value, options);
    this._pendingChange = false;
  }
  /**  @internal */
  _updateValue() {}
  /**  @internal */
  _anyControls(condition) {
    return false;
  }
  /**  @internal */
  _allControlsDisabled() {
    return this.disabled;
  }
  registerOnChange(fn) {
    this._onChange.push(fn);
  }
  /** @internal */
  _unregisterOnChange(fn) {
    removeListItem(this._onChange, fn);
  }
  registerOnDisabledChange(fn) {
    this._onDisabledChange.push(fn);
  }
  /** @internal */
  _unregisterOnDisabledChange(fn) {
    removeListItem(this._onDisabledChange, fn);
  }
  /** @internal */
  _forEachChild(cb) {}
  /** @internal */
  _syncPendingControls() {
    if (this.updateOn === 'submit') {
      if (this._pendingDirty) this.markAsDirty();
      if (this._pendingTouched) this.markAsTouched();
      if (this._pendingChange) {
        this.setValue(this._pendingValue, {
          onlySelf: true,
          emitModelToViewChange: false
        });
        return true;
      }
    }
    return false;
  }
  _applyFormState(formState) {
    if (isFormControlState(formState)) {
      this.value = this._pendingValue = formState.value;
      formState.disabled ? this.disable({
        onlySelf: true,
        emitEvent: false
      }) : this.enable({
        onlySelf: true,
        emitEvent: false
      });
    } else {
      this.value = this._pendingValue = formState;
    }
  }
};
const UntypedFormControl = FormControl;
/**
 * @description
 * Asserts that the given control is an instance of `FormControl`
 *
 * @publicApi
 */
const isFormControl = control => control instanceof FormControl;

/**
 * @description
 * A base class for code shared between the `NgModelGroup` and `FormGroupName` directives.
 *
 * @publicApi
 */
let AbstractFormGroupDirective = /*#__PURE__*/(() => {
  class AbstractFormGroupDirective extends ControlContainer {
    /**
     * @description
     * The parent control for the group
     *
     * @internal
     */
    // TODO(issue/24571): remove '!'.
    _parent;
    /** @nodoc */
    ngOnInit() {
      this._checkParentType();
      // Register the group with its parent group.
      this.formDirective.addFormGroup(this);
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this.formDirective) {
        // Remove the group from its parent group.
        this.formDirective.removeFormGroup(this);
      }
    }
    /**
     * @description
     * The `FormGroup` bound to this directive.
     */
    get control() {
      return this.formDirective.getFormGroup(this);
    }
    /**
     * @description
     * The path to this group from the top-level directive.
     */
    get path() {
      return controlPath(this.name == null ? this.name : this.name.toString(), this._parent);
    }
    /**
     * @description
     * The top-level directive for this group if present, otherwise null.
     */
    get formDirective() {
      return this._parent ? this._parent.formDirective : null;
    }
    /** @internal */
    _checkParentType() {}
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵAbstractFormGroupDirective_BaseFactory;
      return function AbstractFormGroupDirective_Factory(__ngFactoryType__) {
        return (ɵAbstractFormGroupDirective_BaseFactory || (ɵAbstractFormGroupDirective_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](AbstractFormGroupDirective)))(__ngFactoryType__ || AbstractFormGroupDirective);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: AbstractFormGroupDirective,
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return AbstractFormGroupDirective;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function modelParentException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1350 /* RuntimeErrorCode.NGMODEL_IN_FORM_GROUP */, `
    ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
    formGroup's partner directive "formControlName" instead.  Example:

    ${formControlNameExample}

    Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

    Example:

    ${ngModelWithFormGroupExample}`);
}
function formGroupNameException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1351 /* RuntimeErrorCode.NGMODEL_IN_FORM_GROUP_NAME */, `
    ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.

    Option 1: Use formControlName instead of ngModel (reactive strategy):

    ${formGroupNameExample}

    Option 2:  Update ngModel's parent be ngModelGroup (template-driven strategy):

    ${ngModelGroupExample}`);
}
function missingNameException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1352 /* RuntimeErrorCode.NGMODEL_WITHOUT_NAME */, `If ngModel is used within a form tag, either the name attribute must be set or the form
    control must be defined as 'standalone' in ngModelOptions.

    Example 1: <input [(ngModel)]="person.firstName" name="first">
    Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">`);
}
function modelGroupParentException() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1353 /* RuntimeErrorCode.NGMODELGROUP_IN_FORM_GROUP */, `
    ngModelGroup cannot be used with a parent formGroup directive.

    Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):

    ${formGroupNameExample}

    Option 2:  Use a regular form tag instead of the formGroup directive (template-driven strategy):

    ${ngModelGroupExample}`);
}
const modelGroupProvider = {
  provide: ControlContainer,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => NgModelGroup)
};
/**
 * @description
 * Creates and binds a `FormGroup` instance to a DOM element.
 *
 * This directive can only be used as a child of `NgForm` (within `<form>` tags).
 *
 * Use this directive to validate a sub-group of your form separately from the
 * rest of your form, or if some values in your domain model make more sense
 * to consume together in a nested object.
 *
 * Provide a name for the sub-group and it will become the key
 * for the sub-group in the form's full value. If you need direct access, export the directive into
 * a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`).
 *
 * @usageNotes
 *
 * ### Consuming controls in a grouping
 *
 * The following example shows you how to combine controls together in a sub-group
 * of the form.
 *
 * {@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'}
 *
 * @ngModule FormsModule
 * @publicApi
 */
let NgModelGroup = /*#__PURE__*/(() => {
  class NgModelGroup extends AbstractFormGroupDirective {
    /**
     * @description
     * Tracks the name of the `NgModelGroup` bound to the directive. The name corresponds
     * to a key in the parent `NgForm`.
     */
    name = '';
    constructor(parent, validators, asyncValidators) {
      super();
      this._parent = parent;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
    }
    /** @internal */
    _checkParentType() {
      if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw modelGroupParentException();
      }
    }
    static ɵfac = (() => function NgModelGroup_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgModelGroup)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 5), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgModelGroup,
      selectors: [["", "ngModelGroup", ""]],
      inputs: {
        name: [0, "ngModelGroup", "name"]
      },
      exportAs: ["ngModelGroup"],
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([modelGroupProvider]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return NgModelGroup;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const formControlBinding$1 = {
  provide: NgControl,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => NgModel)
};
/**
 * `ngModel` forces an additional change detection run when its inputs change:
 * E.g.:
 * ```
 * <div>{{myModel.valid}}</div>
 * <input [(ngModel)]="myValue" #myModel="ngModel">
 * ```
 * I.e. `ngModel` can export itself on the element and then be used in the template.
 * Normally, this would result in expressions before the `input` that use the exported directive
 * to have an old value as they have been
 * dirty checked before. As this is a very common case for `ngModel`, we added this second change
 * detection run.
 *
 * Notes:
 * - this is just one extra run no matter how many `ngModel`s have been changed.
 * - this is a general problem when using `exportAs` for directives!
 */
const resolvedPromise = /*#__PURE__*/(() => Promise.resolve())();
/**
 * @description
 * Creates a `FormControl` instance from a [domain
 * model](https://en.wikipedia.org/wiki/Domain_model) and binds it to a form control element.
 *
 * The `FormControl` instance tracks the value, user interaction, and
 * validation status of the control and keeps the view synced with the model. If used
 * within a parent form, the directive also registers itself with the form as a child
 * control.
 *
 * This directive is used by itself or as part of a larger form. Use the
 * `ngModel` selector to activate it.
 *
 * It accepts a domain model as an optional `Input`. If you have a one-way binding
 * to `ngModel` with `[]` syntax, changing the domain model's value in the component
 * class sets the value in the view. If you have a two-way binding with `[()]` syntax
 * (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to
 * the domain model in your class.
 *
 * To inspect the properties of the associated `FormControl` (like the validity state),
 * export the directive into a local template variable using `ngModel` as the key (ex:
 * `#myVar="ngModel"`). You can then access the control using the directive's `control` property.
 * However, the most commonly used properties (like `valid` and `dirty`) also exist on the control
 * for direct access. See a full list of properties directly available in
 * `AbstractControlDirective`.
 *
 * @see {@link RadioControlValueAccessor}
 * @see {@link SelectControlValueAccessor}
 *
 * @usageNotes
 *
 * ### Using ngModel on a standalone control
 *
 * The following examples show a simple standalone control using `ngModel`:
 *
 * {@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'}
 *
 * When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute
 * so that the control can be registered with the parent form under that name.
 *
 * In the context of a parent form, it's often unnecessary to include one-way or two-way binding,
 * as the parent form syncs the value for you. You access its properties by exporting it into a
 * local template variable using `ngForm` such as (`#f="ngForm"`). Use the variable where
 * needed on form submission.
 *
 * If you do need to populate initial values into your form, using a one-way binding for
 * `ngModel` tends to be sufficient as long as you use the exported form's value rather
 * than the domain model's value on submit.
 *
 * ### Using ngModel within a form
 *
 * The following example shows controls using `ngModel` within a form:
 *
 * {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
 *
 * ### Using a standalone ngModel within a group
 *
 * The following example shows you how to use a standalone ngModel control
 * within a form. This controls the display of the form, but doesn't contain form data.
 *
 * ```html
 * <form>
 *   <input name="login" ngModel placeholder="Login">
 *   <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
 * </form>
 * <!-- form value: {login: ''} -->
 * ```
 *
 * ### Setting the ngModel `name` attribute through options
 *
 * The following example shows you an alternate way to set the name attribute. Here,
 * an attribute identified as name is used within a custom form control component. To still be able
 * to specify the NgModel's name, you must specify it using the `ngModelOptions` input instead.
 *
 * ```html
 * <form>
 *   <my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
 *   </my-custom-form-control>
 * </form>
 * <!-- form value: {user: ''} -->
 * ```
 *
 * @ngModule FormsModule
 * @publicApi
 */
let NgModel = /*#__PURE__*/(() => {
  class NgModel extends NgControl {
    _changeDetectorRef;
    callSetDisabledState;
    control = (() => new FormControl())();
    // At runtime we coerce arbitrary values assigned to the "disabled" input to a "boolean".
    // This is not reflected in the type of the property because outside of templates, consumers
    // should only deal with booleans. In templates, a string is allowed for convenience and to
    // match the native "disabled attribute" semantics which can be observed on input elements.
    // This static member tells the compiler that values of type "string" can also be assigned
    // to the input in a template.
    /** @nodoc */
    static ngAcceptInputType_isDisabled;
    /** @internal */
    _registered = false;
    /**
     * Internal reference to the view model value.
     * @nodoc
     */
    viewModel;
    /**
     * @description
     * Tracks the name bound to the directive. If a parent form exists, it
     * uses this name as a key to retrieve this control's value.
     */
    name = '';
    /**
     * @description
     * Tracks whether the control is disabled.
     */
    // TODO(issue/24571): remove '!'.
    isDisabled;
    /**
     * @description
     * Tracks the value bound to this directive.
     */
    model;
    /**
     * @description
     * Tracks the configuration options for this `ngModel` instance.
     *
     * **name**: An alternative to setting the name attribute on the form control element. See
     * the [example](api/forms/NgModel#using-ngmodel-on-a-standalone-control) for using `NgModel`
     * as a standalone control.
     *
     * **standalone**: When set to true, the `ngModel` will not register itself with its parent form,
     * and acts as if it's not in the form. Defaults to false. If no parent form exists, this option
     * has no effect.
     *
     * **updateOn**: Defines the event upon which the form control value and validity update.
     * Defaults to 'change'. Possible values: `'change'` | `'blur'` | `'submit'`.
     *
     */
    // TODO(issue/24571): remove '!'.
    options;
    /**
     * @description
     * Event emitter for producing the `ngModelChange` event after
     * the view model updates.
     */
    update = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter())();
    constructor(parent, validators, asyncValidators, valueAccessors, _changeDetectorRef, callSetDisabledState) {
      super();
      this._changeDetectorRef = _changeDetectorRef;
      this.callSetDisabledState = callSetDisabledState;
      this._parent = parent;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
      this.valueAccessor = selectValueAccessor(this, valueAccessors);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      this._checkForErrors();
      if (!this._registered || 'name' in changes) {
        if (this._registered) {
          this._checkName();
          if (this.formDirective) {
            // We can't call `formDirective.removeControl(this)`, because the `name` has already been
            // changed. We also can't reset the name temporarily since the logic in `removeControl`
            // is inside a promise and it won't run immediately. We work around it by giving it an
            // object with the same shape instead.
            const oldName = changes['name'].previousValue;
            this.formDirective.removeControl({
              name: oldName,
              path: this._getPath(oldName)
            });
          }
        }
        this._setUpControl();
      }
      if ('isDisabled' in changes) {
        this._updateDisabled(changes);
      }
      if (isPropertyUpdated(changes, this.viewModel)) {
        this._updateValue(this.model);
        this.viewModel = this.model;
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      this.formDirective && this.formDirective.removeControl(this);
    }
    /**
     * @description
     * Returns an array that represents the path from the top-level form to this control.
     * Each index is the string name of the control on that level.
     */
    get path() {
      return this._getPath(this.name);
    }
    /**
     * @description
     * The top-level directive for this control if present, otherwise null.
     */
    get formDirective() {
      return this._parent ? this._parent.formDirective : null;
    }
    /**
     * @description
     * Sets the new value for the view model and emits an `ngModelChange` event.
     *
     * @param newValue The new value emitted by `ngModelChange`.
     */
    viewToModelUpdate(newValue) {
      this.viewModel = newValue;
      this.update.emit(newValue);
    }
    _setUpControl() {
      this._setUpdateStrategy();
      this._isStandalone() ? this._setUpStandalone() : this.formDirective.addControl(this);
      this._registered = true;
    }
    _setUpdateStrategy() {
      if (this.options && this.options.updateOn != null) {
        this.control._updateOn = this.options.updateOn;
      }
    }
    _isStandalone() {
      return !this._parent || !!(this.options && this.options.standalone);
    }
    _setUpStandalone() {
      setUpControl(this.control, this, this.callSetDisabledState);
      this.control.updateValueAndValidity({
        emitEvent: false
      });
    }
    _checkForErrors() {
      if (!this._isStandalone()) {
        this._checkParentType();
      }
      this._checkName();
    }
    _checkParentType() {
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        if (!(this._parent instanceof NgModelGroup) && this._parent instanceof AbstractFormGroupDirective) {
          throw formGroupNameException();
        } else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
          throw modelParentException();
        }
      }
    }
    _checkName() {
      if (this.options && this.options.name) this.name = this.options.name;
      if (!this._isStandalone() && !this.name && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw missingNameException();
      }
    }
    _updateValue(value) {
      resolvedPromise.then(() => {
        this.control.setValue(value, {
          emitViewToModelChange: false
        });
        this._changeDetectorRef?.markForCheck();
      });
    }
    _updateDisabled(changes) {
      const disabledValue = changes['isDisabled'].currentValue;
      // checking for 0 to avoid breaking change
      const isDisabled = disabledValue !== 0 && (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.booleanAttribute)(disabledValue);
      resolvedPromise.then(() => {
        if (isDisabled && !this.control.disabled) {
          this.control.disable();
        } else if (!isDisabled && this.control.disabled) {
          this.control.enable();
        }
        this._changeDetectorRef?.markForCheck();
      });
    }
    _getPath(controlName) {
      return this._parent ? controlPath(controlName, this._parent) : [controlName];
    }
    static ɵfac = (() => function NgModel_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgModel)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 9), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALUE_ACCESSOR, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ChangeDetectorRef, 8), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](CALL_SET_DISABLED_STATE, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgModel,
      selectors: [["", "ngModel", "", 3, "formControlName", "", 3, "formControl", ""]],
      inputs: {
        name: "name",
        isDisabled: [0, "disabled", "isDisabled"],
        model: [0, "ngModel", "model"],
        options: [0, "ngModelOptions", "options"]
      },
      outputs: {
        update: "ngModelChange"
      },
      exportAs: ["ngModel"],
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formControlBinding$1]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return NgModel;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @description
 *
 * Adds `novalidate` attribute to all forms by default.
 *
 * `novalidate` is used to disable browser's native form validation.
 *
 * If you want to use native validation with Angular forms, just add `ngNativeValidate` attribute:
 *
 * ```
 * <form ngNativeValidate></form>
 * ```
 *
 * @publicApi
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 */
let ɵNgNoValidate = /*#__PURE__*/(() => {
  class ɵNgNoValidate {
    static ɵfac = (() => function ɵNgNoValidate_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ɵNgNoValidate)();
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: ɵNgNoValidate,
      selectors: [["form", 3, "ngNoForm", "", 3, "ngNativeValidate", ""]],
      hostAttrs: ["novalidate", ""],
      standalone: false
    }))();
  }
  return ɵNgNoValidate;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const NUMBER_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => NumberValueAccessor),
  multi: true
};
/**
 * @description
 * The `ControlValueAccessor` for writing a number value and listening to number input changes.
 * The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
 * directives.
 *
 * @usageNotes
 *
 * ### Using a number input with a reactive form.
 *
 * The following example shows how to use a number input with a reactive form.
 *
 * ```ts
 * const totalCountControl = new FormControl();
 * ```
 *
 * ```
 * <input type="number" [formControl]="totalCountControl">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let NumberValueAccessor = /*#__PURE__*/(() => {
  class NumberValueAccessor extends BuiltInControlValueAccessor {
    /**
     * Sets the "value" property on the input element.
     * @nodoc
     */
    writeValue(value) {
      // The value needs to be normalized for IE9, otherwise it is set to 'null' when null
      const normalizedValue = value == null ? '' : value;
      this.setProperty('value', normalizedValue);
    }
    /**
     * Registers a function called when the control value changes.
     * @nodoc
     */
    registerOnChange(fn) {
      this.onChange = value => {
        fn(value == '' ? null : parseFloat(value));
      };
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵNumberValueAccessor_BaseFactory;
      return function NumberValueAccessor_Factory(__ngFactoryType__) {
        return (ɵNumberValueAccessor_BaseFactory || (ɵNumberValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](NumberValueAccessor)))(__ngFactoryType__ || NumberValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NumberValueAccessor,
      selectors: [["input", "type", "number", "formControlName", ""], ["input", "type", "number", "formControl", ""], ["input", "type", "number", "ngModel", ""]],
      hostBindings: function NumberValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("input", function NumberValueAccessor_input_HostBindingHandler($event) {
            return ctx.onChange($event.target.value);
          })("blur", function NumberValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([NUMBER_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return NumberValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const RADIO_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => RadioControlValueAccessor),
  multi: true
};
function throwNameError() {
  throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1202 /* RuntimeErrorCode.NAME_AND_FORM_CONTROL_NAME_MUST_MATCH */, `
      If you define both a name and a formControlName attribute on your radio button, their values
      must match. Ex: <input type="radio" formControlName="food" name="food">
    `);
}
/**
 * @description
 * Class used by Angular to track radio buttons. For internal use only.
 */
let RadioControlRegistry = /*#__PURE__*/(() => {
  class RadioControlRegistry {
    _accessors = [];
    /**
     * @description
     * Adds a control to the internal registry. For internal use only.
     */
    add(control, accessor) {
      this._accessors.push([control, accessor]);
    }
    /**
     * @description
     * Removes a control from the internal registry. For internal use only.
     */
    remove(accessor) {
      for (let i = this._accessors.length - 1; i >= 0; --i) {
        if (this._accessors[i][1] === accessor) {
          this._accessors.splice(i, 1);
          return;
        }
      }
    }
    /**
     * @description
     * Selects a radio button. For internal use only.
     */
    select(accessor) {
      this._accessors.forEach(c => {
        if (this._isSameGroup(c, accessor) && c[1] !== accessor) {
          c[1].fireUncheck(accessor.value);
        }
      });
    }
    _isSameGroup(controlPair, accessor) {
      if (!controlPair[0].control) return false;
      return controlPair[0]._parent === accessor._control._parent && controlPair[1].name === accessor.name;
    }
    static ɵfac = (() => function RadioControlRegistry_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RadioControlRegistry)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: RadioControlRegistry,
      factory: RadioControlRegistry.ɵfac,
      providedIn: 'root'
    }))();
  }
  return RadioControlRegistry;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * The `ControlValueAccessor` for writing radio control values and listening to radio control
 * changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
 * `NgModel` directives.
 *
 * @usageNotes
 *
 * ### Using radio buttons with reactive form directives
 *
 * The follow example shows how to use radio buttons in a reactive form. When using radio buttons in
 * a reactive form, radio buttons in the same group should have the same `formControlName`.
 * Providing a `name` attribute is optional.
 *
 * {@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'}
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let RadioControlValueAccessor = /*#__PURE__*/(() => {
  class RadioControlValueAccessor extends BuiltInControlValueAccessor {
    _registry;
    _injector;
    /** @internal */
    // TODO(issue/24571): remove '!'.
    _state;
    /** @internal */
    // TODO(issue/24571): remove '!'.
    _control;
    /** @internal */
    // TODO(issue/24571): remove '!'.
    _fn;
    setDisabledStateFired = false;
    /**
     * The registered callback function called when a change event occurs on the input element.
     * Note: we declare `onChange` here (also used as host listener) as a function with no arguments
     * to override the `onChange` function (which expects 1 argument) in the parent
     * `BaseControlValueAccessor` class.
     * @nodoc
     */
    onChange = () => {};
    /**
     * @description
     * Tracks the name of the radio input element.
     */
    // TODO(issue/24571): remove '!'.
    name;
    /**
     * @description
     * Tracks the name of the `FormControl` bound to the directive. The name corresponds
     * to a key in the parent `FormGroup` or `FormArray`.
     */
    // TODO(issue/24571): remove '!'.
    formControlName;
    /**
     * @description
     * Tracks the value of the radio input element
     */
    value;
    callSetDisabledState = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.inject)(CALL_SET_DISABLED_STATE, {
      optional: true
    }) ?? setDisabledStateDefault)();
    constructor(renderer, elementRef, _registry, _injector) {
      super(renderer, elementRef);
      this._registry = _registry;
      this._injector = _injector;
    }
    /** @nodoc */
    ngOnInit() {
      this._control = this._injector.get(NgControl);
      this._checkName();
      this._registry.add(this._control, this);
    }
    /** @nodoc */
    ngOnDestroy() {
      this._registry.remove(this);
    }
    /**
     * Sets the "checked" property value on the radio input element.
     * @nodoc
     */
    writeValue(value) {
      this._state = value === this.value;
      this.setProperty('checked', this._state);
    }
    /**
     * Registers a function called when the control value changes.
     * @nodoc
     */
    registerOnChange(fn) {
      this._fn = fn;
      this.onChange = () => {
        fn(this.value);
        this._registry.select(this);
      };
    }
    /** @nodoc */
    setDisabledState(isDisabled) {
      /**
       * `setDisabledState` is supposed to be called whenever the disabled state of a control changes,
       * including upon control creation. However, a longstanding bug caused the method to not fire
       * when an *enabled* control was attached. This bug was fixed in v15 in #47576.
       *
       * This had a side effect: previously, it was possible to instantiate a reactive form control
       * with `[attr.disabled]=true`, even though the corresponding control was enabled in the
       * model. This resulted in a mismatch between the model and the DOM. Now, because
       * `setDisabledState` is always called, the value in the DOM will be immediately overwritten
       * with the "correct" enabled value.
       *
       * However, the fix also created an exceptional case: radio buttons. Because Reactive Forms
       * models the entire group of radio buttons as a single `FormControl`, there is no way to
       * control the disabled state for individual radios, so they can no longer be configured as
       * disabled. Thus, we keep the old behavior for radio buttons, so that `[attr.disabled]`
       * continues to work. Specifically, we drop the first call to `setDisabledState` if `disabled`
       * is `false`, and we are not in legacy mode.
       */
      if (this.setDisabledStateFired || isDisabled || this.callSetDisabledState === 'whenDisabledForLegacyCode') {
        this.setProperty('disabled', isDisabled);
      }
      this.setDisabledStateFired = true;
    }
    /**
     * Sets the "value" on the radio input element and unchecks it.
     *
     * @param value
     */
    fireUncheck(value) {
      this.writeValue(value);
    }
    _checkName() {
      if (this.name && this.formControlName && this.name !== this.formControlName && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throwNameError();
      }
      if (!this.name && this.formControlName) this.name = this.formControlName;
    }
    static ɵfac = (() => function RadioControlValueAccessor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RadioControlValueAccessor)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](RadioControlRegistry), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Injector));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: RadioControlValueAccessor,
      selectors: [["input", "type", "radio", "formControlName", ""], ["input", "type", "radio", "formControl", ""], ["input", "type", "radio", "ngModel", ""]],
      hostBindings: function RadioControlValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("change", function RadioControlValueAccessor_change_HostBindingHandler() {
            return ctx.onChange();
          })("blur", function RadioControlValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      inputs: {
        name: "name",
        formControlName: "formControlName",
        value: "value"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([RADIO_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return RadioControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const RANGE_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => RangeValueAccessor),
  multi: true
};
/**
 * @description
 * The `ControlValueAccessor` for writing a range value and listening to range input changes.
 * The value accessor is used by the `FormControlDirective`, `FormControlName`, and  `NgModel`
 * directives.
 *
 * @usageNotes
 *
 * ### Using a range input with a reactive form
 *
 * The following example shows how to use a range input with a reactive form.
 *
 * ```ts
 * const ageControl = new FormControl();
 * ```
 *
 * ```
 * <input type="range" [formControl]="ageControl">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let RangeValueAccessor = /*#__PURE__*/(() => {
  class RangeValueAccessor extends BuiltInControlValueAccessor {
    /**
     * Sets the "value" property on the input element.
     * @nodoc
     */
    writeValue(value) {
      this.setProperty('value', parseFloat(value));
    }
    /**
     * Registers a function called when the control value changes.
     * @nodoc
     */
    registerOnChange(fn) {
      this.onChange = value => {
        fn(value == '' ? null : parseFloat(value));
      };
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵRangeValueAccessor_BaseFactory;
      return function RangeValueAccessor_Factory(__ngFactoryType__) {
        return (ɵRangeValueAccessor_BaseFactory || (ɵRangeValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](RangeValueAccessor)))(__ngFactoryType__ || RangeValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: RangeValueAccessor,
      selectors: [["input", "type", "range", "formControlName", ""], ["input", "type", "range", "formControl", ""], ["input", "type", "range", "ngModel", ""]],
      hostBindings: function RangeValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("change", function RangeValueAccessor_change_HostBindingHandler($event) {
            return ctx.onChange($event.target.value);
          })("input", function RangeValueAccessor_input_HostBindingHandler($event) {
            return ctx.onChange($event.target.value);
          })("blur", function RangeValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([RANGE_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return RangeValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Token to provide to turn off the ngModel warning on formControl and formControlName.
 */
const NG_MODEL_WITH_FORM_CONTROL_WARNING = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken(ngDevMode ? 'NgModelWithFormControlWarning' : '');
const formControlBinding = {
  provide: NgControl,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => FormControlDirective)
};
/**
 * @description
 * Synchronizes a standalone `FormControl` instance to a form control element.
 *
 * Note that support for using the `ngModel` input property and `ngModelChange` event with reactive
 * form directives was deprecated in Angular v6 and is scheduled for removal in
 * a future version of Angular.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 * @see {@link FormControl}
 * @see {@link AbstractControl}
 *
 * @usageNotes
 *
 * The following example shows how to register a standalone control and set its value.
 *
 * {@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'}
 *
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let FormControlDirective = /*#__PURE__*/(() => {
  class FormControlDirective extends NgControl {
    _ngModelWarningConfig;
    callSetDisabledState;
    /**
     * Internal reference to the view model value.
     * @nodoc
     */
    viewModel;
    /**
     * @description
     * Tracks the `FormControl` instance bound to the directive.
     */
    // TODO(issue/24571): remove '!'.
    form;
    /**
     * @description
     * Triggers a warning in dev mode that this input should not be used with reactive forms.
     */
    set isDisabled(isDisabled) {
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        console.warn(disabledAttrWarning);
      }
    }
    // TODO(kara): remove next 4 properties once deprecation period is over
    /** @deprecated as of v6 */
    model;
    /** @deprecated as of v6 */
    update = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter())();
    /**
     * @description
     * Static property used to track whether any ngModel warnings have been sent across
     * all instances of FormControlDirective. Used to support warning config of "once".
     *
     * @internal
     */
    static _ngModelWarningSentOnce = false;
    /**
     * @description
     * Instance property used to track whether an ngModel warning has been sent out for this
     * particular `FormControlDirective` instance. Used to support warning config of "always".
     *
     * @internal
     */
    _ngModelWarningSent = false;
    constructor(validators, asyncValidators, valueAccessors, _ngModelWarningConfig, callSetDisabledState) {
      super();
      this._ngModelWarningConfig = _ngModelWarningConfig;
      this.callSetDisabledState = callSetDisabledState;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
      this.valueAccessor = selectValueAccessor(this, valueAccessors);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      if (this._isControlChanged(changes)) {
        const previousForm = changes['form'].previousValue;
        if (previousForm) {
          cleanUpControl(previousForm, this, /* validateControlPresenceOnChange */false);
        }
        setUpControl(this.form, this, this.callSetDisabledState);
        this.form.updateValueAndValidity({
          emitEvent: false
        });
      }
      if (isPropertyUpdated(changes, this.viewModel)) {
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          _ngModelWarning('formControl', FormControlDirective, this, this._ngModelWarningConfig);
        }
        this.form.setValue(this.model);
        this.viewModel = this.model;
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this.form) {
        cleanUpControl(this.form, this, /* validateControlPresenceOnChange */false);
      }
    }
    /**
     * @description
     * Returns an array that represents the path from the top-level form to this control.
     * Each index is the string name of the control on that level.
     */
    get path() {
      return [];
    }
    /**
     * @description
     * The `FormControl` bound to this directive.
     */
    get control() {
      return this.form;
    }
    /**
     * @description
     * Sets the new value for the view model and emits an `ngModelChange` event.
     *
     * @param newValue The new value for the view model.
     */
    viewToModelUpdate(newValue) {
      this.viewModel = newValue;
      this.update.emit(newValue);
    }
    _isControlChanged(changes) {
      return changes.hasOwnProperty('form');
    }
    static ɵfac = (() => function FormControlDirective_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormControlDirective)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALUE_ACCESSOR, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_MODEL_WITH_FORM_CONTROL_WARNING, 8), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](CALL_SET_DISABLED_STATE, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: FormControlDirective,
      selectors: [["", "formControl", ""]],
      inputs: {
        form: [0, "formControl", "form"],
        isDisabled: [0, "disabled", "isDisabled"],
        model: [0, "ngModel", "model"]
      },
      outputs: {
        update: "ngModelChange"
      },
      exportAs: ["ngForm"],
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formControlBinding]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return FormControlDirective;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const formDirectiveProvider = {
  provide: ControlContainer,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => FormGroupDirective)
};
/**
 * @description
 *
 * Binds an existing `FormGroup` or `FormRecord` to a DOM element.
 *
 * This directive accepts an existing `FormGroup` instance. It will then use this
 * `FormGroup` instance to match any child `FormControl`, `FormGroup`/`FormRecord`,
 * and `FormArray` instances to child `FormControlName`, `FormGroupName`,
 * and `FormArrayName` directives.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 * @see {@link AbstractControl}
 *
 * @usageNotes
 * ### Register Form Group
 *
 * The following example registers a `FormGroup` with first name and last name controls,
 * and listens for the *ngSubmit* event when the button is clicked.
 *
 * {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
 *
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let FormGroupDirective = /*#__PURE__*/(() => {
  class FormGroupDirective extends ControlContainer {
    callSetDisabledState;
    /**
     * @description
     * Reports whether the form submission has been triggered.
     */
    get submitted() {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.untracked)(this._submittedReactive);
    }
    // TODO(atscott): Remove once invalid API usage is cleaned up internally
    set submitted(value) {
      this._submittedReactive.set(value);
    }
    /** @internal */
    _submitted = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.computed)(() => this._submittedReactive()))();
    _submittedReactive = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.signal)(false))();
    /**
     * Reference to an old form group input value, which is needed to cleanup
     * old instance in case it was replaced with a new one.
     */
    _oldForm;
    /**
     * Callback that should be invoked when controls in FormGroup or FormArray collection change
     * (added or removed). This callback triggers corresponding DOM updates.
     */
    _onCollectionChange = () => this._updateDomValue();
    /**
     * @description
     * Tracks the list of added `FormControlName` instances
     */
    directives = [];
    /**
     * @description
     * Tracks the `FormGroup` bound to this directive.
     */
    form = null;
    /**
     * @description
     * Emits an event when the form submission has been triggered.
     */
    ngSubmit = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter())();
    constructor(validators, asyncValidators, callSetDisabledState) {
      super();
      this.callSetDisabledState = callSetDisabledState;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      this._checkFormPresent();
      if (changes.hasOwnProperty('form')) {
        this._updateValidators();
        this._updateDomValue();
        this._updateRegistrations();
        this._oldForm = this.form;
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this.form) {
        cleanUpValidators(this.form, this);
        // Currently the `onCollectionChange` callback is rewritten each time the
        // `_registerOnCollectionChange` function is invoked. The implication is that cleanup should
        // happen *only* when the `onCollectionChange` callback was set by this directive instance.
        // Otherwise it might cause overriding a callback of some other directive instances. We should
        // consider updating this logic later to make it similar to how `onChange` callbacks are
        // handled, see https://github.com/angular/angular/issues/39732 for additional info.
        if (this.form._onCollectionChange === this._onCollectionChange) {
          this.form._registerOnCollectionChange(() => {});
        }
      }
    }
    /**
     * @description
     * Returns this directive's instance.
     */
    get formDirective() {
      return this;
    }
    /**
     * @description
     * Returns the `FormGroup` bound to this directive.
     */
    get control() {
      return this.form;
    }
    /**
     * @description
     * Returns an array representing the path to this group. Because this directive
     * always lives at the top level of a form, it always an empty array.
     */
    get path() {
      return [];
    }
    /**
     * @description
     * Method that sets up the control directive in this group, re-calculates its value
     * and validity, and adds the instance to the internal list of directives.
     *
     * @param dir The `FormControlName` directive instance.
     */
    addControl(dir) {
      const ctrl = this.form.get(dir.path);
      setUpControl(ctrl, dir, this.callSetDisabledState);
      ctrl.updateValueAndValidity({
        emitEvent: false
      });
      this.directives.push(dir);
      return ctrl;
    }
    /**
     * @description
     * Retrieves the `FormControl` instance from the provided `FormControlName` directive
     *
     * @param dir The `FormControlName` directive instance.
     */
    getControl(dir) {
      return this.form.get(dir.path);
    }
    /**
     * @description
     * Removes the `FormControlName` instance from the internal list of directives
     *
     * @param dir The `FormControlName` directive instance.
     */
    removeControl(dir) {
      cleanUpControl(dir.control || null, dir, /* validateControlPresenceOnChange */false);
      removeListItem$1(this.directives, dir);
    }
    /**
     * Adds a new `FormGroupName` directive instance to the form.
     *
     * @param dir The `FormGroupName` directive instance.
     */
    addFormGroup(dir) {
      this._setUpFormContainer(dir);
    }
    /**
     * Performs the necessary cleanup when a `FormGroupName` directive instance is removed from the
     * view.
     *
     * @param dir The `FormGroupName` directive instance.
     */
    removeFormGroup(dir) {
      this._cleanUpFormContainer(dir);
    }
    /**
     * @description
     * Retrieves the `FormGroup` for a provided `FormGroupName` directive instance
     *
     * @param dir The `FormGroupName` directive instance.
     */
    getFormGroup(dir) {
      return this.form.get(dir.path);
    }
    /**
     * Performs the necessary setup when a `FormArrayName` directive instance is added to the view.
     *
     * @param dir The `FormArrayName` directive instance.
     */
    addFormArray(dir) {
      this._setUpFormContainer(dir);
    }
    /**
     * Performs the necessary cleanup when a `FormArrayName` directive instance is removed from the
     * view.
     *
     * @param dir The `FormArrayName` directive instance.
     */
    removeFormArray(dir) {
      this._cleanUpFormContainer(dir);
    }
    /**
     * @description
     * Retrieves the `FormArray` for a provided `FormArrayName` directive instance.
     *
     * @param dir The `FormArrayName` directive instance.
     */
    getFormArray(dir) {
      return this.form.get(dir.path);
    }
    /**
     * Sets the new value for the provided `FormControlName` directive.
     *
     * @param dir The `FormControlName` directive instance.
     * @param value The new value for the directive's control.
     */
    updateModel(dir, value) {
      const ctrl = this.form.get(dir.path);
      ctrl.setValue(value);
    }
    /**
     * @description
     * Method called with the "submit" event is triggered on the form.
     * Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
     *
     * @param $event The "submit" event object
     */
    onSubmit($event) {
      this._submittedReactive.set(true);
      syncPendingControls(this.form, this.directives);
      this.ngSubmit.emit($event);
      this.form._events.next(new FormSubmittedEvent(this.control));
      // Forms with `method="dialog"` have some special behavior that won't reload the page and that
      // shouldn't be prevented. Note that we need to null check the `event` and the `target`, because
      // some internal apps call this method directly with the wrong arguments.
      return $event?.target?.method === 'dialog';
    }
    /**
     * @description
     * Method called when the "reset" event is triggered on the form.
     */
    onReset() {
      this.resetForm();
    }
    /**
     * @description
     * Resets the form to an initial value and resets its submitted status.
     *
     * @param value The new value for the form.
     */
    resetForm(value = undefined) {
      this.form.reset(value);
      this._submittedReactive.set(false);
      this.form._events.next(new FormResetEvent(this.form));
    }
    /** @internal */
    _updateDomValue() {
      this.directives.forEach(dir => {
        const oldCtrl = dir.control;
        const newCtrl = this.form.get(dir.path);
        if (oldCtrl !== newCtrl) {
          // Note: the value of the `dir.control` may not be defined, for example when it's a first
          // `FormControl` that is added to a `FormGroup` instance (via `addControl` call).
          cleanUpControl(oldCtrl || null, dir);
          // Check whether new control at the same location inside the corresponding `FormGroup` is an
          // instance of `FormControl` and perform control setup only if that's the case.
          // Note: we don't need to clear the list of directives (`this.directives`) here, it would be
          // taken care of in the `removeControl` method invoked when corresponding `formControlName`
          // directive instance is being removed (invoked from `FormControlName.ngOnDestroy`).
          if (isFormControl(newCtrl)) {
            setUpControl(newCtrl, dir, this.callSetDisabledState);
            dir.control = newCtrl;
          }
        }
      });
      this.form._updateTreeValidity({
        emitEvent: false
      });
    }
    _setUpFormContainer(dir) {
      const ctrl = this.form.get(dir.path);
      setUpFormContainer(ctrl, dir);
      // NOTE: this operation looks unnecessary in case no new validators were added in
      // `setUpFormContainer` call. Consider updating this code to match the logic in
      // `_cleanUpFormContainer` function.
      ctrl.updateValueAndValidity({
        emitEvent: false
      });
    }
    _cleanUpFormContainer(dir) {
      if (this.form) {
        const ctrl = this.form.get(dir.path);
        if (ctrl) {
          const isControlUpdated = cleanUpFormContainer(ctrl, dir);
          if (isControlUpdated) {
            // Run validity check only in case a control was updated (i.e. view validators were
            // removed) as removing view validators might cause validity to change.
            ctrl.updateValueAndValidity({
              emitEvent: false
            });
          }
        }
      }
    }
    _updateRegistrations() {
      this.form._registerOnCollectionChange(this._onCollectionChange);
      if (this._oldForm) {
        this._oldForm._registerOnCollectionChange(() => {});
      }
    }
    _updateValidators() {
      setUpValidators(this.form, this);
      if (this._oldForm) {
        cleanUpValidators(this._oldForm, this);
      }
    }
    _checkFormPresent() {
      if (!this.form && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw missingFormException();
      }
    }
    static ɵfac = (() => function FormGroupDirective_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormGroupDirective)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](CALL_SET_DISABLED_STATE, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: FormGroupDirective,
      selectors: [["", "formGroup", ""]],
      hostBindings: function FormGroupDirective_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("submit", function FormGroupDirective_submit_HostBindingHandler($event) {
            return ctx.onSubmit($event);
          })("reset", function FormGroupDirective_reset_HostBindingHandler() {
            return ctx.onReset();
          });
        }
      },
      inputs: {
        form: [0, "formGroup", "form"]
      },
      outputs: {
        ngSubmit: "ngSubmit"
      },
      exportAs: ["ngForm"],
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formDirectiveProvider]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return FormGroupDirective;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const formGroupNameProvider = {
  provide: ControlContainer,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => FormGroupName)
};
/**
 * @description
 *
 * Syncs a nested `FormGroup` or `FormRecord` to a DOM element.
 *
 * This directive can only be used with a parent `FormGroupDirective`.
 *
 * It accepts the string name of the nested `FormGroup` or `FormRecord` to link, and
 * looks for a `FormGroup` or `FormRecord` registered with that name in the parent
 * `FormGroup` instance you passed into `FormGroupDirective`.
 *
 * Use nested form groups to validate a sub-group of a
 * form separately from the rest or to group the values of certain
 * controls into their own nested object.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 *
 * @usageNotes
 *
 * ### Access the group by name
 *
 * The following example uses the `AbstractControl.get` method to access the
 * associated `FormGroup`
 *
 * ```ts
 *   this.form.get('name');
 * ```
 *
 * ### Access individual controls in the group
 *
 * The following example uses the `AbstractControl.get` method to access
 * individual controls within the group using dot syntax.
 *
 * ```ts
 *   this.form.get('name.first');
 * ```
 *
 * ### Register a nested `FormGroup`.
 *
 * The following example registers a nested *name* `FormGroup` within an existing `FormGroup`,
 * and provides methods to retrieve the nested `FormGroup` and individual controls.
 *
 * {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'}
 *
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let FormGroupName = /*#__PURE__*/(() => {
  class FormGroupName extends AbstractFormGroupDirective {
    /**
     * @description
     * Tracks the name of the `FormGroup` bound to the directive. The name corresponds
     * to a key in the parent `FormGroup` or `FormArray`.
     * Accepts a name as a string or a number.
     * The name in the form of a string is useful for individual forms,
     * while the numerical form allows for form groups to be bound
     * to indices when iterating over groups in a `FormArray`.
     */
    name = null;
    constructor(parent, validators, asyncValidators) {
      super();
      this._parent = parent;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
    }
    /** @internal */
    _checkParentType() {
      if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw groupParentException();
      }
    }
    static ɵfac = (() => function FormGroupName_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormGroupName)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 13), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: FormGroupName,
      selectors: [["", "formGroupName", ""]],
      inputs: {
        name: [0, "formGroupName", "name"]
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formGroupNameProvider]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return FormGroupName;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const formArrayNameProvider = {
  provide: ControlContainer,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => FormArrayName)
};
/**
 * @description
 *
 * Syncs a nested `FormArray` to a DOM element.
 *
 * This directive is designed to be used with a parent `FormGroupDirective` (selector:
 * `[formGroup]`).
 *
 * It accepts the string name of the nested `FormArray` you want to link, and
 * will look for a `FormArray` registered with that name in the parent
 * `FormGroup` instance you passed into `FormGroupDirective`.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 * @see {@link AbstractControl}
 *
 * @usageNotes
 *
 * ### Example
 *
 * {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'}
 *
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let FormArrayName = /*#__PURE__*/(() => {
  class FormArrayName extends ControlContainer {
    /** @internal */
    _parent;
    /**
     * @description
     * Tracks the name of the `FormArray` bound to the directive. The name corresponds
     * to a key in the parent `FormGroup` or `FormArray`.
     * Accepts a name as a string or a number.
     * The name in the form of a string is useful for individual forms,
     * while the numerical form allows for form arrays to be bound
     * to indices when iterating over arrays in a `FormArray`.
     */
    name = null;
    constructor(parent, validators, asyncValidators) {
      super();
      this._parent = parent;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
    }
    /**
     * A lifecycle method called when the directive's inputs are initialized. For internal use only.
     * @throws If the directive does not have a valid parent.
     * @nodoc
     */
    ngOnInit() {
      this._checkParentType();
      this.formDirective.addFormArray(this);
    }
    /**
     * A lifecycle method called before the directive's instance is destroyed. For internal use only.
     * @nodoc
     */
    ngOnDestroy() {
      if (this.formDirective) {
        this.formDirective.removeFormArray(this);
      }
    }
    /**
     * @description
     * The `FormArray` bound to this directive.
     */
    get control() {
      return this.formDirective.getFormArray(this);
    }
    /**
     * @description
     * The top-level directive for this group if present, otherwise null.
     */
    get formDirective() {
      return this._parent ? this._parent.formDirective : null;
    }
    /**
     * @description
     * Returns an array that represents the path from the top-level form to this control.
     * Each index is the string name of the control on that level.
     */
    get path() {
      return controlPath(this.name == null ? this.name : this.name.toString(), this._parent);
    }
    _checkParentType() {
      if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw arrayParentException();
      }
    }
    static ɵfac = (() => function FormArrayName_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormArrayName)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 13), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: FormArrayName,
      selectors: [["", "formArrayName", ""]],
      inputs: {
        name: [0, "formArrayName", "name"]
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([formArrayNameProvider]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return FormArrayName;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function _hasInvalidParent(parent) {
  return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) && !(parent instanceof FormArrayName);
}
const controlNameBinding = {
  provide: NgControl,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => FormControlName)
};
/**
 * @description
 * Syncs a `FormControl` in an existing `FormGroup` to a form control
 * element by name.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 * @see {@link FormControl}
 * @see {@link AbstractControl}
 *
 * @usageNotes
 *
 * ### Register `FormControl` within a group
 *
 * The following example shows how to register multiple form controls within a form group
 * and set their value.
 *
 * {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
 *
 * To see `formControlName` examples with different form control types, see:
 *
 * * Radio buttons: `RadioControlValueAccessor`
 * * Selects: `SelectControlValueAccessor`
 *
 * ### Use with ngModel is deprecated
 *
 * Support for using the `ngModel` input property and `ngModelChange` event with reactive
 * form directives has been deprecated in Angular v6 and is scheduled for removal in
 * a future version of Angular.
 *
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let FormControlName = /*#__PURE__*/(() => {
  class FormControlName extends NgControl {
    _ngModelWarningConfig;
    _added = false;
    /**
     * Internal reference to the view model value.
     * @internal
     */
    viewModel;
    /**
     * @description
     * Tracks the `FormControl` instance bound to the directive.
     */
    // TODO(issue/24571): remove '!'.
    control;
    /**
     * @description
     * Tracks the name of the `FormControl` bound to the directive. The name corresponds
     * to a key in the parent `FormGroup` or `FormArray`.
     * Accepts a name as a string or a number.
     * The name in the form of a string is useful for individual forms,
     * while the numerical form allows for form controls to be bound
     * to indices when iterating over controls in a `FormArray`.
     */
    name = null;
    /**
     * @description
     * Triggers a warning in dev mode that this input should not be used with reactive forms.
     */
    set isDisabled(isDisabled) {
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        console.warn(disabledAttrWarning);
      }
    }
    // TODO(kara): remove next 4 properties once deprecation period is over
    /** @deprecated as of v6 */
    model;
    /** @deprecated as of v6 */
    update = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter())();
    /**
     * @description
     * Static property used to track whether any ngModel warnings have been sent across
     * all instances of FormControlName. Used to support warning config of "once".
     *
     * @internal
     */
    static _ngModelWarningSentOnce = false;
    /**
     * @description
     * Instance property used to track whether an ngModel warning has been sent out for this
     * particular FormControlName instance. Used to support warning config of "always".
     *
     * @internal
     */
    _ngModelWarningSent = false;
    constructor(parent, validators, asyncValidators, valueAccessors, _ngModelWarningConfig) {
      super();
      this._ngModelWarningConfig = _ngModelWarningConfig;
      this._parent = parent;
      this._setValidators(validators);
      this._setAsyncValidators(asyncValidators);
      this.valueAccessor = selectValueAccessor(this, valueAccessors);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      if (!this._added) this._setUpControl();
      if (isPropertyUpdated(changes, this.viewModel)) {
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          _ngModelWarning('formControlName', FormControlName, this, this._ngModelWarningConfig);
        }
        this.viewModel = this.model;
        this.formDirective.updateModel(this, this.model);
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this.formDirective) {
        this.formDirective.removeControl(this);
      }
    }
    /**
     * @description
     * Sets the new value for the view model and emits an `ngModelChange` event.
     *
     * @param newValue The new value for the view model.
     */
    viewToModelUpdate(newValue) {
      this.viewModel = newValue;
      this.update.emit(newValue);
    }
    /**
     * @description
     * Returns an array that represents the path from the top-level form to this control.
     * Each index is the string name of the control on that level.
     */
    get path() {
      return controlPath(this.name == null ? this.name : this.name.toString(), this._parent);
    }
    /**
     * @description
     * The top-level directive for this group if present, otherwise null.
     */
    get formDirective() {
      return this._parent ? this._parent.formDirective : null;
    }
    _checkParentType() {
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        if (!(this._parent instanceof FormGroupName) && this._parent instanceof AbstractFormGroupDirective) {
          throw ngModelGroupException();
        } else if (!(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) && !(this._parent instanceof FormArrayName)) {
          throw controlParentException(this.name);
        }
      }
    }
    _setUpControl() {
      this._checkParentType();
      this.control = this.formDirective.addControl(this);
      this._added = true;
    }
    static ɵfac = (() => function FormControlName_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormControlName)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](ControlContainer, 13), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_ASYNC_VALIDATORS, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_VALUE_ACCESSOR, 10), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NG_MODEL_WITH_FORM_CONTROL_WARNING, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: FormControlName,
      selectors: [["", "formControlName", ""]],
      inputs: {
        name: [0, "formControlName", "name"],
        isDisabled: [0, "disabled", "isDisabled"],
        model: [0, "ngModel", "model"]
      },
      outputs: {
        update: "ngModelChange"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([controlNameBinding]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return FormControlName;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const SELECT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => SelectControlValueAccessor),
  multi: true
};
function _buildValueString$1(id, value) {
  if (id == null) return `${value}`;
  if (value && typeof value === 'object') value = 'Object';
  return `${id}: ${value}`.slice(0, 50);
}
function _extractId$1(valueString) {
  return valueString.split(':')[0];
}
/**
 * @description
 * The `ControlValueAccessor` for writing select control values and listening to select control
 * changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
 * `NgModel` directives.
 *
 * @usageNotes
 *
 * ### Using select controls in a reactive form
 *
 * The following examples show how to use a select control in a reactive form.
 *
 * {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'}
 *
 * ### Using select controls in a template-driven form
 *
 * To use a select in a template-driven form, simply add an `ngModel` and a `name`
 * attribute to the main `<select>` tag.
 *
 * {@example forms/ts/selectControl/select_control_example.ts region='Component'}
 *
 * ### Customizing option selection
 *
 * Angular uses object identity to select option. It's possible for the identities of items
 * to change while the data does not. This can happen, for example, if the items are produced
 * from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the
 * second response will produce objects with different identities.
 *
 * To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
 * `compareWith` takes a **function** which has two arguments: `option1` and `option2`.
 * If `compareWith` is given, Angular selects option by the return value of the function.
 *
 * ```ts
 * const selectedCountriesControl = new FormControl();
 * ```
 *
 * ```
 * <select [compareWith]="compareFn"  [formControl]="selectedCountriesControl">
 *     <option *ngFor="let country of countries" [ngValue]="country">
 *         {{country.name}}
 *     </option>
 * </select>
 *
 * compareFn(c1: Country, c2: Country): boolean {
 *     return c1 && c2 ? c1.id === c2.id : c1 === c2;
 * }
 * ```
 *
 * **Note:** We listen to the 'change' event because 'input' events aren't fired
 * for selects in IE, see:
 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let SelectControlValueAccessor = /*#__PURE__*/(() => {
  class SelectControlValueAccessor extends BuiltInControlValueAccessor {
    /** @nodoc */
    value;
    /** @internal */
    _optionMap = (() => new Map())();
    /** @internal */
    _idCounter = 0;
    /**
     * @description
     * Tracks the option comparison algorithm for tracking identities when
     * checking for changes.
     */
    set compareWith(fn) {
      if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1201 /* RuntimeErrorCode.COMPAREWITH_NOT_A_FN */, `compareWith must be a function, but received ${JSON.stringify(fn)}`);
      }
      this._compareWith = fn;
    }
    _compareWith = (() => Object.is)();
    /**
     * Sets the "value" property on the select element.
     * @nodoc
     */
    writeValue(value) {
      this.value = value;
      const id = this._getOptionId(value);
      const valueString = _buildValueString$1(id, value);
      this.setProperty('value', valueString);
    }
    /**
     * Registers a function called when the control value changes.
     * @nodoc
     */
    registerOnChange(fn) {
      this.onChange = valueString => {
        this.value = this._getOptionValue(valueString);
        fn(this.value);
      };
    }
    /** @internal */
    _registerOption() {
      return (this._idCounter++).toString();
    }
    /** @internal */
    _getOptionId(value) {
      for (const id of this._optionMap.keys()) {
        if (this._compareWith(this._optionMap.get(id), value)) return id;
      }
      return null;
    }
    /** @internal */
    _getOptionValue(valueString) {
      const id = _extractId$1(valueString);
      return this._optionMap.has(id) ? this._optionMap.get(id) : valueString;
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵSelectControlValueAccessor_BaseFactory;
      return function SelectControlValueAccessor_Factory(__ngFactoryType__) {
        return (ɵSelectControlValueAccessor_BaseFactory || (ɵSelectControlValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](SelectControlValueAccessor)))(__ngFactoryType__ || SelectControlValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: SelectControlValueAccessor,
      selectors: [["select", "formControlName", "", 3, "multiple", ""], ["select", "formControl", "", 3, "multiple", ""], ["select", "ngModel", "", 3, "multiple", ""]],
      hostBindings: function SelectControlValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("change", function SelectControlValueAccessor_change_HostBindingHandler($event) {
            return ctx.onChange($event.target.value);
          })("blur", function SelectControlValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      inputs: {
        compareWith: "compareWith"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([SELECT_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return SelectControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Marks `<option>` as dynamic, so Angular can be notified when options change.
 *
 * @see {@link SelectControlValueAccessor}
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let NgSelectOption = /*#__PURE__*/(() => {
  class NgSelectOption {
    _element;
    _renderer;
    _select;
    /**
     * @description
     * ID of the option element
     */
    // TODO(issue/24571): remove '!'.
    id;
    constructor(_element, _renderer, _select) {
      this._element = _element;
      this._renderer = _renderer;
      this._select = _select;
      if (this._select) this.id = this._select._registerOption();
    }
    /**
     * @description
     * Tracks the value bound to the option element. Unlike the value binding,
     * ngValue supports binding to objects.
     */
    set ngValue(value) {
      if (this._select == null) return;
      this._select._optionMap.set(this.id, value);
      this._setElementValue(_buildValueString$1(this.id, value));
      this._select.writeValue(this._select.value);
    }
    /**
     * @description
     * Tracks simple string values bound to the option element.
     * For objects, use the `ngValue` input binding.
     */
    set value(value) {
      this._setElementValue(value);
      if (this._select) this._select.writeValue(this._select.value);
    }
    /** @internal */
    _setElementValue(value) {
      this._renderer.setProperty(this._element.nativeElement, 'value', value);
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this._select) {
        this._select._optionMap.delete(this.id);
        this._select.writeValue(this._select.value);
      }
    }
    static ɵfac = (() => function NgSelectOption_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NgSelectOption)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](SelectControlValueAccessor, 9));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: NgSelectOption,
      selectors: [["option"]],
      inputs: {
        ngValue: "ngValue",
        value: "value"
      },
      standalone: false
    }))();
  }
  return NgSelectOption;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const SELECT_MULTIPLE_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => SelectMultipleControlValueAccessor),
  multi: true
};
function _buildValueString(id, value) {
  if (id == null) return `${value}`;
  if (typeof value === 'string') value = `'${value}'`;
  if (value && typeof value === 'object') value = 'Object';
  return `${id}: ${value}`.slice(0, 50);
}
function _extractId(valueString) {
  return valueString.split(':')[0];
}
/** Mock interface for HTMLCollection */
class HTMLCollection {
  // TODO(issue/24571): remove '!'.
  length;
}
/**
 * @description
 * The `ControlValueAccessor` for writing multi-select control values and listening to multi-select
 * control changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
 * `NgModel` directives.
 *
 * @see {@link SelectControlValueAccessor}
 *
 * @usageNotes
 *
 * ### Using a multi-select control
 *
 * The follow example shows you how to use a multi-select control with a reactive form.
 *
 * ```ts
 * const countryControl = new FormControl();
 * ```
 *
 * ```
 * <select multiple name="countries" [formControl]="countryControl">
 *   <option *ngFor="let country of countries" [ngValue]="country">
 *     {{ country.name }}
 *   </option>
 * </select>
 * ```
 *
 * ### Customizing option selection
 *
 * To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
 * See the `SelectControlValueAccessor` for usage.
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let SelectMultipleControlValueAccessor = /*#__PURE__*/(() => {
  class SelectMultipleControlValueAccessor extends BuiltInControlValueAccessor {
    /**
     * The current value.
     * @nodoc
     */
    value;
    /** @internal */
    _optionMap = (() => new Map())();
    /** @internal */
    _idCounter = 0;
    /**
     * @description
     * Tracks the option comparison algorithm for tracking identities when
     * checking for changes.
     */
    set compareWith(fn) {
      if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"](1201 /* RuntimeErrorCode.COMPAREWITH_NOT_A_FN */, `compareWith must be a function, but received ${JSON.stringify(fn)}`);
      }
      this._compareWith = fn;
    }
    _compareWith = (() => Object.is)();
    /**
     * Sets the "value" property on one or of more of the select's options.
     * @nodoc
     */
    writeValue(value) {
      this.value = value;
      let optionSelectedStateSetter;
      if (Array.isArray(value)) {
        // convert values to ids
        const ids = value.map(v => this._getOptionId(v));
        optionSelectedStateSetter = (opt, o) => {
          opt._setSelected(ids.indexOf(o.toString()) > -1);
        };
      } else {
        optionSelectedStateSetter = (opt, o) => {
          opt._setSelected(false);
        };
      }
      this._optionMap.forEach(optionSelectedStateSetter);
    }
    /**
     * Registers a function called when the control value changes
     * and writes an array of the selected options.
     * @nodoc
     */
    registerOnChange(fn) {
      this.onChange = element => {
        const selected = [];
        const selectedOptions = element.selectedOptions;
        if (selectedOptions !== undefined) {
          const options = selectedOptions;
          for (let i = 0; i < options.length; i++) {
            const opt = options[i];
            const val = this._getOptionValue(opt.value);
            selected.push(val);
          }
        }
        // Degrade to use `options` when `selectedOptions` property is not available.
        // Note: the `selectedOptions` is available in all supported browsers, but the Domino lib
        // doesn't have it currently, see https://github.com/fgnass/domino/issues/177.
        else {
          const options = element.options;
          for (let i = 0; i < options.length; i++) {
            const opt = options[i];
            if (opt.selected) {
              const val = this._getOptionValue(opt.value);
              selected.push(val);
            }
          }
        }
        this.value = selected;
        fn(selected);
      };
    }
    /** @internal */
    _registerOption(value) {
      const id = (this._idCounter++).toString();
      this._optionMap.set(id, value);
      return id;
    }
    /** @internal */
    _getOptionId(value) {
      for (const id of this._optionMap.keys()) {
        if (this._compareWith(this._optionMap.get(id)._value, value)) return id;
      }
      return null;
    }
    /** @internal */
    _getOptionValue(valueString) {
      const id = _extractId(valueString);
      return this._optionMap.has(id) ? this._optionMap.get(id)._value : valueString;
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵSelectMultipleControlValueAccessor_BaseFactory;
      return function SelectMultipleControlValueAccessor_Factory(__ngFactoryType__) {
        return (ɵSelectMultipleControlValueAccessor_BaseFactory || (ɵSelectMultipleControlValueAccessor_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](SelectMultipleControlValueAccessor)))(__ngFactoryType__ || SelectMultipleControlValueAccessor);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: SelectMultipleControlValueAccessor,
      selectors: [["select", "multiple", "", "formControlName", ""], ["select", "multiple", "", "formControl", ""], ["select", "multiple", "", "ngModel", ""]],
      hostBindings: function SelectMultipleControlValueAccessor_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("change", function SelectMultipleControlValueAccessor_change_HostBindingHandler($event) {
            return ctx.onChange($event.target);
          })("blur", function SelectMultipleControlValueAccessor_blur_HostBindingHandler() {
            return ctx.onTouched();
          });
        }
      },
      inputs: {
        compareWith: "compareWith"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([SELECT_MULTIPLE_VALUE_ACCESSOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return SelectMultipleControlValueAccessor;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Marks `<option>` as dynamic, so Angular can be notified when options change.
 *
 * @see {@link SelectMultipleControlValueAccessor}
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let ɵNgSelectMultipleOption = /*#__PURE__*/(() => {
  class ɵNgSelectMultipleOption {
    _element;
    _renderer;
    _select;
    // TODO(issue/24571): remove '!'.
    id;
    /** @internal */
    _value;
    constructor(_element, _renderer, _select) {
      this._element = _element;
      this._renderer = _renderer;
      this._select = _select;
      if (this._select) {
        this.id = this._select._registerOption(this);
      }
    }
    /**
     * @description
     * Tracks the value bound to the option element. Unlike the value binding,
     * ngValue supports binding to objects.
     */
    set ngValue(value) {
      if (this._select == null) return;
      this._value = value;
      this._setElementValue(_buildValueString(this.id, value));
      this._select.writeValue(this._select.value);
    }
    /**
     * @description
     * Tracks simple string values bound to the option element.
     * For objects, use the `ngValue` input binding.
     */
    set value(value) {
      if (this._select) {
        this._value = value;
        this._setElementValue(_buildValueString(this.id, value));
        this._select.writeValue(this._select.value);
      } else {
        this._setElementValue(value);
      }
    }
    /** @internal */
    _setElementValue(value) {
      this._renderer.setProperty(this._element.nativeElement, 'value', value);
    }
    /** @internal */
    _setSelected(selected) {
      this._renderer.setProperty(this._element.nativeElement, 'selected', selected);
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this._select) {
        this._select._optionMap.delete(this.id);
        this._select.writeValue(this._select.value);
      }
    }
    static ɵfac = (() => function ɵNgSelectMultipleOption_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ɵNgSelectMultipleOption)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](SelectMultipleControlValueAccessor, 9));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: ɵNgSelectMultipleOption,
      selectors: [["option"]],
      inputs: {
        ngValue: "ngValue",
        value: "value"
      },
      standalone: false
    }))();
  }
  return ɵNgSelectMultipleOption;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Method that updates string to integer if not already a number
 *
 * @param value The value to convert to integer.
 * @returns value of parameter converted to number or integer.
 */
function toInteger(value) {
  return typeof value === 'number' ? value : parseInt(value, 10);
}
/**
 * Method that ensures that provided value is a float (and converts it to float if needed).
 *
 * @param value The value to convert to float.
 * @returns value of parameter converted to number or float.
 */
function toFloat(value) {
  return typeof value === 'number' ? value : parseFloat(value);
}
/**
 * A base class for Validator-based Directives. The class contains common logic shared across such
 * Directives.
 *
 * For internal use only, this class is not intended for use outside of the Forms package.
 */
let AbstractValidatorDirective = /*#__PURE__*/(() => {
  class AbstractValidatorDirective {
    _validator = (() => nullValidator)();
    _onChange;
    /**
     * A flag that tracks whether this validator is enabled.
     *
     * Marking it `internal` (vs `protected`), so that this flag can be used in host bindings of
     * directive classes that extend this base class.
     * @internal
     */
    _enabled;
    /** @nodoc */
    ngOnChanges(changes) {
      if (this.inputName in changes) {
        const input = this.normalizeInput(changes[this.inputName].currentValue);
        this._enabled = this.enabled(input);
        this._validator = this._enabled ? this.createValidator(input) : nullValidator;
        if (this._onChange) {
          this._onChange();
        }
      }
    }
    /** @nodoc */
    validate(control) {
      return this._validator(control);
    }
    /** @nodoc */
    registerOnValidatorChange(fn) {
      this._onChange = fn;
    }
    /**
     * @description
     * Determines whether this validator should be active or not based on an input.
     * Base class implementation checks whether an input is defined (if the value is different from
     * `null` and `undefined`). Validator classes that extend this base class can override this
     * function with the logic specific to a particular validator directive.
     */
    enabled(input) {
      return input != null /* both `null` and `undefined` */;
    }
    static ɵfac = (() => function AbstractValidatorDirective_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || AbstractValidatorDirective)();
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: AbstractValidatorDirective,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return AbstractValidatorDirective;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `MaxValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const MAX_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => MaxValidator),
  multi: true
};
/**
 * A directive which installs the {@link MaxValidator} for any `formControlName`,
 * `formControl`, or control with `ngModel` that also has a `max` attribute.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a max validator
 *
 * The following example shows how to add a max validator to an input attached to an
 * ngModel binding.
 *
 * ```html
 * <input type="number" ngModel max="4">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let MaxValidator = /*#__PURE__*/(() => {
  class MaxValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the max bound to this directive.
     */
    max;
    /** @internal */
    inputName = 'max';
    /** @internal */
    normalizeInput = input => toFloat(input);
    /** @internal */
    createValidator = max => maxValidator(max);
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵMaxValidator_BaseFactory;
      return function MaxValidator_Factory(__ngFactoryType__) {
        return (ɵMaxValidator_BaseFactory || (ɵMaxValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](MaxValidator)))(__ngFactoryType__ || MaxValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: MaxValidator,
      selectors: [["input", "type", "number", "max", "", "formControlName", ""], ["input", "type", "number", "max", "", "formControl", ""], ["input", "type", "number", "max", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function MaxValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("max", ctx._enabled ? ctx.max : null);
        }
      },
      inputs: {
        max: "max"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([MAX_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return MaxValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `MinValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const MIN_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => MinValidator),
  multi: true
};
/**
 * A directive which installs the {@link MinValidator} for any `formControlName`,
 * `formControl`, or control with `ngModel` that also has a `min` attribute.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a min validator
 *
 * The following example shows how to add a min validator to an input attached to an
 * ngModel binding.
 *
 * ```html
 * <input type="number" ngModel min="4">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let MinValidator = /*#__PURE__*/(() => {
  class MinValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the min bound to this directive.
     */
    min;
    /** @internal */
    inputName = 'min';
    /** @internal */
    normalizeInput = input => toFloat(input);
    /** @internal */
    createValidator = min => minValidator(min);
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵMinValidator_BaseFactory;
      return function MinValidator_Factory(__ngFactoryType__) {
        return (ɵMinValidator_BaseFactory || (ɵMinValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](MinValidator)))(__ngFactoryType__ || MinValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: MinValidator,
      selectors: [["input", "type", "number", "min", "", "formControlName", ""], ["input", "type", "number", "min", "", "formControl", ""], ["input", "type", "number", "min", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function MinValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("min", ctx._enabled ? ctx.min : null);
        }
      },
      inputs: {
        min: "min"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([MIN_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return MinValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `RequiredValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const REQUIRED_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => RequiredValidator),
  multi: true
};
/**
 * @description
 * Provider which adds `CheckboxRequiredValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const CHECKBOX_REQUIRED_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => CheckboxRequiredValidator),
  multi: true
};
/**
 * @description
 * A directive that adds the `required` validator to any controls marked with the
 * `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a required validator using template-driven forms
 *
 * ```
 * <input name="fullName" ngModel required>
 * ```
 *
 * @ngModule FormsModule
 * @ngModule ReactiveFormsModule
 * @publicApi
 */
let RequiredValidator = /*#__PURE__*/(() => {
  class RequiredValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the required attribute bound to this directive.
     */
    required;
    /** @internal */
    inputName = 'required';
    /** @internal */
    normalizeInput = (() => _angular_core__WEBPACK_IMPORTED_MODULE_0__.booleanAttribute)();
    /** @internal */
    createValidator = input => requiredValidator;
    /** @nodoc */
    enabled(input) {
      return input;
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵRequiredValidator_BaseFactory;
      return function RequiredValidator_Factory(__ngFactoryType__) {
        return (ɵRequiredValidator_BaseFactory || (ɵRequiredValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](RequiredValidator)))(__ngFactoryType__ || RequiredValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: RequiredValidator,
      selectors: [["", "required", "", "formControlName", "", 3, "type", "checkbox"], ["", "required", "", "formControl", "", 3, "type", "checkbox"], ["", "required", "", "ngModel", "", 3, "type", "checkbox"]],
      hostVars: 1,
      hostBindings: function RequiredValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("required", ctx._enabled ? "" : null);
        }
      },
      inputs: {
        required: "required"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([REQUIRED_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return RequiredValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * A Directive that adds the `required` validator to checkbox controls marked with the
 * `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a required checkbox validator using template-driven forms
 *
 * The following example shows how to add a checkbox required validator to an input attached to an
 * ngModel binding.
 *
 * ```
 * <input type="checkbox" name="active" ngModel required>
 * ```
 *
 * @publicApi
 * @ngModule FormsModule
 * @ngModule ReactiveFormsModule
 */
let CheckboxRequiredValidator = /*#__PURE__*/(() => {
  class CheckboxRequiredValidator extends RequiredValidator {
    /** @internal */
    createValidator = input => requiredTrueValidator;
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵCheckboxRequiredValidator_BaseFactory;
      return function CheckboxRequiredValidator_Factory(__ngFactoryType__) {
        return (ɵCheckboxRequiredValidator_BaseFactory || (ɵCheckboxRequiredValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](CheckboxRequiredValidator)))(__ngFactoryType__ || CheckboxRequiredValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: CheckboxRequiredValidator,
      selectors: [["input", "type", "checkbox", "required", "", "formControlName", ""], ["input", "type", "checkbox", "required", "", "formControl", ""], ["input", "type", "checkbox", "required", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function CheckboxRequiredValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("required", ctx._enabled ? "" : null);
        }
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([CHECKBOX_REQUIRED_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return CheckboxRequiredValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `EmailValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const EMAIL_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => EmailValidator),
  multi: true
};
/**
 * A directive that adds the `email` validator to controls marked with the
 * `email` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * The email validation is based on the WHATWG HTML specification with some enhancements to
 * incorporate more RFC rules. More information can be found on the [Validators.email
 * page](api/forms/Validators#email).
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding an email validator
 *
 * The following example shows how to add an email validator to an input attached to an ngModel
 * binding.
 *
 * ```
 * <input type="email" name="email" ngModel email>
 * <input type="email" name="email" ngModel email="true">
 * <input type="email" name="email" ngModel [email]="true">
 * ```
 *
 * @publicApi
 * @ngModule FormsModule
 * @ngModule ReactiveFormsModule
 */
let EmailValidator = /*#__PURE__*/(() => {
  class EmailValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the email attribute bound to this directive.
     */
    email;
    /** @internal */
    inputName = 'email';
    /** @internal */
    normalizeInput = (() => _angular_core__WEBPACK_IMPORTED_MODULE_0__.booleanAttribute)();
    /** @internal */
    createValidator = input => emailValidator;
    /** @nodoc */
    enabled(input) {
      return input;
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵEmailValidator_BaseFactory;
      return function EmailValidator_Factory(__ngFactoryType__) {
        return (ɵEmailValidator_BaseFactory || (ɵEmailValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](EmailValidator)))(__ngFactoryType__ || EmailValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: EmailValidator,
      selectors: [["", "email", "", "formControlName", ""], ["", "email", "", "formControl", ""], ["", "email", "", "ngModel", ""]],
      inputs: {
        email: "email"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([EMAIL_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return EmailValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `MinLengthValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const MIN_LENGTH_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => MinLengthValidator),
  multi: true
};
/**
 * A directive that adds minimum length validation to controls marked with the
 * `minlength` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a minimum length validator
 *
 * The following example shows how to add a minimum length validator to an input attached to an
 * ngModel binding.
 *
 * ```html
 * <input name="firstName" ngModel minlength="4">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let MinLengthValidator = /*#__PURE__*/(() => {
  class MinLengthValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the minimum length bound to this directive.
     */
    minlength;
    /** @internal */
    inputName = 'minlength';
    /** @internal */
    normalizeInput = input => toInteger(input);
    /** @internal */
    createValidator = minlength => minLengthValidator(minlength);
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵMinLengthValidator_BaseFactory;
      return function MinLengthValidator_Factory(__ngFactoryType__) {
        return (ɵMinLengthValidator_BaseFactory || (ɵMinLengthValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](MinLengthValidator)))(__ngFactoryType__ || MinLengthValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: MinLengthValidator,
      selectors: [["", "minlength", "", "formControlName", ""], ["", "minlength", "", "formControl", ""], ["", "minlength", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function MinLengthValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("minlength", ctx._enabled ? ctx.minlength : null);
        }
      },
      inputs: {
        minlength: "minlength"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([MIN_LENGTH_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return MinLengthValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `MaxLengthValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const MAX_LENGTH_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => MaxLengthValidator),
  multi: true
};
/**
 * A directive that adds maximum length validation to controls marked with the
 * `maxlength` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a maximum length validator
 *
 * The following example shows how to add a maximum length validator to an input attached to an
 * ngModel binding.
 *
 * ```html
 * <input name="firstName" ngModel maxlength="25">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let MaxLengthValidator = /*#__PURE__*/(() => {
  class MaxLengthValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the maximum length bound to this directive.
     */
    maxlength;
    /** @internal */
    inputName = 'maxlength';
    /** @internal */
    normalizeInput = input => toInteger(input);
    /** @internal */
    createValidator = maxlength => maxLengthValidator(maxlength);
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵMaxLengthValidator_BaseFactory;
      return function MaxLengthValidator_Factory(__ngFactoryType__) {
        return (ɵMaxLengthValidator_BaseFactory || (ɵMaxLengthValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](MaxLengthValidator)))(__ngFactoryType__ || MaxLengthValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: MaxLengthValidator,
      selectors: [["", "maxlength", "", "formControlName", ""], ["", "maxlength", "", "formControl", ""], ["", "maxlength", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function MaxLengthValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("maxlength", ctx._enabled ? ctx.maxlength : null);
        }
      },
      inputs: {
        maxlength: "maxlength"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([MAX_LENGTH_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return MaxLengthValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * Provider which adds `PatternValidator` to the `NG_VALIDATORS` multi-provider list.
 */
const PATTERN_VALIDATOR = {
  provide: NG_VALIDATORS,
  useExisting: /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(() => PatternValidator),
  multi: true
};
/**
 * @description
 * A directive that adds regex pattern validation to controls marked with the
 * `pattern` attribute. The regex must match the entire control value.
 * The directive is provided with the `NG_VALIDATORS` multi-provider list.
 *
 * @see [Form Validation](guide/forms/form-validation)
 *
 * @usageNotes
 *
 * ### Adding a pattern validator
 *
 * The following example shows how to add a pattern validator to an input attached to an
 * ngModel binding.
 *
 * ```html
 * <input name="firstName" ngModel pattern="[a-zA-Z ]*">
 * ```
 *
 * @ngModule ReactiveFormsModule
 * @ngModule FormsModule
 * @publicApi
 */
let PatternValidator = /*#__PURE__*/(() => {
  class PatternValidator extends AbstractValidatorDirective {
    /**
     * @description
     * Tracks changes to the pattern bound to this directive.
     */
    pattern; // This input is always defined, since the name matches selector.
    /** @internal */
    inputName = 'pattern';
    /** @internal */
    normalizeInput = input => input;
    /** @internal */
    createValidator = input => patternValidator(input);
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵPatternValidator_BaseFactory;
      return function PatternValidator_Factory(__ngFactoryType__) {
        return (ɵPatternValidator_BaseFactory || (ɵPatternValidator_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](PatternValidator)))(__ngFactoryType__ || PatternValidator);
      };
    })())();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({
      type: PatternValidator,
      selectors: [["", "pattern", "", "formControlName", ""], ["", "pattern", "", "formControl", ""], ["", "pattern", "", "ngModel", ""]],
      hostVars: 1,
      hostBindings: function PatternValidator_HostBindings(rf, ctx) {
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("pattern", ctx._enabled ? ctx.pattern : null);
        }
      },
      inputs: {
        pattern: "pattern"
      },
      standalone: false,
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([PATTERN_VALIDATOR]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵInheritDefinitionFeature"]]
    }))();
  }
  return PatternValidator;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const SHARED_FORM_DIRECTIVES = [ɵNgNoValidate, NgSelectOption, ɵNgSelectMultipleOption, DefaultValueAccessor, NumberValueAccessor, RangeValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor, RadioControlValueAccessor, NgControlStatus, NgControlStatusGroup, RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator, CheckboxRequiredValidator, EmailValidator, MinValidator, MaxValidator];
const TEMPLATE_DRIVEN_DIRECTIVES = [NgModel, NgModelGroup, NgForm];
const REACTIVE_DRIVEN_DIRECTIVES = [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];
/**
 * Internal module used for sharing directives between FormsModule and ReactiveFormsModule
 */
let ɵInternalFormsSharedModule = /*#__PURE__*/(() => {
  class ɵInternalFormsSharedModule {
    static ɵfac = (() => function ɵInternalFormsSharedModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ɵInternalFormsSharedModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({
      type: ɵInternalFormsSharedModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({}))();
  }
  return ɵInternalFormsSharedModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Tracks the value and validity state of an array of `FormControl`,
 * `FormGroup` or `FormArray` instances.
 *
 * A `FormArray` aggregates the values of each child `FormControl` into an array.
 * It calculates its status by reducing the status values of its children. For example, if one of
 * the controls in a `FormArray` is invalid, the entire array becomes invalid.
 *
 * `FormArray` accepts one generic argument, which is the type of the controls inside.
 * If you need a heterogenous array, use {@link UntypedFormArray}.
 *
 * `FormArray` is one of the four fundamental building blocks used to define forms in Angular,
 * along with `FormControl`, `FormGroup`, and `FormRecord`.
 *
 * @usageNotes
 *
 * ### Create an array of form controls
 *
 * ```
 * const arr = new FormArray([
 *   new FormControl('Nancy', Validators.minLength(2)),
 *   new FormControl('Drew'),
 * ]);
 *
 * console.log(arr.value);   // ['Nancy', 'Drew']
 * console.log(arr.status);  // 'VALID'
 * ```
 *
 * ### Create a form array with array-level validators
 *
 * You include array-level validators and async validators. These come in handy
 * when you want to perform validation that considers the value of more than one child
 * control.
 *
 * The two types of validators are passed in separately as the second and third arg
 * respectively, or together as part of an options object.
 *
 * ```
 * const arr = new FormArray([
 *   new FormControl('Nancy'),
 *   new FormControl('Drew')
 * ], {validators: myValidator, asyncValidators: myAsyncValidator});
 * ```
 *
 * ### Set the updateOn property for all controls in a form array
 *
 * The options object is used to set a default value for each child
 * control's `updateOn` property. If you set `updateOn` to `'blur'` at the
 * array level, all child controls default to 'blur', unless the child
 * has explicitly specified a different `updateOn` value.
 *
 * ```ts
 * const arr = new FormArray([
 *    new FormControl()
 * ], {updateOn: 'blur'});
 * ```
 *
 * ### Adding or removing controls from a form array
 *
 * To change the controls in the array, use the `push`, `insert`, `removeAt` or `clear` methods
 * in `FormArray` itself. These methods ensure the controls are properly tracked in the
 * form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
 * the `FormArray` directly, as that result in strange and unexpected behavior such
 * as broken change detection.
 *
 * @publicApi
 */
class FormArray extends AbstractControl {
  /**
   * Creates a new `FormArray` instance.
   *
   * @param controls An array of child controls. Each child control is given an index
   * where it is registered.
   *
   * @param validatorOrOpts A synchronous validator function, or an array of
   * such functions, or an `AbstractControlOptions` object that contains validation functions
   * and a validation trigger.
   *
   * @param asyncValidator A single async validator or array of async validator functions
   *
   */
  constructor(controls, validatorOrOpts, asyncValidator) {
    super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
    this.controls = controls;
    this._initObservables();
    this._setUpdateStrategy(validatorOrOpts);
    this._setUpControls();
    this.updateValueAndValidity({
      onlySelf: true,
      // If `asyncValidator` is present, it will trigger control status change from `PENDING` to
      // `VALID` or `INVALID`.
      // The status should be broadcasted via the `statusChanges` observable, so we set `emitEvent`
      // to `true` to allow that during the control creation process.
      emitEvent: !!this.asyncValidator
    });
  }
  controls;
  /**
   * Get the `AbstractControl` at the given `index` in the array.
   *
   * @param index Index in the array to retrieve the control. If `index` is negative, it will wrap
   *     around from the back, and if index is greatly negative (less than `-length`), the result is
   * undefined. This behavior is the same as `Array.at(index)`.
   */
  at(index) {
    return this.controls[this._adjustIndex(index)];
  }
  /**
   * Insert a new `AbstractControl` at the end of the array.
   *
   * @param control Form control to be inserted
   * @param options Specifies whether this FormArray instance should emit events after a new
   *     control is added.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control is
   * inserted. When false, no events are emitted.
   */
  push(control, options = {}) {
    this.controls.push(control);
    this._registerControl(control);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
    this._onCollectionChange();
  }
  /**
   * Insert a new `AbstractControl` at the given `index` in the array.
   *
   * @param index Index in the array to insert the control. If `index` is negative, wraps around
   *     from the back. If `index` is greatly negative (less than `-length`), prepends to the array.
   * This behavior is the same as `Array.splice(index, 0, control)`.
   * @param control Form control to be inserted
   * @param options Specifies whether this FormArray instance should emit events after a new
   *     control is inserted.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control is
   * inserted. When false, no events are emitted.
   */
  insert(index, control, options = {}) {
    this.controls.splice(index, 0, control);
    this._registerControl(control);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
  }
  /**
   * Remove the control at the given `index` in the array.
   *
   * @param index Index in the array to remove the control.  If `index` is negative, wraps around
   *     from the back. If `index` is greatly negative (less than `-length`), removes the first
   *     element. This behavior is the same as `Array.splice(index, 1)`.
   * @param options Specifies whether this FormArray instance should emit events after a
   *     control is removed.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control is
   * removed. When false, no events are emitted.
   */
  removeAt(index, options = {}) {
    // Adjust the index, then clamp it at no less than 0 to prevent undesired underflows.
    let adjustedIndex = this._adjustIndex(index);
    if (adjustedIndex < 0) adjustedIndex = 0;
    if (this.controls[adjustedIndex]) this.controls[adjustedIndex]._registerOnCollectionChange(() => {});
    this.controls.splice(adjustedIndex, 1);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
  }
  /**
   * Replace an existing control.
   *
   * @param index Index in the array to replace the control. If `index` is negative, wraps around
   *     from the back. If `index` is greatly negative (less than `-length`), replaces the first
   *     element. This behavior is the same as `Array.splice(index, 1, control)`.
   * @param control The `AbstractControl` control to replace the existing control
   * @param options Specifies whether this FormArray instance should emit events after an
   *     existing control is replaced with a new one.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control is
   * replaced with a new one. When false, no events are emitted.
   */
  setControl(index, control, options = {}) {
    // Adjust the index, then clamp it at no less than 0 to prevent undesired underflows.
    let adjustedIndex = this._adjustIndex(index);
    if (adjustedIndex < 0) adjustedIndex = 0;
    if (this.controls[adjustedIndex]) this.controls[adjustedIndex]._registerOnCollectionChange(() => {});
    this.controls.splice(adjustedIndex, 1);
    if (control) {
      this.controls.splice(adjustedIndex, 0, control);
      this._registerControl(control);
    }
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
    this._onCollectionChange();
  }
  /**
   * Length of the control array.
   */
  get length() {
    return this.controls.length;
  }
  /**
   * Sets the value of the `FormArray`. It accepts an array that matches
   * the structure of the control.
   *
   * This method performs strict checks, and throws an error if you try
   * to set the value of a control that doesn't exist or if you exclude the
   * value of a control.
   *
   * @usageNotes
   * ### Set the values for the controls in the form array
   *
   * ```
   * const arr = new FormArray([
   *   new FormControl(),
   *   new FormControl()
   * ]);
   * console.log(arr.value);   // [null, null]
   *
   * arr.setValue(['Nancy', 'Drew']);
   * console.log(arr.value);   // ['Nancy', 'Drew']
   * ```
   *
   * @param value Array of values for the controls
   * @param options Configure options that determine how the control propagates changes and
   * emits events after the value changes
   *
   * * `onlySelf`: When true, each change only affects this control, and not its parent. Default
   * is false.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges`
   * observables emit events with the latest status and value when the control value is updated.
   * When false, no events are emitted.
   * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
   * updateValueAndValidity} method.
   */
  setValue(value, options = {}) {
    assertAllValuesPresent(this, false, value);
    value.forEach((newValue, index) => {
      assertControlPresent(this, false, index);
      this.at(index).setValue(newValue, {
        onlySelf: true,
        emitEvent: options.emitEvent
      });
    });
    this.updateValueAndValidity(options);
  }
  /**
   * Patches the value of the `FormArray`. It accepts an array that matches the
   * structure of the control, and does its best to match the values to the correct
   * controls in the group.
   *
   * It accepts both super-sets and sub-sets of the array without throwing an error.
   *
   * @usageNotes
   * ### Patch the values for controls in a form array
   *
   * ```
   * const arr = new FormArray([
   *    new FormControl(),
   *    new FormControl()
   * ]);
   * console.log(arr.value);   // [null, null]
   *
   * arr.patchValue(['Nancy']);
   * console.log(arr.value);   // ['Nancy', null]
   * ```
   *
   * @param value Array of latest values for the controls
   * @param options Configure options that determine how the control propagates changes and
   * emits events after the value changes
   *
   * * `onlySelf`: When true, each change only affects this control, and not its parent. Default
   * is false.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when the control
   * value is updated. When false, no events are emitted. The configuration options are passed to
   * the {@link AbstractControl#updateValueAndValidity updateValueAndValidity} method.
   */
  patchValue(value, options = {}) {
    // Even though the `value` argument type doesn't allow `null` and `undefined` values, the
    // `patchValue` can be called recursively and inner data structures might have these values,
    // so we just ignore such cases when a field containing FormArray instance receives `null` or
    // `undefined` as a value.
    if (value == null /* both `null` and `undefined` */) return;
    value.forEach((newValue, index) => {
      if (this.at(index)) {
        this.at(index).patchValue(newValue, {
          onlySelf: true,
          emitEvent: options.emitEvent
        });
      }
    });
    this.updateValueAndValidity(options);
  }
  /**
   * Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the
   * value of all descendants to null or null maps.
   *
   * You reset to a specific form state by passing in an array of states
   * that matches the structure of the control. The state is a standalone value
   * or a form state object with both a value and a disabled status.
   *
   * @usageNotes
   * ### Reset the values in a form array
   *
   * ```ts
   * const arr = new FormArray([
   *    new FormControl(),
   *    new FormControl()
   * ]);
   * arr.reset(['name', 'last name']);
   *
   * console.log(arr.value);  // ['name', 'last name']
   * ```
   *
   * ### Reset the values in a form array and the disabled status for the first control
   *
   * ```
   * arr.reset([
   *   {value: 'name', disabled: true},
   *   'last'
   * ]);
   *
   * console.log(arr.value);  // ['last']
   * console.log(arr.at(0).status);  // 'DISABLED'
   * ```
   *
   * @param value Array of values for the controls
   * @param options Configure options that determine how the control propagates changes and
   * emits events after the value changes
   *
   * * `onlySelf`: When true, each change only affects this control, and not its parent. Default
   * is false.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges`
   * observables emit events with the latest status and value when the control is reset.
   * When false, no events are emitted.
   * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
   * updateValueAndValidity} method.
   */
  reset(value = [], options = {}) {
    this._forEachChild((control, index) => {
      control.reset(value[index], {
        onlySelf: true,
        emitEvent: options.emitEvent
      });
    });
    this._updatePristine(options, this);
    this._updateTouched(options, this);
    this.updateValueAndValidity(options);
  }
  /**
   * The aggregate value of the array, including any disabled controls.
   *
   * Reports all values regardless of disabled status.
   */
  getRawValue() {
    return this.controls.map(control => control.getRawValue());
  }
  /**
   * Remove all controls in the `FormArray`.
   *
   * @param options Specifies whether this FormArray instance should emit events after all
   *     controls are removed.
   * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
   * `valueChanges` observables emit events with the latest status and value when all controls
   * in this FormArray instance are removed. When false, no events are emitted.
   *
   * @usageNotes
   * ### Remove all elements from a FormArray
   *
   * ```ts
   * const arr = new FormArray([
   *    new FormControl(),
   *    new FormControl()
   * ]);
   * console.log(arr.length);  // 2
   *
   * arr.clear();
   * console.log(arr.length);  // 0
   * ```
   *
   * It's a simpler and more efficient alternative to removing all elements one by one:
   *
   * ```ts
   * const arr = new FormArray([
   *    new FormControl(),
   *    new FormControl()
   * ]);
   *
   * while (arr.length) {
   *    arr.removeAt(0);
   * }
   * ```
   */
  clear(options = {}) {
    if (this.controls.length < 1) return;
    this._forEachChild(control => control._registerOnCollectionChange(() => {}));
    this.controls.splice(0);
    this.updateValueAndValidity({
      emitEvent: options.emitEvent
    });
  }
  /**
   * Adjusts a negative index by summing it with the length of the array. For very negative
   * indices, the result may remain negative.
   * @internal
   */
  _adjustIndex(index) {
    return index < 0 ? index + this.length : index;
  }
  /** @internal */
  _syncPendingControls() {
    let subtreeUpdated = this.controls.reduce((updated, child) => {
      return child._syncPendingControls() ? true : updated;
    }, false);
    if (subtreeUpdated) this.updateValueAndValidity({
      onlySelf: true
    });
    return subtreeUpdated;
  }
  /** @internal */
  _forEachChild(cb) {
    this.controls.forEach((control, index) => {
      cb(control, index);
    });
  }
  /** @internal */
  _updateValue() {
    this.value = this.controls.filter(control => control.enabled || this.disabled).map(control => control.value);
  }
  /** @internal */
  _anyControls(condition) {
    return this.controls.some(control => control.enabled && condition(control));
  }
  /** @internal */
  _setUpControls() {
    this._forEachChild(control => this._registerControl(control));
  }
  /** @internal */
  _allControlsDisabled() {
    for (const control of this.controls) {
      if (control.enabled) return false;
    }
    return this.controls.length > 0 || this.disabled;
  }
  _registerControl(control) {
    control.setParent(this);
    control._registerOnCollectionChange(this._onCollectionChange);
  }
  /** @internal */
  _find(name) {
    return this.at(name) ?? null;
  }
}
const UntypedFormArray = FormArray;
/**
 * @description
 * Asserts that the given control is an instance of `FormArray`
 *
 * @publicApi
 */
const isFormArray = control => control instanceof FormArray;
function isAbstractControlOptions(options) {
  return !!options && (options.asyncValidators !== undefined || options.validators !== undefined || options.updateOn !== undefined);
}
/**
 * @description
 * Creates an `AbstractControl` from a user-specified configuration.
 *
 * The `FormBuilder` provides syntactic sugar that shortens creating instances of a
 * `FormControl`, `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to
 * build complex forms.
 *
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 *
 * @publicApi
 */
let FormBuilder = /*#__PURE__*/(() => {
  class FormBuilder {
    useNonNullable = false;
    /**
     * @description
     * Returns a FormBuilder in which automatically constructed `FormControl` elements
     * have `{nonNullable: true}` and are non-nullable.
     *
     * **Constructing non-nullable controls**
     *
     * When constructing a control, it will be non-nullable, and will reset to its initial value.
     *
     * ```ts
     * let nnfb = new FormBuilder().nonNullable;
     * let name = nnfb.control('Alex'); // FormControl<string>
     * name.reset();
     * console.log(name); // 'Alex'
     * ```
     *
     * **Constructing non-nullable groups or arrays**
     *
     * When constructing a group or array, all automatically created inner controls will be
     * non-nullable, and will reset to their initial values.
     *
     * ```ts
     * let nnfb = new FormBuilder().nonNullable;
     * let name = nnfb.group({who: 'Alex'}); // FormGroup<{who: FormControl<string>}>
     * name.reset();
     * console.log(name); // {who: 'Alex'}
     * ```
     * **Constructing *nullable* fields on groups or arrays**
     *
     * It is still possible to have a nullable field. In particular, any `FormControl` which is
     * *already* constructed will not be altered. For example:
     *
     * ```ts
     * let nnfb = new FormBuilder().nonNullable;
     * // FormGroup<{who: FormControl<string|null>}>
     * let name = nnfb.group({who: new FormControl('Alex')});
     * name.reset(); console.log(name); // {who: null}
     * ```
     *
     * Because the inner control is constructed explicitly by the caller, the builder has
     * no control over how it is created, and cannot exclude the `null`.
     */
    get nonNullable() {
      const nnfb = new FormBuilder();
      nnfb.useNonNullable = true;
      return nnfb;
    }
    group(controls, options = null) {
      const reducedControls = this._reduceControls(controls);
      let newOptions = {};
      if (isAbstractControlOptions(options)) {
        // `options` are `AbstractControlOptions`
        newOptions = options;
      } else if (options !== null) {
        // `options` are legacy form group options
        newOptions.validators = options.validator;
        newOptions.asyncValidators = options.asyncValidator;
      }
      return new FormGroup(reducedControls, newOptions);
    }
    /**
     * @description
     * Constructs a new `FormRecord` instance. Accepts a single generic argument, which is an object
     * containing all the keys and corresponding inner control types.
     *
     * @param controls A collection of child controls. The key for each child is the name
     * under which it is registered.
     *
     * @param options Configuration options object for the `FormRecord`. The object should have the
     * `AbstractControlOptions` type and might contain the following fields:
     * * `validators`: A synchronous validator function, or an array of validator functions.
     * * `asyncValidators`: A single async validator or array of async validator functions.
     * * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur'
     * | submit').
     */
    record(controls, options = null) {
      const reducedControls = this._reduceControls(controls);
      // Cast to `any` because the inferred types are not as specific as Element.
      return new FormRecord(reducedControls, options);
    }
    /**
     * @description
     * Constructs a new `FormControl` with the given state, validators and options. Sets
     * `{nonNullable: true}` in the options to get a non-nullable control. Otherwise, the
     * control will be nullable. Accepts a single generic argument, which is the type  of the
     * control's value.
     *
     * @param formState Initializes the control with an initial state value, or
     * with an object that contains both a value and a disabled status.
     *
     * @param validatorOrOpts A synchronous validator function, or an array of
     * such functions, or a `FormControlOptions` object that contains
     * validation functions and a validation trigger.
     *
     * @param asyncValidator A single async validator or array of async validator
     * functions.
     *
     * @usageNotes
     *
     * ### Initialize a control as disabled
     *
     * The following example returns a control with an initial value in a disabled state.
     *
     * <code-example path="forms/ts/formBuilder/form_builder_example.ts" region="disabled-control">
     * </code-example>
     */
    control(formState, validatorOrOpts, asyncValidator) {
      let newOptions = {};
      if (!this.useNonNullable) {
        return new FormControl(formState, validatorOrOpts, asyncValidator);
      }
      if (isAbstractControlOptions(validatorOrOpts)) {
        // If the second argument is options, then they are copied.
        newOptions = validatorOrOpts;
      } else {
        // If the other arguments are validators, they are copied into an options object.
        newOptions.validators = validatorOrOpts;
        newOptions.asyncValidators = asyncValidator;
      }
      return new FormControl(formState, {
        ...newOptions,
        nonNullable: true
      });
    }
    /**
     * Constructs a new `FormArray` from the given array of configurations,
     * validators and options. Accepts a single generic argument, which is the type of each control
     * inside the array.
     *
     * @param controls An array of child controls or control configs. Each child control is given an
     *     index when it is registered.
     *
     * @param validatorOrOpts A synchronous validator function, or an array of such functions, or an
     *     `AbstractControlOptions` object that contains
     * validation functions and a validation trigger.
     *
     * @param asyncValidator A single async validator or array of async validator functions.
     */
    array(controls, validatorOrOpts, asyncValidator) {
      const createdControls = controls.map(c => this._createControl(c));
      // Cast to `any` because the inferred types are not as specific as Element.
      return new FormArray(createdControls, validatorOrOpts, asyncValidator);
    }
    /** @internal */
    _reduceControls(controls) {
      const createdControls = {};
      Object.keys(controls).forEach(controlName => {
        createdControls[controlName] = this._createControl(controls[controlName]);
      });
      return createdControls;
    }
    /** @internal */
    _createControl(controls) {
      if (controls instanceof FormControl) {
        return controls;
      } else if (controls instanceof AbstractControl) {
        // A control; just return it
        return controls;
      } else if (Array.isArray(controls)) {
        // ControlConfig Tuple
        const value = controls[0];
        const validator = controls.length > 1 ? controls[1] : null;
        const asyncValidator = controls.length > 2 ? controls[2] : null;
        return this.control(value, validator, asyncValidator);
      } else {
        // T or FormControlState<T>
        return this.control(controls);
      }
    }
    static ɵfac = (() => function FormBuilder_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormBuilder)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: FormBuilder,
      factory: FormBuilder.ɵfac,
      providedIn: 'root'
    }))();
  }
  return FormBuilder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 * `NonNullableFormBuilder` is similar to {@link FormBuilder}, but automatically constructed
 * {@link FormControl} elements have `{nonNullable: true}` and are non-nullable.
 *
 * @publicApi
 */
let NonNullableFormBuilder = /*#__PURE__*/(() => {
  class NonNullableFormBuilder {
    static ɵfac = (() => function NonNullableFormBuilder_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NonNullableFormBuilder)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: NonNullableFormBuilder,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__.inject)(FormBuilder).nonNullable)(),
      providedIn: 'root'
    }))();
  }
  return NonNullableFormBuilder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * UntypedFormBuilder is the same as `FormBuilder`, but it provides untyped controls.
 */
let UntypedFormBuilder = /*#__PURE__*/(() => {
  class UntypedFormBuilder extends FormBuilder {
    group(controlsConfig, options = null) {
      return super.group(controlsConfig, options);
    }
    /**
     * Like `FormBuilder#control`, except the resulting control is untyped.
     */
    control(formState, validatorOrOpts, asyncValidator) {
      return super.control(formState, validatorOrOpts, asyncValidator);
    }
    /**
     * Like `FormBuilder#array`, except the resulting array is untyped.
     */
    array(controlsConfig, validatorOrOpts, asyncValidator) {
      return super.array(controlsConfig, validatorOrOpts, asyncValidator);
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵUntypedFormBuilder_BaseFactory;
      return function UntypedFormBuilder_Factory(__ngFactoryType__) {
        return (ɵUntypedFormBuilder_BaseFactory || (ɵUntypedFormBuilder_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetInheritedFactory"](UntypedFormBuilder)))(__ngFactoryType__ || UntypedFormBuilder);
      };
    })())();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: UntypedFormBuilder,
      factory: UntypedFormBuilder.ɵfac,
      providedIn: 'root'
    }))();
  }
  return UntypedFormBuilder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @module
 * @description
 * Entry point for all public APIs of the forms package.
 */
/**
 * @publicApi
 */
const VERSION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_0__.Version('19.0.0');

/**
 * Exports the required providers and directives for template-driven forms,
 * making them available for import by NgModules that import this module.
 *
 * @see [Forms Overview](guide/forms)
 * @see [Template-driven Forms Guide](guide/forms)
 *
 * @publicApi
 */
let FormsModule = /*#__PURE__*/(() => {
  class FormsModule {
    /**
     * @description
     * Provides options for configuring the forms module.
     *
     * @param opts An object of configuration options
     * * `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more
     * correct, or to only call it `whenDisabled`, which is the legacy behavior.
     */
    static withConfig(opts) {
      return {
        ngModule: FormsModule,
        providers: [{
          provide: CALL_SET_DISABLED_STATE,
          useValue: opts.callSetDisabledState ?? setDisabledStateDefault
        }]
      };
    }
    static ɵfac = (() => function FormsModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || FormsModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({
      type: FormsModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({
      imports: [ɵInternalFormsSharedModule]
    }))();
  }
  return FormsModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Exports the required infrastructure and directives for reactive forms,
 * making them available for import by NgModules that import this module.
 *
 * @see [Forms Overview](guide/forms)
 * @see [Reactive Forms Guide](guide/forms/reactive-forms)
 *
 * @publicApi
 */
let ReactiveFormsModule = /*#__PURE__*/(() => {
  class ReactiveFormsModule {
    /**
     * @description
     * Provides options for configuring the reactive forms module.
     *
     * @param opts An object of configuration options
     * * `warnOnNgModelWithFormControl` Configures when to emit a warning when an `ngModel`
     * binding is used with reactive form directives.
     * * `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more
     * correct, or to only call it `whenDisabled`, which is the legacy behavior.
     */
    static withConfig(opts) {
      return {
        ngModule: ReactiveFormsModule,
        providers: [{
          provide: NG_MODEL_WITH_FORM_CONTROL_WARNING,
          useValue: opts.warnOnNgModelWithFormControl ?? 'always'
        }, {
          provide: CALL_SET_DISABLED_STATE,
          useValue: opts.callSetDisabledState ?? setDisabledStateDefault
        }]
      };
    }
    static ɵfac = (() => function ReactiveFormsModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ReactiveFormsModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({
      type: ReactiveFormsModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({
      imports: [ɵInternalFormsSharedModule]
    }))();
  }
  return ReactiveFormsModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * @module
 * @description
 * This module is used for handling user input, by defining and building a `FormGroup` that
 * consists of `FormControl` objects, and mapping them onto the DOM. `FormControl`
 * objects can then be used to read information from the form DOM elements.
 *
 * Forms providers are not included in default providers; you must import these providers
 * explicitly.
 */

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
// This file only reexports content of the `src` folder. Keep it that way.

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 5251:
/*!********************************************************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+platform-browser@19.0.0_@angular+animations@19.0.0_@angular+core@19.0.0_rxjs@7_fe651220636ef1b4484702c47bc17b74/node_modules/@angular/platform-browser/fesm2022/animations.mjs ***!
  \********************************************************************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ANIMATION_MODULE_TYPE: () => (/* reexport safe */ _angular_core__WEBPACK_IMPORTED_MODULE_0__.ANIMATION_MODULE_TYPE),
/* harmony export */   BrowserAnimationsModule: () => (/* binding */ BrowserAnimationsModule),
/* harmony export */   NoopAnimationsModule: () => (/* binding */ NoopAnimationsModule),
/* harmony export */   provideAnimations: () => (/* binding */ provideAnimations),
/* harmony export */   provideNoopAnimations: () => (/* binding */ provideNoopAnimations),
/* harmony export */   "ɵInjectableAnimationEngine": () => (/* binding */ InjectableAnimationEngine)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/platform-browser */ 4604);
/* harmony import */ var _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/animations/browser */ 8747);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ 6216);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */








let InjectableAnimationEngine = /*#__PURE__*/(() => {
  class InjectableAnimationEngine extends _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationEngine"] {
    // The `ApplicationRef` is injected here explicitly to force the dependency ordering.
    // Since the `ApplicationRef` should be created earlier before the `AnimationEngine`, they
    // both have `ngOnDestroy` hooks and `flush()` must be called after all views are destroyed.
    constructor(doc, driver, normalizer) {
      super(doc, driver, normalizer);
    }
    ngOnDestroy() {
      this.flush();
    }
    static ɵfac = (() => function InjectableAnimationEngine_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || InjectableAnimationEngine)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_2__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__.AnimationDriver), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationStyleNormalizer"]));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({
      token: InjectableAnimationEngine,
      factory: InjectableAnimationEngine.ɵfac
    }))();
  }
  return InjectableAnimationEngine;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function instantiateDefaultStyleNormalizer() {
  return new _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵWebAnimationsStyleNormalizer"]();
}
function instantiateRendererFactory(renderer, engine, zone) {
  return new _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationRendererFactory"](renderer, engine, zone);
}
const SHARED_ANIMATION_PROVIDERS = [{
  provide: _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationStyleNormalizer"],
  useFactory: instantiateDefaultStyleNormalizer
}, {
  provide: _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationEngine"],
  useClass: InjectableAnimationEngine
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_0__.RendererFactory2,
  useFactory: instantiateRendererFactory,
  deps: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__["ɵDomRendererFactory2"], _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵAnimationEngine"], _angular_core__WEBPACK_IMPORTED_MODULE_0__.NgZone]
}];
/**
 * Separate providers from the actual module so that we can do a local modification in Google3 to
 * include them in the BrowserModule.
 */
const BROWSER_ANIMATIONS_PROVIDERS = [{
  provide: _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__.AnimationDriver,
  useFactory: () => new _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__["ɵWebAnimationsDriver"]()
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ANIMATION_MODULE_TYPE,
  useValue: 'BrowserAnimations'
}, ...SHARED_ANIMATION_PROVIDERS];
/**
 * Separate providers from the actual module so that we can do a local modification in Google3 to
 * include them in the BrowserTestingModule.
 */
const BROWSER_NOOP_ANIMATIONS_PROVIDERS = [{
  provide: _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__.AnimationDriver,
  useClass: _angular_animations_browser__WEBPACK_IMPORTED_MODULE_1__.NoopAnimationDriver
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ANIMATION_MODULE_TYPE,
  useValue: 'NoopAnimations'
}, ...SHARED_ANIMATION_PROVIDERS];

/**
 * Exports `BrowserModule` with additional dependency-injection providers
 * for use with animations. See [Animations](guide/animations).
 * @publicApi
 */
let BrowserAnimationsModule = /*#__PURE__*/(() => {
  class BrowserAnimationsModule {
    /**
     * Configures the module based on the specified object.
     *
     * @param config Object used to configure the behavior of the `BrowserAnimationsModule`.
     * @see {@link BrowserAnimationsModuleConfig}
     *
     * @usageNotes
     * When registering the `BrowserAnimationsModule`, you can use the `withConfig`
     * function as follows:
     * ```
     * @NgModule({
     *   imports: [BrowserAnimationsModule.withConfig(config)]
     * })
     * class MyNgModule {}
     * ```
     */
    static withConfig(config) {
      return {
        ngModule: BrowserAnimationsModule,
        providers: config.disableAnimations ? BROWSER_NOOP_ANIMATIONS_PROVIDERS : BROWSER_ANIMATIONS_PROVIDERS
      };
    }
    static ɵfac = (() => function BrowserAnimationsModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BrowserAnimationsModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({
      type: BrowserAnimationsModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({
      providers: BROWSER_ANIMATIONS_PROVIDERS,
      imports: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__.BrowserModule]
    }))();
  }
  return BrowserAnimationsModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Returns the set of dependency-injection providers
 * to enable animations in an application. See [animations guide](guide/animations)
 * to learn more about animations in Angular.
 *
 * @usageNotes
 *
 * The function is useful when you want to enable animations in an application
 * bootstrapped using the `bootstrapApplication` function. In this scenario there
 * is no need to import the `BrowserAnimationsModule` NgModule at all, just add
 * providers returned by this function to the `providers` list as show below.
 *
 * ```typescript
 * bootstrapApplication(RootComponent, {
 *   providers: [
 *     provideAnimations()
 *   ]
 * });
 * ```
 *
 * @publicApi
 */
function provideAnimations() {
  (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵperformanceMarkFeature"])('NgEagerAnimations');
  // Return a copy to prevent changes to the original array in case any in-place
  // alterations are performed to the `provideAnimations` call results in app code.
  return [...BROWSER_ANIMATIONS_PROVIDERS];
}
/**
 * A null player that must be imported to allow disabling of animations.
 * @publicApi
 */
let NoopAnimationsModule = /*#__PURE__*/(() => {
  class NoopAnimationsModule {
    static ɵfac = (() => function NoopAnimationsModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NoopAnimationsModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({
      type: NoopAnimationsModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({
      providers: BROWSER_NOOP_ANIMATIONS_PROVIDERS,
      imports: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__.BrowserModule]
    }))();
  }
  return NoopAnimationsModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Returns the set of dependency-injection providers
 * to disable animations in an application. See [animations guide](guide/animations)
 * to learn more about animations in Angular.
 *
 * @usageNotes
 *
 * The function is useful when you want to bootstrap an application using
 * the `bootstrapApplication` function, but you need to disable animations
 * (for example, when running tests).
 *
 * ```typescript
 * bootstrapApplication(RootComponent, {
 *   providers: [
 *     provideNoopAnimations()
 *   ]
 * });
 * ```
 *
 * @publicApi
 */
function provideNoopAnimations() {
  // Return a copy to prevent changes to the original array in case any in-place
  // alterations are performed to the `provideNoopAnimations` call results in app code.
  return [...BROWSER_NOOP_ANIMATIONS_PROVIDERS];
}

/**
 * @module
 * @description
 * Entry point for all animation APIs of the animation browser package.
 */

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 4604:
/*!**************************************************************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+platform-browser@19.0.0_@angular+animations@19.0.0_@angular+core@19.0.0_rxjs@7_fe651220636ef1b4484702c47bc17b74/node_modules/@angular/platform-browser/fesm2022/platform-browser.mjs ***!
  \**************************************************************************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   BrowserModule: () => (/* binding */ BrowserModule),
/* harmony export */   By: () => (/* binding */ By),
/* harmony export */   DomSanitizer: () => (/* binding */ DomSanitizer),
/* harmony export */   EVENT_MANAGER_PLUGINS: () => (/* binding */ EVENT_MANAGER_PLUGINS),
/* harmony export */   EventManager: () => (/* binding */ EventManager),
/* harmony export */   EventManagerPlugin: () => (/* binding */ EventManagerPlugin),
/* harmony export */   HAMMER_GESTURE_CONFIG: () => (/* binding */ HAMMER_GESTURE_CONFIG),
/* harmony export */   HAMMER_LOADER: () => (/* binding */ HAMMER_LOADER),
/* harmony export */   HammerGestureConfig: () => (/* binding */ HammerGestureConfig),
/* harmony export */   HammerModule: () => (/* binding */ HammerModule),
/* harmony export */   HydrationFeatureKind: () => (/* binding */ HydrationFeatureKind),
/* harmony export */   Meta: () => (/* binding */ Meta),
/* harmony export */   REMOVE_STYLES_ON_COMPONENT_DESTROY: () => (/* binding */ REMOVE_STYLES_ON_COMPONENT_DESTROY),
/* harmony export */   Title: () => (/* binding */ Title),
/* harmony export */   VERSION: () => (/* binding */ VERSION),
/* harmony export */   bootstrapApplication: () => (/* binding */ bootstrapApplication),
/* harmony export */   createApplication: () => (/* binding */ createApplication),
/* harmony export */   disableDebugTools: () => (/* binding */ disableDebugTools),
/* harmony export */   enableDebugTools: () => (/* binding */ enableDebugTools),
/* harmony export */   platformBrowser: () => (/* binding */ platformBrowser),
/* harmony export */   provideClientHydration: () => (/* binding */ provideClientHydration),
/* harmony export */   provideProtractorTestingSupport: () => (/* binding */ provideProtractorTestingSupport),
/* harmony export */   withEventReplay: () => (/* binding */ withEventReplay),
/* harmony export */   withHttpTransferCacheOptions: () => (/* binding */ withHttpTransferCacheOptions),
/* harmony export */   withI18nSupport: () => (/* binding */ withI18nSupport),
/* harmony export */   withIncrementalHydration: () => (/* binding */ withIncrementalHydration),
/* harmony export */   withNoHttpTransferCache: () => (/* binding */ withNoHttpTransferCache),
/* harmony export */   "ɵBrowserDomAdapter": () => (/* binding */ BrowserDomAdapter),
/* harmony export */   "ɵBrowserGetTestability": () => (/* binding */ BrowserGetTestability),
/* harmony export */   "ɵDomEventsPlugin": () => (/* binding */ DomEventsPlugin),
/* harmony export */   "ɵDomRendererFactory2": () => (/* binding */ DomRendererFactory2),
/* harmony export */   "ɵDomSanitizerImpl": () => (/* binding */ DomSanitizerImpl),
/* harmony export */   "ɵHammerGesturesPlugin": () => (/* binding */ HammerGesturesPlugin),
/* harmony export */   "ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS": () => (/* binding */ INTERNAL_BROWSER_PLATFORM_PROVIDERS),
/* harmony export */   "ɵKeyEventsPlugin": () => (/* binding */ KeyEventsPlugin),
/* harmony export */   "ɵSharedStylesHost": () => (/* binding */ SharedStylesHost),
/* harmony export */   "ɵgetDOM": () => (/* reexport safe */ _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"]),
/* harmony export */   "ɵinitDomAdapter": () => (/* binding */ initDomAdapter)
/* harmony export */ });
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common/http */ 8143);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */







/**
 * Provides DOM operations in any browser environment.
 *
 * @security Tread carefully! Interacting with the DOM directly is dangerous and
 * can introduce XSS risks.
 */
class GenericBrowserDomAdapter extends _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵDomAdapter"] {
  supportsDOMEvents = true;
}

/**
 * A `DomAdapter` powered by full browser DOM APIs.
 *
 * @security Tread carefully! Interacting with the DOM directly is dangerous and
 * can introduce XSS risks.
 */
/* tslint:disable:requireParameterType no-console */
class BrowserDomAdapter extends GenericBrowserDomAdapter {
  static makeCurrent() {
    (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵsetRootDomAdapter"])(new BrowserDomAdapter());
  }
  onAndCancel(el, evt, listener) {
    el.addEventListener(evt, listener);
    return () => {
      el.removeEventListener(evt, listener);
    };
  }
  dispatchEvent(el, evt) {
    el.dispatchEvent(evt);
  }
  remove(node) {
    node.remove();
  }
  createElement(tagName, doc) {
    doc = doc || this.getDefaultDocument();
    return doc.createElement(tagName);
  }
  createHtmlDocument() {
    return document.implementation.createHTMLDocument('fakeTitle');
  }
  getDefaultDocument() {
    return document;
  }
  isElementNode(node) {
    return node.nodeType === Node.ELEMENT_NODE;
  }
  isShadowRoot(node) {
    return node instanceof DocumentFragment;
  }
  /** @deprecated No longer being used in Ivy code. To be removed in version 14. */
  getGlobalEventTarget(doc, target) {
    if (target === 'window') {
      return window;
    }
    if (target === 'document') {
      return doc;
    }
    if (target === 'body') {
      return doc.body;
    }
    return null;
  }
  getBaseHref(doc) {
    const href = getBaseElementHref();
    return href == null ? null : relativePath(href);
  }
  resetBaseElement() {
    baseElement = null;
  }
  getUserAgent() {
    return window.navigator.userAgent;
  }
  getCookie(name) {
    return (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵparseCookieValue"])(document.cookie, name);
  }
}
let baseElement = null;
function getBaseElementHref() {
  baseElement = baseElement || document.querySelector('base');
  return baseElement ? baseElement.getAttribute('href') : null;
}
function relativePath(url) {
  // The base URL doesn't really matter, we just need it so relative paths have something
  // to resolve against. In the browser `HTMLBaseElement.href` is always absolute.
  return new URL(url, document.baseURI).pathname;
}
class BrowserGetTestability {
  addToWindow(registry) {
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAngularTestability'] = (elem, findInAncestors = true) => {
      const testability = registry.findTestabilityInTree(elem, findInAncestors);
      if (testability == null) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5103 /* RuntimeErrorCode.TESTABILITY_NOT_FOUND */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Could not find testability for element.');
      }
      return testability;
    };
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularTestabilities'] = () => registry.getAllTestabilities();
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularRootElements'] = () => registry.getAllRootElements();
    const whenAllStable = callback => {
      const testabilities = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['getAllAngularTestabilities']();
      let count = testabilities.length;
      const decrement = function () {
        count--;
        if (count == 0) {
          callback();
        }
      };
      testabilities.forEach(testability => {
        testability.whenStable(decrement);
      });
    };
    if (!_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers']) {
      _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers'] = [];
    }
    _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['frameworkStabilizers'].push(whenAllStable);
  }
  findTestabilityInTree(registry, elem, findInAncestors) {
    if (elem == null) {
      return null;
    }
    const t = registry.getTestability(elem);
    if (t != null) {
      return t;
    } else if (!findInAncestors) {
      return null;
    }
    if ((0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().isShadowRoot(elem)) {
      return this.findTestabilityInTree(registry, elem.host, true);
    }
    return this.findTestabilityInTree(registry, elem.parentElement, true);
  }
}

/**
 * A factory for `HttpXhrBackend` that uses the `XMLHttpRequest` browser API.
 */
let BrowserXhr = /*#__PURE__*/(() => {
  class BrowserXhr {
    build() {
      return new XMLHttpRequest();
    }
    static ɵfac = (() => function BrowserXhr_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BrowserXhr)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: BrowserXhr,
      factory: BrowserXhr.ɵfac
    }))();
  }
  return BrowserXhr;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * The injection token for plugins of the `EventManager` service.
 *
 * @publicApi
 */
const EVENT_MANAGER_PLUGINS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'EventManagerPlugins' : '');
/**
 * An injectable service that provides event management for Angular
 * through a browser plug-in.
 *
 * @publicApi
 */
let EventManager = /*#__PURE__*/(() => {
  class EventManager {
    _zone;
    _plugins;
    _eventNameToPlugin = (() => new Map())();
    /**
     * Initializes an instance of the event-manager service.
     */
    constructor(plugins, _zone) {
      this._zone = _zone;
      plugins.forEach(plugin => {
        plugin.manager = this;
      });
      this._plugins = plugins.slice().reverse();
    }
    /**
     * Registers a handler for a specific element and event.
     *
     * @param element The HTML element to receive event notifications.
     * @param eventName The name of the event to listen for.
     * @param handler A function to call when the notification occurs. Receives the
     * event object as an argument.
     * @returns  A callback function that can be used to remove the handler.
     */
    addEventListener(element, eventName, handler) {
      const plugin = this._findPluginFor(eventName);
      return plugin.addEventListener(element, eventName, handler);
    }
    /**
     * Retrieves the compilation zone in which event listeners are registered.
     */
    getZone() {
      return this._zone;
    }
    /** @internal */
    _findPluginFor(eventName) {
      let plugin = this._eventNameToPlugin.get(eventName);
      if (plugin) {
        return plugin;
      }
      const plugins = this._plugins;
      plugin = plugins.find(plugin => plugin.supports(eventName));
      if (!plugin) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5101 /* RuntimeErrorCode.NO_PLUGIN_FOR_EVENT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `No event manager plugin found for event ${eventName}`);
      }
      this._eventNameToPlugin.set(eventName, plugin);
      return plugin;
    }
    static ɵfac = (() => function EventManager_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || EventManager)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](EVENT_MANAGER_PLUGINS), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: EventManager,
      factory: EventManager.ɵfac
    }))();
  }
  return EventManager;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * The plugin definition for the `EventManager` class
 *
 * It can be used as a base class to create custom manager plugins, i.e. you can create your own
 * class that extends the `EventManagerPlugin` one.
 *
 * @publicApi
 */
class EventManagerPlugin {
  _doc;
  // TODO: remove (has some usage in G3)
  constructor(_doc) {
    this._doc = _doc;
  }
  // Using non-null assertion because it's set by EventManager's constructor
  manager;
}

/** The style elements attribute name used to set value of `APP_ID` token. */
const APP_ID_ATTRIBUTE_NAME = 'ng-app-id';
/**
 * Removes all provided elements from the document.
 * @param elements An array of HTML Elements.
 */
function removeElements(elements) {
  for (const element of elements) {
    element.remove();
  }
}
/**
 * Creates a `style` element with the provided inline style content.
 * @param style A string of the inline style content.
 * @param doc A DOM Document to use to create the element.
 * @returns An HTMLStyleElement instance.
 */
function createStyleElement(style, doc) {
  const styleElement = doc.createElement('style');
  styleElement.textContent = style;
  return styleElement;
}
/**
 * Searches a DOM document's head element for style elements with a matching application
 * identifier attribute (`ng-app-id`) to the provide identifier and adds usage records for each.
 * @param doc An HTML DOM document instance.
 * @param appId A string containing an Angular application identifer.
 * @param usages A Map object for tracking style usage.
 */
function addServerStyles(doc, appId, usages) {
  const styleElements = doc.head?.querySelectorAll(`style[${APP_ID_ATTRIBUTE_NAME}="${appId}"]`);
  if (styleElements) {
    for (const styleElement of styleElements) {
      if (styleElement.textContent) {
        styleElement.removeAttribute(APP_ID_ATTRIBUTE_NAME);
        usages.set(styleElement.textContent, {
          usage: 0,
          elements: [styleElement]
        });
      }
    }
  }
}
/**
 * Creates a `link` element for the provided external style URL.
 * @param url A string of the URL for the stylesheet.
 * @param doc A DOM Document to use to create the element.
 * @returns An HTMLLinkElement instance.
 */
function createLinkElement(url, doc) {
  const linkElement = doc.createElement('link');
  linkElement.setAttribute('rel', 'stylesheet');
  linkElement.setAttribute('href', url);
  return linkElement;
}
let SharedStylesHost = /*#__PURE__*/(() => {
  class SharedStylesHost {
    doc;
    appId;
    nonce;
    /**
     * Provides usage information for active inline style content and associated HTML <style> elements.
     * Embedded styles typically originate from the `styles` metadata of a rendered component.
     */
    inline = (() => new Map())();
    /**
     * Provides usage information for active external style URLs and the associated HTML <link> elements.
     * External styles typically originate from the `ɵɵExternalStylesFeature` of a rendered component.
     */
    external = (() => new Map())();
    /**
     * Set of host DOM nodes that will have styles attached.
     */
    hosts = (() => new Set())();
    /**
     * Whether the application code is currently executing on a server.
     */
    isServer;
    constructor(doc, appId, nonce, platformId = {}) {
      this.doc = doc;
      this.appId = appId;
      this.nonce = nonce;
      this.isServer = (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__.isPlatformServer)(platformId);
      addServerStyles(doc, appId, this.inline);
      this.hosts.add(doc.head);
    }
    /**
     * Adds embedded styles to the DOM via HTML `style` elements.
     * @param styles An array of style content strings.
     */
    addStyles(styles, urls) {
      for (const value of styles) {
        this.addUsage(value, this.inline, createStyleElement);
      }
      urls?.forEach(value => this.addUsage(value, this.external, createLinkElement));
    }
    /**
     * Removes embedded styles from the DOM that were added as HTML `style` elements.
     * @param styles An array of style content strings.
     */
    removeStyles(styles, urls) {
      for (const value of styles) {
        this.removeUsage(value, this.inline);
      }
      urls?.forEach(value => this.removeUsage(value, this.external));
    }
    addUsage(value, usages, creator) {
      // Attempt to get any current usage of the value
      const record = usages.get(value);
      // If existing, just increment the usage count
      if (record) {
        if ((typeof ngDevMode === 'undefined' || ngDevMode) && record.usage === 0) {
          // A usage count of zero indicates a preexisting server generated style.
          // This attribute is solely used for debugging purposes of SSR style reuse.
          record.elements.forEach(element => element.setAttribute('ng-style-reused', ''));
        }
        record.usage++;
      } else {
        // Otherwise, create an entry to track the elements and add element for each host
        usages.set(value, {
          usage: 1,
          elements: [...this.hosts].map(host => this.addElement(host, creator(value, this.doc)))
        });
      }
    }
    removeUsage(value, usages) {
      // Attempt to get any current usage of the value
      const record = usages.get(value);
      // If there is a record, reduce the usage count and if no longer used,
      // remove from DOM and delete usage record.
      if (record) {
        record.usage--;
        if (record.usage <= 0) {
          removeElements(record.elements);
          usages.delete(value);
        }
      }
    }
    ngOnDestroy() {
      for (const [, {
        elements
      }] of [...this.inline, ...this.external]) {
        removeElements(elements);
      }
      this.hosts.clear();
    }
    /**
     * Adds a host node to the set of style hosts and adds all existing style usage to
     * the newly added host node.
     *
     * This is currently only used for Shadow DOM encapsulation mode.
     */
    addHost(hostNode) {
      this.hosts.add(hostNode);
      // Add existing styles to new host
      for (const [style, {
        elements
      }] of this.inline) {
        elements.push(this.addElement(hostNode, createStyleElement(style, this.doc)));
      }
      for (const [url, {
        elements
      }] of this.external) {
        elements.push(this.addElement(hostNode, createLinkElement(url, this.doc)));
      }
    }
    removeHost(hostNode) {
      this.hosts.delete(hostNode);
    }
    addElement(host, element) {
      // Add a nonce if present
      if (this.nonce) {
        element.setAttribute('nonce', this.nonce);
      }
      // Add application identifier when on the server to support client-side reuse
      if (this.isServer) {
        element.setAttribute(APP_ID_ATTRIBUTE_NAME, this.appId);
      }
      // Insert the element into the DOM with the host node as parent
      return host.appendChild(element);
    }
    static ɵfac = (() => function SharedStylesHost_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || SharedStylesHost)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_ID), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.CSP_NONCE, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: SharedStylesHost,
      factory: SharedStylesHost.ɵfac
    }))();
  }
  return SharedStylesHost;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const NAMESPACE_URIS = {
  'svg': 'http://www.w3.org/2000/svg',
  'xhtml': 'http://www.w3.org/1999/xhtml',
  'xlink': 'http://www.w3.org/1999/xlink',
  'xml': 'http://www.w3.org/XML/1998/namespace',
  'xmlns': 'http://www.w3.org/2000/xmlns/',
  'math': 'http://www.w3.org/1998/Math/MathML'
};
const COMPONENT_REGEX = /%COMP%/g;
const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
/**
 * The default value for the `REMOVE_STYLES_ON_COMPONENT_DESTROY` DI token.
 */
const REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT = true;
/**
 * A DI token that indicates whether styles
 * of destroyed components should be removed from DOM.
 *
 * By default, the value is set to `true`.
 * @publicApi
 */
const REMOVE_STYLES_ON_COMPONENT_DESTROY = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'RemoveStylesOnCompDestroy' : '', {
  providedIn: 'root',
  factory: () => REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT
});
function shimContentAttribute(componentShortId) {
  return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimHostAttribute(componentShortId) {
  return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimStylesContent(compId, styles) {
  return styles.map(s => s.replace(COMPONENT_REGEX, compId));
}
let DomRendererFactory2 = /*#__PURE__*/(() => {
  class DomRendererFactory2 {
    eventManager;
    sharedStylesHost;
    appId;
    removeStylesOnCompDestroy;
    doc;
    platformId;
    ngZone;
    nonce;
    rendererByCompId = (() => new Map())();
    defaultRenderer;
    platformIsServer;
    constructor(eventManager, sharedStylesHost, appId, removeStylesOnCompDestroy, doc, platformId, ngZone, nonce = null) {
      this.eventManager = eventManager;
      this.sharedStylesHost = sharedStylesHost;
      this.appId = appId;
      this.removeStylesOnCompDestroy = removeStylesOnCompDestroy;
      this.doc = doc;
      this.platformId = platformId;
      this.ngZone = ngZone;
      this.nonce = nonce;
      this.platformIsServer = (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__.isPlatformServer)(platformId);
      this.defaultRenderer = new DefaultDomRenderer2(eventManager, doc, ngZone, this.platformIsServer);
    }
    createRenderer(element, type) {
      if (!element || !type) {
        return this.defaultRenderer;
      }
      if (this.platformIsServer && type.encapsulation === _angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewEncapsulation.ShadowDom) {
        // Domino does not support shadow DOM.
        type = {
          ...type,
          encapsulation: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewEncapsulation.Emulated
        };
      }
      const renderer = this.getOrCreateRenderer(element, type);
      // Renderers have different logic due to different encapsulation behaviours.
      // Ex: for emulated, an attribute is added to the element.
      if (renderer instanceof EmulatedEncapsulationDomRenderer2) {
        renderer.applyToHost(element);
      } else if (renderer instanceof NoneEncapsulationDomRenderer) {
        renderer.applyStyles();
      }
      return renderer;
    }
    getOrCreateRenderer(element, type) {
      const rendererByCompId = this.rendererByCompId;
      let renderer = rendererByCompId.get(type.id);
      if (!renderer) {
        const doc = this.doc;
        const ngZone = this.ngZone;
        const eventManager = this.eventManager;
        const sharedStylesHost = this.sharedStylesHost;
        const removeStylesOnCompDestroy = this.removeStylesOnCompDestroy;
        const platformIsServer = this.platformIsServer;
        switch (type.encapsulation) {
          case _angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewEncapsulation.Emulated:
            renderer = new EmulatedEncapsulationDomRenderer2(eventManager, sharedStylesHost, type, this.appId, removeStylesOnCompDestroy, doc, ngZone, platformIsServer);
            break;
          case _angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewEncapsulation.ShadowDom:
            return new ShadowDomRenderer(eventManager, sharedStylesHost, element, type, doc, ngZone, this.nonce, platformIsServer);
          default:
            renderer = new NoneEncapsulationDomRenderer(eventManager, sharedStylesHost, type, removeStylesOnCompDestroy, doc, ngZone, platformIsServer);
            break;
        }
        rendererByCompId.set(type.id, renderer);
      }
      return renderer;
    }
    ngOnDestroy() {
      this.rendererByCompId.clear();
    }
    static ɵfac = (() => function DomRendererFactory2_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DomRendererFactory2)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](EventManager), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](SharedStylesHost), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_ID), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](REMOVE_STYLES_ON_COMPONENT_DESTROY), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.CSP_NONCE));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DomRendererFactory2,
      factory: DomRendererFactory2.ɵfac
    }))();
  }
  return DomRendererFactory2;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
class DefaultDomRenderer2 {
  eventManager;
  doc;
  ngZone;
  platformIsServer;
  data = /*#__PURE__*/(() => Object.create(null))();
  /**
   * By default this renderer throws when encountering synthetic properties
   * This can be disabled for example by the AsyncAnimationRendererFactory
   */
  throwOnSyntheticProps = true;
  constructor(eventManager, doc, ngZone, platformIsServer) {
    this.eventManager = eventManager;
    this.doc = doc;
    this.ngZone = ngZone;
    this.platformIsServer = platformIsServer;
  }
  destroy() {}
  destroyNode = null;
  createElement(name, namespace) {
    if (namespace) {
      // TODO: `|| namespace` was added in
      // https://github.com/angular/angular/commit/2b9cc8503d48173492c29f5a271b61126104fbdb to
      // support how Ivy passed around the namespace URI rather than short name at the time. It did
      // not, however extend the support to other parts of the system (setAttribute, setAttribute,
      // and the ServerRenderer). We should decide what exactly the semantics for dealing with
      // namespaces should be and make it consistent.
      // Related issues:
      // https://github.com/angular/angular/issues/44028
      // https://github.com/angular/angular/issues/44883
      return this.doc.createElementNS(NAMESPACE_URIS[namespace] || namespace, name);
    }
    return this.doc.createElement(name);
  }
  createComment(value) {
    return this.doc.createComment(value);
  }
  createText(value) {
    return this.doc.createTextNode(value);
  }
  appendChild(parent, newChild) {
    const targetParent = isTemplateNode(parent) ? parent.content : parent;
    targetParent.appendChild(newChild);
  }
  insertBefore(parent, newChild, refChild) {
    if (parent) {
      const targetParent = isTemplateNode(parent) ? parent.content : parent;
      targetParent.insertBefore(newChild, refChild);
    }
  }
  removeChild(_parent, oldChild) {
    oldChild.remove();
  }
  selectRootElement(selectorOrNode, preserveContent) {
    let el = typeof selectorOrNode === 'string' ? this.doc.querySelector(selectorOrNode) : selectorOrNode;
    if (!el) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](-5104 /* RuntimeErrorCode.ROOT_NODE_NOT_FOUND */, (typeof ngDevMode === 'undefined' || ngDevMode) && `The selector "${selectorOrNode}" did not match any elements`);
    }
    if (!preserveContent) {
      el.textContent = '';
    }
    return el;
  }
  parentNode(node) {
    return node.parentNode;
  }
  nextSibling(node) {
    return node.nextSibling;
  }
  setAttribute(el, name, value, namespace) {
    if (namespace) {
      name = namespace + ':' + name;
      const namespaceUri = NAMESPACE_URIS[namespace];
      if (namespaceUri) {
        el.setAttributeNS(namespaceUri, name, value);
      } else {
        el.setAttribute(name, value);
      }
    } else {
      el.setAttribute(name, value);
    }
  }
  removeAttribute(el, name, namespace) {
    if (namespace) {
      const namespaceUri = NAMESPACE_URIS[namespace];
      if (namespaceUri) {
        el.removeAttributeNS(namespaceUri, name);
      } else {
        el.removeAttribute(`${namespace}:${name}`);
      }
    } else {
      el.removeAttribute(name);
    }
  }
  addClass(el, name) {
    el.classList.add(name);
  }
  removeClass(el, name) {
    el.classList.remove(name);
  }
  setStyle(el, style, value, flags) {
    if (flags & (_angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererStyleFlags2.DashCase | _angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererStyleFlags2.Important)) {
      el.style.setProperty(style, value, flags & _angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererStyleFlags2.Important ? 'important' : '');
    } else {
      el.style[style] = value;
    }
  }
  removeStyle(el, style, flags) {
    if (flags & _angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererStyleFlags2.DashCase) {
      // removeProperty has no effect when used on camelCased properties.
      el.style.removeProperty(style);
    } else {
      el.style[style] = '';
    }
  }
  setProperty(el, name, value) {
    if (el == null) {
      return;
    }
    (typeof ngDevMode === 'undefined' || ngDevMode) && this.throwOnSyntheticProps && checkNoSyntheticProp(name, 'property');
    el[name] = value;
  }
  setValue(node, value) {
    node.nodeValue = value;
  }
  listen(target, event, callback) {
    (typeof ngDevMode === 'undefined' || ngDevMode) && this.throwOnSyntheticProps && checkNoSyntheticProp(event, 'listener');
    if (typeof target === 'string') {
      target = (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().getGlobalEventTarget(this.doc, target);
      if (!target) {
        throw new Error(`Unsupported event target ${target} for event ${event}`);
      }
    }
    return this.eventManager.addEventListener(target, event, this.decoratePreventDefault(callback));
  }
  decoratePreventDefault(eventHandler) {
    // `DebugNode.triggerEventHandler` needs to know if the listener was created with
    // decoratePreventDefault or is a listener added outside the Angular context so it can handle
    // the two differently. In the first case, the special '__ngUnwrap__' token is passed to the
    // unwrap the listener (see below).
    return event => {
      // Ivy uses '__ngUnwrap__' as a special token that allows us to unwrap the function
      // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`. The
      // debug_node can inspect the listener toString contents for the existence of this special
      // token. Because the token is a string literal, it is ensured to not be modified by compiled
      // code.
      if (event === '__ngUnwrap__') {
        return eventHandler;
      }
      // Run the event handler inside the ngZone because event handlers are not patched
      // by Zone on the server. This is required only for tests.
      const allowDefaultBehavior = this.platformIsServer ? this.ngZone.runGuarded(() => eventHandler(event)) : eventHandler(event);
      if (allowDefaultBehavior === false) {
        event.preventDefault();
      }
      return undefined;
    };
  }
}
const AT_CHARCODE = /*#__PURE__*/(() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name, nameKind) {
  if (name.charCodeAt(0) === AT_CHARCODE) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5105 /* RuntimeErrorCode.UNEXPECTED_SYNTHETIC_PROPERTY */, `Unexpected synthetic ${nameKind} ${name} found. Please make sure that:
  - Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application.
  - There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`);
  }
}
function isTemplateNode(node) {
  return node.tagName === 'TEMPLATE' && node.content !== undefined;
}
class ShadowDomRenderer extends DefaultDomRenderer2 {
  sharedStylesHost;
  hostEl;
  shadowRoot;
  constructor(eventManager, sharedStylesHost, hostEl, component, doc, ngZone, nonce, platformIsServer) {
    super(eventManager, doc, ngZone, platformIsServer);
    this.sharedStylesHost = sharedStylesHost;
    this.hostEl = hostEl;
    this.shadowRoot = hostEl.attachShadow({
      mode: 'open'
    });
    this.sharedStylesHost.addHost(this.shadowRoot);
    const styles = shimStylesContent(component.id, component.styles);
    for (const style of styles) {
      const styleEl = document.createElement('style');
      if (nonce) {
        styleEl.setAttribute('nonce', nonce);
      }
      styleEl.textContent = style;
      this.shadowRoot.appendChild(styleEl);
    }
    // Apply any external component styles to the shadow root for the component's element.
    // The ShadowDOM renderer uses an alternative execution path for component styles that
    // does not use the SharedStylesHost that other encapsulation modes leverage. Much like
    // the manual addition of embedded styles directly above, any external stylesheets
    // must be manually added here to ensure ShadowDOM components are correctly styled.
    // TODO: Consider reworking the DOM Renderers to consolidate style handling.
    const styleUrls = component.getExternalStyles?.();
    if (styleUrls) {
      for (const styleUrl of styleUrls) {
        const linkEl = createLinkElement(styleUrl, doc);
        if (nonce) {
          linkEl.setAttribute('nonce', nonce);
        }
        this.shadowRoot.appendChild(linkEl);
      }
    }
  }
  nodeOrShadowRoot(node) {
    return node === this.hostEl ? this.shadowRoot : node;
  }
  appendChild(parent, newChild) {
    return super.appendChild(this.nodeOrShadowRoot(parent), newChild);
  }
  insertBefore(parent, newChild, refChild) {
    return super.insertBefore(this.nodeOrShadowRoot(parent), newChild, refChild);
  }
  removeChild(_parent, oldChild) {
    return super.removeChild(null, oldChild);
  }
  parentNode(node) {
    return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(node)));
  }
  destroy() {
    this.sharedStylesHost.removeHost(this.shadowRoot);
  }
}
class NoneEncapsulationDomRenderer extends DefaultDomRenderer2 {
  sharedStylesHost;
  removeStylesOnCompDestroy;
  styles;
  styleUrls;
  constructor(eventManager, sharedStylesHost, component, removeStylesOnCompDestroy, doc, ngZone, platformIsServer, compId) {
    super(eventManager, doc, ngZone, platformIsServer);
    this.sharedStylesHost = sharedStylesHost;
    this.removeStylesOnCompDestroy = removeStylesOnCompDestroy;
    this.styles = compId ? shimStylesContent(compId, component.styles) : component.styles;
    this.styleUrls = component.getExternalStyles?.(compId);
  }
  applyStyles() {
    this.sharedStylesHost.addStyles(this.styles, this.styleUrls);
  }
  destroy() {
    if (!this.removeStylesOnCompDestroy) {
      return;
    }
    this.sharedStylesHost.removeStyles(this.styles, this.styleUrls);
  }
}
class EmulatedEncapsulationDomRenderer2 extends NoneEncapsulationDomRenderer {
  contentAttr;
  hostAttr;
  constructor(eventManager, sharedStylesHost, component, appId, removeStylesOnCompDestroy, doc, ngZone, platformIsServer) {
    const compId = appId + '-' + component.id;
    super(eventManager, sharedStylesHost, component, removeStylesOnCompDestroy, doc, ngZone, platformIsServer, compId);
    this.contentAttr = shimContentAttribute(compId);
    this.hostAttr = shimHostAttribute(compId);
  }
  applyToHost(element) {
    this.applyStyles();
    this.setAttribute(element, this.hostAttr, '');
  }
  createElement(parent, name) {
    const el = super.createElement(parent, name);
    super.setAttribute(el, this.contentAttr, '');
    return el;
  }
}
let DomEventsPlugin = /*#__PURE__*/(() => {
  class DomEventsPlugin extends EventManagerPlugin {
    constructor(doc) {
      super(doc);
    }
    // This plugin should come last in the list of plugins, because it accepts all
    // events.
    supports(eventName) {
      return true;
    }
    addEventListener(element, eventName, handler) {
      element.addEventListener(eventName, handler, false);
      return () => this.removeEventListener(element, eventName, handler);
    }
    removeEventListener(target, eventName, callback) {
      return target.removeEventListener(eventName, callback);
    }
    static ɵfac = (() => function DomEventsPlugin_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DomEventsPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DomEventsPlugin,
      factory: DomEventsPlugin.ɵfac
    }))();
  }
  return DomEventsPlugin;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Defines supported modifiers for key events.
 */
const MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf https://www.w3.org/TR/DOM-Level-3-Events-key/
const _keyMap = {
  '\b': 'Backspace',
  '\t': 'Tab',
  '\x7F': 'Delete',
  '\x1B': 'Escape',
  'Del': 'Delete',
  'Esc': 'Escape',
  'Left': 'ArrowLeft',
  'Right': 'ArrowRight',
  'Up': 'ArrowUp',
  'Down': 'ArrowDown',
  'Menu': 'ContextMenu',
  'Scroll': 'ScrollLock',
  'Win': 'OS'
};
/**
 * Retrieves modifiers from key-event objects.
 */
const MODIFIER_KEY_GETTERS = {
  'alt': event => event.altKey,
  'control': event => event.ctrlKey,
  'meta': event => event.metaKey,
  'shift': event => event.shiftKey
};
/**
 * A browser plug-in that provides support for handling of key events in Angular.
 */
let KeyEventsPlugin = /*#__PURE__*/(() => {
  class KeyEventsPlugin extends EventManagerPlugin {
    /**
     * Initializes an instance of the browser plug-in.
     * @param doc The document in which key events will be detected.
     */
    constructor(doc) {
      super(doc);
    }
    /**
     * Reports whether a named key event is supported.
     * @param eventName The event name to query.
     * @return True if the named key event is supported.
     */
    supports(eventName) {
      return KeyEventsPlugin.parseEventName(eventName) != null;
    }
    /**
     * Registers a handler for a specific element and key event.
     * @param element The HTML element to receive event notifications.
     * @param eventName The name of the key event to listen for.
     * @param handler A function to call when the notification occurs. Receives the
     * event object as an argument.
     * @returns The key event that was registered.
     */
    addEventListener(element, eventName, handler) {
      const parsedEvent = KeyEventsPlugin.parseEventName(eventName);
      const outsideHandler = KeyEventsPlugin.eventCallback(parsedEvent['fullKey'], handler, this.manager.getZone());
      return this.manager.getZone().runOutsideAngular(() => {
        return (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
      });
    }
    /**
     * Parses the user provided full keyboard event definition and normalizes it for
     * later internal use. It ensures the string is all lowercase, converts special
     * characters to a standard spelling, and orders all the values consistently.
     *
     * @param eventName The name of the key event to listen for.
     * @returns an object with the full, normalized string, and the dom event name
     * or null in the case when the event doesn't match a keyboard event.
     */
    static parseEventName(eventName) {
      const parts = eventName.toLowerCase().split('.');
      const domEventName = parts.shift();
      if (parts.length === 0 || !(domEventName === 'keydown' || domEventName === 'keyup')) {
        return null;
      }
      const key = KeyEventsPlugin._normalizeKey(parts.pop());
      let fullKey = '';
      let codeIX = parts.indexOf('code');
      if (codeIX > -1) {
        parts.splice(codeIX, 1);
        fullKey = 'code.';
      }
      MODIFIER_KEYS.forEach(modifierName => {
        const index = parts.indexOf(modifierName);
        if (index > -1) {
          parts.splice(index, 1);
          fullKey += modifierName + '.';
        }
      });
      fullKey += key;
      if (parts.length != 0 || key.length === 0) {
        // returning null instead of throwing to let another plugin process the event
        return null;
      }
      // NOTE: Please don't rewrite this as so, as it will break JSCompiler property renaming.
      //       The code must remain in the `result['domEventName']` form.
      // return {domEventName, fullKey};
      const result = {};
      result['domEventName'] = domEventName;
      result['fullKey'] = fullKey;
      return result;
    }
    /**
     * Determines whether the actual keys pressed match the configured key code string.
     * The `fullKeyCode` event is normalized in the `parseEventName` method when the
     * event is attached to the DOM during the `addEventListener` call. This is unseen
     * by the end user and is normalized for internal consistency and parsing.
     *
     * @param event The keyboard event.
     * @param fullKeyCode The normalized user defined expected key event string
     * @returns boolean.
     */
    static matchEventFullKeyCode(event, fullKeyCode) {
      let keycode = _keyMap[event.key] || event.key;
      let key = '';
      if (fullKeyCode.indexOf('code.') > -1) {
        keycode = event.code;
        key = 'code.';
      }
      // the keycode could be unidentified so we have to check here
      if (keycode == null || !keycode) return false;
      keycode = keycode.toLowerCase();
      if (keycode === ' ') {
        keycode = 'space'; // for readability
      } else if (keycode === '.') {
        keycode = 'dot'; // because '.' is used as a separator in event names
      }
      MODIFIER_KEYS.forEach(modifierName => {
        if (modifierName !== keycode) {
          const modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
          if (modifierGetter(event)) {
            key += modifierName + '.';
          }
        }
      });
      key += keycode;
      return key === fullKeyCode;
    }
    /**
     * Configures a handler callback for a key event.
     * @param fullKey The event name that combines all simultaneous keystrokes.
     * @param handler The function that responds to the key event.
     * @param zone The zone in which the event occurred.
     * @returns A callback function.
     */
    static eventCallback(fullKey, handler, zone) {
      return event => {
        if (KeyEventsPlugin.matchEventFullKeyCode(event, fullKey)) {
          zone.runGuarded(() => handler(event));
        }
      };
    }
    /** @internal */
    static _normalizeKey(keyName) {
      return keyName === 'esc' ? 'escape' : keyName;
    }
    static ɵfac = (() => function KeyEventsPlugin_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || KeyEventsPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: KeyEventsPlugin,
      factory: KeyEventsPlugin.ɵfac
    }))();
  }
  return KeyEventsPlugin;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Bootstraps an instance of an Angular application and renders a standalone component as the
 * application's root component. More information about standalone components can be found in [this
 * guide](guide/components/importing).
 *
 * @usageNotes
 * The root component passed into this function *must* be a standalone one (should have the
 * `standalone: true` flag in the `@Component` decorator config).
 *
 * ```typescript
 * @Component({
 *   standalone: true,
 *   template: 'Hello world!'
 * })
 * class RootComponent {}
 *
 * const appRef: ApplicationRef = await bootstrapApplication(RootComponent);
 * ```
 *
 * You can add the list of providers that should be available in the application injector by
 * specifying the `providers` field in an object passed as the second argument:
 *
 * ```typescript
 * await bootstrapApplication(RootComponent, {
 *   providers: [
 *     {provide: BACKEND_URL, useValue: 'https://yourdomain.com/api'}
 *   ]
 * });
 * ```
 *
 * The `importProvidersFrom` helper method can be used to collect all providers from any
 * existing NgModule (and transitively from all NgModules that it imports):
 *
 * ```typescript
 * await bootstrapApplication(RootComponent, {
 *   providers: [
 *     importProvidersFrom(SomeNgModule)
 *   ]
 * });
 * ```
 *
 * Note: the `bootstrapApplication` method doesn't include [Testability](api/core/Testability) by
 * default. You can add [Testability](api/core/Testability) by getting the list of necessary
 * providers using `provideProtractorTestingSupport()` function and adding them into the `providers`
 * array, for example:
 *
 * ```typescript
 * import {provideProtractorTestingSupport} from '@angular/platform-browser';
 *
 * await bootstrapApplication(RootComponent, {providers: [provideProtractorTestingSupport()]});
 * ```
 *
 * @param rootComponent A reference to a standalone component that should be rendered.
 * @param options Extra configuration for the bootstrap operation, see `ApplicationConfig` for
 *     additional info.
 * @returns A promise that returns an `ApplicationRef` instance once resolved.
 *
 * @publicApi
 */
function bootstrapApplication(rootComponent, options) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinternalCreateApplication"])({
    rootComponent,
    ...createProvidersConfig(options)
  });
}
/**
 * Create an instance of an Angular application without bootstrapping any components. This is useful
 * for the situation where one wants to decouple application environment creation (a platform and
 * associated injectors) from rendering components on a screen. Components can be subsequently
 * bootstrapped on the returned `ApplicationRef`.
 *
 * @param options Extra configuration for the application environment, see `ApplicationConfig` for
 *     additional info.
 * @returns A promise that returns an `ApplicationRef` instance once resolved.
 *
 * @publicApi
 */
function createApplication(options) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinternalCreateApplication"])(createProvidersConfig(options));
}
function createProvidersConfig(options) {
  return {
    appProviders: [...BROWSER_MODULE_PROVIDERS, ...(options?.providers ?? [])],
    platformProviders: INTERNAL_BROWSER_PLATFORM_PROVIDERS
  };
}
/**
 * Returns a set of providers required to setup [Testability](api/core/Testability) for an
 * application bootstrapped using the `bootstrapApplication` function. The set of providers is
 * needed to support testing an application with Protractor (which relies on the Testability APIs
 * to be present).
 *
 * @returns An array of providers required to setup Testability for an application and make it
 *     available for testing using Protractor.
 *
 * @publicApi
 */
function provideProtractorTestingSupport() {
  // Return a copy to prevent changes to the original array in case any in-place
  // alterations are performed to the `provideProtractorTestingSupport` call results in app
  // code.
  return [...TESTABILITY_PROVIDERS];
}
function initDomAdapter() {
  BrowserDomAdapter.makeCurrent();
}
function errorHandler() {
  return new _angular_core__WEBPACK_IMPORTED_MODULE_1__.ErrorHandler();
}
function _document() {
  // Tell ivy about the global document
  (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetDocument"])(document);
  return document;
}
const INTERNAL_BROWSER_PLATFORM_PROVIDERS = [{
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID,
  useValue: _angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵPLATFORM_BROWSER_ID"]
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_INITIALIZER,
  useValue: initDomAdapter,
  multi: true
}, {
  provide: _angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT,
  useFactory: _document,
  deps: []
}];
/**
 * A factory function that returns a `PlatformRef` instance associated with browser service
 * providers.
 *
 * @publicApi
 */
const platformBrowser = /*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.createPlatformFactory)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.platformCore, 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
/**
 * Internal marker to signal whether providers from the `BrowserModule` are already present in DI.
 * This is needed to avoid loading `BrowserModule` providers twice. We can't rely on the
 * `BrowserModule` presence itself, since the standalone-based bootstrap just imports
 * `BrowserModule` providers without referencing the module itself.
 */
const BROWSER_MODULE_PROVIDERS_MARKER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'BrowserModule Providers Marker' : '');
const TESTABILITY_PROVIDERS = [{
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵTESTABILITY_GETTER"],
  useClass: BrowserGetTestability,
  deps: []
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵTESTABILITY"],
  useClass: _angular_core__WEBPACK_IMPORTED_MODULE_1__.Testability,
  deps: [_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone, _angular_core__WEBPACK_IMPORTED_MODULE_1__.TestabilityRegistry, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵTESTABILITY_GETTER"]]
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.Testability,
  // Also provide as `Testability` for backwards-compatibility.
  useClass: _angular_core__WEBPACK_IMPORTED_MODULE_1__.Testability,
  deps: [_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone, _angular_core__WEBPACK_IMPORTED_MODULE_1__.TestabilityRegistry, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵTESTABILITY_GETTER"]]
}];
const BROWSER_MODULE_PROVIDERS = [{
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵINJECTOR_SCOPE"],
  useValue: 'root'
}, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ErrorHandler,
  useFactory: errorHandler,
  deps: []
}, {
  provide: EVENT_MANAGER_PLUGINS,
  useClass: DomEventsPlugin,
  multi: true,
  deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT, _angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone, _angular_core__WEBPACK_IMPORTED_MODULE_1__.PLATFORM_ID]
}, {
  provide: EVENT_MANAGER_PLUGINS,
  useClass: KeyEventsPlugin,
  multi: true,
  deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT]
}, DomRendererFactory2, SharedStylesHost, EventManager, {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.RendererFactory2,
  useExisting: DomRendererFactory2
}, {
  provide: _angular_common__WEBPACK_IMPORTED_MODULE_0__.XhrFactory,
  useClass: BrowserXhr,
  deps: []
}, typeof ngDevMode === 'undefined' || ngDevMode ? {
  provide: BROWSER_MODULE_PROVIDERS_MARKER,
  useValue: true
} : []];
/**
 * Exports required infrastructure for all Angular apps.
 * Included by default in all Angular apps created with the CLI
 * `new` command.
 * Re-exports `CommonModule` and `ApplicationModule`, making their
 * exports and providers available to all apps.
 *
 * @publicApi
 */
let BrowserModule = /*#__PURE__*/(() => {
  class BrowserModule {
    constructor(providersAlreadyPresent) {
      if ((typeof ngDevMode === 'undefined' || ngDevMode) && providersAlreadyPresent) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5100 /* RuntimeErrorCode.BROWSER_MODULE_ALREADY_LOADED */, `Providers from the \`BrowserModule\` have already been loaded. If you need access ` + `to common directives such as NgIf and NgFor, import the \`CommonModule\` instead.`);
      }
    }
    static ɵfac = (() => function BrowserModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || BrowserModule)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](BROWSER_MODULE_PROVIDERS_MARKER, 12));
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({
      type: BrowserModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({
      providers: [...BROWSER_MODULE_PROVIDERS, ...TESTABILITY_PROVIDERS],
      imports: [_angular_common__WEBPACK_IMPORTED_MODULE_0__.CommonModule, _angular_core__WEBPACK_IMPORTED_MODULE_1__.ApplicationModule]
    }))();
  }
  return BrowserModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * A service for managing HTML `<meta>` tags.
 *
 * Properties of the `MetaDefinition` object match the attributes of the
 * HTML `<meta>` tag. These tags define document metadata that is important for
 * things like configuring a Content Security Policy, defining browser compatibility
 * and security settings, setting HTTP Headers, defining rich content for social sharing,
 * and Search Engine Optimization (SEO).
 *
 * To identify specific `<meta>` tags in a document, use an attribute selection
 * string in the format `"tag_attribute='value string'"`.
 * For example, an `attrSelector` value of `"name='description'"` matches a tag
 * whose `name` attribute has the value `"description"`.
 * Selectors are used with the `querySelector()` Document method,
 * in the format `meta[{attrSelector}]`.
 *
 * @see [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta)
 * @see [Document.querySelector()](https://developer.mozilla.org/docs/Web/API/Document/querySelector)
 *
 *
 * @publicApi
 */
let Meta = /*#__PURE__*/(() => {
  class Meta {
    _doc;
    _dom;
    constructor(_doc) {
      this._doc = _doc;
      this._dom = (0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])();
    }
    /**
     * Retrieves or creates a specific `<meta>` tag element in the current HTML document.
     * In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
     * values in the provided tag definition, and verifies that all other attribute values are equal.
     * If an existing element is found, it is returned and is not modified in any way.
     * @param tag The definition of a `<meta>` element to match or create.
     * @param forceCreation True to create a new element without checking whether one already exists.
     * @returns The existing element with the same attributes and values if found,
     * the new element if no match is found, or `null` if the tag parameter is not defined.
     */
    addTag(tag, forceCreation = false) {
      if (!tag) return null;
      return this._getOrCreateElement(tag, forceCreation);
    }
    /**
     * Retrieves or creates a set of `<meta>` tag elements in the current HTML document.
     * In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
     * values in the provided tag definition, and verifies that all other attribute values are equal.
     * @param tags An array of tag definitions to match or create.
     * @param forceCreation True to create new elements without checking whether they already exist.
     * @returns The matching elements if found, or the new elements.
     */
    addTags(tags, forceCreation = false) {
      if (!tags) return [];
      return tags.reduce((result, tag) => {
        if (tag) {
          result.push(this._getOrCreateElement(tag, forceCreation));
        }
        return result;
      }, []);
    }
    /**
     * Retrieves a `<meta>` tag element in the current HTML document.
     * @param attrSelector The tag attribute and value to match against, in the format
     * `"tag_attribute='value string'"`.
     * @returns The matching element, if any.
     */
    getTag(attrSelector) {
      if (!attrSelector) return null;
      return this._doc.querySelector(`meta[${attrSelector}]`) || null;
    }
    /**
     * Retrieves a set of `<meta>` tag elements in the current HTML document.
     * @param attrSelector The tag attribute and value to match against, in the format
     * `"tag_attribute='value string'"`.
     * @returns The matching elements, if any.
     */
    getTags(attrSelector) {
      if (!attrSelector) return [];
      const list /*NodeList*/ = this._doc.querySelectorAll(`meta[${attrSelector}]`);
      return list ? [].slice.call(list) : [];
    }
    /**
     * Modifies an existing `<meta>` tag element in the current HTML document.
     * @param tag The tag description with which to replace the existing tag content.
     * @param selector A tag attribute and value to match against, to identify
     * an existing tag. A string in the format `"tag_attribute=`value string`"`.
     * If not supplied, matches a tag with the same `name` or `property` attribute value as the
     * replacement tag.
     * @return The modified element.
     */
    updateTag(tag, selector) {
      if (!tag) return null;
      selector = selector || this._parseSelector(tag);
      const meta = this.getTag(selector);
      if (meta) {
        return this._setMetaElementAttributes(tag, meta);
      }
      return this._getOrCreateElement(tag, true);
    }
    /**
     * Removes an existing `<meta>` tag element from the current HTML document.
     * @param attrSelector A tag attribute and value to match against, to identify
     * an existing tag. A string in the format `"tag_attribute=`value string`"`.
     */
    removeTag(attrSelector) {
      this.removeTagElement(this.getTag(attrSelector));
    }
    /**
     * Removes an existing `<meta>` tag element from the current HTML document.
     * @param meta The tag definition to match against to identify an existing tag.
     */
    removeTagElement(meta) {
      if (meta) {
        this._dom.remove(meta);
      }
    }
    _getOrCreateElement(meta, forceCreation = false) {
      if (!forceCreation) {
        const selector = this._parseSelector(meta);
        // It's allowed to have multiple elements with the same name so it's not enough to
        // just check that element with the same name already present on the page. We also need to
        // check if element has tag attributes
        const elem = this.getTags(selector).filter(elem => this._containsAttributes(meta, elem))[0];
        if (elem !== undefined) return elem;
      }
      const element = this._dom.createElement('meta');
      this._setMetaElementAttributes(meta, element);
      const head = this._doc.getElementsByTagName('head')[0];
      head.appendChild(element);
      return element;
    }
    _setMetaElementAttributes(tag, el) {
      Object.keys(tag).forEach(prop => el.setAttribute(this._getMetaKeyMap(prop), tag[prop]));
      return el;
    }
    _parseSelector(tag) {
      const attr = tag.name ? 'name' : 'property';
      return `${attr}="${tag[attr]}"`;
    }
    _containsAttributes(tag, elem) {
      return Object.keys(tag).every(key => elem.getAttribute(this._getMetaKeyMap(key)) === tag[key]);
    }
    _getMetaKeyMap(prop) {
      return META_KEYS_MAP[prop] || prop;
    }
    static ɵfac = (() => function Meta_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Meta)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: Meta,
      factory: Meta.ɵfac,
      providedIn: 'root'
    }))();
  }
  return Meta;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Mapping for MetaDefinition properties with their correct meta attribute names
 */
const META_KEYS_MAP = {
  httpEquiv: 'http-equiv'
};

/**
 * A service that can be used to get and set the title of a current HTML document.
 *
 * Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
 * it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
 * (representing the `<title>` tag). Instead, this service can be used to set and get the current
 * title value.
 *
 * @publicApi
 */
let Title = /*#__PURE__*/(() => {
  class Title {
    _doc;
    constructor(_doc) {
      this._doc = _doc;
    }
    /**
     * Get the title of the current HTML document.
     */
    getTitle() {
      return this._doc.title;
    }
    /**
     * Set the title of the current HTML document.
     * @param newTitle
     */
    setTitle(newTitle) {
      this._doc.title = newTitle || '';
    }
    static ɵfac = (() => function Title_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Title)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: Title,
      factory: Title.ɵfac,
      providedIn: 'root'
    }))();
  }
  return Title;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Exports the value under a given `name` in the global property `ng`. For example `ng.probe` if
 * `name` is `'probe'`.
 * @param name Name under which it will be exported. Keep in mind this will be a property of the
 * global `ng` object.
 * @param value The value to export.
 */
function exportNgVar(name, value) {
  if (typeof COMPILED === 'undefined' || !COMPILED) {
    // Note: we can't export `ng` when using closure enhanced optimization as:
    // - closure declares globals itself for minified names, which sometimes clobber our `ng` global
    // - we can't declare a closure extern as the namespace `ng` is already used within Google
    //   for typings for angularJS (via `goog.provide('ng....')`).
    const ng = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['ng'] = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵglobal"]['ng'] || {};
    ng[name] = value;
  }
}
class ChangeDetectionPerfRecord {
  msPerTick;
  numTicks;
  constructor(msPerTick, numTicks) {
    this.msPerTick = msPerTick;
    this.numTicks = numTicks;
  }
}
/**
 * Entry point for all Angular profiling-related debug tools. This object
 * corresponds to the `ng.profiler` in the dev console.
 */
class AngularProfiler {
  appRef;
  constructor(ref) {
    this.appRef = ref.injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ApplicationRef);
  }
  // tslint:disable:no-console
  /**
   * Exercises change detection in a loop and then prints the average amount of
   * time in milliseconds how long a single round of change detection takes for
   * the current state of the UI. It runs a minimum of 5 rounds for a minimum
   * of 500 milliseconds.
   *
   * Optionally, a user may pass a `config` parameter containing a map of
   * options. Supported options are:
   *
   * `record` (boolean) - causes the profiler to record a CPU profile while
   * it exercises the change detector. Example:
   *
   * ```
   * ng.profiler.timeChangeDetection({record: true})
   * ```
   */
  timeChangeDetection(config) {
    const record = config && config['record'];
    const profileName = 'Change Detection';
    // Profiler is not available in Android browsers without dev tools opened
    if (record && 'profile' in console && typeof console.profile === 'function') {
      console.profile(profileName);
    }
    const start = performance.now();
    let numTicks = 0;
    while (numTicks < 5 || performance.now() - start < 500) {
      this.appRef.tick();
      numTicks++;
    }
    const end = performance.now();
    if (record && 'profileEnd' in console && typeof console.profileEnd === 'function') {
      console.profileEnd(profileName);
    }
    const msPerTick = (end - start) / numTicks;
    console.log(`ran ${numTicks} change detection cycles`);
    console.log(`${msPerTick.toFixed(2)} ms per check`);
    return new ChangeDetectionPerfRecord(msPerTick, numTicks);
  }
}
const PROFILER_GLOBAL_NAME = 'profiler';
/**
 * Enabled Angular debug tools that are accessible via your browser's
 * developer console.
 *
 * Usage:
 *
 * 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
 * 1. Type `ng.` (usually the console will show auto-complete suggestion)
 * 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
 *    then hit Enter.
 *
 * @publicApi
 */
function enableDebugTools(ref) {
  exportNgVar(PROFILER_GLOBAL_NAME, new AngularProfiler(ref));
  return ref;
}
/**
 * Disables Angular tools.
 *
 * @publicApi
 */
function disableDebugTools() {
  exportNgVar(PROFILER_GLOBAL_NAME, null);
}

/**
 * Predicates for use with {@link DebugElement}'s query functions.
 *
 * @publicApi
 */
class By {
  /**
   * Match all nodes.
   *
   * @usageNotes
   * ### Example
   *
   * {@example platform-browser/dom/debug/ts/by/by.ts region='by_all'}
   */
  static all() {
    return () => true;
  }
  /**
   * Match elements by the given CSS selector.
   *
   * @usageNotes
   * ### Example
   *
   * {@example platform-browser/dom/debug/ts/by/by.ts region='by_css'}
   */
  static css(selector) {
    return debugElement => {
      return debugElement.nativeElement != null ? elementMatches(debugElement.nativeElement, selector) : false;
    };
  }
  /**
   * Match nodes that have the given directive present.
   *
   * @usageNotes
   * ### Example
   *
   * {@example platform-browser/dom/debug/ts/by/by.ts region='by_directive'}
   */
  static directive(type) {
    return debugNode => debugNode.providerTokens.indexOf(type) !== -1;
  }
}
function elementMatches(n, selector) {
  if ((0,_angular_common__WEBPACK_IMPORTED_MODULE_0__["ɵgetDOM"])().isElementNode(n)) {
    return n.matches && n.matches(selector) || n.msMatchesSelector && n.msMatchesSelector(selector) || n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
  }
  return false;
}

/**
 * Supported HammerJS recognizer event names.
 */
const EVENT_NAMES = {
  // pan
  'pan': true,
  'panstart': true,
  'panmove': true,
  'panend': true,
  'pancancel': true,
  'panleft': true,
  'panright': true,
  'panup': true,
  'pandown': true,
  // pinch
  'pinch': true,
  'pinchstart': true,
  'pinchmove': true,
  'pinchend': true,
  'pinchcancel': true,
  'pinchin': true,
  'pinchout': true,
  // press
  'press': true,
  'pressup': true,
  // rotate
  'rotate': true,
  'rotatestart': true,
  'rotatemove': true,
  'rotateend': true,
  'rotatecancel': true,
  // swipe
  'swipe': true,
  'swipeleft': true,
  'swiperight': true,
  'swipeup': true,
  'swipedown': true,
  // tap
  'tap': true,
  'doubletap': true
};
/**
 * DI token for providing [HammerJS](https://hammerjs.github.io/) support to Angular.
 * @see {@link HammerGestureConfig}
 *
 * @ngModule HammerModule
 * @publicApi
 */
const HAMMER_GESTURE_CONFIG = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('HammerGestureConfig');
/**
 * Injection token used to provide a HammerLoader to Angular.
 *
 * @see {@link HammerLoader}
 *
 * @publicApi
 */
const HAMMER_LOADER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('HammerLoader');
/**
 * An injectable [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager)
 * for gesture recognition. Configures specific event recognition.
 * @publicApi
 */
let HammerGestureConfig = /*#__PURE__*/(() => {
  class HammerGestureConfig {
    /**
     * A set of supported event names for gestures to be used in Angular.
     * Angular supports all built-in recognizers, as listed in
     * [HammerJS documentation](https://hammerjs.github.io/).
     */
    events = [];
    /**
     * Maps gesture event names to a set of configuration options
     * that specify overrides to the default values for specific properties.
     *
     * The key is a supported event name to be configured,
     * and the options object contains a set of properties, with override values
     * to be applied to the named recognizer event.
     * For example, to disable recognition of the rotate event, specify
     *  `{"rotate": {"enable": false}}`.
     *
     * Properties that are not present take the HammerJS default values.
     * For information about which properties are supported for which events,
     * and their allowed and default values, see
     * [HammerJS documentation](https://hammerjs.github.io/).
     *
     */
    overrides = {};
    /**
     * Properties whose default values can be overridden for a given event.
     * Different sets of properties apply to different events.
     * For information about which properties are supported for which events,
     * and their allowed and default values, see
     * [HammerJS documentation](https://hammerjs.github.io/).
     */
    options;
    /**
     * Creates a [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager)
     * and attaches it to a given HTML element.
     * @param element The element that will recognize gestures.
     * @returns A HammerJS event-manager object.
     */
    buildHammer(element) {
      const mc = new Hammer(element, this.options);
      mc.get('pinch').set({
        enable: true
      });
      mc.get('rotate').set({
        enable: true
      });
      for (const eventName in this.overrides) {
        mc.get(eventName).set(this.overrides[eventName]);
      }
      return mc;
    }
    static ɵfac = (() => function HammerGestureConfig_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HammerGestureConfig)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: HammerGestureConfig,
      factory: HammerGestureConfig.ɵfac
    }))();
  }
  return HammerGestureConfig;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Event plugin that adds Hammer support to an application.
 *
 * @ngModule HammerModule
 */
let HammerGesturesPlugin = /*#__PURE__*/(() => {
  class HammerGesturesPlugin extends EventManagerPlugin {
    _config;
    console;
    loader;
    _loaderPromise = null;
    constructor(doc, _config, console, loader) {
      super(doc);
      this._config = _config;
      this.console = console;
      this.loader = loader;
    }
    supports(eventName) {
      if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) {
        return false;
      }
      if (!window.Hammer && !this.loader) {
        if (typeof ngDevMode === 'undefined' || ngDevMode) {
          this.console.warn(`The "${eventName}" event cannot be bound because Hammer.JS is not ` + `loaded and no custom loader has been specified.`);
        }
        return false;
      }
      return true;
    }
    addEventListener(element, eventName, handler) {
      const zone = this.manager.getZone();
      eventName = eventName.toLowerCase();
      // If Hammer is not present but a loader is specified, we defer adding the event listener
      // until Hammer is loaded.
      if (!window.Hammer && this.loader) {
        this._loaderPromise = this._loaderPromise || zone.runOutsideAngular(() => this.loader());
        // This `addEventListener` method returns a function to remove the added listener.
        // Until Hammer is loaded, the returned function needs to *cancel* the registration rather
        // than remove anything.
        let cancelRegistration = false;
        let deregister = () => {
          cancelRegistration = true;
        };
        zone.runOutsideAngular(() => this._loaderPromise.then(() => {
          // If Hammer isn't actually loaded when the custom loader resolves, give up.
          if (!window.Hammer) {
            if (typeof ngDevMode === 'undefined' || ngDevMode) {
              this.console.warn(`The custom HAMMER_LOADER completed, but Hammer.JS is not present.`);
            }
            deregister = () => {};
            return;
          }
          if (!cancelRegistration) {
            // Now that Hammer is loaded and the listener is being loaded for real,
            // the deregistration function changes from canceling registration to
            // removal.
            deregister = this.addEventListener(element, eventName, handler);
          }
        }).catch(() => {
          if (typeof ngDevMode === 'undefined' || ngDevMode) {
            this.console.warn(`The "${eventName}" event cannot be bound because the custom ` + `Hammer.JS loader failed.`);
          }
          deregister = () => {};
        }));
        // Return a function that *executes* `deregister` (and not `deregister` itself) so that we
        // can change the behavior of `deregister` once the listener is added. Using a closure in
        // this way allows us to avoid any additional data structures to track listener removal.
        return () => {
          deregister();
        };
      }
      return zone.runOutsideAngular(() => {
        // Creating the manager bind events, must be done outside of angular
        const mc = this._config.buildHammer(element);
        const callback = function (eventObj) {
          zone.runGuarded(function () {
            handler(eventObj);
          });
        };
        mc.on(eventName, callback);
        return () => {
          mc.off(eventName, callback);
          // destroy mc to prevent memory leak
          if (typeof mc.destroy === 'function') {
            mc.destroy();
          }
        };
      });
    }
    isCustomEvent(eventName) {
      return this._config.events.indexOf(eventName) > -1;
    }
    static ɵfac = (() => function HammerGesturesPlugin_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HammerGesturesPlugin)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](HAMMER_GESTURE_CONFIG), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](HAMMER_LOADER, 8));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: HammerGesturesPlugin,
      factory: HammerGesturesPlugin.ɵfac
    }))();
  }
  return HammerGesturesPlugin;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Adds support for HammerJS.
 *
 * Import this module at the root of your application so that Angular can work with
 * HammerJS to detect gesture events.
 *
 * Note that applications still need to include the HammerJS script itself. This module
 * simply sets up the coordination layer between HammerJS and Angular's `EventManager`.
 *
 * @publicApi
 */
let HammerModule = /*#__PURE__*/(() => {
  class HammerModule {
    static ɵfac = (() => function HammerModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || HammerModule)();
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({
      type: HammerModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({
      providers: [{
        provide: EVENT_MANAGER_PLUGINS,
        useClass: HammerGesturesPlugin,
        multi: true,
        deps: [_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT, HAMMER_GESTURE_CONFIG, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"], [new _angular_core__WEBPACK_IMPORTED_MODULE_1__.Optional(), HAMMER_LOADER]]
      }, {
        provide: HAMMER_GESTURE_CONFIG,
        useClass: HammerGestureConfig,
        deps: []
      }]
    }))();
  }
  return HammerModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing
 * values to be safe to use in the different DOM contexts.
 *
 * For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be
 * sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on
 * the website.
 *
 * In specific situations, it might be necessary to disable sanitization, for example if the
 * application genuinely needs to produce a `javascript:` style link with a dynamic value in it.
 * Users can bypass security by constructing a value with one of the `bypassSecurityTrust...`
 * methods, and then binding to that value from the template.
 *
 * These situations should be very rare, and extraordinary care must be taken to avoid creating a
 * Cross Site Scripting (XSS) security bug!
 *
 * When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as
 * close as possible to the source of the value, to make it easy to verify no security bug is
 * created by its use.
 *
 * It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that
 * does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous
 * code. The sanitizer leaves safe values intact.
 *
 * @security Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in
 * sanitization for the value passed in. Carefully check and audit all values and code paths going
 * into this call. Make sure any user data is appropriately escaped for this security context.
 * For more detail, see the [Security Guide](https://g.co/ng/security).
 *
 * @publicApi
 */
let DomSanitizer = /*#__PURE__*/(() => {
  class DomSanitizer {
    static ɵfac = (() => function DomSanitizer_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DomSanitizer)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DomSanitizer,
      factory: function DomSanitizer_Factory(__ngFactoryType__) {
        let __ngConditionalFactory__ = null;
        if (__ngFactoryType__) {
          __ngConditionalFactory__ = new (__ngFactoryType__ || DomSanitizer)();
        } else {
          __ngConditionalFactory__ = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](DomSanitizerImpl);
        }
        return __ngConditionalFactory__;
      },
      providedIn: 'root'
    }))();
  }
  return DomSanitizer;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
let DomSanitizerImpl = /*#__PURE__*/(() => {
  class DomSanitizerImpl extends DomSanitizer {
    _doc;
    constructor(_doc) {
      super();
      this._doc = _doc;
    }
    sanitize(ctx, value) {
      if (value == null) return null;
      switch (ctx) {
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.NONE:
          return value;
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.HTML:
          if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "HTML" /* BypassType.Html */)) {
            return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
          }
          return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ_sanitizeHtml"])(this._doc, String(value)).toString();
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.STYLE:
          if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "Style" /* BypassType.Style */)) {
            return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
          }
          return value;
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.SCRIPT:
          if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "Script" /* BypassType.Script */)) {
            return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
          }
          throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5200 /* RuntimeErrorCode.SANITIZATION_UNSAFE_SCRIPT */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'unsafe value used in a script context');
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.URL:
          if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "URL" /* BypassType.Url */)) {
            return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
          }
          return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ_sanitizeUrl"])(String(value));
        case _angular_core__WEBPACK_IMPORTED_MODULE_1__.SecurityContext.RESOURCE_URL:
          if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵallowSanitizationBypassAndThrow"])(value, "ResourceURL" /* BypassType.ResourceUrl */)) {
            return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunwrapSafeValue"])(value);
          }
          throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5201 /* RuntimeErrorCode.SANITIZATION_UNSAFE_RESOURCE_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `unsafe value used in a resource URL context (see ${_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵXSS_SECURITY_URL"]})`);
        default:
          throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](5202 /* RuntimeErrorCode.SANITIZATION_UNEXPECTED_CTX */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Unexpected SecurityContext ${ctx} (see ${_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵXSS_SECURITY_URL"]})`);
      }
    }
    bypassSecurityTrustHtml(value) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustHtml"])(value);
    }
    bypassSecurityTrustStyle(value) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustStyle"])(value);
    }
    bypassSecurityTrustScript(value) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustScript"])(value);
    }
    bypassSecurityTrustUrl(value) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustUrl"])(value);
    }
    bypassSecurityTrustResourceUrl(value) {
      return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵbypassSanitizationTrustResourceUrl"])(value);
    }
    static ɵfac = (() => function DomSanitizerImpl_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DomSanitizerImpl)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_0__.DOCUMENT));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DomSanitizerImpl,
      factory: DomSanitizerImpl.ɵfac,
      providedIn: 'root'
    }))();
  }
  return DomSanitizerImpl;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * The list of features as an enum to uniquely type each `HydrationFeature`.
 * @see {@link HydrationFeature}
 *
 * @publicApi
 */
var HydrationFeatureKind = /*#__PURE__*/function (HydrationFeatureKind) {
  HydrationFeatureKind[HydrationFeatureKind["NoHttpTransferCache"] = 0] = "NoHttpTransferCache";
  HydrationFeatureKind[HydrationFeatureKind["HttpTransferCacheOptions"] = 1] = "HttpTransferCacheOptions";
  HydrationFeatureKind[HydrationFeatureKind["I18nSupport"] = 2] = "I18nSupport";
  HydrationFeatureKind[HydrationFeatureKind["EventReplay"] = 3] = "EventReplay";
  HydrationFeatureKind[HydrationFeatureKind["IncrementalHydration"] = 4] = "IncrementalHydration";
  return HydrationFeatureKind;
}(HydrationFeatureKind || {});
/**
 * Helper function to create an object that represents a Hydration feature.
 */
function hydrationFeature(ɵkind, ɵproviders = [], ɵoptions = {}) {
  return {
    ɵkind,
    ɵproviders
  };
}
/**
 * Disables HTTP transfer cache. Effectively causes HTTP requests to be performed twice: once on the
 * server and other one on the browser.
 *
 * @publicApi
 */
function withNoHttpTransferCache() {
  // This feature has no providers and acts as a flag that turns off
  // HTTP transfer cache (which otherwise is turned on by default).
  return hydrationFeature(HydrationFeatureKind.NoHttpTransferCache);
}
/**
 * The function accepts an object, which allows to configure cache parameters,
 * such as which headers should be included (no headers are included by default),
 * whether POST requests should be cached or a callback function to determine if a
 * particular request should be cached.
 *
 * @publicApi
 */
function withHttpTransferCacheOptions(options) {
  // This feature has no providers and acts as a flag to pass options to the HTTP transfer cache.
  return hydrationFeature(HydrationFeatureKind.HttpTransferCacheOptions, (0,_angular_common_http__WEBPACK_IMPORTED_MODULE_2__["ɵwithHttpTransferCache"])(options));
}
/**
 * Enables support for hydrating i18n blocks.
 *
 * @developerPreview
 * @publicApi
 */
function withI18nSupport() {
  return hydrationFeature(HydrationFeatureKind.I18nSupport, (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵwithI18nSupport"])());
}
/**
 * Enables support for replaying user events (e.g. `click`s) that happened on a page
 * before hydration logic has completed. Once an application is hydrated, all captured
 * events are replayed and relevant event listeners are executed.
 *
 * @usageNotes
 *
 * Basic example of how you can enable event replay in your application when
 * `bootstrapApplication` function is used:
 * ```
 * bootstrapApplication(AppComponent, {
 *   providers: [provideClientHydration(withEventReplay())]
 * });
 * ```
 * @publicApi
 * @see {@link provideClientHydration}
 */
function withEventReplay() {
  return hydrationFeature(HydrationFeatureKind.EventReplay, (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵwithEventReplay"])());
}
/**
 * Enables support for incremental hydration using the `hydrate` trigger syntax.
 *
 * @usageNotes
 *
 * Basic example of how you can enable incremental hydration in your application when
 * the `bootstrapApplication` function is used:
 * ```
 * bootstrapApplication(AppComponent, {
 *   providers: [provideClientHydration(withIncrementalHydration())]
 * });
 * ```
 * @experimental
 * @publicApi
 * @see {@link provideClientHydration}
 */
function withIncrementalHydration() {
  return hydrationFeature(HydrationFeatureKind.IncrementalHydration, (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵwithIncrementalHydration"])());
}
/**
 * Returns an `ENVIRONMENT_INITIALIZER` token setup with a function
 * that verifies whether compatible ZoneJS was used in an application
 * and logs a warning in a console if it's not the case.
 */
function provideZoneJsCompatibilityDetector() {
  return [{
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ENVIRONMENT_INITIALIZER,
    useValue: () => {
      const ngZone = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
      const isZoneless = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵZONELESS_ENABLED"]);
      // Checking `ngZone instanceof NgZone` would be insufficient here,
      // because custom implementations might use NgZone as a base class.
      if (!isZoneless && ngZone.constructor !== _angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone) {
        const console = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]);
        const message = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵformatRuntimeError"])(-5000 /* RuntimeErrorCode.UNSUPPORTED_ZONEJS_INSTANCE */, 'Angular detected that hydration was enabled for an application ' + 'that uses a custom or a noop Zone.js implementation. ' + 'This is not yet a fully supported configuration.');
        // tslint:disable-next-line:no-console
        console.warn(message);
      }
    },
    multi: true
  }];
}
/**
 * Sets up providers necessary to enable hydration functionality for the application.
 *
 * By default, the function enables the recommended set of features for the optimal
 * performance for most of the applications. It includes the following features:
 *
 * * Reconciling DOM hydration. Learn more about it [here](guide/hydration).
 * * [`HttpClient`](api/common/http/HttpClient) response caching while running on the server and
 * transferring this cache to the client to avoid extra HTTP requests. Learn more about data caching
 * [here](guide/ssr#caching-data-when-using-httpclient).
 *
 * These functions allow you to disable some of the default features or enable new ones:
 *
 * * {@link withNoHttpTransferCache} to disable HTTP transfer cache
 * * {@link withHttpTransferCacheOptions} to configure some HTTP transfer cache options
 * * {@link withI18nSupport} to enable hydration support for i18n blocks
 * * {@link withEventReplay} to enable support for replaying user events
 *
 * @usageNotes
 *
 * Basic example of how you can enable hydration in your application when
 * `bootstrapApplication` function is used:
 * ```
 * bootstrapApplication(AppComponent, {
 *   providers: [provideClientHydration()]
 * });
 * ```
 *
 * Alternatively if you are using NgModules, you would add `provideClientHydration`
 * to your root app module's provider list.
 * ```
 * @NgModule({
 *   declarations: [RootCmp],
 *   bootstrap: [RootCmp],
 *   providers: [provideClientHydration()],
 * })
 * export class AppModule {}
 * ```
 *
 * @see {@link withNoHttpTransferCache}
 * @see {@link withHttpTransferCacheOptions}
 * @see {@link withI18nSupport}
 * @see {@link withEventReplay}
 *
 * @param features Optional features to configure additional router behaviors.
 * @returns A set of providers to enable hydration.
 *
 * @publicApi
 */
function provideClientHydration(...features) {
  const providers = [];
  const featuresKind = new Set();
  const hasHttpTransferCacheOptions = featuresKind.has(HydrationFeatureKind.HttpTransferCacheOptions);
  for (const {
    ɵproviders,
    ɵkind
  } of features) {
    featuresKind.add(ɵkind);
    if (ɵproviders.length) {
      providers.push(ɵproviders);
    }
  }
  if (typeof ngDevMode !== 'undefined' && ngDevMode && featuresKind.has(HydrationFeatureKind.NoHttpTransferCache) && hasHttpTransferCacheOptions) {
    // TODO: Make this a runtime error
    throw new Error('Configuration error: found both withHttpTransferCacheOptions() and withNoHttpTransferCache() in the same call to provideClientHydration(), which is a contradiction.');
  }
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.makeEnvironmentProviders)([typeof ngDevMode !== 'undefined' && ngDevMode ? provideZoneJsCompatibilityDetector() : [], (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵwithDomHydration"])(), featuresKind.has(HydrationFeatureKind.NoHttpTransferCache) || hasHttpTransferCacheOptions ? [] : (0,_angular_common_http__WEBPACK_IMPORTED_MODULE_2__["ɵwithHttpTransferCache"])({}), providers]);
}

/**
 * @module
 * @description
 * Entry point for all public APIs of the platform-browser package.
 */
/**
 * @publicApi
 */
const VERSION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.Version('19.0.0');

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
// This file only reexports content of the `src` folder. Keep it that way.

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 4947:
/*!******************************************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@angular+router@19.0.0_@angular+common@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone.js@0_5223e208939e2bb7d783c325435b884c/node_modules/@angular/router/fesm2022/router.mjs ***!
  \******************************************************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ActivatedRoute: () => (/* binding */ ActivatedRoute),
/* harmony export */   ActivatedRouteSnapshot: () => (/* binding */ ActivatedRouteSnapshot),
/* harmony export */   ActivationEnd: () => (/* binding */ ActivationEnd),
/* harmony export */   ActivationStart: () => (/* binding */ ActivationStart),
/* harmony export */   BaseRouteReuseStrategy: () => (/* binding */ BaseRouteReuseStrategy),
/* harmony export */   ChildActivationEnd: () => (/* binding */ ChildActivationEnd),
/* harmony export */   ChildActivationStart: () => (/* binding */ ChildActivationStart),
/* harmony export */   ChildrenOutletContexts: () => (/* binding */ ChildrenOutletContexts),
/* harmony export */   DefaultTitleStrategy: () => (/* binding */ DefaultTitleStrategy),
/* harmony export */   DefaultUrlSerializer: () => (/* binding */ DefaultUrlSerializer),
/* harmony export */   EventType: () => (/* binding */ EventType),
/* harmony export */   GuardsCheckEnd: () => (/* binding */ GuardsCheckEnd),
/* harmony export */   GuardsCheckStart: () => (/* binding */ GuardsCheckStart),
/* harmony export */   NavigationCancel: () => (/* binding */ NavigationCancel),
/* harmony export */   NavigationCancellationCode: () => (/* binding */ NavigationCancellationCode),
/* harmony export */   NavigationEnd: () => (/* binding */ NavigationEnd),
/* harmony export */   NavigationError: () => (/* binding */ NavigationError),
/* harmony export */   NavigationSkipped: () => (/* binding */ NavigationSkipped),
/* harmony export */   NavigationSkippedCode: () => (/* binding */ NavigationSkippedCode),
/* harmony export */   NavigationStart: () => (/* binding */ NavigationStart),
/* harmony export */   NoPreloading: () => (/* binding */ NoPreloading),
/* harmony export */   OutletContext: () => (/* binding */ OutletContext),
/* harmony export */   PRIMARY_OUTLET: () => (/* binding */ PRIMARY_OUTLET),
/* harmony export */   PreloadAllModules: () => (/* binding */ PreloadAllModules),
/* harmony export */   PreloadingStrategy: () => (/* binding */ PreloadingStrategy),
/* harmony export */   ROUTER_CONFIGURATION: () => (/* binding */ ROUTER_CONFIGURATION),
/* harmony export */   ROUTER_INITIALIZER: () => (/* binding */ ROUTER_INITIALIZER),
/* harmony export */   ROUTER_OUTLET_DATA: () => (/* binding */ ROUTER_OUTLET_DATA),
/* harmony export */   ROUTES: () => (/* binding */ ROUTES),
/* harmony export */   RedirectCommand: () => (/* binding */ RedirectCommand),
/* harmony export */   ResolveEnd: () => (/* binding */ ResolveEnd),
/* harmony export */   ResolveStart: () => (/* binding */ ResolveStart),
/* harmony export */   RouteConfigLoadEnd: () => (/* binding */ RouteConfigLoadEnd),
/* harmony export */   RouteConfigLoadStart: () => (/* binding */ RouteConfigLoadStart),
/* harmony export */   RouteReuseStrategy: () => (/* binding */ RouteReuseStrategy),
/* harmony export */   Router: () => (/* binding */ Router),
/* harmony export */   RouterEvent: () => (/* binding */ RouterEvent),
/* harmony export */   RouterLink: () => (/* binding */ RouterLink),
/* harmony export */   RouterLinkActive: () => (/* binding */ RouterLinkActive),
/* harmony export */   RouterLinkWithHref: () => (/* binding */ RouterLink),
/* harmony export */   RouterModule: () => (/* binding */ RouterModule),
/* harmony export */   RouterOutlet: () => (/* binding */ RouterOutlet),
/* harmony export */   RouterPreloader: () => (/* binding */ RouterPreloader),
/* harmony export */   RouterState: () => (/* binding */ RouterState),
/* harmony export */   RouterStateSnapshot: () => (/* binding */ RouterStateSnapshot),
/* harmony export */   RoutesRecognized: () => (/* binding */ RoutesRecognized),
/* harmony export */   Scroll: () => (/* binding */ Scroll),
/* harmony export */   TitleStrategy: () => (/* binding */ TitleStrategy),
/* harmony export */   UrlHandlingStrategy: () => (/* binding */ UrlHandlingStrategy),
/* harmony export */   UrlSegment: () => (/* binding */ UrlSegment),
/* harmony export */   UrlSegmentGroup: () => (/* binding */ UrlSegmentGroup),
/* harmony export */   UrlSerializer: () => (/* binding */ UrlSerializer),
/* harmony export */   UrlTree: () => (/* binding */ UrlTree),
/* harmony export */   VERSION: () => (/* binding */ VERSION),
/* harmony export */   convertToParamMap: () => (/* binding */ convertToParamMap),
/* harmony export */   createUrlTreeFromSnapshot: () => (/* binding */ createUrlTreeFromSnapshot),
/* harmony export */   defaultUrlMatcher: () => (/* binding */ defaultUrlMatcher),
/* harmony export */   mapToCanActivate: () => (/* binding */ mapToCanActivate),
/* harmony export */   mapToCanActivateChild: () => (/* binding */ mapToCanActivateChild),
/* harmony export */   mapToCanDeactivate: () => (/* binding */ mapToCanDeactivate),
/* harmony export */   mapToCanMatch: () => (/* binding */ mapToCanMatch),
/* harmony export */   mapToResolve: () => (/* binding */ mapToResolve),
/* harmony export */   provideRouter: () => (/* binding */ provideRouter),
/* harmony export */   provideRoutes: () => (/* binding */ provideRoutes),
/* harmony export */   withComponentInputBinding: () => (/* binding */ withComponentInputBinding),
/* harmony export */   withDebugTracing: () => (/* binding */ withDebugTracing),
/* harmony export */   withDisabledInitialNavigation: () => (/* binding */ withDisabledInitialNavigation),
/* harmony export */   withEnabledBlockingInitialNavigation: () => (/* binding */ withEnabledBlockingInitialNavigation),
/* harmony export */   withHashLocation: () => (/* binding */ withHashLocation),
/* harmony export */   withInMemoryScrolling: () => (/* binding */ withInMemoryScrolling),
/* harmony export */   withNavigationErrorHandler: () => (/* binding */ withNavigationErrorHandler),
/* harmony export */   withPreloading: () => (/* binding */ withPreloading),
/* harmony export */   withRouterConfig: () => (/* binding */ withRouterConfig),
/* harmony export */   withViewTransitions: () => (/* binding */ withViewTransitions),
/* harmony export */   "ɵEmptyOutletComponent": () => (/* binding */ ɵEmptyOutletComponent),
/* harmony export */   "ɵROUTER_PROVIDERS": () => (/* binding */ ROUTER_PROVIDERS),
/* harmony export */   "ɵafterNextNavigation": () => (/* binding */ afterNextNavigation),
/* harmony export */   "ɵloadChildren": () => (/* binding */ loadChildren)
/* harmony export */ });
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ 9178);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 580);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs */ 2049);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs */ 2836);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 1428);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! rxjs */ 8638);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! rxjs */ 8440);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! rxjs */ 3966);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! rxjs */ 5851);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! rxjs */ 7954);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! rxjs */ 3471);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! rxjs */ 4985);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! rxjs */ 2273);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs/operators */ 6634);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs/operators */ 462);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rxjs/operators */ 1969);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! rxjs/operators */ 348);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! rxjs/operators */ 4484);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! rxjs/operators */ 1292);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! rxjs/operators */ 8898);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! rxjs/operators */ 826);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! rxjs/operators */ 4997);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! rxjs/operators */ 5685);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! rxjs/operators */ 8719);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! rxjs/operators */ 997);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! rxjs/operators */ 6418);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! rxjs/operators */ 1437);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! rxjs/operators */ 5359);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! rxjs/operators */ 5996);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! rxjs/operators */ 6018);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! rxjs/operators */ 473);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! rxjs/operators */ 4053);
/* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! @angular/platform-browser */ 4604);
/**
 * @license Angular v19.0.0
 * (c) 2010-2024 Google LLC. https://angular.io/
 * License: MIT
 */









/**
 * The primary routing outlet.
 *
 * @publicApi
 */
const PRIMARY_OUTLET = 'primary';
/**
 * A private symbol used to store the value of `Route.title` inside the `Route.data` if it is a
 * static string or `Route.resolve` if anything else. This allows us to reuse the existing route
 * data/resolvers to support the title feature without new instrumentation in the `Router` pipeline.
 */
const RouteTitleKey = /* @__PURE__ */Symbol('RouteTitle');
class ParamsAsMap {
  params;
  constructor(params) {
    this.params = params || {};
  }
  has(name) {
    return Object.prototype.hasOwnProperty.call(this.params, name);
  }
  get(name) {
    if (this.has(name)) {
      const v = this.params[name];
      return Array.isArray(v) ? v[0] : v;
    }
    return null;
  }
  getAll(name) {
    if (this.has(name)) {
      const v = this.params[name];
      return Array.isArray(v) ? v : [v];
    }
    return [];
  }
  get keys() {
    return Object.keys(this.params);
  }
}
/**
 * Converts a `Params` instance to a `ParamMap`.
 * @param params The instance to convert.
 * @returns The new map instance.
 *
 * @publicApi
 */
function convertToParamMap(params) {
  return new ParamsAsMap(params);
}
/**
 * Matches the route configuration (`route`) against the actual URL (`segments`).
 *
 * When no matcher is defined on a `Route`, this is the matcher used by the Router by default.
 *
 * @param segments The remaining unmatched segments in the current navigation
 * @param segmentGroup The current segment group being matched
 * @param route The `Route` to match against.
 *
 * @see {@link UrlMatchResult}
 * @see {@link Route}
 *
 * @returns The resulting match information or `null` if the `route` should not match.
 * @publicApi
 */
function defaultUrlMatcher(segments, segmentGroup, route) {
  const parts = route.path.split('/');
  if (parts.length > segments.length) {
    // The actual URL is shorter than the config, no match
    return null;
  }
  if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || parts.length < segments.length)) {
    // The config is longer than the actual URL but we are looking for a full match, return null
    return null;
  }
  const posParams = {};
  // Check each config part against the actual URL
  for (let index = 0; index < parts.length; index++) {
    const part = parts[index];
    const segment = segments[index];
    const isParameter = part[0] === ':';
    if (isParameter) {
      posParams[part.substring(1)] = segment;
    } else if (part !== segment.path) {
      // The actual URL part does not match the config, no match
      return null;
    }
  }
  return {
    consumed: segments.slice(0, parts.length),
    posParams
  };
}
function shallowEqualArrays(a, b) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; ++i) {
    if (!shallowEqual(a[i], b[i])) return false;
  }
  return true;
}
function shallowEqual(a, b) {
  // While `undefined` should never be possible, it would sometimes be the case in IE 11
  // and pre-chromium Edge. The check below accounts for this edge case.
  const k1 = a ? getDataKeys(a) : undefined;
  const k2 = b ? getDataKeys(b) : undefined;
  if (!k1 || !k2 || k1.length != k2.length) {
    return false;
  }
  let key;
  for (let i = 0; i < k1.length; i++) {
    key = k1[i];
    if (!equalArraysOrString(a[key], b[key])) {
      return false;
    }
  }
  return true;
}
/**
 * Gets the keys of an object, including `symbol` keys.
 */
function getDataKeys(obj) {
  return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
}
/**
 * Test equality for arrays of strings or a string.
 */
function equalArraysOrString(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    const aSorted = [...a].sort();
    const bSorted = [...b].sort();
    return aSorted.every((val, index) => bSorted[index] === val);
  } else {
    return a === b;
  }
}
/**
 * Return the last element of an array.
 */
function last(a) {
  return a.length > 0 ? a[a.length - 1] : null;
}
function wrapIntoObservable(value) {
  if ((0,rxjs__WEBPACK_IMPORTED_MODULE_0__.isObservable)(value)) {
    return value;
  }
  if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisPromise"])(value)) {
    // Use `Promise.resolve()` to wrap promise-like instances.
    // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
    // change detection.
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(Promise.resolve(value));
  }
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(value);
}
const pathCompareMap = {
  'exact': equalSegmentGroups,
  'subset': containsSegmentGroup
};
const paramCompareMap = {
  'exact': equalParams,
  'subset': containsParams,
  'ignored': () => true
};
function containsTree(container, containee, options) {
  return pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) && paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) && !(options.fragment === 'exact' && container.fragment !== containee.fragment);
}
function equalParams(container, containee) {
  // TODO: This does not handle array params correctly.
  return shallowEqual(container, containee);
}
function equalSegmentGroups(container, containee, matrixParams) {
  if (!equalPath(container.segments, containee.segments)) return false;
  if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) {
    return false;
  }
  if (container.numberOfChildren !== containee.numberOfChildren) return false;
  for (const c in containee.children) {
    if (!container.children[c]) return false;
    if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams)) return false;
  }
  return true;
}
function containsParams(container, containee) {
  return Object.keys(containee).length <= Object.keys(container).length && Object.keys(containee).every(key => equalArraysOrString(container[key], containee[key]));
}
function containsSegmentGroup(container, containee, matrixParams) {
  return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams);
}
function containsSegmentGroupHelper(container, containee, containeePaths, matrixParams) {
  if (container.segments.length > containeePaths.length) {
    const current = container.segments.slice(0, containeePaths.length);
    if (!equalPath(current, containeePaths)) return false;
    if (containee.hasChildren()) return false;
    if (!matrixParamsMatch(current, containeePaths, matrixParams)) return false;
    return true;
  } else if (container.segments.length === containeePaths.length) {
    if (!equalPath(container.segments, containeePaths)) return false;
    if (!matrixParamsMatch(container.segments, containeePaths, matrixParams)) return false;
    for (const c in containee.children) {
      if (!container.children[c]) return false;
      if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) {
        return false;
      }
    }
    return true;
  } else {
    const current = containeePaths.slice(0, container.segments.length);
    const next = containeePaths.slice(container.segments.length);
    if (!equalPath(container.segments, current)) return false;
    if (!matrixParamsMatch(container.segments, current, matrixParams)) return false;
    if (!container.children[PRIMARY_OUTLET]) return false;
    return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next, matrixParams);
  }
}
function matrixParamsMatch(containerPaths, containeePaths, options) {
  return containeePaths.every((containeeSegment, i) => {
    return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters);
  });
}
/**
 * @description
 *
 * Represents the parsed URL.
 *
 * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
 * serialized tree.
 * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const tree: UrlTree =
 *       router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
 *     const f = tree.fragment; // return 'fragment'
 *     const q = tree.queryParams; // returns {debug: 'true'}
 *     const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
 *     const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
 *     g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
 *     g.children['support'].segments; // return 1 segment 'help'
 *   }
 * }
 * ```
 *
 * @publicApi
 */
class UrlTree {
  root;
  queryParams;
  fragment;
  /** @internal */
  _queryParamMap;
  constructor(/** The root segment group of the URL tree */
  root = new UrlSegmentGroup([], {}), /** The query params of the URL */
  queryParams = {}, /** The fragment of the URL */
  fragment = null) {
    this.root = root;
    this.queryParams = queryParams;
    this.fragment = fragment;
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      if (root.segments.length > 0) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4015 /* RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT */, 'The root `UrlSegmentGroup` should not contain `segments`. ' + 'Instead, these segments belong in the `children` so they can be associated with a named outlet.');
      }
    }
  }
  get queryParamMap() {
    this._queryParamMap ??= convertToParamMap(this.queryParams);
    return this._queryParamMap;
  }
  /** @docsNotRequired */
  toString() {
    return DEFAULT_SERIALIZER.serialize(this);
  }
}
/**
 * @description
 *
 * Represents the parsed URL segment group.
 *
 * See `UrlTree` for more information.
 *
 * @publicApi
 */
class UrlSegmentGroup {
  segments;
  children;
  /** The parent node in the url tree */
  parent = null;
  constructor(/** The URL segments of this group. See `UrlSegment` for more information */
  segments, /** The list of children of this group */
  children) {
    this.segments = segments;
    this.children = children;
    Object.values(children).forEach(v => v.parent = this);
  }
  /** Whether the segment has child segments */
  hasChildren() {
    return this.numberOfChildren > 0;
  }
  /** Number of child segments */
  get numberOfChildren() {
    return Object.keys(this.children).length;
  }
  /** @docsNotRequired */
  toString() {
    return serializePaths(this);
  }
}
/**
 * @description
 *
 * Represents a single URL segment.
 *
 * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
 * parameters associated with the segment.
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const tree: UrlTree = router.parseUrl('/team;id=33');
 *     const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
 *     const s: UrlSegment[] = g.segments;
 *     s[0].path; // returns 'team'
 *     s[0].parameters; // returns {id: 33}
 *   }
 * }
 * ```
 *
 * @publicApi
 */
class UrlSegment {
  path;
  parameters;
  /** @internal */
  _parameterMap;
  constructor(/** The path part of a URL segment */
  path, /** The matrix parameters associated with a segment */
  parameters) {
    this.path = path;
    this.parameters = parameters;
  }
  get parameterMap() {
    this._parameterMap ??= convertToParamMap(this.parameters);
    return this._parameterMap;
  }
  /** @docsNotRequired */
  toString() {
    return serializePath(this);
  }
}
function equalSegments(as, bs) {
  return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters));
}
function equalPath(as, bs) {
  if (as.length !== bs.length) return false;
  return as.every((a, i) => a.path === bs[i].path);
}
function mapChildrenIntoArray(segment, fn) {
  let res = [];
  Object.entries(segment.children).forEach(([childOutlet, child]) => {
    if (childOutlet === PRIMARY_OUTLET) {
      res = res.concat(fn(child, childOutlet));
    }
  });
  Object.entries(segment.children).forEach(([childOutlet, child]) => {
    if (childOutlet !== PRIMARY_OUTLET) {
      res = res.concat(fn(child, childOutlet));
    }
  });
  return res;
}
/**
 * @description
 *
 * Serializes and deserializes a URL string into a URL tree.
 *
 * The url serialization strategy is customizable. You can
 * make all URLs case insensitive by providing a custom UrlSerializer.
 *
 * See `DefaultUrlSerializer` for an example of a URL serializer.
 *
 * @publicApi
 */
let UrlSerializer = /*#__PURE__*/(() => {
  class UrlSerializer {
    static ɵfac = (() => function UrlSerializer_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UrlSerializer)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: UrlSerializer,
      factory: () => (() => new DefaultUrlSerializer())(),
      providedIn: 'root'
    }))();
  }
  return UrlSerializer;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 *
 * A default implementation of the `UrlSerializer`.
 *
 * Example URLs:
 *
 * ```
 * /inbox/33(popup:compose)
 * /inbox/33;open=true/messages/44
 * ```
 *
 * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
 * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
 * specify route specific parameters.
 *
 * @publicApi
 */
class DefaultUrlSerializer {
  /** Parses a url into a `UrlTree` */
  parse(url) {
    const p = new UrlParser(url);
    return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
  }
  /** Converts a `UrlTree` into a url */
  serialize(tree) {
    const segment = `/${serializeSegment(tree.root, true)}`;
    const query = serializeQueryParams(tree.queryParams);
    const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : '';
    return `${segment}${query}${fragment}`;
  }
}
const DEFAULT_SERIALIZER = /*#__PURE__*/new DefaultUrlSerializer();
function serializePaths(segment) {
  return segment.segments.map(p => serializePath(p)).join('/');
}
function serializeSegment(segment, root) {
  if (!segment.hasChildren()) {
    return serializePaths(segment);
  }
  if (root) {
    const primary = segment.children[PRIMARY_OUTLET] ? serializeSegment(segment.children[PRIMARY_OUTLET], false) : '';
    const children = [];
    Object.entries(segment.children).forEach(([k, v]) => {
      if (k !== PRIMARY_OUTLET) {
        children.push(`${k}:${serializeSegment(v, false)}`);
      }
    });
    return children.length > 0 ? `${primary}(${children.join('//')})` : primary;
  } else {
    const children = mapChildrenIntoArray(segment, (v, k) => {
      if (k === PRIMARY_OUTLET) {
        return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
      }
      return [`${k}:${serializeSegment(v, false)}`];
    });
    // use no parenthesis if the only child is a primary outlet route
    if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) {
      return `${serializePaths(segment)}/${children[0]}`;
    }
    return `${serializePaths(segment)}/(${children.join('//')})`;
  }
}
/**
 * Encodes a URI string with the default encoding. This function will only ever be called from
 * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
 * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
 * have to be encoded per https://url.spec.whatwg.org.
 */
function encodeUriString(s) {
  return encodeURIComponent(s).replace(/%40/g, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',');
}
/**
 * This function should be used to encode both keys and values in a query string key/value. In
 * the following URL, you need to call encodeUriQuery on "k" and "v":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
function encodeUriQuery(s) {
  return encodeUriString(s).replace(/%3B/gi, ';');
}
/**
 * This function should be used to encode a URL fragment. In the following URL, you need to call
 * encodeUriFragment on "f":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
function encodeUriFragment(s) {
  return encodeURI(s);
}
/**
 * This function should be run on any URI segment as well as the key and value in a key/value
 * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
 * "mk", and "mv":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
function encodeUriSegment(s) {
  return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
}
function decode(s) {
  return decodeURIComponent(s);
}
// Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
// decodeURIComponent function will not decode "+" as a space.
function decodeQuery(s) {
  return decode(s.replace(/\+/g, '%20'));
}
function serializePath(path) {
  return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;
}
function serializeMatrixParams(params) {
  return Object.entries(params).map(([key, value]) => `;${encodeUriSegment(key)}=${encodeUriSegment(value)}`).join('');
}
function serializeQueryParams(params) {
  const strParams = Object.entries(params).map(([name, value]) => {
    return Array.isArray(value) ? value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') : `${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
  }).filter(s => s);
  return strParams.length ? `?${strParams.join('&')}` : '';
}
const SEGMENT_RE = /^[^\/()?;#]+/;
function matchSegments(str) {
  const match = str.match(SEGMENT_RE);
  return match ? match[0] : '';
}
const MATRIX_PARAM_SEGMENT_RE = /^[^\/()?;=#]+/;
function matchMatrixKeySegments(str) {
  const match = str.match(MATRIX_PARAM_SEGMENT_RE);
  return match ? match[0] : '';
}
const QUERY_PARAM_RE = /^[^=?&#]+/;
// Return the name of the query param at the start of the string or an empty string
function matchQueryParams(str) {
  const match = str.match(QUERY_PARAM_RE);
  return match ? match[0] : '';
}
const QUERY_PARAM_VALUE_RE = /^[^&#]+/;
// Return the value of the query param at the start of the string or an empty string
function matchUrlQueryParamValue(str) {
  const match = str.match(QUERY_PARAM_VALUE_RE);
  return match ? match[0] : '';
}
class UrlParser {
  url;
  remaining;
  constructor(url) {
    this.url = url;
    this.remaining = url;
  }
  parseRootSegment() {
    this.consumeOptional('/');
    if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
      return new UrlSegmentGroup([], {});
    }
    // The root segment group never has segments
    return new UrlSegmentGroup([], this.parseChildren());
  }
  parseQueryParams() {
    const params = {};
    if (this.consumeOptional('?')) {
      do {
        this.parseQueryParam(params);
      } while (this.consumeOptional('&'));
    }
    return params;
  }
  parseFragment() {
    return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
  }
  parseChildren() {
    if (this.remaining === '') {
      return {};
    }
    this.consumeOptional('/');
    const segments = [];
    if (!this.peekStartsWith('(')) {
      segments.push(this.parseSegment());
    }
    while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
      this.capture('/');
      segments.push(this.parseSegment());
    }
    let children = {};
    if (this.peekStartsWith('/(')) {
      this.capture('/');
      children = this.parseParens(true);
    }
    let res = {};
    if (this.peekStartsWith('(')) {
      res = this.parseParens(false);
    }
    if (segments.length > 0 || Object.keys(children).length > 0) {
      res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
    }
    return res;
  }
  // parse a segment with its matrix parameters
  // ie `name;k1=v1;k2`
  parseSegment() {
    const path = matchSegments(this.remaining);
    if (path === '' && this.peekStartsWith(';')) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4009 /* RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Empty path url segment cannot have parameters: '${this.remaining}'.`);
    }
    this.capture(path);
    return new UrlSegment(decode(path), this.parseMatrixParams());
  }
  parseMatrixParams() {
    const params = {};
    while (this.consumeOptional(';')) {
      this.parseParam(params);
    }
    return params;
  }
  parseParam(params) {
    const key = matchMatrixKeySegments(this.remaining);
    if (!key) {
      return;
    }
    this.capture(key);
    let value = '';
    if (this.consumeOptional('=')) {
      const valueMatch = matchSegments(this.remaining);
      if (valueMatch) {
        value = valueMatch;
        this.capture(value);
      }
    }
    params[decode(key)] = decode(value);
  }
  // Parse a single query parameter `name[=value]`
  parseQueryParam(params) {
    const key = matchQueryParams(this.remaining);
    if (!key) {
      return;
    }
    this.capture(key);
    let value = '';
    if (this.consumeOptional('=')) {
      const valueMatch = matchUrlQueryParamValue(this.remaining);
      if (valueMatch) {
        value = valueMatch;
        this.capture(value);
      }
    }
    const decodedKey = decodeQuery(key);
    const decodedVal = decodeQuery(value);
    if (params.hasOwnProperty(decodedKey)) {
      // Append to existing values
      let currentVal = params[decodedKey];
      if (!Array.isArray(currentVal)) {
        currentVal = [currentVal];
        params[decodedKey] = currentVal;
      }
      currentVal.push(decodedVal);
    } else {
      // Create a new value
      params[decodedKey] = decodedVal;
    }
  }
  // parse `(a/b//outlet_name:c/d)`
  parseParens(allowPrimary) {
    const segments = {};
    this.capture('(');
    while (!this.consumeOptional(')') && this.remaining.length > 0) {
      const path = matchSegments(this.remaining);
      const next = this.remaining[path.length];
      // if is is not one of these characters, then the segment was unescaped
      // or the group was not closed
      if (next !== '/' && next !== ')' && next !== ';') {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4010 /* RuntimeErrorCode.UNPARSABLE_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot parse url '${this.url}'`);
      }
      let outletName = undefined;
      if (path.indexOf(':') > -1) {
        outletName = path.slice(0, path.indexOf(':'));
        this.capture(outletName);
        this.capture(':');
      } else if (allowPrimary) {
        outletName = PRIMARY_OUTLET;
      }
      const children = this.parseChildren();
      segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] : new UrlSegmentGroup([], children);
      this.consumeOptional('//');
    }
    return segments;
  }
  peekStartsWith(str) {
    return this.remaining.startsWith(str);
  }
  // Consumes the prefix when it is present and returns whether it has been consumed
  consumeOptional(str) {
    if (this.peekStartsWith(str)) {
      this.remaining = this.remaining.substring(str.length);
      return true;
    }
    return false;
  }
  capture(str) {
    if (!this.consumeOptional(str)) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4011 /* RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Expected "${str}".`);
    }
  }
}
function createRoot(rootCandidate) {
  return rootCandidate.segments.length > 0 ? new UrlSegmentGroup([], {
    [PRIMARY_OUTLET]: rootCandidate
  }) : rootCandidate;
}
/**
 * Recursively
 * - merges primary segment children into their parents
 * - drops empty children (those which have no segments and no children themselves). This latter
 * prevents serializing a group into something like `/a(aux:)`, where `aux` is an empty child
 * segment.
 * - merges named outlets without a primary segment sibling into the children. This prevents
 * serializing a URL like `//(a:a)(b:b) instead of `/(a:a//b:b)` when the aux b route lives on the
 * root but the `a` route lives under an empty path primary route.
 */
function squashSegmentGroup(segmentGroup) {
  const newChildren = {};
  for (const [childOutlet, child] of Object.entries(segmentGroup.children)) {
    const childCandidate = squashSegmentGroup(child);
    // moves named children in an empty path primary child into this group
    if (childOutlet === PRIMARY_OUTLET && childCandidate.segments.length === 0 && childCandidate.hasChildren()) {
      for (const [grandChildOutlet, grandChild] of Object.entries(childCandidate.children)) {
        newChildren[grandChildOutlet] = grandChild;
      }
    } // don't add empty children
    else if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) {
      newChildren[childOutlet] = childCandidate;
    }
  }
  const s = new UrlSegmentGroup(segmentGroup.segments, newChildren);
  return mergeTrivialChildren(s);
}
/**
 * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`.
 *
 * When a segment group has only one child which is a primary outlet, merges that child into the
 * parent. That is, the child segment group's segments are merged into the `s` and the child's
 * children become the children of `s`. Think of this like a 'squash', merging the child segment
 * group into the parent.
 */
function mergeTrivialChildren(s) {
  if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
    const c = s.children[PRIMARY_OUTLET];
    return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
  }
  return s;
}
function isUrlTree(v) {
  return v instanceof UrlTree;
}

/**
 * Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`.
 *
 * @publicApi
 *
 *
 * @param relativeTo The `ActivatedRouteSnapshot` to apply the commands to
 * @param commands An array of URL fragments with which to construct the new URL tree.
 * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
 * segments, followed by the parameters for each segment.
 * The fragments are applied to the one provided in the `relativeTo` parameter.
 * @param queryParams The query parameters for the `UrlTree`. `null` if the `UrlTree` does not have
 *     any query parameters.
 * @param fragment The fragment for the `UrlTree`. `null` if the `UrlTree` does not have a fragment.
 *
 * @usageNotes
 *
 * ```
 * // create /team/33/user/11
 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]);
 *
 * // create /team/33;expand=true/user/11
 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]);
 *
 * // you can collapse static segments like this (this works only with the first passed-in value):
 * createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]);
 *
 * // If the first segment can contain slashes, and you do not want the router to split it,
 * // you can do the following:
 * createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]);
 *
 * // create /team/33/(user/11//right:chat)
 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right:
 * 'chat'}}], null, null);
 *
 * // remove the right secondary node
 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
 *
 * // For the examples below, assume the current URL is for the `/team/33/user/11` and the
 * `ActivatedRouteSnapshot` points to `user/11`:
 *
 * // navigate to /team/33/user/11/details
 * createUrlTreeFromSnapshot(snapshot, ['details']);
 *
 * // navigate to /team/33/user/22
 * createUrlTreeFromSnapshot(snapshot, ['../22']);
 *
 * // navigate to /team/44/user/22
 * createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']);
 * ```
 */
function createUrlTreeFromSnapshot(relativeTo, commands, queryParams = null, fragment = null) {
  const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo);
  return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment);
}
function createSegmentGroupFromRoute(route) {
  let targetGroup;
  function createSegmentGroupFromRouteRecursive(currentRoute) {
    const childOutlets = {};
    for (const childSnapshot of currentRoute.children) {
      const root = createSegmentGroupFromRouteRecursive(childSnapshot);
      childOutlets[childSnapshot.outlet] = root;
    }
    const segmentGroup = new UrlSegmentGroup(currentRoute.url, childOutlets);
    if (currentRoute === route) {
      targetGroup = segmentGroup;
    }
    return segmentGroup;
  }
  const rootCandidate = createSegmentGroupFromRouteRecursive(route.root);
  const rootSegmentGroup = createRoot(rootCandidate);
  return targetGroup ?? rootSegmentGroup;
}
function createUrlTreeFromSegmentGroup(relativeTo, commands, queryParams, fragment) {
  let root = relativeTo;
  while (root.parent) {
    root = root.parent;
  }
  // There are no commands so the `UrlTree` goes to the same path as the one created from the
  // `UrlSegmentGroup`. All we need to do is update the `queryParams` and `fragment` without
  // applying any other logic.
  if (commands.length === 0) {
    return tree(root, root, root, queryParams, fragment);
  }
  const nav = computeNavigation(commands);
  if (nav.toRoot()) {
    return tree(root, root, new UrlSegmentGroup([], {}), queryParams, fragment);
  }
  const position = findStartingPositionForTargetGroup(nav, root, relativeTo);
  const newSegmentGroup = position.processChildren ? updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands) : updateSegmentGroup(position.segmentGroup, position.index, nav.commands);
  return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment);
}
function isMatrixParams(command) {
  return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
}
/**
 * Determines if a given command has an `outlets` map. When we encounter a command
 * with an outlets k/v map, we need to apply each outlet individually to the existing segment.
 */
function isCommandWithOutlets(command) {
  return typeof command === 'object' && command != null && command.outlets;
}
function tree(oldRoot, oldSegmentGroup, newSegmentGroup, queryParams, fragment) {
  let qp = {};
  if (queryParams) {
    Object.entries(queryParams).forEach(([name, value]) => {
      qp[name] = Array.isArray(value) ? value.map(v => `${v}`) : `${value}`;
    });
  }
  let rootCandidate;
  if (oldRoot === oldSegmentGroup) {
    rootCandidate = newSegmentGroup;
  } else {
    rootCandidate = replaceSegment(oldRoot, oldSegmentGroup, newSegmentGroup);
  }
  const newRoot = createRoot(squashSegmentGroup(rootCandidate));
  return new UrlTree(newRoot, qp, fragment);
}
/**
 * Replaces the `oldSegment` which is located in some child of the `current` with the `newSegment`.
 * This also has the effect of creating new `UrlSegmentGroup` copies to update references. This
 * shouldn't be necessary but the fallback logic for an invalid ActivatedRoute in the creation uses
 * the Router's current url tree. If we don't create new segment groups, we end up modifying that
 * value.
 */
function replaceSegment(current, oldSegment, newSegment) {
  const children = {};
  Object.entries(current.children).forEach(([outletName, c]) => {
    if (c === oldSegment) {
      children[outletName] = newSegment;
    } else {
      children[outletName] = replaceSegment(c, oldSegment, newSegment);
    }
  });
  return new UrlSegmentGroup(current.segments, children);
}
class Navigation {
  isAbsolute;
  numberOfDoubleDots;
  commands;
  constructor(isAbsolute, numberOfDoubleDots, commands) {
    this.isAbsolute = isAbsolute;
    this.numberOfDoubleDots = numberOfDoubleDots;
    this.commands = commands;
    if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4003 /* RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Root segment cannot have matrix parameters');
    }
    const cmdWithOutlet = commands.find(isCommandWithOutlets);
    if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4004 /* RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) && '{outlets:{}} has to be the last command');
    }
  }
  toRoot() {
    return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
  }
}
/** Transforms commands to a normalized `Navigation` */
function computeNavigation(commands) {
  if (typeof commands[0] === 'string' && commands.length === 1 && commands[0] === '/') {
    return new Navigation(true, 0, commands);
  }
  let numberOfDoubleDots = 0;
  let isAbsolute = false;
  const res = commands.reduce((res, cmd, cmdIdx) => {
    if (typeof cmd === 'object' && cmd != null) {
      if (cmd.outlets) {
        const outlets = {};
        Object.entries(cmd.outlets).forEach(([name, commands]) => {
          outlets[name] = typeof commands === 'string' ? commands.split('/') : commands;
        });
        return [...res, {
          outlets
        }];
      }
      if (cmd.segmentPath) {
        return [...res, cmd.segmentPath];
      }
    }
    if (!(typeof cmd === 'string')) {
      return [...res, cmd];
    }
    if (cmdIdx === 0) {
      cmd.split('/').forEach((urlPart, partIndex) => {
        if (partIndex == 0 && urlPart === '.') {
          // skip './a'
        } else if (partIndex == 0 && urlPart === '') {
          //  '/a'
          isAbsolute = true;
        } else if (urlPart === '..') {
          //  '../a'
          numberOfDoubleDots++;
        } else if (urlPart != '') {
          res.push(urlPart);
        }
      });
      return res;
    }
    return [...res, cmd];
  }, []);
  return new Navigation(isAbsolute, numberOfDoubleDots, res);
}
class Position {
  segmentGroup;
  processChildren;
  index;
  constructor(segmentGroup, processChildren, index) {
    this.segmentGroup = segmentGroup;
    this.processChildren = processChildren;
    this.index = index;
  }
}
function findStartingPositionForTargetGroup(nav, root, target) {
  if (nav.isAbsolute) {
    return new Position(root, true, 0);
  }
  if (!target) {
    // `NaN` is used only to maintain backwards compatibility with incorrectly mocked
    // `ActivatedRouteSnapshot` in tests. In prior versions of this code, the position here was
    // determined based on an internal property that was rarely mocked, resulting in `NaN`. In
    // reality, this code path should _never_ be touched since `target` is not allowed to be falsey.
    return new Position(root, false, NaN);
  }
  if (target.parent === null) {
    return new Position(target, true, 0);
  }
  const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
  const index = target.segments.length - 1 + modifier;
  return createPositionApplyingDoubleDots(target, index, nav.numberOfDoubleDots);
}
function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
  let g = group;
  let ci = index;
  let dd = numberOfDoubleDots;
  while (dd > ci) {
    dd -= ci;
    g = g.parent;
    if (!g) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4005 /* RuntimeErrorCode.INVALID_DOUBLE_DOTS */, (typeof ngDevMode === 'undefined' || ngDevMode) && "Invalid number of '../'");
    }
    ci = g.segments.length;
  }
  return new Position(g, false, ci - dd);
}
function getOutlets(commands) {
  if (isCommandWithOutlets(commands[0])) {
    return commands[0].outlets;
  }
  return {
    [PRIMARY_OUTLET]: commands
  };
}
function updateSegmentGroup(segmentGroup, startIndex, commands) {
  segmentGroup ??= new UrlSegmentGroup([], {});
  if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
    return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
  }
  const m = prefixedWith(segmentGroup, startIndex, commands);
  const slicedCommands = commands.slice(m.commandIndex);
  if (m.match && m.pathIndex < segmentGroup.segments.length) {
    const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
    g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
    return updateSegmentGroupChildren(g, 0, slicedCommands);
  } else if (m.match && slicedCommands.length === 0) {
    return new UrlSegmentGroup(segmentGroup.segments, {});
  } else if (m.match && !segmentGroup.hasChildren()) {
    return createNewSegmentGroup(segmentGroup, startIndex, commands);
  } else if (m.match) {
    return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
  } else {
    return createNewSegmentGroup(segmentGroup, startIndex, commands);
  }
}
function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
  if (commands.length === 0) {
    return new UrlSegmentGroup(segmentGroup.segments, {});
  } else {
    const outlets = getOutlets(commands);
    const children = {};
    // If the set of commands applies to anything other than the primary outlet and the child
    // segment is an empty path primary segment on its own, we want to apply the commands to the
    // empty child path rather than here. The outcome is that the empty primary child is effectively
    // removed from the final output UrlTree. Imagine the following config:
    //
    // {path: '', children: [{path: '**', outlet: 'popup'}]}.
    //
    // Navigation to /(popup:a) will activate the child outlet correctly Given a follow-up
    // navigation with commands
    // ['/', {outlets: {'popup': 'b'}}], we _would not_ want to apply the outlet commands to the
    // root segment because that would result in
    // //(popup:a)(popup:b) since the outlet command got applied one level above where it appears in
    // the `ActivatedRoute` rather than updating the existing one.
    //
    // Because empty paths do not appear in the URL segments and the fact that the segments used in
    // the output `UrlTree` are squashed to eliminate these empty paths where possible
    // https://github.com/angular/angular/blob/13f10de40e25c6900ca55bd83b36bd533dacfa9e/packages/router/src/url_tree.ts#L755
    // it can be hard to determine what is the right thing to do when applying commands to a
    // `UrlSegmentGroup` that is created from an "unsquashed"/expanded `ActivatedRoute` tree.
    // This code effectively "squashes" empty path primary routes when they have no siblings on
    // the same level of the tree.
    if (Object.keys(outlets).some(o => o !== PRIMARY_OUTLET) && segmentGroup.children[PRIMARY_OUTLET] && segmentGroup.numberOfChildren === 1 && segmentGroup.children[PRIMARY_OUTLET].segments.length === 0) {
      const childrenOfEmptyChild = updateSegmentGroupChildren(segmentGroup.children[PRIMARY_OUTLET], startIndex, commands);
      return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children);
    }
    Object.entries(outlets).forEach(([outlet, commands]) => {
      if (typeof commands === 'string') {
        commands = [commands];
      }
      if (commands !== null) {
        children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
      }
    });
    Object.entries(segmentGroup.children).forEach(([childOutlet, child]) => {
      if (outlets[childOutlet] === undefined) {
        children[childOutlet] = child;
      }
    });
    return new UrlSegmentGroup(segmentGroup.segments, children);
  }
}
function prefixedWith(segmentGroup, startIndex, commands) {
  let currentCommandIndex = 0;
  let currentPathIndex = startIndex;
  const noMatch = {
    match: false,
    pathIndex: 0,
    commandIndex: 0
  };
  while (currentPathIndex < segmentGroup.segments.length) {
    if (currentCommandIndex >= commands.length) return noMatch;
    const path = segmentGroup.segments[currentPathIndex];
    const command = commands[currentCommandIndex];
    // Do not try to consume command as part of the prefixing if it has outlets because it can
    // contain outlets other than the one being processed. Consuming the outlets command would
    // result in other outlets being ignored.
    if (isCommandWithOutlets(command)) {
      break;
    }
    const curr = `${command}`;
    const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
    if (currentPathIndex > 0 && curr === undefined) break;
    if (curr && next && typeof next === 'object' && next.outlets === undefined) {
      if (!compare(curr, next, path)) return noMatch;
      currentCommandIndex += 2;
    } else {
      if (!compare(curr, {}, path)) return noMatch;
      currentCommandIndex++;
    }
    currentPathIndex++;
  }
  return {
    match: true,
    pathIndex: currentPathIndex,
    commandIndex: currentCommandIndex
  };
}
function createNewSegmentGroup(segmentGroup, startIndex, commands) {
  const paths = segmentGroup.segments.slice(0, startIndex);
  let i = 0;
  while (i < commands.length) {
    const command = commands[i];
    if (isCommandWithOutlets(command)) {
      const children = createNewSegmentChildren(command.outlets);
      return new UrlSegmentGroup(paths, children);
    }
    // if we start with an object literal, we need to reuse the path part from the segment
    if (i === 0 && isMatrixParams(commands[0])) {
      const p = segmentGroup.segments[startIndex];
      paths.push(new UrlSegment(p.path, stringify(commands[0])));
      i++;
      continue;
    }
    const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`;
    const next = i < commands.length - 1 ? commands[i + 1] : null;
    if (curr && next && isMatrixParams(next)) {
      paths.push(new UrlSegment(curr, stringify(next)));
      i += 2;
    } else {
      paths.push(new UrlSegment(curr, {}));
      i++;
    }
  }
  return new UrlSegmentGroup(paths, {});
}
function createNewSegmentChildren(outlets) {
  const children = {};
  Object.entries(outlets).forEach(([outlet, commands]) => {
    if (typeof commands === 'string') {
      commands = [commands];
    }
    if (commands !== null) {
      children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
    }
  });
  return children;
}
function stringify(params) {
  const res = {};
  Object.entries(params).forEach(([k, v]) => res[k] = `${v}`);
  return res;
}
function compare(path, params, segment) {
  return path == segment.path && shallowEqual(params, segment.parameters);
}
const IMPERATIVE_NAVIGATION = 'imperative';
/**
 * Identifies the type of a router event.
 *
 * @publicApi
 */
var EventType = /*#__PURE__*/function (EventType) {
  EventType[EventType["NavigationStart"] = 0] = "NavigationStart";
  EventType[EventType["NavigationEnd"] = 1] = "NavigationEnd";
  EventType[EventType["NavigationCancel"] = 2] = "NavigationCancel";
  EventType[EventType["NavigationError"] = 3] = "NavigationError";
  EventType[EventType["RoutesRecognized"] = 4] = "RoutesRecognized";
  EventType[EventType["ResolveStart"] = 5] = "ResolveStart";
  EventType[EventType["ResolveEnd"] = 6] = "ResolveEnd";
  EventType[EventType["GuardsCheckStart"] = 7] = "GuardsCheckStart";
  EventType[EventType["GuardsCheckEnd"] = 8] = "GuardsCheckEnd";
  EventType[EventType["RouteConfigLoadStart"] = 9] = "RouteConfigLoadStart";
  EventType[EventType["RouteConfigLoadEnd"] = 10] = "RouteConfigLoadEnd";
  EventType[EventType["ChildActivationStart"] = 11] = "ChildActivationStart";
  EventType[EventType["ChildActivationEnd"] = 12] = "ChildActivationEnd";
  EventType[EventType["ActivationStart"] = 13] = "ActivationStart";
  EventType[EventType["ActivationEnd"] = 14] = "ActivationEnd";
  EventType[EventType["Scroll"] = 15] = "Scroll";
  EventType[EventType["NavigationSkipped"] = 16] = "NavigationSkipped";
  return EventType;
}(EventType || {});
/**
 * Base for events the router goes through, as opposed to events tied to a specific
 * route. Fired one time for any given navigation.
 *
 * The following code shows how a class subscribes to router events.
 *
 * ```ts
 * import {Event, RouterEvent, Router} from '@angular/router';
 *
 * class MyService {
 *   constructor(public router: Router) {
 *     router.events.pipe(
 *        filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent)
 *     ).subscribe((e: RouterEvent) => {
 *       // Do something
 *     });
 *   }
 * }
 * ```
 *
 * @see {@link Event}
 * @see [Router events summary](guide/routing/router-reference#router-events)
 * @publicApi
 */
class RouterEvent {
  id;
  url;
  constructor(/** A unique ID that the router assigns to every router navigation. */
  id, /** The URL that is the destination for this navigation. */
  url) {
    this.id = id;
    this.url = url;
  }
}
/**
 * An event triggered when a navigation starts.
 *
 * @publicApi
 */
class NavigationStart extends RouterEvent {
  type = /*#__PURE__*/(() => EventType.NavigationStart)();
  /**
   * Identifies the call or event that triggered the navigation.
   * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.
   *
   * @see {@link NavigationEnd}
   * @see {@link NavigationCancel}
   * @see {@link NavigationError}
   */
  navigationTrigger;
  /**
   * The navigation state that was previously supplied to the `pushState` call,
   * when the navigation is triggered by a `popstate` event. Otherwise null.
   *
   * The state object is defined by `NavigationExtras`, and contains any
   * developer-defined state value, as well as a unique ID that
   * the router assigns to every router transition/navigation.
   *
   * From the perspective of the router, the router never "goes back".
   * When the user clicks on the back button in the browser,
   * a new navigation ID is created.
   *
   * Use the ID in this previous-state object to differentiate between a newly created
   * state and one returned to by a `popstate` event, so that you can restore some
   * remembered state, such as scroll position.
   *
   */
  restoredState;
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  navigationTrigger = 'imperative', /** @docsNotRequired */
  restoredState = null) {
    super(id, url);
    this.navigationTrigger = navigationTrigger;
    this.restoredState = restoredState;
  }
  /** @docsNotRequired */
  toString() {
    return `NavigationStart(id: ${this.id}, url: '${this.url}')`;
  }
}
/**
 * An event triggered when a navigation ends successfully.
 *
 * @see {@link NavigationStart}
 * @see {@link NavigationCancel}
 * @see {@link NavigationError}
 *
 * @publicApi
 */
class NavigationEnd extends RouterEvent {
  urlAfterRedirects;
  type = /*#__PURE__*/(() => EventType.NavigationEnd)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
  }
  /** @docsNotRequired */
  toString() {
    return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
  }
}
/**
 * A code for the `NavigationCancel` event of the `Router` to indicate the
 * reason a navigation failed.
 *
 * @publicApi
 */
var NavigationCancellationCode = /*#__PURE__*/function (NavigationCancellationCode) {
  /**
   * A navigation failed because a guard returned a `UrlTree` to redirect.
   */
  NavigationCancellationCode[NavigationCancellationCode["Redirect"] = 0] = "Redirect";
  /**
   * A navigation failed because a more recent navigation started.
   */
  NavigationCancellationCode[NavigationCancellationCode["SupersededByNewNavigation"] = 1] = "SupersededByNewNavigation";
  /**
   * A navigation failed because one of the resolvers completed without emitting a value.
   */
  NavigationCancellationCode[NavigationCancellationCode["NoDataFromResolver"] = 2] = "NoDataFromResolver";
  /**
   * A navigation failed because a guard returned `false`.
   */
  NavigationCancellationCode[NavigationCancellationCode["GuardRejected"] = 3] = "GuardRejected";
  return NavigationCancellationCode;
}(NavigationCancellationCode || {});
/**
 * A code for the `NavigationSkipped` event of the `Router` to indicate the
 * reason a navigation was skipped.
 *
 * @publicApi
 */
var NavigationSkippedCode = /*#__PURE__*/function (NavigationSkippedCode) {
  /**
   * A navigation was skipped because the navigation URL was the same as the current Router URL.
   */
  NavigationSkippedCode[NavigationSkippedCode["IgnoredSameUrlNavigation"] = 0] = "IgnoredSameUrlNavigation";
  /**
   * A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both
   * the current Router URL and the target of the navigation.
   *
   * @see {@link UrlHandlingStrategy}
   */
  NavigationSkippedCode[NavigationSkippedCode["IgnoredByUrlHandlingStrategy"] = 1] = "IgnoredByUrlHandlingStrategy";
  return NavigationSkippedCode;
}(NavigationSkippedCode || {});
/**
 * An event triggered when a navigation is canceled, directly or indirectly.
 * This can happen for several reasons including when a route guard
 * returns `false` or initiates a redirect by returning a `UrlTree`.
 *
 * @see {@link NavigationStart}
 * @see {@link NavigationEnd}
 * @see {@link NavigationError}
 *
 * @publicApi
 */
class NavigationCancel extends RouterEvent {
  reason;
  code;
  type = /*#__PURE__*/(() => EventType.NavigationCancel)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url,
  /**
   * A description of why the navigation was cancelled. For debug purposes only. Use `code`
   * instead for a stable cancellation reason that can be used in production.
   */
  reason,
  /**
   * A code to indicate why the navigation was canceled. This cancellation code is stable for
   * the reason and can be relied on whereas the `reason` string could change and should not be
   * used in production.
   */
  code) {
    super(id, url);
    this.reason = reason;
    this.code = code;
  }
  /** @docsNotRequired */
  toString() {
    return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;
  }
}
/**
 * An event triggered when a navigation is skipped.
 * This can happen for a couple reasons including onSameUrlHandling
 * is set to `ignore` and the navigation URL is not different than the
 * current state.
 *
 * @publicApi
 */
class NavigationSkipped extends RouterEvent {
  reason;
  code;
  type = /*#__PURE__*/(() => EventType.NavigationSkipped)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url,
  /**
   * A description of why the navigation was skipped. For debug purposes only. Use `code`
   * instead for a stable skipped reason that can be used in production.
   */
  reason,
  /**
   * A code to indicate why the navigation was skipped. This code is stable for
   * the reason and can be relied on whereas the `reason` string could change and should not be
   * used in production.
   */
  code) {
    super(id, url);
    this.reason = reason;
    this.code = code;
  }
}
/**
 * An event triggered when a navigation fails due to an unexpected error.
 *
 * @see {@link NavigationStart}
 * @see {@link NavigationEnd}
 * @see {@link NavigationCancel}
 *
 * @publicApi
 */
class NavigationError extends RouterEvent {
  error;
  target;
  type = /*#__PURE__*/(() => EventType.NavigationError)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  error,
  /**
   * The target of the navigation when the error occurred.
   *
   * Note that this can be `undefined` because an error could have occurred before the
   * `RouterStateSnapshot` was created for the navigation.
   */
  target) {
    super(id, url);
    this.error = error;
    this.target = target;
  }
  /** @docsNotRequired */
  toString() {
    return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
  }
}
/**
 * An event triggered when routes are recognized.
 *
 * @publicApi
 */
class RoutesRecognized extends RouterEvent {
  urlAfterRedirects;
  state;
  type = /*#__PURE__*/(() => EventType.RoutesRecognized)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects, /** @docsNotRequired */
  state) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
    this.state = state;
  }
  /** @docsNotRequired */
  toString() {
    return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  }
}
/**
 * An event triggered at the start of the Guard phase of routing.
 *
 * @see {@link GuardsCheckEnd}
 *
 * @publicApi
 */
class GuardsCheckStart extends RouterEvent {
  urlAfterRedirects;
  state;
  type = /*#__PURE__*/(() => EventType.GuardsCheckStart)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects, /** @docsNotRequired */
  state) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
    this.state = state;
  }
  toString() {
    return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  }
}
/**
 * An event triggered at the end of the Guard phase of routing.
 *
 * @see {@link GuardsCheckStart}
 *
 * @publicApi
 */
class GuardsCheckEnd extends RouterEvent {
  urlAfterRedirects;
  state;
  shouldActivate;
  type = /*#__PURE__*/(() => EventType.GuardsCheckEnd)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects, /** @docsNotRequired */
  state, /** @docsNotRequired */
  shouldActivate) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
    this.state = state;
    this.shouldActivate = shouldActivate;
  }
  toString() {
    return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`;
  }
}
/**
 * An event triggered at the start of the Resolve phase of routing.
 *
 * Runs in the "resolve" phase whether or not there is anything to resolve.
 * In future, may change to only run when there are things to be resolved.
 *
 * @see {@link ResolveEnd}
 *
 * @publicApi
 */
class ResolveStart extends RouterEvent {
  urlAfterRedirects;
  state;
  type = /*#__PURE__*/(() => EventType.ResolveStart)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects, /** @docsNotRequired */
  state) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
    this.state = state;
  }
  toString() {
    return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  }
}
/**
 * An event triggered at the end of the Resolve phase of routing.
 * @see {@link ResolveStart}
 *
 * @publicApi
 */
class ResolveEnd extends RouterEvent {
  urlAfterRedirects;
  state;
  type = /*#__PURE__*/(() => EventType.ResolveEnd)();
  constructor(/** @docsNotRequired */
  id, /** @docsNotRequired */
  url, /** @docsNotRequired */
  urlAfterRedirects, /** @docsNotRequired */
  state) {
    super(id, url);
    this.urlAfterRedirects = urlAfterRedirects;
    this.state = state;
  }
  toString() {
    return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  }
}
/**
 * An event triggered before lazy loading a route configuration.
 *
 * @see {@link RouteConfigLoadEnd}
 *
 * @publicApi
 */
class RouteConfigLoadStart {
  route;
  type = /*#__PURE__*/(() => EventType.RouteConfigLoadStart)();
  constructor(/** @docsNotRequired */
  route) {
    this.route = route;
  }
  toString() {
    return `RouteConfigLoadStart(path: ${this.route.path})`;
  }
}
/**
 * An event triggered when a route has been lazy loaded.
 *
 * @see {@link RouteConfigLoadStart}
 *
 * @publicApi
 */
class RouteConfigLoadEnd {
  route;
  type = /*#__PURE__*/(() => EventType.RouteConfigLoadEnd)();
  constructor(/** @docsNotRequired */
  route) {
    this.route = route;
  }
  toString() {
    return `RouteConfigLoadEnd(path: ${this.route.path})`;
  }
}
/**
 * An event triggered at the start of the child-activation
 * part of the Resolve phase of routing.
 * @see {@link ChildActivationEnd}
 * @see {@link ResolveStart}
 *
 * @publicApi
 */
class ChildActivationStart {
  snapshot;
  type = /*#__PURE__*/(() => EventType.ChildActivationStart)();
  constructor(/** @docsNotRequired */
  snapshot) {
    this.snapshot = snapshot;
  }
  toString() {
    const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
    return `ChildActivationStart(path: '${path}')`;
  }
}
/**
 * An event triggered at the end of the child-activation part
 * of the Resolve phase of routing.
 * @see {@link ChildActivationStart}
 * @see {@link ResolveStart}
 * @publicApi
 */
class ChildActivationEnd {
  snapshot;
  type = /*#__PURE__*/(() => EventType.ChildActivationEnd)();
  constructor(/** @docsNotRequired */
  snapshot) {
    this.snapshot = snapshot;
  }
  toString() {
    const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
    return `ChildActivationEnd(path: '${path}')`;
  }
}
/**
 * An event triggered at the start of the activation part
 * of the Resolve phase of routing.
 * @see {@link ActivationEnd}
 * @see {@link ResolveStart}
 *
 * @publicApi
 */
class ActivationStart {
  snapshot;
  type = /*#__PURE__*/(() => EventType.ActivationStart)();
  constructor(/** @docsNotRequired */
  snapshot) {
    this.snapshot = snapshot;
  }
  toString() {
    const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
    return `ActivationStart(path: '${path}')`;
  }
}
/**
 * An event triggered at the end of the activation part
 * of the Resolve phase of routing.
 * @see {@link ActivationStart}
 * @see {@link ResolveStart}
 *
 * @publicApi
 */
class ActivationEnd {
  snapshot;
  type = /*#__PURE__*/(() => EventType.ActivationEnd)();
  constructor(/** @docsNotRequired */
  snapshot) {
    this.snapshot = snapshot;
  }
  toString() {
    const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
    return `ActivationEnd(path: '${path}')`;
  }
}
/**
 * An event triggered by scrolling.
 *
 * @publicApi
 */
class Scroll {
  routerEvent;
  position;
  anchor;
  type = /*#__PURE__*/(() => EventType.Scroll)();
  constructor(/** @docsNotRequired */
  routerEvent, /** @docsNotRequired */
  position, /** @docsNotRequired */
  anchor) {
    this.routerEvent = routerEvent;
    this.position = position;
    this.anchor = anchor;
  }
  toString() {
    const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null;
    return `Scroll(anchor: '${this.anchor}', position: '${pos}')`;
  }
}
class BeforeActivateRoutes {}
class RedirectRequest {
  url;
  navigationBehaviorOptions;
  constructor(url, navigationBehaviorOptions) {
    this.url = url;
    this.navigationBehaviorOptions = navigationBehaviorOptions;
  }
}
function stringifyEvent(routerEvent) {
  switch (routerEvent.type) {
    case EventType.ActivationEnd:
      return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
    case EventType.ActivationStart:
      return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
    case EventType.ChildActivationEnd:
      return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
    case EventType.ChildActivationStart:
      return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
    case EventType.GuardsCheckEnd:
      return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`;
    case EventType.GuardsCheckStart:
      return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
    case EventType.NavigationCancel:
      return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
    case EventType.NavigationSkipped:
      return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
    case EventType.NavigationEnd:
      return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`;
    case EventType.NavigationError:
      return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`;
    case EventType.NavigationStart:
      return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
    case EventType.ResolveEnd:
      return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
    case EventType.ResolveStart:
      return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
    case EventType.RouteConfigLoadEnd:
      return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`;
    case EventType.RouteConfigLoadStart:
      return `RouteConfigLoadStart(path: ${routerEvent.route.path})`;
    case EventType.RoutesRecognized:
      return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
    case EventType.Scroll:
      const pos = routerEvent.position ? `${routerEvent.position[0]}, ${routerEvent.position[1]}` : null;
      return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`;
  }
}

/**
 * Creates an `EnvironmentInjector` if the `Route` has providers and one does not already exist
 * and returns the injector. Otherwise, if the `Route` does not have `providers`, returns the
 * `currentInjector`.
 *
 * @param route The route that might have providers
 * @param currentInjector The parent injector of the `Route`
 */
function getOrCreateRouteInjectorIfNeeded(route, currentInjector) {
  if (route.providers && !route._injector) {
    route._injector = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.createEnvironmentInjector)(route.providers, currentInjector, `Route: ${route.path}`);
  }
  return route._injector ?? currentInjector;
}
function getLoadedRoutes$1(route) {
  return route._loadedRoutes;
}
function getLoadedInjector(route) {
  return route._loadedInjector;
}
function getLoadedComponent(route) {
  return route._loadedComponent;
}
function getProvidersInjector(route) {
  return route._injector;
}
function validateConfig(config, parentPath = '', requireStandaloneComponents = false) {
  // forEach doesn't iterate undefined values
  for (let i = 0; i < config.length; i++) {
    const route = config[i];
    const fullPath = getFullPath(parentPath, route);
    validateNode(route, fullPath, requireStandaloneComponents);
  }
}
function assertStandalone(fullPath, component) {
  if (component && (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisNgModule"])(component)) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. You are using 'loadComponent' with a module, ` + `but it must be used with standalone components. Use 'loadChildren' instead.`);
  } else if (component && !(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.isStandalone)(component)) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. The component must be standalone.`);
  }
}
function validateNode(route, fullPath, requireStandaloneComponents) {
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    if (!route) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `
      Invalid configuration of route '${fullPath}': Encountered undefined route.
      The reason might be an extra comma.

      Example:
      const routes: Routes = [
        { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
        { path: 'dashboard',  component: DashboardComponent },, << two commas
        { path: 'detail/:id', component: HeroDetailComponent }
      ];
    `);
    }
    if (Array.isArray(route)) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': Array cannot be specified`);
    }
    if (!route.redirectTo && !route.component && !route.loadComponent && !route.children && !route.loadChildren && route.outlet && route.outlet !== PRIMARY_OUTLET) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`);
    }
    if (route.redirectTo && route.children) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`);
    }
    if (route.redirectTo && route.loadChildren) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`);
    }
    if (route.children && route.loadChildren) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`);
    }
    if (route.redirectTo && (route.component || route.loadComponent)) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and component/loadComponent cannot be used together`);
    }
    if (route.component && route.loadComponent) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': component and loadComponent cannot be used together`);
    }
    if (route.redirectTo && route.canActivate) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and canActivate cannot be used together. Redirects happen before activation ` + `so canActivate will never be executed.`);
    }
    if (route.path && route.matcher) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path and matcher cannot be used together`);
    }
    if (route.redirectTo === void 0 && !route.component && !route.loadComponent && !route.children && !route.loadChildren) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`);
    }
    if (route.path === void 0 && route.matcher === void 0) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`);
    }
    if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path cannot start with a slash`);
    }
    if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
      const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`;
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '{path: "${fullPath}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`);
    }
    if (requireStandaloneComponents) {
      assertStandalone(fullPath, route.component);
    }
  }
  if (route.children) {
    validateConfig(route.children, fullPath, requireStandaloneComponents);
  }
}
function getFullPath(parentPath, currentRoute) {
  if (!currentRoute) {
    return parentPath;
  }
  if (!parentPath && !currentRoute.path) {
    return '';
  } else if (parentPath && !currentRoute.path) {
    return `${parentPath}/`;
  } else if (!parentPath && currentRoute.path) {
    return currentRoute.path;
  } else {
    return `${parentPath}/${currentRoute.path}`;
  }
}
/** Returns the `route.outlet` or PRIMARY_OUTLET if none exists. */
function getOutlet(route) {
  return route.outlet || PRIMARY_OUTLET;
}
/**
 * Sorts the `routes` such that the ones with an outlet matching `outletName` come first.
 * The order of the configs is otherwise preserved.
 */
function sortByMatchingOutlets(routes, outletName) {
  const sortedConfig = routes.filter(r => getOutlet(r) === outletName);
  sortedConfig.push(...routes.filter(r => getOutlet(r) !== outletName));
  return sortedConfig;
}
/**
 * Gets the first injector in the snapshot's parent tree.
 *
 * If the `Route` has a static list of providers, the returned injector will be the one created from
 * those. If it does not exist, the returned injector may come from the parents, which may be from a
 * loaded config or their static providers.
 *
 * Returns `null` if there is neither this nor any parents have a stored injector.
 *
 * Generally used for retrieving the injector to use for getting tokens for guards/resolvers and
 * also used for getting the correct injector to use for creating components.
 */
function getClosestRouteInjector(snapshot) {
  if (!snapshot) return null;
  // If the current route has its own injector, which is created from the static providers on the
  // route itself, we should use that. Otherwise, we start at the parent since we do not want to
  // include the lazy loaded injector from this route.
  if (snapshot.routeConfig?._injector) {
    return snapshot.routeConfig._injector;
  }
  for (let s = snapshot.parent; s; s = s.parent) {
    const route = s.routeConfig;
    // Note that the order here is important. `_loadedInjector` stored on the route with
    // `loadChildren: () => NgModule` so it applies to child routes with priority. The `_injector`
    // is created from the static providers on that parent route, so it applies to the children as
    // well, but only if there is no lazy loaded NgModuleRef injector.
    if (route?._loadedInjector) return route._loadedInjector;
    if (route?._injector) return route._injector;
  }
  return null;
}

/**
 * Store contextual information about a `RouterOutlet`
 *
 * @publicApi
 */
class OutletContext {
  rootInjector;
  outlet = null;
  route = null;
  children;
  attachRef = null;
  get injector() {
    return getClosestRouteInjector(this.route?.snapshot) ?? this.rootInjector;
  }
  constructor(rootInjector) {
    this.rootInjector = rootInjector;
    this.children = new ChildrenOutletContexts(this.rootInjector);
  }
}
/**
 * Store contextual information about the children (= nested) `RouterOutlet`
 *
 * @publicApi
 */
let ChildrenOutletContexts = /*#__PURE__*/(() => {
  class ChildrenOutletContexts {
    rootInjector;
    // contexts for child outlets, by name.
    contexts = (() => new Map())();
    /** @nodoc */
    constructor(rootInjector) {
      this.rootInjector = rootInjector;
    }
    /** Called when a `RouterOutlet` directive is instantiated */
    onChildOutletCreated(childName, outlet) {
      const context = this.getOrCreateContext(childName);
      context.outlet = outlet;
      this.contexts.set(childName, context);
    }
    /**
     * Called when a `RouterOutlet` directive is destroyed.
     * We need to keep the context as the outlet could be destroyed inside a NgIf and might be
     * re-created later.
     */
    onChildOutletDestroyed(childName) {
      const context = this.getContext(childName);
      if (context) {
        context.outlet = null;
        context.attachRef = null;
      }
    }
    /**
     * Called when the corresponding route is deactivated during navigation.
     * Because the component get destroyed, all children outlet are destroyed.
     */
    onOutletDeactivated() {
      const contexts = this.contexts;
      this.contexts = new Map();
      return contexts;
    }
    onOutletReAttached(contexts) {
      this.contexts = contexts;
    }
    getOrCreateContext(childName) {
      let context = this.getContext(childName);
      if (!context) {
        context = new OutletContext(this.rootInjector);
        this.contexts.set(childName, context);
      }
      return context;
    }
    getContext(childName) {
      return this.contexts.get(childName) || null;
    }
    static ɵfac = (() => function ChildrenOutletContexts_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ChildrenOutletContexts)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.EnvironmentInjector));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: ChildrenOutletContexts,
      factory: ChildrenOutletContexts.ɵfac,
      providedIn: 'root'
    }))();
  }
  return ChildrenOutletContexts;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
class Tree {
  /** @internal */
  _root;
  constructor(root) {
    this._root = root;
  }
  get root() {
    return this._root.value;
  }
  /**
   * @internal
   */
  parent(t) {
    const p = this.pathFromRoot(t);
    return p.length > 1 ? p[p.length - 2] : null;
  }
  /**
   * @internal
   */
  children(t) {
    const n = findNode(t, this._root);
    return n ? n.children.map(t => t.value) : [];
  }
  /**
   * @internal
   */
  firstChild(t) {
    const n = findNode(t, this._root);
    return n && n.children.length > 0 ? n.children[0].value : null;
  }
  /**
   * @internal
   */
  siblings(t) {
    const p = findPath(t, this._root);
    if (p.length < 2) return [];
    const c = p[p.length - 2].children.map(c => c.value);
    return c.filter(cc => cc !== t);
  }
  /**
   * @internal
   */
  pathFromRoot(t) {
    return findPath(t, this._root).map(s => s.value);
  }
}
// DFS for the node matching the value
function findNode(value, node) {
  if (value === node.value) return node;
  for (const child of node.children) {
    const node = findNode(value, child);
    if (node) return node;
  }
  return null;
}
// Return the path to the node with the given value using DFS
function findPath(value, node) {
  if (value === node.value) return [node];
  for (const child of node.children) {
    const path = findPath(value, child);
    if (path.length) {
      path.unshift(node);
      return path;
    }
  }
  return [];
}
class TreeNode {
  value;
  children;
  constructor(value, children) {
    this.value = value;
    this.children = children;
  }
  toString() {
    return `TreeNode(${this.value})`;
  }
}
// Return the list of T indexed by outlet name
function nodeChildrenAsMap(node) {
  const map = {};
  if (node) {
    node.children.forEach(child => map[child.value.outlet] = child);
  }
  return map;
}

/**
 * Represents the state of the router as a tree of activated routes.
 *
 * @usageNotes
 *
 * Every node in the route tree is an `ActivatedRoute` instance
 * that knows about the "consumed" URL segments, the extracted parameters,
 * and the resolved data.
 * Use the `ActivatedRoute` properties to traverse the tree from any node.
 *
 * The following fragment shows how a component gets the root node
 * of the current state to establish its own route tree:
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const state: RouterState = router.routerState;
 *     const root: ActivatedRoute = state.root;
 *     const child = root.firstChild;
 *     const id: Observable<string> = child.params.map(p => p.id);
 *     //...
 *   }
 * }
 * ```
 *
 * @see {@link ActivatedRoute}
 * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)
 *
 * @publicApi
 */
class RouterState extends Tree {
  snapshot;
  /** @internal */
  constructor(root, /** The current snapshot of the router state */
  snapshot) {
    super(root);
    this.snapshot = snapshot;
    setRouterState(this, root);
  }
  toString() {
    return this.snapshot.toString();
  }
}
function createEmptyState(rootComponent) {
  const snapshot = createEmptyStateSnapshot(rootComponent);
  const emptyUrl = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject([new UrlSegment('', {})]);
  const emptyParams = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject({});
  const emptyData = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject({});
  const emptyQueryParams = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject({});
  const fragment = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject('');
  const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
  activated.snapshot = snapshot.root;
  return new RouterState(new TreeNode(activated, []), snapshot);
}
function createEmptyStateSnapshot(rootComponent) {
  const emptyParams = {};
  const emptyData = {};
  const emptyQueryParams = {};
  const fragment = '';
  const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, {});
  return new RouterStateSnapshot('', new TreeNode(activated, []));
}
/**
 * Provides access to information about a route associated with a component
 * that is loaded in an outlet.
 * Use to traverse the `RouterState` tree and extract information from nodes.
 *
 * The following example shows how to construct a component using information from a
 * currently activated route.
 *
 * Note: the observables in this class only emit when the current and previous values differ based
 * on shallow equality. For example, changing deeply nested properties in resolved `data` will not
 * cause the `ActivatedRoute.data` `Observable` to emit a new value.
 *
 * {@example router/activated-route/module.ts region="activated-route"
 *     header="activated-route.component.ts"}
 *
 * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)
 *
 * @publicApi
 */
class ActivatedRoute {
  urlSubject;
  paramsSubject;
  queryParamsSubject;
  fragmentSubject;
  dataSubject;
  outlet;
  component;
  /** The current snapshot of this route */
  snapshot;
  /** @internal */
  _futureSnapshot;
  /** @internal */
  _routerState;
  /** @internal */
  _paramMap;
  /** @internal */
  _queryParamMap;
  /** An Observable of the resolved route title */
  title;
  /** An observable of the URL segments matched by this route. */
  url;
  /** An observable of the matrix parameters scoped to this route. */
  params;
  /** An observable of the query parameters shared by all the routes. */
  queryParams;
  /** An observable of the URL fragment shared by all the routes. */
  fragment;
  /** An observable of the static and resolved data of this route. */
  data;
  /** @internal */
  constructor(/** @internal */
  urlSubject, /** @internal */
  paramsSubject, /** @internal */
  queryParamsSubject, /** @internal */
  fragmentSubject, /** @internal */
  dataSubject, /** The outlet name of the route, a constant. */
  outlet, /** The component of the route, a constant. */
  component, futureSnapshot) {
    this.urlSubject = urlSubject;
    this.paramsSubject = paramsSubject;
    this.queryParamsSubject = queryParamsSubject;
    this.fragmentSubject = fragmentSubject;
    this.dataSubject = dataSubject;
    this.outlet = outlet;
    this.component = component;
    this._futureSnapshot = futureSnapshot;
    this.title = this.dataSubject?.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(d => d[RouteTitleKey])) ?? (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(undefined);
    // TODO(atscott): Verify that these can be changed to `.asObservable()` with TGP.
    this.url = urlSubject;
    this.params = paramsSubject;
    this.queryParams = queryParamsSubject;
    this.fragment = fragmentSubject;
    this.data = dataSubject;
  }
  /** The configuration used to match this route. */
  get routeConfig() {
    return this._futureSnapshot.routeConfig;
  }
  /** The root of the router state. */
  get root() {
    return this._routerState.root;
  }
  /** The parent of this route in the router state tree. */
  get parent() {
    return this._routerState.parent(this);
  }
  /** The first child of this route in the router state tree. */
  get firstChild() {
    return this._routerState.firstChild(this);
  }
  /** The children of this route in the router state tree. */
  get children() {
    return this._routerState.children(this);
  }
  /** The path from the root of the router state tree to this route. */
  get pathFromRoot() {
    return this._routerState.pathFromRoot(this);
  }
  /**
   * An Observable that contains a map of the required and optional parameters
   * specific to the route.
   * The map supports retrieving single and multiple values from the same parameter.
   */
  get paramMap() {
    this._paramMap ??= this.params.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(p => convertToParamMap(p)));
    return this._paramMap;
  }
  /**
   * An Observable that contains a map of the query parameters available to all routes.
   * The map supports retrieving single and multiple values from the query parameter.
   */
  get queryParamMap() {
    this._queryParamMap ??= this.queryParams.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(p => convertToParamMap(p)));
    return this._queryParamMap;
  }
  toString() {
    return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;
  }
}
/**
 * Returns the inherited params, data, and resolve for a given route.
 *
 * By default, we do not inherit parent data unless the current route is path-less or the parent
 * route is component-less.
 */
function getInherited(route, parent, paramsInheritanceStrategy = 'emptyOnly') {
  let inherited;
  const {
    routeConfig
  } = route;
  if (parent !== null && (paramsInheritanceStrategy === 'always' ||
  // inherit parent data if route is empty path
  routeConfig?.path === '' ||
  // inherit parent data if parent was componentless
  !parent.component && !parent.routeConfig?.loadComponent)) {
    inherited = {
      params: {
        ...parent.params,
        ...route.params
      },
      data: {
        ...parent.data,
        ...route.data
      },
      resolve: {
        // Snapshots are created with data inherited from parent and guards (i.e. canActivate) can
        // change data because it's not frozen...
        // This first line could be deleted chose to break/disallow mutating the `data` object in
        // guards.
        // Note that data from parents still override this mutated data so anyone relying on this
        // might be surprised that it doesn't work if parent data is inherited but otherwise does.
        ...route.data,
        // Ensure inherited resolved data overrides inherited static data
        ...parent.data,
        // static data from the current route overrides any inherited data
        ...routeConfig?.data,
        // resolved data from current route overrides everything
        ...route._resolvedData
      }
    };
  } else {
    inherited = {
      params: {
        ...route.params
      },
      data: {
        ...route.data
      },
      resolve: {
        ...route.data,
        ...(route._resolvedData ?? {})
      }
    };
  }
  if (routeConfig && hasStaticTitle(routeConfig)) {
    inherited.resolve[RouteTitleKey] = routeConfig.title;
  }
  return inherited;
}
/**
 * @description
 *
 * Contains the information about a route associated with a component loaded in an
 * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
 * traverse the router state tree.
 *
 * The following example initializes a component with route information extracted
 * from the snapshot of the root node at the time of creation.
 *
 * ```
 * @Component({templateUrl:'./my-component.html'})
 * class MyComponent {
 *   constructor(route: ActivatedRoute) {
 *     const id: string = route.snapshot.params.id;
 *     const url: string = route.snapshot.url.join('');
 *     const user = route.snapshot.data.user;
 *   }
 * }
 * ```
 *
 * @publicApi
 */
class ActivatedRouteSnapshot {
  url;
  params;
  queryParams;
  fragment;
  data;
  outlet;
  component;
  /** The configuration used to match this route **/
  routeConfig;
  /** @internal */
  _resolve;
  /** @internal */
  _resolvedData;
  /** @internal */
  _routerState;
  /** @internal */
  _paramMap;
  /** @internal */
  _queryParamMap;
  /** The resolved route title */
  get title() {
    // Note: This _must_ be a getter because the data is mutated in the resolvers. Title will not be
    // available at the time of class instantiation.
    return this.data?.[RouteTitleKey];
  }
  /** @internal */
  constructor(/** The URL segments matched by this route */
  url,
  /**
   *  The matrix parameters scoped to this route.
   *
   *  You can compute all params (or data) in the router state or to get params outside
   *  of an activated component by traversing the `RouterState` tree as in the following
   *  example:
   *  ```
   *  collectRouteParams(router: Router) {
   *    let params = {};
   *    let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root];
   *    while (stack.length > 0) {
   *      const route = stack.pop()!;
   *      params = {...params, ...route.params};
   *      stack.push(...route.children);
   *    }
   *    return params;
   *  }
   *  ```
   */
  params, /** The query parameters shared by all the routes */
  queryParams, /** The URL fragment shared by all the routes */
  fragment, /** The static and resolved data of this route */
  data, /** The outlet name of the route */
  outlet, /** The component of the route */
  component, routeConfig, resolve) {
    this.url = url;
    this.params = params;
    this.queryParams = queryParams;
    this.fragment = fragment;
    this.data = data;
    this.outlet = outlet;
    this.component = component;
    this.routeConfig = routeConfig;
    this._resolve = resolve;
  }
  /** The root of the router state */
  get root() {
    return this._routerState.root;
  }
  /** The parent of this route in the router state tree */
  get parent() {
    return this._routerState.parent(this);
  }
  /** The first child of this route in the router state tree */
  get firstChild() {
    return this._routerState.firstChild(this);
  }
  /** The children of this route in the router state tree */
  get children() {
    return this._routerState.children(this);
  }
  /** The path from the root of the router state tree to this route */
  get pathFromRoot() {
    return this._routerState.pathFromRoot(this);
  }
  get paramMap() {
    this._paramMap ??= convertToParamMap(this.params);
    return this._paramMap;
  }
  get queryParamMap() {
    this._queryParamMap ??= convertToParamMap(this.queryParams);
    return this._queryParamMap;
  }
  toString() {
    const url = this.url.map(segment => segment.toString()).join('/');
    const matched = this.routeConfig ? this.routeConfig.path : '';
    return `Route(url:'${url}', path:'${matched}')`;
  }
}
/**
 * @description
 *
 * Represents the state of the router at a moment in time.
 *
 * This is a tree of activated route snapshots. Every node in this tree knows about
 * the "consumed" URL segments, the extracted parameters, and the resolved data.
 *
 * The following example shows how a component is initialized with information
 * from the snapshot of the root node's state at the time of creation.
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const state: RouterState = router.routerState;
 *     const snapshot: RouterStateSnapshot = state.snapshot;
 *     const root: ActivatedRouteSnapshot = snapshot.root;
 *     const child = root.firstChild;
 *     const id: Observable<string> = child.params.map(p => p.id);
 *     //...
 *   }
 * }
 * ```
 *
 * @publicApi
 */
class RouterStateSnapshot extends Tree {
  url;
  /** @internal */
  constructor(/** The url from which this snapshot was created */
  url, root) {
    super(root);
    this.url = url;
    setRouterState(this, root);
  }
  toString() {
    return serializeNode(this._root);
  }
}
function setRouterState(state, node) {
  node.value._routerState = state;
  node.children.forEach(c => setRouterState(state, c));
}
function serializeNode(node) {
  const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : '';
  return `${node.value}${c}`;
}
/**
 * The expectation is that the activate route is created with the right set of parameters.
 * So we push new values into the observables only when they are not the initial values.
 * And we detect that by checking if the snapshot field is set.
 */
function advanceActivatedRoute(route) {
  if (route.snapshot) {
    const currentSnapshot = route.snapshot;
    const nextSnapshot = route._futureSnapshot;
    route.snapshot = nextSnapshot;
    if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
      route.queryParamsSubject.next(nextSnapshot.queryParams);
    }
    if (currentSnapshot.fragment !== nextSnapshot.fragment) {
      route.fragmentSubject.next(nextSnapshot.fragment);
    }
    if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
      route.paramsSubject.next(nextSnapshot.params);
    }
    if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
      route.urlSubject.next(nextSnapshot.url);
    }
    if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
      route.dataSubject.next(nextSnapshot.data);
    }
  } else {
    route.snapshot = route._futureSnapshot;
    // this is for resolved data
    route.dataSubject.next(route._futureSnapshot.data);
  }
}
function equalParamsAndUrlSegments(a, b) {
  const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
  const parentsMismatch = !a.parent !== !b.parent;
  return equalUrlParams && !parentsMismatch && (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent));
}
function hasStaticTitle(config) {
  return typeof config.title === 'string' || config.title === null;
}

/**
 * An `InjectionToken` provided by the `RouterOutlet` and can be set using the `routerOutletData`
 * input.
 *
 * When unset, this value is `null` by default.
 *
 * @usageNotes
 *
 * To set the data from the template of the component with `router-outlet`:
 * ```
 * <router-outlet [routerOutletData]="{name: 'Angular'}" />
 * ```
 *
 * To read the data in the routed component:
 * ```
 * data = inject(ROUTER_OUTLET_DATA) as Signal<{name: string}>;
 * ```
 *
 * @publicApi
 */
const ROUTER_OUTLET_DATA = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'RouterOutlet data' : '');
/**
 * @description
 *
 * Acts as a placeholder that Angular dynamically fills based on the current router state.
 *
 * Each outlet can have a unique name, determined by the optional `name` attribute.
 * The name cannot be set or changed dynamically. If not set, default value is "primary".
 *
 * ```
 * <router-outlet></router-outlet>
 * <router-outlet name='left'></router-outlet>
 * <router-outlet name='right'></router-outlet>
 * ```
 *
 * Named outlets can be the targets of secondary routes.
 * The `Route` object for a secondary route has an `outlet` property to identify the target outlet:
 *
 * `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}`
 *
 * Using named outlets and secondary routes, you can target multiple outlets in
 * the same `RouterLink` directive.
 *
 * The router keeps track of separate branches in a navigation tree for each named outlet and
 * generates a representation of that tree in the URL.
 * The URL for a secondary route uses the following syntax to specify both the primary and secondary
 * routes at the same time:
 *
 * `http://base-path/primary-route-path(outlet-name:route-path)`
 *
 * A router outlet emits an activate event when a new component is instantiated,
 * deactivate event when a component is destroyed.
 * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the
 * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to
 * detach the subtree.
 *
 * ```
 * <router-outlet
 *   (activate)='onActivate($event)'
 *   (deactivate)='onDeactivate($event)'
 *   (attach)='onAttach($event)'
 *   (detach)='onDetach($event)'></router-outlet>
 * ```
 *
 * @see {@link RouterLink}
 * @see {@link Route}
 * @ngModule RouterModule
 *
 * @publicApi
 */
let RouterOutlet = /*#__PURE__*/(() => {
  class RouterOutlet {
    activated = null;
    /** @internal */
    get activatedComponentRef() {
      return this.activated;
    }
    _activatedRoute = null;
    /**
     * The name of the outlet
     *
     */
    name = (() => PRIMARY_OUTLET)();
    activateEvents = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_1__.EventEmitter())();
    deactivateEvents = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_1__.EventEmitter())();
    /**
     * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a
     * previously detached subtree.
     **/
    attachEvents = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_1__.EventEmitter())();
    /**
     * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the
     * subtree.
     */
    detachEvents = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_1__.EventEmitter())();
    /**
     * Data that will be provided to the child injector through the `ROUTER_OUTLET_DATA` token.
     *
     * When unset, the value of the token is `undefined` by default.
     */
    routerOutletData = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.input)(undefined))();
    parentContexts = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ChildrenOutletContexts))();
    location = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ViewContainerRef))();
    changeDetector = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ChangeDetectorRef))();
    inputBinder = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(INPUT_BINDER, {
      optional: true
    }))();
    /** @nodoc */
    supportsBindingToComponentInputs = true;
    /** @nodoc */
    ngOnChanges(changes) {
      if (changes['name']) {
        const {
          firstChange,
          previousValue
        } = changes['name'];
        if (firstChange) {
          // The first change is handled by ngOnInit. Because ngOnChanges doesn't get called when no
          // input is set at all, we need to centrally handle the first change there.
          return;
        }
        // unregister with the old name
        if (this.isTrackedInParentContexts(previousValue)) {
          this.deactivate();
          this.parentContexts.onChildOutletDestroyed(previousValue);
        }
        // register the new name
        this.initializeOutletWithName();
      }
    }
    /** @nodoc */
    ngOnDestroy() {
      // Ensure that the registered outlet is this one before removing it on the context.
      if (this.isTrackedInParentContexts(this.name)) {
        this.parentContexts.onChildOutletDestroyed(this.name);
      }
      this.inputBinder?.unsubscribeFromRouteData(this);
    }
    isTrackedInParentContexts(outletName) {
      return this.parentContexts.getContext(outletName)?.outlet === this;
    }
    /** @nodoc */
    ngOnInit() {
      this.initializeOutletWithName();
    }
    initializeOutletWithName() {
      this.parentContexts.onChildOutletCreated(this.name, this);
      if (this.activated) {
        return;
      }
      // If the outlet was not instantiated at the time the route got activated we need to populate
      // the outlet when it is initialized (ie inside a NgIf)
      const context = this.parentContexts.getContext(this.name);
      if (context?.route) {
        if (context.attachRef) {
          // `attachRef` is populated when there is an existing component to mount
          this.attach(context.attachRef, context.route);
        } else {
          // otherwise the component defined in the configuration is created
          this.activateWith(context.route, context.injector);
        }
      }
    }
    get isActivated() {
      return !!this.activated;
    }
    /**
     * @returns The currently activated component instance.
     * @throws An error if the outlet is not activated.
     */
    get component() {
      if (!this.activated) throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
      return this.activated.instance;
    }
    get activatedRoute() {
      if (!this.activated) throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
      return this._activatedRoute;
    }
    get activatedRouteData() {
      if (this._activatedRoute) {
        return this._activatedRoute.snapshot.data;
      }
      return {};
    }
    /**
     * Called when the `RouteReuseStrategy` instructs to detach the subtree
     */
    detach() {
      if (!this.activated) throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
      this.location.detach();
      const cmp = this.activated;
      this.activated = null;
      this._activatedRoute = null;
      this.detachEvents.emit(cmp.instance);
      return cmp;
    }
    /**
     * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
     */
    attach(ref, activatedRoute) {
      this.activated = ref;
      this._activatedRoute = activatedRoute;
      this.location.insert(ref.hostView);
      this.inputBinder?.bindActivatedRouteToOutletComponent(this);
      this.attachEvents.emit(ref.instance);
    }
    deactivate() {
      if (this.activated) {
        const c = this.component;
        this.activated.destroy();
        this.activated = null;
        this._activatedRoute = null;
        this.deactivateEvents.emit(c);
      }
    }
    activateWith(activatedRoute, environmentInjector) {
      if (this.isActivated) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4013 /* RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Cannot activate an already activated outlet');
      }
      this._activatedRoute = activatedRoute;
      const location = this.location;
      const snapshot = activatedRoute.snapshot;
      const component = snapshot.component;
      const childContexts = this.parentContexts.getOrCreateContext(this.name).children;
      const injector = new OutletInjector(activatedRoute, childContexts, location.injector, this.routerOutletData);
      this.activated = location.createComponent(component, {
        index: location.length,
        injector,
        environmentInjector: environmentInjector
      });
      // Calling `markForCheck` to make sure we will run the change detection when the
      // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
      this.changeDetector.markForCheck();
      this.inputBinder?.bindActivatedRouteToOutletComponent(this);
      this.activateEvents.emit(this.activated.instance);
    }
    static ɵfac = (() => function RouterOutlet_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterOutlet)();
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: RouterOutlet,
      selectors: [["router-outlet"]],
      inputs: {
        name: "name",
        routerOutletData: [1, "routerOutletData"]
      },
      outputs: {
        activateEvents: "activate",
        deactivateEvents: "deactivate",
        attachEvents: "attach",
        detachEvents: "detach"
      },
      exportAs: ["outlet"],
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return RouterOutlet;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
class OutletInjector {
  route;
  childContexts;
  parent;
  outletData;
  /**
   * This injector has a special handing for the `ActivatedRoute` and
   * `ChildrenOutletContexts` tokens: it returns corresponding values for those
   * tokens dynamically. This behavior is different from the regular injector logic,
   * when we initialize and store a value, which is later returned for all inject
   * requests.
   *
   * In some cases (e.g. when using `@defer`), this dynamic behavior requires special
   * handling. This function allows to identify an instance of the `OutletInjector` and
   * create an instance of it without referring to the class itself (so this logic can
   * be invoked from the `core` package). This helps to retain dynamic behavior for the
   * mentioned tokens.
   *
   * Note: it's a temporary solution and we should explore how to support this case better.
   */
  __ngOutletInjector(parentInjector) {
    return new OutletInjector(this.route, this.childContexts, parentInjector, this.outletData);
  }
  constructor(route, childContexts, parent, outletData) {
    this.route = route;
    this.childContexts = childContexts;
    this.parent = parent;
    this.outletData = outletData;
  }
  get(token, notFoundValue) {
    if (token === ActivatedRoute) {
      return this.route;
    }
    if (token === ChildrenOutletContexts) {
      return this.childContexts;
    }
    if (token === ROUTER_OUTLET_DATA) {
      return this.outletData;
    }
    return this.parent.get(token, notFoundValue);
  }
}
const INPUT_BINDER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('');
/**
 * Injectable used as a tree-shakable provider for opting in to binding router data to component
 * inputs.
 *
 * The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or
 * activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params,
 * queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`.
 * Importantly, when an input does not have an item in the route data with a matching key, this
 * input is set to `undefined`. If it were not done this way, the previous information would be
 * retained if the data got removed from the route (i.e. if a query parameter is removed).
 *
 * The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that
 * the subscriptions are cleaned up.
 */
let RoutedComponentInputBinder = /*#__PURE__*/(() => {
  class RoutedComponentInputBinder {
    outletDataSubscriptions = (() => new Map())();
    bindActivatedRouteToOutletComponent(outlet) {
      this.unsubscribeFromRouteData(outlet);
      this.subscribeToRouteData(outlet);
    }
    unsubscribeFromRouteData(outlet) {
      this.outletDataSubscriptions.get(outlet)?.unsubscribe();
      this.outletDataSubscriptions.delete(outlet);
    }
    subscribeToRouteData(outlet) {
      const {
        activatedRoute
      } = outlet;
      const dataSubscription = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.combineLatest)([activatedRoute.queryParams, activatedRoute.params, activatedRoute.data]).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(([queryParams, params, data], index) => {
        data = {
          ...queryParams,
          ...params,
          ...data
        };
        // Get the first result from the data subscription synchronously so it's available to
        // the component as soon as possible (and doesn't require a second change detection).
        if (index === 0) {
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(data);
        }
        // Promise.resolve is used to avoid synchronously writing the wrong data when
        // two of the Observables in the `combineLatest` stream emit one after
        // another.
        return Promise.resolve(data);
      })).subscribe(data => {
        // Outlet may have been deactivated or changed names to be associated with a different
        // route
        if (!outlet.isActivated || !outlet.activatedComponentRef || outlet.activatedRoute !== activatedRoute || activatedRoute.component === null) {
          this.unsubscribeFromRouteData(outlet);
          return;
        }
        const mirror = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.reflectComponentType)(activatedRoute.component);
        if (!mirror) {
          this.unsubscribeFromRouteData(outlet);
          return;
        }
        for (const {
          templateName
        } of mirror.inputs) {
          outlet.activatedComponentRef.setInput(templateName, data[templateName]);
        }
      });
      this.outletDataSubscriptions.set(outlet, dataSubscription);
    }
    static ɵfac = (() => function RoutedComponentInputBinder_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RoutedComponentInputBinder)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: RoutedComponentInputBinder,
      factory: RoutedComponentInputBinder.ɵfac
    }))();
  }
  return RoutedComponentInputBinder;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function createRouterState(routeReuseStrategy, curr, prevState) {
  const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
  return new RouterState(root, curr);
}
function createNode(routeReuseStrategy, curr, prevState) {
  // reuse an activated route that is currently displayed on the screen
  if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
    const value = prevState.value;
    value._futureSnapshot = curr.value;
    const children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
    return new TreeNode(value, children);
  } else {
    if (routeReuseStrategy.shouldAttach(curr.value)) {
      // retrieve an activated route that is used to be displayed, but is not currently displayed
      const detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);
      if (detachedRouteHandle !== null) {
        const tree = detachedRouteHandle.route;
        tree.value._futureSnapshot = curr.value;
        tree.children = curr.children.map(c => createNode(routeReuseStrategy, c));
        return tree;
      }
    }
    const value = createActivatedRoute(curr.value);
    const children = curr.children.map(c => createNode(routeReuseStrategy, c));
    return new TreeNode(value, children);
  }
}
function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
  return curr.children.map(child => {
    for (const p of prevState.children) {
      if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) {
        return createNode(routeReuseStrategy, child, p);
      }
    }
    return createNode(routeReuseStrategy, child);
  });
}
function createActivatedRoute(c) {
  return new ActivatedRoute(new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject(c.url), new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject(c.params), new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject(c.queryParams), new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject(c.fragment), new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject(c.data), c.outlet, c.component, c);
}

/**
 * Can be returned by a `Router` guard to instruct the `Router` to redirect rather than continue
 * processing the path of the in-flight navigation. The `redirectTo` indicates _where_ the new
 * navigation should go to and the optional `navigationBehaviorOptions` can provide more information
 * about _how_ to perform the navigation.
 *
 * ```ts
 * const route: Route = {
 *   path: "user/:userId",
 *   component: User,
 *   canActivate: [
 *     () => {
 *       const router = inject(Router);
 *       const authService = inject(AuthenticationService);
 *
 *       if (!authService.isLoggedIn()) {
 *         const loginPath = router.parseUrl("/login");
 *         return new RedirectCommand(loginPath, {
 *           skipLocationChange: "true",
 *         });
 *       }
 *
 *       return true;
 *     },
 *   ],
 * };
 * ```
 * @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access)
 *
 * @publicApi
 */
class RedirectCommand {
  redirectTo;
  navigationBehaviorOptions;
  constructor(redirectTo, navigationBehaviorOptions) {
    this.redirectTo = redirectTo;
    this.navigationBehaviorOptions = navigationBehaviorOptions;
  }
}
const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
function redirectingNavigationError(urlSerializer, redirect) {
  const {
    redirectTo,
    navigationBehaviorOptions
  } = isUrlTree(redirect) ? {
    redirectTo: redirect,
    navigationBehaviorOptions: undefined
  } : redirect;
  const error = navigationCancelingError(ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`, NavigationCancellationCode.Redirect);
  error.url = redirectTo;
  error.navigationBehaviorOptions = navigationBehaviorOptions;
  return error;
}
function navigationCancelingError(message, code) {
  const error = new Error(`NavigationCancelingError: ${message || ''}`);
  error[NAVIGATION_CANCELING_ERROR] = true;
  error.cancellationCode = code;
  return error;
}
function isRedirectingNavigationCancelingError(error) {
  return isNavigationCancelingError(error) && isUrlTree(error.url);
}
function isNavigationCancelingError(error) {
  return !!error && error[NAVIGATION_CANCELING_ERROR];
}
let warnedAboutUnsupportedInputBinding = false;
const activateRoutes = (rootContexts, routeReuseStrategy, forwardEvent, inputBindingEnabled) => (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(t => {
  new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent, inputBindingEnabled).activate(rootContexts);
  return t;
});
class ActivateRoutes {
  routeReuseStrategy;
  futureState;
  currState;
  forwardEvent;
  inputBindingEnabled;
  constructor(routeReuseStrategy, futureState, currState, forwardEvent, inputBindingEnabled) {
    this.routeReuseStrategy = routeReuseStrategy;
    this.futureState = futureState;
    this.currState = currState;
    this.forwardEvent = forwardEvent;
    this.inputBindingEnabled = inputBindingEnabled;
  }
  activate(parentContexts) {
    const futureRoot = this.futureState._root;
    const currRoot = this.currState ? this.currState._root : null;
    this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
    advanceActivatedRoute(this.futureState.root);
    this.activateChildRoutes(futureRoot, currRoot, parentContexts);
  }
  // De-activate the child route that are not re-used for the future state
  deactivateChildRoutes(futureNode, currNode, contexts) {
    const children = nodeChildrenAsMap(currNode);
    // Recurse on the routes active in the future state to de-activate deeper children
    futureNode.children.forEach(futureChild => {
      const childOutletName = futureChild.value.outlet;
      this.deactivateRoutes(futureChild, children[childOutletName], contexts);
      delete children[childOutletName];
    });
    // De-activate the routes that will not be re-used
    Object.values(children).forEach(v => {
      this.deactivateRouteAndItsChildren(v, contexts);
    });
  }
  deactivateRoutes(futureNode, currNode, parentContext) {
    const future = futureNode.value;
    const curr = currNode ? currNode.value : null;
    if (future === curr) {
      // Reusing the node, check to see if the children need to be de-activated
      if (future.component) {
        // If we have a normal route, we need to go through an outlet.
        const context = parentContext.getContext(future.outlet);
        if (context) {
          this.deactivateChildRoutes(futureNode, currNode, context.children);
        }
      } else {
        // if we have a componentless route, we recurse but keep the same outlet map.
        this.deactivateChildRoutes(futureNode, currNode, parentContext);
      }
    } else {
      if (curr) {
        // Deactivate the current route which will not be re-used
        this.deactivateRouteAndItsChildren(currNode, parentContext);
      }
    }
  }
  deactivateRouteAndItsChildren(route, parentContexts) {
    // If there is no component, the Route is never attached to an outlet (because there is no
    // component to attach).
    if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
      this.detachAndStoreRouteSubtree(route, parentContexts);
    } else {
      this.deactivateRouteAndOutlet(route, parentContexts);
    }
  }
  detachAndStoreRouteSubtree(route, parentContexts) {
    const context = parentContexts.getContext(route.value.outlet);
    const contexts = context && route.value.component ? context.children : parentContexts;
    const children = nodeChildrenAsMap(route);
    for (const treeNode of Object.values(children)) {
      this.deactivateRouteAndItsChildren(treeNode, contexts);
    }
    if (context && context.outlet) {
      const componentRef = context.outlet.detach();
      const contexts = context.children.onOutletDeactivated();
      this.routeReuseStrategy.store(route.value.snapshot, {
        componentRef,
        route,
        contexts
      });
    }
  }
  deactivateRouteAndOutlet(route, parentContexts) {
    const context = parentContexts.getContext(route.value.outlet);
    // The context could be `null` if we are on a componentless route but there may still be
    // children that need deactivating.
    const contexts = context && route.value.component ? context.children : parentContexts;
    const children = nodeChildrenAsMap(route);
    for (const treeNode of Object.values(children)) {
      this.deactivateRouteAndItsChildren(treeNode, contexts);
    }
    if (context) {
      if (context.outlet) {
        // Destroy the component
        context.outlet.deactivate();
        // Destroy the contexts for all the outlets that were in the component
        context.children.onOutletDeactivated();
      }
      // Clear the information about the attached component on the context but keep the reference to
      // the outlet. Clear even if outlet was not yet activated to avoid activating later with old
      // info
      context.attachRef = null;
      context.route = null;
    }
  }
  activateChildRoutes(futureNode, currNode, contexts) {
    const children = nodeChildrenAsMap(currNode);
    futureNode.children.forEach(c => {
      this.activateRoutes(c, children[c.value.outlet], contexts);
      this.forwardEvent(new ActivationEnd(c.value.snapshot));
    });
    if (futureNode.children.length) {
      this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
    }
  }
  activateRoutes(futureNode, currNode, parentContexts) {
    const future = futureNode.value;
    const curr = currNode ? currNode.value : null;
    advanceActivatedRoute(future);
    // reusing the node
    if (future === curr) {
      if (future.component) {
        // If we have a normal route, we need to go through an outlet.
        const context = parentContexts.getOrCreateContext(future.outlet);
        this.activateChildRoutes(futureNode, currNode, context.children);
      } else {
        // if we have a componentless route, we recurse but keep the same outlet map.
        this.activateChildRoutes(futureNode, currNode, parentContexts);
      }
    } else {
      if (future.component) {
        // if we have a normal route, we need to place the component into the outlet and recurse.
        const context = parentContexts.getOrCreateContext(future.outlet);
        if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
          const stored = this.routeReuseStrategy.retrieve(future.snapshot);
          this.routeReuseStrategy.store(future.snapshot, null);
          context.children.onOutletReAttached(stored.contexts);
          context.attachRef = stored.componentRef;
          context.route = stored.route.value;
          if (context.outlet) {
            // Attach right away when the outlet has already been instantiated
            // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
            context.outlet.attach(stored.componentRef, stored.route.value);
          }
          advanceActivatedRoute(stored.route.value);
          this.activateChildRoutes(futureNode, null, context.children);
        } else {
          context.attachRef = null;
          context.route = future;
          if (context.outlet) {
            // Activate the outlet when it has already been instantiated
            // Otherwise it will get activated from its `ngOnInit` when instantiated
            context.outlet.activateWith(future, context.injector);
          }
          this.activateChildRoutes(futureNode, null, context.children);
        }
      } else {
        // if we have a componentless route, we recurse but keep the same outlet map.
        this.activateChildRoutes(futureNode, null, parentContexts);
      }
    }
    if (typeof ngDevMode === 'undefined' || ngDevMode) {
      const context = parentContexts.getOrCreateContext(future.outlet);
      const outlet = context.outlet;
      if (outlet && this.inputBindingEnabled && !outlet.supportsBindingToComponentInputs && !warnedAboutUnsupportedInputBinding) {
        console.warn(`'withComponentInputBinding' feature is enabled but ` + `this application is using an outlet that may not support binding to component inputs.`);
        warnedAboutUnsupportedInputBinding = true;
      }
    }
  }
}
class CanActivate {
  path;
  route;
  constructor(path) {
    this.path = path;
    this.route = this.path[this.path.length - 1];
  }
}
class CanDeactivate {
  component;
  route;
  constructor(component, route) {
    this.component = component;
    this.route = route;
  }
}
function getAllRouteGuards(future, curr, parentContexts) {
  const futureRoot = future._root;
  const currRoot = curr ? curr._root : null;
  return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
}
function getCanActivateChild(p) {
  const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
  if (!canActivateChild || canActivateChild.length === 0) return null;
  return {
    node: p,
    guards: canActivateChild
  };
}
function getTokenOrFunctionIdentity(tokenOrFunction, injector) {
  const NOT_FOUND = Symbol();
  const result = injector.get(tokenOrFunction, NOT_FOUND);
  if (result === NOT_FOUND) {
    if (typeof tokenOrFunction === 'function' && !(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵisInjectable"])(tokenOrFunction)) {
      // We think the token is just a function so return it as-is
      return tokenOrFunction;
    } else {
      // This will throw the not found error
      return injector.get(tokenOrFunction);
    }
  }
  return result;
}
function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = {
  canDeactivateChecks: [],
  canActivateChecks: []
}) {
  const prevChildren = nodeChildrenAsMap(currNode);
  // Process the children of the future route
  futureNode.children.forEach(c => {
    getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
    delete prevChildren[c.value.outlet];
  });
  // Process any children left from the current route (not active for the future route)
  Object.entries(prevChildren).forEach(([k, v]) => deactivateRouteAndItsChildren(v, contexts.getContext(k), checks));
  return checks;
}
function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = {
  canDeactivateChecks: [],
  canActivateChecks: []
}) {
  const future = futureNode.value;
  const curr = currNode ? currNode.value : null;
  const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
  // reusing the node
  if (curr && future.routeConfig === curr.routeConfig) {
    const shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);
    if (shouldRun) {
      checks.canActivateChecks.push(new CanActivate(futurePath));
    } else {
      // we need to set the data
      future.data = curr.data;
      future._resolvedData = curr._resolvedData;
    }
    // If we have a component, we need to go through an outlet.
    if (future.component) {
      getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
      // if we have a componentless route, we recurse but keep the same outlet map.
    } else {
      getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
    }
    if (shouldRun && context && context.outlet && context.outlet.isActivated) {
      checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, curr));
    }
  } else {
    if (curr) {
      deactivateRouteAndItsChildren(currNode, context, checks);
    }
    checks.canActivateChecks.push(new CanActivate(futurePath));
    // If we have a component, we need to go through an outlet.
    if (future.component) {
      getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
      // if we have a componentless route, we recurse but keep the same outlet map.
    } else {
      getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
    }
  }
  return checks;
}
function shouldRunGuardsAndResolvers(curr, future, mode) {
  if (typeof mode === 'function') {
    return mode(curr, future);
  }
  switch (mode) {
    case 'pathParamsChange':
      return !equalPath(curr.url, future.url);
    case 'pathParamsOrQueryParamsChange':
      return !equalPath(curr.url, future.url) || !shallowEqual(curr.queryParams, future.queryParams);
    case 'always':
      return true;
    case 'paramsOrQueryParamsChange':
      return !equalParamsAndUrlSegments(curr, future) || !shallowEqual(curr.queryParams, future.queryParams);
    case 'paramsChange':
    default:
      return !equalParamsAndUrlSegments(curr, future);
  }
}
function deactivateRouteAndItsChildren(route, context, checks) {
  const children = nodeChildrenAsMap(route);
  const r = route.value;
  Object.entries(children).forEach(([childName, node]) => {
    if (!r.component) {
      deactivateRouteAndItsChildren(node, context, checks);
    } else if (context) {
      deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
    } else {
      deactivateRouteAndItsChildren(node, null, checks);
    }
  });
  if (!r.component) {
    checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  } else if (context && context.outlet && context.outlet.isActivated) {
    checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
  } else {
    checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  }
}

/**
 * Simple function check, but generic so type inference will flow. Example:
 *
 * function product(a: number, b: number) {
 *   return a * b;
 * }
 *
 * if (isFunction<product>(fn)) {
 *   return fn(1, 2);
 * } else {
 *   throw "Must provide the `product` function";
 * }
 */
function isFunction(v) {
  return typeof v === 'function';
}
function isBoolean(v) {
  return typeof v === 'boolean';
}
function isCanLoad(guard) {
  return guard && isFunction(guard.canLoad);
}
function isCanActivate(guard) {
  return guard && isFunction(guard.canActivate);
}
function isCanActivateChild(guard) {
  return guard && isFunction(guard.canActivateChild);
}
function isCanDeactivate(guard) {
  return guard && isFunction(guard.canDeactivate);
}
function isCanMatch(guard) {
  return guard && isFunction(guard.canMatch);
}
function isEmptyError(e) {
  return e instanceof rxjs__WEBPACK_IMPORTED_MODULE_8__.EmptyError || e?.name === 'EmptyError';
}
const INITIAL_VALUE = /* @__PURE__ */Symbol('INITIAL_VALUE');
function prioritizedGuardValue() {
  return (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(obs => {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.combineLatest)(obs.map(o => o.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.take)(1), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_10__.startWith)(INITIAL_VALUE)))).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(results => {
      for (const result of results) {
        if (result === true) {
          // If result is true, check the next one
          continue;
        } else if (result === INITIAL_VALUE) {
          // If guard has not finished, we need to stop processing.
          return INITIAL_VALUE;
        } else if (result === false || isRedirect(result)) {
          // Result finished and was not true. Return the result.
          // Note that we only allow false/UrlTree/RedirectCommand. Other values are considered invalid and
          // ignored.
          return result;
        }
      }
      // Everything resolved to true. Return true.
      return true;
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(item => item !== INITIAL_VALUE), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.take)(1));
  });
}
function isRedirect(val) {
  return isUrlTree(val) || val instanceof RedirectCommand;
}
function checkGuards(injector, forwardEvent) {
  return (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(t => {
    const {
      targetSnapshot,
      currentSnapshot,
      guards: {
        canActivateChecks,
        canDeactivateChecks
      }
    } = t;
    if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({
        ...t,
        guardsResult: true
      });
    }
    return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, injector).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(canDeactivate => {
      return canDeactivate && isBoolean(canDeactivate) ? runCanActivateChecks(targetSnapshot, canActivateChecks, injector, forwardEvent) : (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canDeactivate);
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(guardsResult => ({
      ...t,
      guardsResult
    })));
  });
}
function runCanDeactivateChecks(checks, futureRSS, currRSS, injector) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(checks).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(check => runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)(result => {
    return result !== true;
  }, true));
}
function runCanActivateChecks(futureSnapshot, checks, injector, forwardEvent) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(checks).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.concatMap)(check => {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_15__.concat)(fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, injector), runCanActivate(futureSnapshot, check.route, injector));
  }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)(result => {
    return result !== true;
  }, true));
}
/**
 * This should fire off `ActivationStart` events for each route being activated at this
 * level.
 * In other words, if you're activating `a` and `b` below, `path` will contain the
 * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
 * return
 * `true` so checks continue to run.
 */
function fireActivationStart(snapshot, forwardEvent) {
  if (snapshot !== null && forwardEvent) {
    forwardEvent(new ActivationStart(snapshot));
  }
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
}
/**
 * This should fire off `ChildActivationStart` events for each route being activated at this
 * level.
 * In other words, if you're activating `a` and `b` below, `path` will contain the
 * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
 * return
 * `true` so checks continue to run.
 */
function fireChildActivationStart(snapshot, forwardEvent) {
  if (snapshot !== null && forwardEvent) {
    forwardEvent(new ChildActivationStart(snapshot));
  }
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
}
function runCanActivate(futureRSS, futureARS, injector) {
  const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
  if (!canActivate || canActivate.length === 0) return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
  const canActivateObservables = canActivate.map(canActivate => {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_16__.defer)(() => {
      const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
      const guard = getTokenOrFunctionIdentity(canActivate, closestInjector);
      const guardVal = isCanActivate(guard) ? guard.canActivate(futureARS, futureRSS) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(closestInjector, () => guard(futureARS, futureRSS));
      return wrapIntoObservable(guardVal).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)());
    });
  });
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canActivateObservables).pipe(prioritizedGuardValue());
}
function runCanActivateChild(futureRSS, path, injector) {
  const futureARS = path[path.length - 1];
  const canActivateChildGuards = path.slice(0, path.length - 1).reverse().map(p => getCanActivateChild(p)).filter(_ => _ !== null);
  const canActivateChildGuardsMapped = canActivateChildGuards.map(d => {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_16__.defer)(() => {
      const guardsMapped = d.guards.map(canActivateChild => {
        const closestInjector = getClosestRouteInjector(d.node) ?? injector;
        const guard = getTokenOrFunctionIdentity(canActivateChild, closestInjector);
        const guardVal = isCanActivateChild(guard) ? guard.canActivateChild(futureARS, futureRSS) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(closestInjector, () => guard(futureARS, futureRSS));
        return wrapIntoObservable(guardVal).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)());
      });
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(guardsMapped).pipe(prioritizedGuardValue());
    });
  });
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
}
function runCanDeactivate(component, currARS, currRSS, futureRSS, injector) {
  const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
  if (!canDeactivate || canDeactivate.length === 0) return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
  const canDeactivateObservables = canDeactivate.map(c => {
    const closestInjector = getClosestRouteInjector(currARS) ?? injector;
    const guard = getTokenOrFunctionIdentity(c, closestInjector);
    const guardVal = isCanDeactivate(guard) ? guard.canDeactivate(component, currARS, currRSS, futureRSS) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(closestInjector, () => guard(component, currARS, currRSS, futureRSS));
    return wrapIntoObservable(guardVal).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)());
  });
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canDeactivateObservables).pipe(prioritizedGuardValue());
}
function runCanLoadGuards(injector, route, segments, urlSerializer) {
  const canLoad = route.canLoad;
  if (canLoad === undefined || canLoad.length === 0) {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
  }
  const canLoadObservables = canLoad.map(injectionToken => {
    const guard = getTokenOrFunctionIdentity(injectionToken, injector);
    const guardVal = isCanLoad(guard) ? guard.canLoad(route, segments) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(injector, () => guard(route, segments));
    return wrapIntoObservable(guardVal);
  });
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
}
function redirectIfUrlTree(urlSerializer) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_17__.pipe)((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(result => {
    if (typeof result === 'boolean') return;
    throw redirectingNavigationError(urlSerializer, result);
  }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(result => result === true));
}
function runCanMatchGuards(injector, route, segments, urlSerializer) {
  const canMatch = route.canMatch;
  if (!canMatch || canMatch.length === 0) return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(true);
  const canMatchObservables = canMatch.map(injectionToken => {
    const guard = getTokenOrFunctionIdentity(injectionToken, injector);
    const guardVal = isCanMatch(guard) ? guard.canMatch(route, segments) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(injector, () => guard(route, segments));
    return wrapIntoObservable(guardVal);
  });
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
}
class NoMatch {
  segmentGroup;
  constructor(segmentGroup) {
    this.segmentGroup = segmentGroup || null;
  }
}
class AbsoluteRedirect extends Error {
  urlTree;
  constructor(urlTree) {
    super();
    this.urlTree = urlTree;
  }
}
function noMatch$1(segmentGroup) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_19__.throwError)(new NoMatch(segmentGroup));
}
function absoluteRedirect(newTree) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_19__.throwError)(new AbsoluteRedirect(newTree));
}
function namedOutletsRedirect(redirectTo) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_19__.throwError)(new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4000 /* RuntimeErrorCode.NAMED_OUTLET_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));
}
function canLoadFails(route) {
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_19__.throwError)(navigationCancelingError((typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot load children because the guard of the route "path: '${route.path}'" returned false`, NavigationCancellationCode.GuardRejected));
}
class ApplyRedirects {
  urlSerializer;
  urlTree;
  constructor(urlSerializer, urlTree) {
    this.urlSerializer = urlSerializer;
    this.urlTree = urlTree;
  }
  lineralizeSegments(route, urlTree) {
    let res = [];
    let c = urlTree.root;
    while (true) {
      res = res.concat(c.segments);
      if (c.numberOfChildren === 0) {
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(res);
      }
      if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
        return namedOutletsRedirect(`${route.redirectTo}`);
      }
      c = c.children[PRIMARY_OUTLET];
    }
  }
  applyRedirectCommands(segments, redirectTo, posParams, currentSnapshot, injector) {
    if (typeof redirectTo !== 'string') {
      const redirectToFn = redirectTo;
      const {
        queryParams,
        fragment,
        routeConfig,
        url,
        outlet,
        params,
        data,
        title
      } = currentSnapshot;
      const newRedirect = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(injector, () => redirectToFn({
        params,
        data,
        queryParams,
        fragment,
        routeConfig,
        url,
        outlet,
        title
      }));
      if (newRedirect instanceof UrlTree) {
        throw new AbsoluteRedirect(newRedirect);
      }
      redirectTo = newRedirect;
    }
    const newTree = this.applyRedirectCreateUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
    if (redirectTo[0] === '/') {
      throw new AbsoluteRedirect(newTree);
    }
    return newTree;
  }
  applyRedirectCreateUrlTree(redirectTo, urlTree, segments, posParams) {
    const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
    return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
  }
  createQueryParams(redirectToParams, actualParams) {
    const res = {};
    Object.entries(redirectToParams).forEach(([k, v]) => {
      const copySourceValue = typeof v === 'string' && v[0] === ':';
      if (copySourceValue) {
        const sourceName = v.substring(1);
        res[k] = actualParams[sourceName];
      } else {
        res[k] = v;
      }
    });
    return res;
  }
  createSegmentGroup(redirectTo, group, segments, posParams) {
    const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
    let children = {};
    Object.entries(group.children).forEach(([name, child]) => {
      children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);
    });
    return new UrlSegmentGroup(updatedSegments, children);
  }
  createSegments(redirectTo, redirectToSegments, actualSegments, posParams) {
    return redirectToSegments.map(s => s.path[0] === ':' ? this.findPosParam(redirectTo, s, posParams) : this.findOrReturn(s, actualSegments));
  }
  findPosParam(redirectTo, redirectToUrlSegment, posParams) {
    const pos = posParams[redirectToUrlSegment.path.substring(1)];
    if (!pos) throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4001 /* RuntimeErrorCode.MISSING_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
    return pos;
  }
  findOrReturn(redirectToUrlSegment, actualSegments) {
    let idx = 0;
    for (const s of actualSegments) {
      if (s.path === redirectToUrlSegment.path) {
        actualSegments.splice(idx);
        return s;
      }
      idx++;
    }
    return redirectToUrlSegment;
  }
}
const noMatch = {
  matched: false,
  consumedSegments: [],
  remainingSegments: [],
  parameters: {},
  positionalParamSegments: {}
};
function matchWithChecks(segmentGroup, route, segments, injector, urlSerializer) {
  const result = match(segmentGroup, route, segments);
  if (!result.matched) {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(result);
  }
  // Only create the Route's `EnvironmentInjector` if it matches the attempted
  // navigation
  injector = getOrCreateRouteInjectorIfNeeded(route, injector);
  return runCanMatchGuards(injector, route, segments, urlSerializer).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(v => v === true ? result : {
    ...noMatch
  }));
}
function match(segmentGroup, route, segments) {
  if (route.path === '**') {
    return createWildcardMatchResult(segments);
  }
  if (route.path === '') {
    if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
      return {
        ...noMatch
      };
    }
    return {
      matched: true,
      consumedSegments: [],
      remainingSegments: segments,
      parameters: {},
      positionalParamSegments: {}
    };
  }
  const matcher = route.matcher || defaultUrlMatcher;
  const res = matcher(segments, segmentGroup, route);
  if (!res) return {
    ...noMatch
  };
  const posParams = {};
  Object.entries(res.posParams ?? {}).forEach(([k, v]) => {
    posParams[k] = v.path;
  });
  const parameters = res.consumed.length > 0 ? {
    ...posParams,
    ...res.consumed[res.consumed.length - 1].parameters
  } : posParams;
  return {
    matched: true,
    consumedSegments: res.consumed,
    remainingSegments: segments.slice(res.consumed.length),
    // TODO(atscott): investigate combining parameters and positionalParamSegments
    parameters,
    positionalParamSegments: res.posParams ?? {}
  };
}
function createWildcardMatchResult(segments) {
  return {
    matched: true,
    parameters: segments.length > 0 ? last(segments).parameters : {},
    consumedSegments: segments,
    remainingSegments: [],
    positionalParamSegments: {}
  };
}
function split(segmentGroup, consumedSegments, slicedSegments, config) {
  if (slicedSegments.length > 0 && containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
    const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
    return {
      segmentGroup: s,
      slicedSegments: []
    };
  }
  if (slicedSegments.length === 0 && containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
    const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
    return {
      segmentGroup: s,
      slicedSegments
    };
  }
  const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
  return {
    segmentGroup: s,
    slicedSegments
  };
}
function addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
  const res = {};
  for (const r of routes) {
    if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
      const s = new UrlSegmentGroup([], {});
      res[getOutlet(r)] = s;
    }
  }
  return {
    ...children,
    ...res
  };
}
function createChildrenForEmptyPaths(routes, primarySegment) {
  const res = {};
  res[PRIMARY_OUTLET] = primarySegment;
  for (const r of routes) {
    if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
      const s = new UrlSegmentGroup([], {});
      res[getOutlet(r)] = s;
    }
  }
  return res;
}
function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
  return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet(r) !== PRIMARY_OUTLET);
}
function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
  return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r));
}
function emptyPathMatch(segmentGroup, slicedSegments, r) {
  if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
    return false;
  }
  return r.path === '';
}
function noLeftoversInUrl(segmentGroup, segments, outlet) {
  return segments.length === 0 && !segmentGroup.children[outlet];
}

/**
 * Class used to indicate there were no additional route config matches but that all segments of
 * the URL were consumed during matching so the route was URL matched. When this happens, we still
 * try to match child configs in case there are empty path children.
 */
class NoLeftoversInUrl {}
function recognize$1(injector, configLoader, rootComponentType, config, urlTree, urlSerializer, paramsInheritanceStrategy = 'emptyOnly') {
  return new Recognizer(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer).recognize();
}
const MAX_ALLOWED_REDIRECTS = 31;
class Recognizer {
  injector;
  configLoader;
  rootComponentType;
  config;
  urlTree;
  paramsInheritanceStrategy;
  urlSerializer;
  applyRedirects;
  absoluteRedirectCount = 0;
  allowRedirects = true;
  constructor(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer) {
    this.injector = injector;
    this.configLoader = configLoader;
    this.rootComponentType = rootComponentType;
    this.config = config;
    this.urlTree = urlTree;
    this.paramsInheritanceStrategy = paramsInheritanceStrategy;
    this.urlSerializer = urlSerializer;
    this.applyRedirects = new ApplyRedirects(this.urlSerializer, this.urlTree);
  }
  noMatchError(e) {
    return new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4002 /* RuntimeErrorCode.NO_MATCH */, typeof ngDevMode === 'undefined' || ngDevMode ? `Cannot match any routes. URL Segment: '${e.segmentGroup}'` : `'${e.segmentGroup}'`);
  }
  recognize() {
    const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;
    return this.match(rootSegmentGroup).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(({
      children,
      rootSnapshot
    }) => {
      const rootNode = new TreeNode(rootSnapshot, children);
      const routeState = new RouterStateSnapshot('', rootNode);
      const tree = createUrlTreeFromSnapshot(rootSnapshot, [], this.urlTree.queryParams, this.urlTree.fragment);
      // https://github.com/angular/angular/issues/47307
      // Creating the tree stringifies the query params
      // We don't want to do this here so reassign them to the original.
      tree.queryParams = this.urlTree.queryParams;
      routeState.url = this.urlSerializer.serialize(tree);
      return {
        state: routeState,
        tree
      };
    }));
  }
  match(rootSegmentGroup) {
    // Use Object.freeze to prevent readers of the Router state from modifying it outside
    // of a navigation, resulting in the router being out of sync with the browser.
    const rootSnapshot = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze({
      ...this.urlTree.queryParams
    }), this.urlTree.fragment, Object.freeze({}), PRIMARY_OUTLET, this.rootComponentType, null, {});
    return this.processSegmentGroup(this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET, rootSnapshot).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(children => {
      return {
        children,
        rootSnapshot
      };
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(e => {
      if (e instanceof AbsoluteRedirect) {
        this.urlTree = e.urlTree;
        return this.match(e.urlTree.root);
      }
      if (e instanceof NoMatch) {
        throw this.noMatchError(e);
      }
      throw e;
    }));
  }
  processSegmentGroup(injector, config, segmentGroup, outlet, parentRoute) {
    if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
      return this.processChildren(injector, config, segmentGroup, parentRoute);
    }
    return this.processSegment(injector, config, segmentGroup, segmentGroup.segments, outlet, true, parentRoute).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(child => child instanceof TreeNode ? [child] : []));
  }
  /**
   * Matches every child outlet in the `segmentGroup` to a `Route` in the config. Returns `null` if
   * we cannot find a match for _any_ of the children.
   *
   * @param config - The `Routes` to match against
   * @param segmentGroup - The `UrlSegmentGroup` whose children need to be matched against the
   *     config.
   */
  processChildren(injector, config, segmentGroup, parentRoute) {
    // Expand outlets one at a time, starting with the primary outlet. We need to do it this way
    // because an absolute redirect from the primary outlet takes precedence.
    const childOutlets = [];
    for (const child of Object.keys(segmentGroup.children)) {
      if (child === 'primary') {
        childOutlets.unshift(child);
      } else {
        childOutlets.push(child);
      }
    }
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(childOutlets).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.concatMap)(childOutlet => {
      const child = segmentGroup.children[childOutlet];
      // Sort the config so that routes with outlets that match the one being activated
      // appear first, followed by routes for other outlets, which might match if they have
      // an empty path.
      const sortedConfig = sortByMatchingOutlets(config, childOutlet);
      return this.processSegmentGroup(injector, sortedConfig, child, childOutlet, parentRoute);
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_21__.scan)((children, outletChildren) => {
      children.push(...outletChildren);
      return children;
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_22__.defaultIfEmpty)(null), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_23__.last)(), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(children => {
      if (children === null) return noMatch$1(segmentGroup);
      // Because we may have matched two outlets to the same empty path segment, we can have
      // multiple activated results for the same outlet. We should merge the children of
      // these results so the final return value is only one `TreeNode` per outlet.
      const mergedChildren = mergeEmptyPathMatches(children);
      if (typeof ngDevMode === 'undefined' || ngDevMode) {
        // This should really never happen - we are only taking the first match for each
        // outlet and merge the empty path matches.
        checkOutletNameUniqueness(mergedChildren);
      }
      sortActivatedRouteSnapshots(mergedChildren);
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(mergedChildren);
    }));
  }
  processSegment(injector, routes, segmentGroup, segments, outlet, allowRedirects, parentRoute) {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(routes).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.concatMap)(r => {
      return this.processSegmentAgainstRoute(r._injector ?? injector, routes, r, segmentGroup, segments, outlet, allowRedirects, parentRoute).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(e => {
        if (e instanceof NoMatch) {
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(null);
        }
        throw e;
      }));
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)(x => !!x), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(e => {
      if (isEmptyError(e)) {
        if (noLeftoversInUrl(segmentGroup, segments, outlet)) {
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(new NoLeftoversInUrl());
        }
        return noMatch$1(segmentGroup);
      }
      throw e;
    }));
  }
  processSegmentAgainstRoute(injector, routes, route, rawSegment, segments, outlet, allowRedirects, parentRoute) {
    // We allow matches to empty paths when the outlets differ so we can match a url like `/(b:b)` to
    // a config like
    // * `{path: '', children: [{path: 'b', outlet: 'b'}]}`
    // or even
    // * `{path: '', outlet: 'a', children: [{path: 'b', outlet: 'b'}]`
    //
    // The exception here is when the segment outlet is for the primary outlet. This would
    // result in a match inside the named outlet because all children there are written as primary
    // outlets. So we need to prevent child named outlet matches in a url like `/b` in a config like
    // * `{path: '', outlet: 'x' children: [{path: 'b'}]}`
    // This should only match if the url is `/(x:b)`.
    if (getOutlet(route) !== outlet && (outlet === PRIMARY_OUTLET || !emptyPathMatch(rawSegment, segments, route))) {
      return noMatch$1(rawSegment);
    }
    if (route.redirectTo === undefined) {
      return this.matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute);
    }
    if (this.allowRedirects && allowRedirects) {
      return this.expandSegmentAgainstRouteUsingRedirect(injector, rawSegment, routes, route, segments, outlet, parentRoute);
    }
    return noMatch$1(rawSegment);
  }
  expandSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet, parentRoute) {
    const {
      matched,
      parameters,
      consumedSegments,
      positionalParamSegments,
      remainingSegments
    } = match(segmentGroup, route, segments);
    if (!matched) return noMatch$1(segmentGroup);
    // TODO(atscott): Move all of this under an if(ngDevMode) as a breaking change and allow stack
    // size exceeded in production
    if (typeof route.redirectTo === 'string' && route.redirectTo[0] === '/') {
      this.absoluteRedirectCount++;
      if (this.absoluteRedirectCount > MAX_ALLOWED_REDIRECTS) {
        if (ngDevMode) {
          throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4016 /* RuntimeErrorCode.INFINITE_REDIRECT */, `Detected possible infinite redirect when redirecting from '${this.urlTree}' to '${route.redirectTo}'.\n` + `This is currently a dev mode only error but will become a` + ` call stack size exceeded error in production in a future major version.`);
        }
        this.allowRedirects = false;
      }
    }
    const currentSnapshot = new ActivatedRouteSnapshot(segments, parameters, Object.freeze({
      ...this.urlTree.queryParams
    }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
    const inherited = getInherited(currentSnapshot, parentRoute, this.paramsInheritanceStrategy);
    currentSnapshot.params = Object.freeze(inherited.params);
    currentSnapshot.data = Object.freeze(inherited.data);
    const newTree = this.applyRedirects.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments, currentSnapshot, injector);
    return this.applyRedirects.lineralizeSegments(route, newTree).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(newSegments => {
      return this.processSegment(injector, routes, segmentGroup, newSegments.concat(remainingSegments), outlet, false, parentRoute);
    }));
  }
  matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute) {
    const matchResult = matchWithChecks(rawSegment, route, segments, injector, this.urlSerializer);
    if (route.path === '**') {
      // Prior versions of the route matching algorithm would stop matching at the wildcard route.
      // We should investigate a better strategy for any existing children. Otherwise, these
      // child segments are silently dropped from the navigation.
      // https://github.com/angular/angular/issues/40089
      rawSegment.children = {};
    }
    return matchResult.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(result => {
      if (!result.matched) {
        return noMatch$1(rawSegment);
      }
      // If the route has an injector created from providers, we should start using that.
      injector = route._injector ?? injector;
      return this.getChildConfig(injector, route, segments).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(({
        routes: childConfig
      }) => {
        const childInjector = route._loadedInjector ?? injector;
        const {
          parameters,
          consumedSegments,
          remainingSegments
        } = result;
        const snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze({
          ...this.urlTree.queryParams
        }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
        const inherited = getInherited(snapshot, parentRoute, this.paramsInheritanceStrategy);
        snapshot.params = Object.freeze(inherited.params);
        snapshot.data = Object.freeze(inherited.data);
        const {
          segmentGroup,
          slicedSegments
        } = split(rawSegment, consumedSegments, remainingSegments, childConfig);
        if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
          return this.processChildren(childInjector, childConfig, segmentGroup, snapshot).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(children => {
            return new TreeNode(snapshot, children);
          }));
        }
        if (childConfig.length === 0 && slicedSegments.length === 0) {
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(new TreeNode(snapshot, []));
        }
        const matchedOnOutlet = getOutlet(route) === outlet;
        // If we matched a config due to empty path match on a different outlet, we need to
        // continue passing the current outlet for the segment rather than switch to PRIMARY.
        // Note that we switch to primary when we have a match because outlet configs look like
        // this: {path: 'a', outlet: 'a', children: [
        //  {path: 'b', component: B},
        //  {path: 'c', component: C},
        // ]}
        // Notice that the children of the named outlet are configured with the primary outlet
        return this.processSegment(childInjector, childConfig, segmentGroup, slicedSegments, matchedOnOutlet ? PRIMARY_OUTLET : outlet, true, snapshot).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(child => {
          return new TreeNode(snapshot, child instanceof TreeNode ? [child] : []);
        }));
      }));
    }));
  }
  getChildConfig(injector, route, segments) {
    if (route.children) {
      // The children belong to the same module
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({
        routes: route.children,
        injector
      });
    }
    if (route.loadChildren) {
      // lazy children belong to the loaded module
      if (route._loadedRoutes !== undefined) {
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({
          routes: route._loadedRoutes,
          injector: route._loadedInjector
        });
      }
      return runCanLoadGuards(injector, route, segments, this.urlSerializer).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(shouldLoadResult => {
        if (shouldLoadResult) {
          return this.configLoader.loadChildren(injector, route).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(cfg => {
            route._loadedRoutes = cfg.routes;
            route._loadedInjector = cfg.injector;
          }));
        }
        return canLoadFails(route);
      }));
    }
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({
      routes: [],
      injector
    });
  }
}
function sortActivatedRouteSnapshots(nodes) {
  nodes.sort((a, b) => {
    if (a.value.outlet === PRIMARY_OUTLET) return -1;
    if (b.value.outlet === PRIMARY_OUTLET) return 1;
    return a.value.outlet.localeCompare(b.value.outlet);
  });
}
function hasEmptyPathConfig(node) {
  const config = node.value.routeConfig;
  return config && config.path === '';
}
/**
 * Finds `TreeNode`s with matching empty path route configs and merges them into `TreeNode` with
 * the children from each duplicate. This is necessary because different outlets can match a
 * single empty path route config and the results need to then be merged.
 */
function mergeEmptyPathMatches(nodes) {
  const result = [];
  // The set of nodes which contain children that were merged from two duplicate empty path nodes.
  const mergedNodes = new Set();
  for (const node of nodes) {
    if (!hasEmptyPathConfig(node)) {
      result.push(node);
      continue;
    }
    const duplicateEmptyPathNode = result.find(resultNode => node.value.routeConfig === resultNode.value.routeConfig);
    if (duplicateEmptyPathNode !== undefined) {
      duplicateEmptyPathNode.children.push(...node.children);
      mergedNodes.add(duplicateEmptyPathNode);
    } else {
      result.push(node);
    }
  }
  // For each node which has children from multiple sources, we need to recompute a new `TreeNode`
  // by also merging those children. This is necessary when there are multiple empty path configs
  // in a row. Put another way: whenever we combine children of two nodes, we need to also check
  // if any of those children can be combined into a single node as well.
  for (const mergedNode of mergedNodes) {
    const mergedChildren = mergeEmptyPathMatches(mergedNode.children);
    result.push(new TreeNode(mergedNode.value, mergedChildren));
  }
  return result.filter(n => !mergedNodes.has(n));
}
function checkOutletNameUniqueness(nodes) {
  const names = {};
  nodes.forEach(n => {
    const routeWithSameOutletName = names[n.value.outlet];
    if (routeWithSameOutletName) {
      const p = routeWithSameOutletName.url.map(s => s.toString()).join('/');
      const c = n.value.url.map(s => s.toString()).join('/');
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4006 /* RuntimeErrorCode.TWO_SEGMENTS_WITH_SAME_OUTLET */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Two segments cannot have the same outlet name: '${p}' and '${c}'.`);
    }
    names[n.value.outlet] = n.value;
  });
}
function getData(route) {
  return route.data || {};
}
function getResolve(route) {
  return route.resolve || {};
}
function recognize(injector, configLoader, rootComponentType, config, serializer, paramsInheritanceStrategy) {
  return (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(t => recognize$1(injector, configLoader, rootComponentType, config, t.extractedUrl, serializer, paramsInheritanceStrategy).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(({
    state: targetSnapshot,
    tree: urlAfterRedirects
  }) => {
    return {
      ...t,
      targetSnapshot,
      urlAfterRedirects
    };
  })));
}
function resolveData(paramsInheritanceStrategy, injector) {
  return (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(t => {
    const {
      targetSnapshot,
      guards: {
        canActivateChecks
      }
    } = t;
    if (!canActivateChecks.length) {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t);
    }
    // Iterating a Set in javascript  happens in insertion order so it is safe to use a `Set` to
    // preserve the correct order that the resolvers should run in.
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#description
    const routesWithResolversToRun = new Set(canActivateChecks.map(check => check.route));
    const routesNeedingDataUpdates = new Set();
    for (const route of routesWithResolversToRun) {
      if (routesNeedingDataUpdates.has(route)) {
        continue;
      }
      // All children under the route with a resolver to run need to recompute inherited data.
      for (const newRoute of flattenRouteTree(route)) {
        routesNeedingDataUpdates.add(newRoute);
      }
    }
    let routesProcessed = 0;
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(routesNeedingDataUpdates).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.concatMap)(route => {
      if (routesWithResolversToRun.has(route)) {
        return runResolve(route, targetSnapshot, paramsInheritanceStrategy, injector);
      } else {
        route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve;
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(void 0);
      }
    }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(() => routesProcessed++), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_24__.takeLast)(1), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(_ => routesProcessed === routesNeedingDataUpdates.size ? (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t) : rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY));
  });
}
/**
 *  Returns the `ActivatedRouteSnapshot` tree as an array, using DFS to traverse the route tree.
 */
function flattenRouteTree(route) {
  const descendants = route.children.map(child => flattenRouteTree(child)).flat();
  return [route, ...descendants];
}
function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, injector) {
  const config = futureARS.routeConfig;
  const resolve = futureARS._resolve;
  if (config?.title !== undefined && !hasStaticTitle(config)) {
    resolve[RouteTitleKey] = config.title;
  }
  return resolveNode(resolve, futureARS, futureRSS, injector).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(resolvedData => {
    futureARS._resolvedData = resolvedData;
    futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve;
    return null;
  }));
}
function resolveNode(resolve, futureARS, futureRSS, injector) {
  const keys = getDataKeys(resolve);
  if (keys.length === 0) {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({});
  }
  const data = {};
  return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(keys).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(key => getResolver(resolve[key], futureARS, futureRSS, injector).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_13__.first)(), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(value => {
    if (value instanceof RedirectCommand) {
      throw redirectingNavigationError(new DefaultUrlSerializer(), value);
    }
    data[key] = value;
  }))), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_24__.takeLast)(1), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_26__.mapTo)(data), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(e => isEmptyError(e) ? rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY : (0,rxjs__WEBPACK_IMPORTED_MODULE_19__.throwError)(e)));
}
function getResolver(injectionToken, futureARS, futureRSS, injector) {
  const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
  const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector);
  const resolverValue = resolver.resolve ? resolver.resolve(futureARS, futureRSS) : (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(closestInjector, () => resolver(futureARS, futureRSS));
  return wrapIntoObservable(resolverValue);
}

/**
 * Perform a side effect through a switchMap for every emission on the source Observable,
 * but return an Observable that is identical to the source. It's essentially the same as
 * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
 * it will wait before continuing with the original value.
 */
function switchTap(next) {
  return (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(v => {
    const nextResult = next(v);
    if (nextResult) {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(nextResult).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(() => v));
    }
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(v);
  });
}

/**
 * Provides a strategy for setting the page title after a router navigation.
 *
 * The built-in implementation traverses the router state snapshot and finds the deepest primary
 * outlet with `title` property. Given the `Routes` below, navigating to
 * `/base/child(popup:aux)` would result in the document title being set to "child".
 * ```
 * [
 *   {path: 'base', title: 'base', children: [
 *     {path: 'child', title: 'child'},
 *   ],
 *   {path: 'aux', outlet: 'popup', title: 'popupTitle'}
 * ]
 * ```
 *
 * This class can be used as a base class for custom title strategies. That is, you can create your
 * own class that extends the `TitleStrategy`. Note that in the above example, the `title`
 * from the named outlet is never used. However, a custom strategy might be implemented to
 * incorporate titles in named outlets.
 *
 * @publicApi
 * @see [Page title guide](guide/routing/common-router-tasks#setting-the-page-title)
 */
let TitleStrategy = /*#__PURE__*/(() => {
  class TitleStrategy {
    /**
     * @returns The `title` of the deepest primary route.
     */
    buildTitle(snapshot) {
      let pageTitle;
      let route = snapshot.root;
      while (route !== undefined) {
        pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle;
        route = route.children.find(child => child.outlet === PRIMARY_OUTLET);
      }
      return pageTitle;
    }
    /**
     * Given an `ActivatedRouteSnapshot`, returns the final value of the
     * `Route.title` property, which can either be a static string or a resolved value.
     */
    getResolvedTitleForRoute(snapshot) {
      return snapshot.data[RouteTitleKey];
    }
    static ɵfac = (() => function TitleStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || TitleStrategy)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: TitleStrategy,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DefaultTitleStrategy))(),
      providedIn: 'root'
    }))();
  }
  return TitleStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * The default `TitleStrategy` used by the router that updates the title using the `Title` service.
 */
let DefaultTitleStrategy = /*#__PURE__*/(() => {
  class DefaultTitleStrategy extends TitleStrategy {
    title;
    constructor(title) {
      super();
      this.title = title;
    }
    /**
     * Sets the title of the browser to the given value.
     *
     * @param title The `pageTitle` from the deepest primary route.
     */
    updateTitle(snapshot) {
      const title = this.buildTitle(snapshot);
      if (title !== undefined) {
        this.title.setTitle(title);
      }
    }
    static ɵfac = (() => function DefaultTitleStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DefaultTitleStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_platform_browser__WEBPACK_IMPORTED_MODULE_27__.Title));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DefaultTitleStrategy,
      factory: DefaultTitleStrategy.ɵfac,
      providedIn: 'root'
    }))();
  }
  return DefaultTitleStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * A DI token for the router service.
 *
 * @publicApi
 */
const ROUTER_CONFIGURATION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router config' : '', {
  providedIn: 'root',
  factory: () => ({})
});

/**
 * This component is used internally within the router to be a placeholder when an empty
 * router-outlet is needed. For example, with a config such as:
 *
 * `{path: 'parent', outlet: 'nav', children: [...]}`
 *
 * In order to render, there needs to be a component on this config, which will default
 * to this `EmptyOutletComponent`.
 */
let ɵEmptyOutletComponent = /*#__PURE__*/(() => {
  class ɵEmptyOutletComponent {
    static ɵfac = (() => function ɵEmptyOutletComponent_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || ɵEmptyOutletComponent)();
    })();
    static ɵcmp = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineComponent"]({
      type: ɵEmptyOutletComponent,
      selectors: [["ng-component"]],
      decls: 1,
      vars: 0,
      template: function _EmptyOutletComponent_Template(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵelement"](0, "router-outlet");
        }
      },
      dependencies: [RouterOutlet],
      encapsulation: 2
    }))();
  }
  return ɵEmptyOutletComponent;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Makes a copy of the config and adds any default required properties.
 */
function standardizeConfig(r) {
  const children = r.children && r.children.map(standardizeConfig);
  const c = children ? {
    ...r,
    children
  } : {
    ...r
  };
  if (!c.component && !c.loadComponent && (children || c.loadChildren) && c.outlet && c.outlet !== PRIMARY_OUTLET) {
    c.component = ɵEmptyOutletComponent;
  }
  return c;
}

/**
 * The DI token for a router configuration.
 *
 * `ROUTES` is a low level API for router configuration via dependency injection.
 *
 * We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,
 * `provideRouter`, or `Router.resetConfig()`.
 *
 * @publicApi
 */
const ROUTES = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'ROUTES' : '');
let RouterConfigLoader = /*#__PURE__*/(() => {
  class RouterConfigLoader {
    componentLoaders = (() => new WeakMap())();
    childrenLoaders = (() => new WeakMap())();
    onLoadStartListener;
    onLoadEndListener;
    compiler = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.Compiler))();
    loadComponent(route) {
      if (this.componentLoaders.get(route)) {
        return this.componentLoaders.get(route);
      } else if (route._loadedComponent) {
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(route._loadedComponent);
      }
      if (this.onLoadStartListener) {
        this.onLoadStartListener(route);
      }
      const loadRunner = wrapIntoObservable(route.loadComponent()).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(maybeUnwrapDefaultExport), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(component => {
        if (this.onLoadEndListener) {
          this.onLoadEndListener(route);
        }
        (typeof ngDevMode === 'undefined' || ngDevMode) && assertStandalone(route.path ?? '', component);
        route._loadedComponent = component;
      }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_28__.finalize)(() => {
        this.componentLoaders.delete(route);
      }));
      // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
      const loader = new rxjs__WEBPACK_IMPORTED_MODULE_29__.ConnectableObservable(loadRunner, () => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject()).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_31__.refCount)());
      this.componentLoaders.set(route, loader);
      return loader;
    }
    loadChildren(parentInjector, route) {
      if (this.childrenLoaders.get(route)) {
        return this.childrenLoaders.get(route);
      } else if (route._loadedRoutes) {
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)({
          routes: route._loadedRoutes,
          injector: route._loadedInjector
        });
      }
      if (this.onLoadStartListener) {
        this.onLoadStartListener(route);
      }
      const moduleFactoryOrRoutes$ = loadChildren(route, this.compiler, parentInjector, this.onLoadEndListener);
      const loadRunner = moduleFactoryOrRoutes$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_28__.finalize)(() => {
        this.childrenLoaders.delete(route);
      }));
      // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
      const loader = new rxjs__WEBPACK_IMPORTED_MODULE_29__.ConnectableObservable(loadRunner, () => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject()).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_31__.refCount)());
      this.childrenLoaders.set(route, loader);
      return loader;
    }
    static ɵfac = (() => function RouterConfigLoader_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterConfigLoader)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: RouterConfigLoader,
      factory: RouterConfigLoader.ɵfac,
      providedIn: 'root'
    }))();
  }
  return RouterConfigLoader;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Executes a `route.loadChildren` callback and converts the result to an array of child routes and
 * an injector if that callback returned a module.
 *
 * This function is used for the route discovery during prerendering
 * in @angular-devkit/build-angular. If there are any updates to the contract here, it will require
 * an update to the extractor.
 */
function loadChildren(route, compiler, parentInjector, onLoadEndListener) {
  return wrapIntoObservable(route.loadChildren()).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(maybeUnwrapDefaultExport), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(t => {
    if (t instanceof _angular_core__WEBPACK_IMPORTED_MODULE_1__.NgModuleFactory || Array.isArray(t)) {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t);
    } else {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(compiler.compileModuleAsync(t));
    }
  }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(factoryOrRoutes => {
    if (onLoadEndListener) {
      onLoadEndListener(route);
    }
    // This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
    // no injector associated with lazy loading a `Route` array.
    let injector;
    let rawRoutes;
    let requireStandaloneComponents = false;
    if (Array.isArray(factoryOrRoutes)) {
      rawRoutes = factoryOrRoutes;
      requireStandaloneComponents = true;
    } else {
      injector = factoryOrRoutes.create(parentInjector).injector;
      // When loading a module that doesn't provide `RouterModule.forChild()` preloader
      // will get stuck in an infinite loop. The child module's Injector will look to
      // its parent `Injector` when it doesn't find any ROUTES so it will return routes
      // for it's parent module instead.
      rawRoutes = injector.get(ROUTES, [], {
        optional: true,
        self: true
      }).flat();
    }
    const routes = rawRoutes.map(standardizeConfig);
    (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(routes, route.path, requireStandaloneComponents);
    return {
      routes,
      injector
    };
  }));
}
function isWrappedDefaultExport(value) {
  // We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
  // dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
  // `default` will be a renamed property.
  return value && typeof value === 'object' && 'default' in value;
}
function maybeUnwrapDefaultExport(input) {
  // As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
  // subject to property renaming, so we reference it with bracket access.
  return isWrappedDefaultExport(input) ? input['default'] : input;
}

/**
 * @description
 *
 * Provides a way to migrate AngularJS applications to Angular.
 *
 * @publicApi
 */
let UrlHandlingStrategy = /*#__PURE__*/(() => {
  class UrlHandlingStrategy {
    static ɵfac = (() => function UrlHandlingStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UrlHandlingStrategy)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: UrlHandlingStrategy,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DefaultUrlHandlingStrategy))(),
      providedIn: 'root'
    }))();
  }
  return UrlHandlingStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @publicApi
 */
let DefaultUrlHandlingStrategy = /*#__PURE__*/(() => {
  class DefaultUrlHandlingStrategy {
    shouldProcessUrl(url) {
      return true;
    }
    extract(url) {
      return url;
    }
    merge(newUrlPart, wholeUrl) {
      return newUrlPart;
    }
    static ɵfac = (() => function DefaultUrlHandlingStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DefaultUrlHandlingStrategy)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DefaultUrlHandlingStrategy,
      factory: DefaultUrlHandlingStrategy.ɵfac,
      providedIn: 'root'
    }))();
  }
  return DefaultUrlHandlingStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/// <reference types="dom-view-transitions" />
const CREATE_VIEW_TRANSITION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'view transition helper' : '');
const VIEW_TRANSITION_OPTIONS = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(ngDevMode ? 'view transition options' : '');
/**
 * A helper function for using browser view transitions. This function skips the call to
 * `startViewTransition` if the browser does not support it.
 *
 * @returns A Promise that resolves when the view transition callback begins.
 */
function createViewTransition(injector, from, to) {
  const transitionOptions = injector.get(VIEW_TRANSITION_OPTIONS);
  const document = injector.get(_angular_common__WEBPACK_IMPORTED_MODULE_32__.DOCUMENT);
  // Create promises outside the Angular zone to avoid causing extra change detections
  return injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone).runOutsideAngular(() => {
    if (!document.startViewTransition || transitionOptions.skipNextTransition) {
      transitionOptions.skipNextTransition = false;
      // The timing of `startViewTransition` is closer to a macrotask. It won't be called
      // until the current event loop exits so we use a promise resolved in a timeout instead
      // of Promise.resolve().
      return new Promise(resolve => setTimeout(resolve));
    }
    let resolveViewTransitionStarted;
    const viewTransitionStarted = new Promise(resolve => {
      resolveViewTransitionStarted = resolve;
    });
    const transition = document.startViewTransition(() => {
      resolveViewTransitionStarted();
      // We don't actually update dom within the transition callback. The resolving of the above
      // promise unblocks the Router navigation, which synchronously activates and deactivates
      // routes (the DOM update). This view transition waits for the next change detection to
      // complete (below), which includes the update phase of the routed components.
      return createRenderPromise(injector);
    });
    const {
      onViewTransitionCreated
    } = transitionOptions;
    if (onViewTransitionCreated) {
      (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(injector, () => onViewTransitionCreated({
        transition,
        from,
        to
      }));
    }
    return viewTransitionStarted;
  });
}
/**
 * Creates a promise that resolves after next render.
 */
function createRenderPromise(injector) {
  return new Promise(resolve => {
    // Wait for the microtask queue to empty after the next render happens (by waiting a macrotask).
    // This ensures any follow-up renders in the microtask queue are completed before the
    // view transition starts animating.
    (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.afterNextRender)({
      read: () => setTimeout(resolve)
    }, {
      injector
    });
  });
}
const NAVIGATION_ERROR_HANDLER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'navigation error handler' : '');
let NavigationTransitions = /*#__PURE__*/(() => {
  class NavigationTransitions {
    currentNavigation = null;
    currentTransition = null;
    lastSuccessfulNavigation = null;
    /**
     * These events are used to communicate back to the Router about the state of the transition. The
     * Router wants to respond to these events in various ways. Because the `NavigationTransition`
     * class is not public, this event subject is not publicly exposed.
     */
    events = (() => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject())();
    /**
     * Used to abort the current transition with an error.
     */
    transitionAbortSubject = (() => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject())();
    configLoader = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(RouterConfigLoader))();
    environmentInjector = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.EnvironmentInjector))();
    urlSerializer = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlSerializer))();
    rootContexts = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ChildrenOutletContexts))();
    location = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_common__WEBPACK_IMPORTED_MODULE_32__.Location))();
    inputBindingEnabled = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(INPUT_BINDER, {
      optional: true
    }) !== null)();
    titleStrategy = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(TitleStrategy))();
    options = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTER_CONFIGURATION, {
      optional: true
    }) || {})();
    paramsInheritanceStrategy = (() => this.options.paramsInheritanceStrategy || 'emptyOnly')();
    urlHandlingStrategy = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlHandlingStrategy))();
    createViewTransition = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(CREATE_VIEW_TRANSITION, {
      optional: true
    }))();
    navigationErrorHandler = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(NAVIGATION_ERROR_HANDLER, {
      optional: true
    }))();
    navigationId = 0;
    get hasRequestedNavigation() {
      return this.navigationId !== 0;
    }
    transitions;
    /**
     * Hook that enables you to pause navigation after the preactivation phase.
     * Used by `RouterModule`.
     *
     * @internal
     */
    afterPreactivation = () => (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(void 0);
    /** @internal */
    rootComponentType = null;
    constructor() {
      const onLoadStart = r => this.events.next(new RouteConfigLoadStart(r));
      const onLoadEnd = r => this.events.next(new RouteConfigLoadEnd(r));
      this.configLoader.onLoadEndListener = onLoadEnd;
      this.configLoader.onLoadStartListener = onLoadStart;
    }
    complete() {
      this.transitions?.complete();
    }
    handleNavigationRequest(request) {
      const id = ++this.navigationId;
      this.transitions?.next({
        ...this.transitions.value,
        ...request,
        id
      });
    }
    setupNavigations(router, initialUrlTree, initialRouterState) {
      this.transitions = new rxjs__WEBPACK_IMPORTED_MODULE_4__.BehaviorSubject({
        id: 0,
        currentUrlTree: initialUrlTree,
        currentRawUrl: initialUrlTree,
        extractedUrl: this.urlHandlingStrategy.extract(initialUrlTree),
        urlAfterRedirects: this.urlHandlingStrategy.extract(initialUrlTree),
        rawUrl: initialUrlTree,
        extras: {},
        resolve: () => {},
        reject: () => {},
        promise: Promise.resolve(true),
        source: IMPERATIVE_NAVIGATION,
        restoredState: null,
        currentSnapshot: initialRouterState.snapshot,
        targetSnapshot: null,
        currentRouterState: initialRouterState,
        targetRouterState: null,
        guards: {
          canActivateChecks: [],
          canDeactivateChecks: []
        },
        guardsResult: null
      });
      return this.transitions.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(t => t.id !== 0),
      // Extract URL
      (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(t => ({
        ...t,
        extractedUrl: this.urlHandlingStrategy.extract(t.rawUrl)
      })),
      // Using switchMap so we cancel executing navigations when a new one comes in
      (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(overallTransitionState => {
        let completed = false;
        let errored = false;
        return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(overallTransitionState).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(t => {
          // It is possible that `switchMap` fails to cancel previous navigations if a new one happens synchronously while the operator
          // is processing the `next` notification of that previous navigation. This can happen when a new navigation (say 2) cancels a
          // previous one (1) and yet another navigation (3) happens synchronously in response to the `NavigationCancel` event for (1).
          // https://github.com/ReactiveX/rxjs/issues/7455
          if (this.navigationId > overallTransitionState.id) {
            const cancellationReason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : '';
            this.cancelNavigationTransition(overallTransitionState, cancellationReason, NavigationCancellationCode.SupersededByNewNavigation);
            return rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY;
          }
          this.currentTransition = overallTransitionState;
          // Store the Navigation object
          this.currentNavigation = {
            id: t.id,
            initialUrl: t.rawUrl,
            extractedUrl: t.extractedUrl,
            targetBrowserUrl: typeof t.extras.browserUrl === 'string' ? this.urlSerializer.parse(t.extras.browserUrl) : t.extras.browserUrl,
            trigger: t.source,
            extras: t.extras,
            previousNavigation: !this.lastSuccessfulNavigation ? null : {
              ...this.lastSuccessfulNavigation,
              previousNavigation: null
            }
          };
          const urlTransition = !router.navigated || this.isUpdatingInternalState() || this.isUpdatedBrowserUrl();
          const onSameUrlNavigation = t.extras.onSameUrlNavigation ?? router.onSameUrlNavigation;
          if (!urlTransition && onSameUrlNavigation !== 'reload') {
            const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation to ${t.rawUrl} was ignored because it is the same as the current Router URL.` : '';
            this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.rawUrl), reason, NavigationSkippedCode.IgnoredSameUrlNavigation));
            t.resolve(false);
            return rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY;
          }
          if (this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl)) {
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t).pipe(
            // Fire NavigationStart event
            (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(t => {
              const transition = this.transitions?.getValue();
              this.events.next(new NavigationStart(t.id, this.urlSerializer.serialize(t.extractedUrl), t.source, t.restoredState));
              if (transition !== this.transitions?.getValue()) {
                return rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY;
              }
              // This delay is required to match old behavior that forced
              // navigation to always be async
              return Promise.resolve(t);
            }),
            // Recognize
            recognize(this.environmentInjector, this.configLoader, this.rootComponentType, router.config, this.urlSerializer, this.paramsInheritanceStrategy),
            // Update URL if in `eager` update mode
            (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(t => {
              overallTransitionState.targetSnapshot = t.targetSnapshot;
              overallTransitionState.urlAfterRedirects = t.urlAfterRedirects;
              this.currentNavigation = {
                ...this.currentNavigation,
                finalUrl: t.urlAfterRedirects
              };
              // Fire RoutesRecognized
              const routesRecognized = new RoutesRecognized(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
              this.events.next(routesRecognized);
            }));
          } else if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(t.currentRawUrl)) {
            /* When the current URL shouldn't be processed, but the previous one
             * was, we handle this "error condition" by navigating to the
             * previously successful URL, but leaving the URL intact.*/
            const {
              id,
              extractedUrl,
              source,
              restoredState,
              extras
            } = t;
            const navStart = new NavigationStart(id, this.urlSerializer.serialize(extractedUrl), source, restoredState);
            this.events.next(navStart);
            const targetSnapshot = createEmptyState(this.rootComponentType).snapshot;
            this.currentTransition = overallTransitionState = {
              ...t,
              targetSnapshot,
              urlAfterRedirects: extractedUrl,
              extras: {
                ...extras,
                skipLocationChange: false,
                replaceUrl: false
              }
            };
            this.currentNavigation.finalUrl = extractedUrl;
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(overallTransitionState);
          } else {
            /* When neither the current or previous URL can be processed, do
             * nothing other than update router's internal reference to the
             * current "settled" URL. This way the next navigation will be coming
             * from the current URL in the browser.
             */
            const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation was ignored because the UrlHandlingStrategy` + ` indicated neither the current URL ${t.currentRawUrl} nor target URL ${t.rawUrl} should be processed.` : '';
            this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, NavigationSkippedCode.IgnoredByUrlHandlingStrategy));
            t.resolve(false);
            return rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY;
          }
        }),
        // --- GUARDS ---
        (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(t => {
          const guardsStart = new GuardsCheckStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
          this.events.next(guardsStart);
        }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(t => {
          this.currentTransition = overallTransitionState = {
            ...t,
            guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, this.rootContexts)
          };
          return overallTransitionState;
        }), checkGuards(this.environmentInjector, evt => this.events.next(evt)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(t => {
          overallTransitionState.guardsResult = t.guardsResult;
          if (t.guardsResult && typeof t.guardsResult !== 'boolean') {
            throw redirectingNavigationError(this.urlSerializer, t.guardsResult);
          }
          const guardsEnd = new GuardsCheckEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);
          this.events.next(guardsEnd);
        }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(t => {
          if (!t.guardsResult) {
            this.cancelNavigationTransition(t, '', NavigationCancellationCode.GuardRejected);
            return false;
          }
          return true;
        }),
        // --- RESOLVE ---
        switchTap(t => {
          if (t.guards.canActivateChecks.length) {
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(t => {
              const resolveStart = new ResolveStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
              this.events.next(resolveStart);
            }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(t => {
              let dataResolved = false;
              return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(t).pipe(resolveData(this.paramsInheritanceStrategy, this.environmentInjector), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)({
                next: () => dataResolved = true,
                complete: () => {
                  if (!dataResolved) {
                    this.cancelNavigationTransition(t, typeof ngDevMode === 'undefined' || ngDevMode ? `At least one route resolver didn't emit any value.` : '', NavigationCancellationCode.NoDataFromResolver);
                  }
                }
              }));
            }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(t => {
              const resolveEnd = new ResolveEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
              this.events.next(resolveEnd);
            }));
          }
          return undefined;
        }),
        // --- LOAD COMPONENTS ---
        switchTap(t => {
          const loadComponents = route => {
            const loaders = [];
            if (route.routeConfig?.loadComponent && !route.routeConfig._loadedComponent) {
              loaders.push(this.configLoader.loadComponent(route.routeConfig).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(loadedComponent => {
                route.component = loadedComponent;
              }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(() => void 0)));
            }
            for (const child of route.children) {
              loaders.push(...loadComponents(child));
            }
            return loaders;
          };
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.combineLatest)(loadComponents(t.targetSnapshot.root)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_22__.defaultIfEmpty)(null), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.take)(1));
        }), switchTap(() => this.afterPreactivation()), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.switchMap)(() => {
          const {
            currentSnapshot,
            targetSnapshot
          } = overallTransitionState;
          const viewTransitionStarted = this.createViewTransition?.(this.environmentInjector, currentSnapshot.root, targetSnapshot.root);
          // If view transitions are enabled, block the navigation until the view
          // transition callback starts. Otherwise, continue immediately.
          return viewTransitionStarted ? (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(viewTransitionStarted).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(() => overallTransitionState)) : (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(overallTransitionState);
        }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(t => {
          const targetRouterState = createRouterState(router.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);
          this.currentTransition = overallTransitionState = {
            ...t,
            targetRouterState
          };
          this.currentNavigation.targetRouterState = targetRouterState;
          return overallTransitionState;
        }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(() => {
          this.events.next(new BeforeActivateRoutes());
        }), activateRoutes(this.rootContexts, router.routeReuseStrategy, evt => this.events.next(evt), this.inputBindingEnabled),
        // Ensure that if some observable used to drive the transition doesn't
        // complete, the navigation still finalizes This should never happen, but
        // this is done as a safety measure to avoid surfacing this error (#49567).
        (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.take)(1), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)({
          next: t => {
            completed = true;
            this.lastSuccessfulNavigation = this.currentNavigation;
            this.events.next(new NavigationEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects)));
            this.titleStrategy?.updateTitle(t.targetRouterState.snapshot);
            t.resolve(true);
          },
          complete: () => {
            completed = true;
          }
        }),
        // There used to be a lot more logic happening directly within the
        // transition Observable. Some of this logic has been refactored out to
        // other places but there may still be errors that happen there. This gives
        // us a way to cancel the transition from the outside. This may also be
        // required in the future to support something like the abort signal of the
        // Navigation API where the navigation gets aborted from outside the
        // transition.
        (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_33__.takeUntil)(this.transitionAbortSubject.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_18__.tap)(err => {
          throw err;
        }))), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_28__.finalize)(() => {
          /* When the navigation stream finishes either through error or success,
           * we set the `completed` or `errored` flag. However, there are some
           * situations where we could get here without either of those being set.
           * For instance, a redirect during NavigationStart. Therefore, this is a
           * catch-all to make sure the NavigationCancel event is fired when a
           * navigation gets cancelled but not caught by other means. */
          if (!completed && !errored) {
            const cancelationReason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : '';
            this.cancelNavigationTransition(overallTransitionState, cancelationReason, NavigationCancellationCode.SupersededByNewNavigation);
          }
          // Only clear current navigation if it is still set to the one that
          // finalized.
          if (this.currentTransition?.id === overallTransitionState.id) {
            this.currentNavigation = null;
            this.currentTransition = null;
          }
        }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(e => {
          errored = true;
          /* This error type is issued during Redirect, and is handled as a
           * cancellation rather than an error. */
          if (isNavigationCancelingError(e)) {
            this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e.message, e.cancellationCode));
            // When redirecting, we need to delay resolving the navigation
            // promise and push it to the redirect navigation
            if (!isRedirectingNavigationCancelingError(e)) {
              overallTransitionState.resolve(false);
            } else {
              this.events.next(new RedirectRequest(e.url, e.navigationBehaviorOptions));
            }
            /* All other errors should reset to the router's internal URL reference
             * to the pre-error state. */
          } else {
            const navigationError = new NavigationError(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e, overallTransitionState.targetSnapshot ?? undefined);
            try {
              const navigationErrorHandlerResult = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.runInInjectionContext)(this.environmentInjector, () => this.navigationErrorHandler?.(navigationError));
              if (navigationErrorHandlerResult instanceof RedirectCommand) {
                const {
                  message,
                  cancellationCode
                } = redirectingNavigationError(this.urlSerializer, navigationErrorHandlerResult);
                this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), message, cancellationCode));
                this.events.next(new RedirectRequest(navigationErrorHandlerResult.redirectTo, navigationErrorHandlerResult.navigationBehaviorOptions));
              } else {
                this.events.next(navigationError);
                throw e;
              }
            } catch (ee) {
              // TODO(atscott): consider flipping the default behavior of
              // resolveNavigationPromiseOnError to be `resolve(false)` when
              // undefined. This is the most sane thing to do given that
              // applications very rarely handle the promise rejection and, as a
              // result, would get "unhandled promise rejection" console logs.
              // The vast majority of applications would not be affected by this
              // change so omitting a migration seems reasonable. Instead,
              // applications that rely on rejection can specifically opt-in to the
              // old behavior.
              if (this.options.resolveNavigationPromiseOnError) {
                overallTransitionState.resolve(false);
              } else {
                overallTransitionState.reject(ee);
              }
            }
          }
          return rxjs__WEBPACK_IMPORTED_MODULE_25__.EMPTY;
        }));
        // casting because `pipe` returns observable({}) when called with 8+ arguments
      }));
    }
    cancelNavigationTransition(t, reason, code) {
      const navCancel = new NavigationCancel(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, code);
      this.events.next(navCancel);
      t.resolve(false);
    }
    /**
     * @returns Whether we're navigating to somewhere that is not what the Router is
     * currently set to.
     */
    isUpdatingInternalState() {
      // TODO(atscott): The serializer should likely be used instead of
      // `UrlTree.toString()`. Custom serializers are often written to handle
      // things better than the default one (objects, for example will be
      // [Object object] with the custom serializer and be "the same" when they
      // aren't).
      // (Same for isUpdatedBrowserUrl)
      return this.currentTransition?.extractedUrl.toString() !== this.currentTransition?.currentUrlTree.toString();
    }
    /**
     * @returns Whether we're updating the browser URL to something new (navigation is going
     * to somewhere not displayed in the URL bar and we will update the URL
     * bar if navigation succeeds).
     */
    isUpdatedBrowserUrl() {
      // The extracted URL is the part of the URL that this application cares about. `extract` may
      // return only part of the browser URL and that part may have not changed even if some other
      // portion of the URL did.
      const currentBrowserUrl = this.urlHandlingStrategy.extract(this.urlSerializer.parse(this.location.path(true)));
      const targetBrowserUrl = this.currentNavigation?.targetBrowserUrl ?? this.currentNavigation?.extractedUrl;
      return currentBrowserUrl.toString() !== targetBrowserUrl?.toString() && !this.currentNavigation?.extras.skipLocationChange;
    }
    static ɵfac = (() => function NavigationTransitions_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NavigationTransitions)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: NavigationTransitions,
      factory: NavigationTransitions.ɵfac,
      providedIn: 'root'
    }))();
  }
  return NavigationTransitions;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function isBrowserTriggeredNavigation(source) {
  return source !== IMPERATIVE_NAVIGATION;
}

/**
 * @description
 *
 * Provides a way to customize when activated routes get reused.
 *
 * @publicApi
 */
let RouteReuseStrategy = /*#__PURE__*/(() => {
  class RouteReuseStrategy {
    static ɵfac = (() => function RouteReuseStrategy_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouteReuseStrategy)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: RouteReuseStrategy,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(DefaultRouteReuseStrategy))(),
      providedIn: 'root'
    }))();
  }
  return RouteReuseStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 *
 * This base route reuse strategy only reuses routes when the matched router configs are
 * identical. This prevents components from being destroyed and recreated
 * when just the route parameters, query parameters or fragment change
 * (that is, the existing component is _reused_).
 *
 * This strategy does not store any routes for later reuse.
 *
 * Angular uses this strategy by default.
 *
 *
 * It can be used as a base class for custom route reuse strategies, i.e. you can create your own
 * class that extends the `BaseRouteReuseStrategy` one.
 * @publicApi
 */
class BaseRouteReuseStrategy {
  /**
   * Whether the given route should detach for later reuse.
   * Always returns false for `BaseRouteReuseStrategy`.
   * */
  shouldDetach(route) {
    return false;
  }
  /**
   * A no-op; the route is never stored since this strategy never detaches routes for later re-use.
   */
  store(route, detachedTree) {}
  /** Returns `false`, meaning the route (and its subtree) is never reattached */
  shouldAttach(route) {
    return false;
  }
  /** Returns `null` because this strategy does not store routes for later re-use. */
  retrieve(route) {
    return null;
  }
  /**
   * Determines if a route should be reused.
   * This strategy returns `true` when the future route config and current route config are
   * identical.
   */
  shouldReuseRoute(future, curr) {
    return future.routeConfig === curr.routeConfig;
  }
}
let DefaultRouteReuseStrategy = /*#__PURE__*/(() => {
  class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵDefaultRouteReuseStrategy_BaseFactory;
      return function DefaultRouteReuseStrategy_Factory(__ngFactoryType__) {
        return (ɵDefaultRouteReuseStrategy_BaseFactory || (ɵDefaultRouteReuseStrategy_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetInheritedFactory"](DefaultRouteReuseStrategy)))(__ngFactoryType__ || DefaultRouteReuseStrategy);
      };
    })())();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DefaultRouteReuseStrategy,
      factory: DefaultRouteReuseStrategy.ɵfac,
      providedIn: 'root'
    }))();
  }
  return DefaultRouteReuseStrategy;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
let StateManager = /*#__PURE__*/(() => {
  class StateManager {
    static ɵfac = (() => function StateManager_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || StateManager)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: StateManager,
      factory: () => (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(HistoryStateManager))(),
      providedIn: 'root'
    }))();
  }
  return StateManager;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
let HistoryStateManager = /*#__PURE__*/(() => {
  class HistoryStateManager extends StateManager {
    location = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_common__WEBPACK_IMPORTED_MODULE_32__.Location))();
    urlSerializer = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlSerializer))();
    options = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTER_CONFIGURATION, {
      optional: true
    }) || {})();
    canceledNavigationResolution = (() => this.options.canceledNavigationResolution || 'replace')();
    urlHandlingStrategy = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlHandlingStrategy))();
    urlUpdateStrategy = (() => this.options.urlUpdateStrategy || 'deferred')();
    currentUrlTree = (() => new UrlTree())();
    getCurrentUrlTree() {
      return this.currentUrlTree;
    }
    rawUrlTree = this.currentUrlTree;
    getRawUrlTree() {
      return this.rawUrlTree;
    }
    /**
     * The id of the currently active page in the router.
     * Updated to the transition's target id on a successful navigation.
     *
     * This is used to track what page the router last activated. When an attempted navigation fails,
     * the router can then use this to compute how to restore the state back to the previously active
     * page.
     */
    currentPageId = 0;
    lastSuccessfulId = (() => -1)();
    restoredState() {
      return this.location.getState();
    }
    /**
     * The ɵrouterPageId of whatever page is currently active in the browser history. This is
     * important for computing the target page id for new navigations because we need to ensure each
     * page id in the browser history is 1 more than the previous entry.
     */
    get browserPageId() {
      if (this.canceledNavigationResolution !== 'computed') {
        return this.currentPageId;
      }
      return this.restoredState()?.ɵrouterPageId ?? this.currentPageId;
    }
    routerState = (() => createEmptyState(null))();
    getRouterState() {
      return this.routerState;
    }
    stateMemento = this.createStateMemento();
    createStateMemento() {
      return {
        rawUrlTree: this.rawUrlTree,
        currentUrlTree: this.currentUrlTree,
        routerState: this.routerState
      };
    }
    registerNonRouterCurrentEntryChangeListener(listener) {
      return this.location.subscribe(event => {
        if (event['type'] === 'popstate') {
          listener(event['url'], event.state);
        }
      });
    }
    handleRouterEvent(e, currentTransition) {
      if (e instanceof NavigationStart) {
        this.stateMemento = this.createStateMemento();
      } else if (e instanceof NavigationSkipped) {
        this.rawUrlTree = currentTransition.initialUrl;
      } else if (e instanceof RoutesRecognized) {
        if (this.urlUpdateStrategy === 'eager') {
          if (!currentTransition.extras.skipLocationChange) {
            const rawUrl = this.urlHandlingStrategy.merge(currentTransition.finalUrl, currentTransition.initialUrl);
            this.setBrowserUrl(currentTransition.targetBrowserUrl ?? rawUrl, currentTransition);
          }
        }
      } else if (e instanceof BeforeActivateRoutes) {
        this.currentUrlTree = currentTransition.finalUrl;
        this.rawUrlTree = this.urlHandlingStrategy.merge(currentTransition.finalUrl, currentTransition.initialUrl);
        this.routerState = currentTransition.targetRouterState;
        if (this.urlUpdateStrategy === 'deferred' && !currentTransition.extras.skipLocationChange) {
          this.setBrowserUrl(currentTransition.targetBrowserUrl ?? this.rawUrlTree, currentTransition);
        }
      } else if (e instanceof NavigationCancel && (e.code === NavigationCancellationCode.GuardRejected || e.code === NavigationCancellationCode.NoDataFromResolver)) {
        this.restoreHistory(currentTransition);
      } else if (e instanceof NavigationError) {
        this.restoreHistory(currentTransition, true);
      } else if (e instanceof NavigationEnd) {
        this.lastSuccessfulId = e.id;
        this.currentPageId = this.browserPageId;
      }
    }
    setBrowserUrl(url, transition) {
      const path = url instanceof UrlTree ? this.urlSerializer.serialize(url) : url;
      if (this.location.isCurrentPathEqualTo(path) || !!transition.extras.replaceUrl) {
        // replacements do not update the target page
        const currentBrowserPageId = this.browserPageId;
        const state = {
          ...transition.extras.state,
          ...this.generateNgRouterState(transition.id, currentBrowserPageId)
        };
        this.location.replaceState(path, '', state);
      } else {
        const state = {
          ...transition.extras.state,
          ...this.generateNgRouterState(transition.id, this.browserPageId + 1)
        };
        this.location.go(path, '', state);
      }
    }
    /**
     * Performs the necessary rollback action to restore the browser URL to the
     * state before the transition.
     */
    restoreHistory(navigation, restoringFromCaughtError = false) {
      if (this.canceledNavigationResolution === 'computed') {
        const currentBrowserPageId = this.browserPageId;
        const targetPagePosition = this.currentPageId - currentBrowserPageId;
        if (targetPagePosition !== 0) {
          this.location.historyGo(targetPagePosition);
        } else if (this.currentUrlTree === navigation.finalUrl && targetPagePosition === 0) {
          // We got to the activation stage (where currentUrlTree is set to the navigation's
          // finalUrl), but we weren't moving anywhere in history (skipLocationChange or replaceUrl).
          // We still need to reset the router state back to what it was when the navigation started.
          this.resetState(navigation);
          this.resetUrlToCurrentUrlTree();
        } else {
          // The browser URL and router state was not updated before the navigation cancelled so
          // there's no restoration needed.
        }
      } else if (this.canceledNavigationResolution === 'replace') {
        // TODO(atscott): It seems like we should _always_ reset the state here. It would be a no-op
        // for `deferred` navigations that haven't change the internal state yet because guards
        // reject. For 'eager' navigations, it seems like we also really should reset the state
        // because the navigation was cancelled. Investigate if this can be done by running TGP.
        if (restoringFromCaughtError) {
          this.resetState(navigation);
        }
        this.resetUrlToCurrentUrlTree();
      }
    }
    resetState(navigation) {
      this.routerState = this.stateMemento.routerState;
      this.currentUrlTree = this.stateMemento.currentUrlTree;
      // Note here that we use the urlHandlingStrategy to get the reset `rawUrlTree` because it may be
      // configured to handle only part of the navigation URL. This means we would only want to reset
      // the part of the navigation handled by the Angular router rather than the whole URL. In
      // addition, the URLHandlingStrategy may be configured to specifically preserve parts of the URL
      // when merging, such as the query params so they are not lost on a refresh.
      this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, navigation.finalUrl ?? this.rawUrlTree);
    }
    resetUrlToCurrentUrlTree() {
      this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', this.generateNgRouterState(this.lastSuccessfulId, this.currentPageId));
    }
    generateNgRouterState(navigationId, routerPageId) {
      if (this.canceledNavigationResolution === 'computed') {
        return {
          navigationId,
          ɵrouterPageId: routerPageId
        };
      }
      return {
        navigationId
      };
    }
    static ɵfac = (() => /* @__PURE__ */(() => {
      let ɵHistoryStateManager_BaseFactory;
      return function HistoryStateManager_Factory(__ngFactoryType__) {
        return (ɵHistoryStateManager_BaseFactory || (ɵHistoryStateManager_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetInheritedFactory"](HistoryStateManager)))(__ngFactoryType__ || HistoryStateManager);
      };
    })())();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: HistoryStateManager,
      factory: HistoryStateManager.ɵfac,
      providedIn: 'root'
    }))();
  }
  return HistoryStateManager;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
var NavigationResult = /*#__PURE__*/function (NavigationResult) {
  NavigationResult[NavigationResult["COMPLETE"] = 0] = "COMPLETE";
  NavigationResult[NavigationResult["FAILED"] = 1] = "FAILED";
  NavigationResult[NavigationResult["REDIRECTING"] = 2] = "REDIRECTING";
  return NavigationResult;
}(NavigationResult || {});
/**
 * Performs the given action once the router finishes its next/current navigation.
 *
 * The navigation is considered complete under the following conditions:
 * - `NavigationCancel` event emits and the code is not `NavigationCancellationCode.Redirect` or
 * `NavigationCancellationCode.SupersededByNewNavigation`. In these cases, the
 * redirecting/superseding navigation must finish.
 * - `NavigationError`, `NavigationEnd`, or `NavigationSkipped` event emits
 */
function afterNextNavigation(router, action) {
  router.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(e => e instanceof NavigationEnd || e instanceof NavigationCancel || e instanceof NavigationError || e instanceof NavigationSkipped), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.map)(e => {
    if (e instanceof NavigationEnd || e instanceof NavigationSkipped) {
      return NavigationResult.COMPLETE;
    }
    const redirecting = e instanceof NavigationCancel ? e.code === NavigationCancellationCode.Redirect || e.code === NavigationCancellationCode.SupersededByNewNavigation : false;
    return redirecting ? NavigationResult.REDIRECTING : NavigationResult.FAILED;
  }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(result => result !== NavigationResult.REDIRECTING), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.take)(1)).subscribe(() => {
    action();
  });
}
function defaultErrorHandler(error) {
  throw error;
}
/**
 * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `true`
 * (exact = true).
 */
const exactMatchOptions = {
  paths: 'exact',
  fragment: 'ignored',
  matrixParams: 'ignored',
  queryParams: 'exact'
};
/**
 * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `false`
 * (exact = false).
 */
const subsetMatchOptions = {
  paths: 'subset',
  fragment: 'ignored',
  matrixParams: 'ignored',
  queryParams: 'subset'
};
/**
 * @description
 *
 * A service that facilitates navigation among views and URL manipulation capabilities.
 * This service is provided in the root scope and configured with [provideRouter](api/router/provideRouter).
 *
 * @see {@link Route}
 * @see {@link provideRouter}
 * @see [Routing and Navigation Guide](guide/routing/common-router-tasks).
 *
 * @ngModule RouterModule
 *
 * @publicApi
 */
let Router = /*#__PURE__*/(() => {
  class Router {
    get currentUrlTree() {
      return this.stateManager.getCurrentUrlTree();
    }
    get rawUrlTree() {
      return this.stateManager.getRawUrlTree();
    }
    disposed = false;
    nonRouterCurrentEntryChangeSubscription;
    console = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]))();
    stateManager = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(StateManager))();
    options = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTER_CONFIGURATION, {
      optional: true
    }) || {})();
    pendingTasks = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵPendingTasks"]))();
    urlUpdateStrategy = (() => this.options.urlUpdateStrategy || 'deferred')();
    navigationTransitions = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(NavigationTransitions))();
    urlSerializer = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlSerializer))();
    location = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_common__WEBPACK_IMPORTED_MODULE_32__.Location))();
    urlHandlingStrategy = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlHandlingStrategy))();
    /**
     * The private `Subject` type for the public events exposed in the getter. This is used internally
     * to push events to. The separate field allows us to expose separate types in the public API
     * (i.e., an Observable rather than the Subject).
     */
    _events = (() => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject())();
    /**
     * An event stream for routing events.
     */
    get events() {
      // TODO(atscott): This _should_ be events.asObservable(). However, this change requires internal
      // cleanup: tests are doing `(route.events as Subject<Event>).next(...)`. This isn't
      // allowed/supported but we still have to fix these or file bugs against the teams before making
      // the change.
      return this._events;
    }
    /**
     * The current state of routing in this NgModule.
     */
    get routerState() {
      return this.stateManager.getRouterState();
    }
    /**
     * True if at least one navigation event has occurred,
     * false otherwise.
     */
    navigated = false;
    /**
     * A strategy for re-using routes.
     *
     * @deprecated Configure using `providers` instead:
     *   `{provide: RouteReuseStrategy, useClass: MyStrategy}`.
     */
    routeReuseStrategy = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(RouteReuseStrategy))();
    /**
     * How to handle a navigation request to the current URL.
     *
     *
     * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
     * @see {@link withRouterConfig}
     * @see {@link provideRouter}
     * @see {@link RouterModule}
     */
    onSameUrlNavigation = (() => this.options.onSameUrlNavigation || 'ignore')();
    config = (() => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTES, {
      optional: true
    })?.flat() ?? [])();
    /**
     * Indicates whether the application has opted in to binding Router data to component inputs.
     *
     * This option is enabled by the `withComponentInputBinding` feature of `provideRouter` or
     * `bindToComponentInputs` in the `ExtraOptions` of `RouterModule.forRoot`.
     */
    componentInputBindingEnabled = (() => !!(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(INPUT_BINDER, {
      optional: true
    }))();
    constructor() {
      this.resetConfig(this.config);
      this.navigationTransitions.setupNavigations(this, this.currentUrlTree, this.routerState).subscribe({
        error: e => {
          this.console.warn(ngDevMode ? `Unhandled Navigation Error: ${e}` : e);
        }
      });
      this.subscribeToNavigationEvents();
    }
    eventsSubscription = (() => new rxjs__WEBPACK_IMPORTED_MODULE_34__.Subscription())();
    subscribeToNavigationEvents() {
      const subscription = this.navigationTransitions.events.subscribe(e => {
        try {
          const currentTransition = this.navigationTransitions.currentTransition;
          const currentNavigation = this.navigationTransitions.currentNavigation;
          if (currentTransition !== null && currentNavigation !== null) {
            this.stateManager.handleRouterEvent(e, currentNavigation);
            if (e instanceof NavigationCancel && e.code !== NavigationCancellationCode.Redirect && e.code !== NavigationCancellationCode.SupersededByNewNavigation) {
              // It seems weird that `navigated` is set to `true` when the navigation is rejected,
              // however it's how things were written initially. Investigation would need to be done
              // to determine if this can be removed.
              this.navigated = true;
            } else if (e instanceof NavigationEnd) {
              this.navigated = true;
            } else if (e instanceof RedirectRequest) {
              const opts = e.navigationBehaviorOptions;
              const mergedTree = this.urlHandlingStrategy.merge(e.url, currentTransition.currentRawUrl);
              const extras = {
                browserUrl: currentTransition.extras.browserUrl,
                info: currentTransition.extras.info,
                skipLocationChange: currentTransition.extras.skipLocationChange,
                // The URL is already updated at this point if we have 'eager' URL
                // updates or if the navigation was triggered by the browser (back
                // button, URL bar, etc). We want to replace that item in history
                // if the navigation is rejected.
                replaceUrl: currentTransition.extras.replaceUrl || this.urlUpdateStrategy === 'eager' || isBrowserTriggeredNavigation(currentTransition.source),
                // allow developer to override default options with RedirectCommand
                ...opts
              };
              this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras, {
                resolve: currentTransition.resolve,
                reject: currentTransition.reject,
                promise: currentTransition.promise
              });
            }
          }
          // Note that it's important to have the Router process the events _before_ the event is
          // pushed through the public observable. This ensures the correct router state is in place
          // before applications observe the events.
          if (isPublicRouterEvent(e)) {
            this._events.next(e);
          }
        } catch (e) {
          this.navigationTransitions.transitionAbortSubject.next(e);
        }
      });
      this.eventsSubscription.add(subscription);
    }
    /** @internal */
    resetRootComponentType(rootComponentType) {
      // TODO: vsavkin router 4.0 should make the root component set to null
      // this will simplify the lifecycle of the router.
      this.routerState.root.component = rootComponentType;
      this.navigationTransitions.rootComponentType = rootComponentType;
    }
    /**
     * Sets up the location change listener and performs the initial navigation.
     */
    initialNavigation() {
      this.setUpLocationChangeListener();
      if (!this.navigationTransitions.hasRequestedNavigation) {
        this.navigateToSyncWithBrowser(this.location.path(true), IMPERATIVE_NAVIGATION, this.stateManager.restoredState());
      }
    }
    /**
     * Sets up the location change listener. This listener detects navigations triggered from outside
     * the Router (the browser back/forward buttons, for example) and schedules a corresponding Router
     * navigation so that the correct events, guards, etc. are triggered.
     */
    setUpLocationChangeListener() {
      // Don't need to use Zone.wrap any more, because zone.js
      // already patch onPopState, so location change callback will
      // run into ngZone
      this.nonRouterCurrentEntryChangeSubscription ??= this.stateManager.registerNonRouterCurrentEntryChangeListener((url, state) => {
        // The `setTimeout` was added in #12160 and is likely to support Angular/AngularJS
        // hybrid apps.
        setTimeout(() => {
          this.navigateToSyncWithBrowser(url, 'popstate', state);
        }, 0);
      });
    }
    /**
     * Schedules a router navigation to synchronize Router state with the browser state.
     *
     * This is done as a response to a popstate event and the initial navigation. These
     * two scenarios represent times when the browser URL/state has been updated and
     * the Router needs to respond to ensure its internal state matches.
     */
    navigateToSyncWithBrowser(url, source, state) {
      const extras = {
        replaceUrl: true
      };
      // TODO: restoredState should always include the entire state, regardless
      // of navigationId. This requires a breaking change to update the type on
      // NavigationStart’s restoredState, which currently requires navigationId
      // to always be present. The Router used to only restore history state if
      // a navigationId was present.
      // The stored navigationId is used by the RouterScroller to retrieve the scroll
      // position for the page.
      const restoredState = state?.navigationId ? state : null;
      // Separate to NavigationStart.restoredState, we must also restore the state to
      // history.state and generate a new navigationId, since it will be overwritten
      if (state) {
        const stateCopy = {
          ...state
        };
        delete stateCopy.navigationId;
        delete stateCopy.ɵrouterPageId;
        if (Object.keys(stateCopy).length !== 0) {
          extras.state = stateCopy;
        }
      }
      const urlTree = this.parseUrl(url);
      this.scheduleNavigation(urlTree, source, restoredState, extras);
    }
    /** The current URL. */
    get url() {
      return this.serializeUrl(this.currentUrlTree);
    }
    /**
     * Returns the current `Navigation` object when the router is navigating,
     * and `null` when idle.
     */
    getCurrentNavigation() {
      return this.navigationTransitions.currentNavigation;
    }
    /**
     * The `Navigation` object of the most recent navigation to succeed and `null` if there
     *     has not been a successful navigation yet.
     */
    get lastSuccessfulNavigation() {
      return this.navigationTransitions.lastSuccessfulNavigation;
    }
    /**
     * Resets the route configuration used for navigation and generating links.
     *
     * @param config The route array for the new configuration.
     *
     * @usageNotes
     *
     * ```
     * router.resetConfig([
     *  { path: 'team/:id', component: TeamCmp, children: [
     *    { path: 'simple', component: SimpleCmp },
     *    { path: 'user/:name', component: UserCmp }
     *  ]}
     * ]);
     * ```
     */
    resetConfig(config) {
      (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(config);
      this.config = config.map(standardizeConfig);
      this.navigated = false;
    }
    /** @nodoc */
    ngOnDestroy() {
      this.dispose();
    }
    /** Disposes of the router. */
    dispose() {
      this.navigationTransitions.complete();
      if (this.nonRouterCurrentEntryChangeSubscription) {
        this.nonRouterCurrentEntryChangeSubscription.unsubscribe();
        this.nonRouterCurrentEntryChangeSubscription = undefined;
      }
      this.disposed = true;
      this.eventsSubscription.unsubscribe();
    }
    /**
     * Appends URL segments to the current URL tree to create a new URL tree.
     *
     * @param commands An array of URL fragments with which to construct the new URL tree.
     * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
     * segments, followed by the parameters for each segment.
     * The fragments are applied to the current URL tree or the one provided  in the `relativeTo`
     * property of the options object, if supplied.
     * @param navigationExtras Options that control the navigation strategy.
     * @returns The new URL tree.
     *
     * @usageNotes
     *
     * ```
     * // create /team/33/user/11
     * router.createUrlTree(['/team', 33, 'user', 11]);
     *
     * // create /team/33;expand=true/user/11
     * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
     *
     * // you can collapse static segments like this (this works only with the first passed-in value):
     * router.createUrlTree(['/team/33/user', userId]);
     *
     * // If the first segment can contain slashes, and you do not want the router to split it,
     * // you can do the following:
     * router.createUrlTree([{segmentPath: '/one/two'}]);
     *
     * // create /team/33/(user/11//right:chat)
     * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
     *
     * // remove the right secondary node
     * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
     *
     * // assuming the current url is `/team/33/user/11` and the route points to `user/11`
     *
     * // navigate to /team/33/user/11/details
     * router.createUrlTree(['details'], {relativeTo: route});
     *
     * // navigate to /team/33/user/22
     * router.createUrlTree(['../22'], {relativeTo: route});
     *
     * // navigate to /team/44/user/22
     * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
     *
     * Note that a value of `null` or `undefined` for `relativeTo` indicates that the
     * tree should be created relative to the root.
     * ```
     */
    createUrlTree(commands, navigationExtras = {}) {
      const {
        relativeTo,
        queryParams,
        fragment,
        queryParamsHandling,
        preserveFragment
      } = navigationExtras;
      const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
      let q = null;
      switch (queryParamsHandling ?? this.options.defaultQueryParamsHandling) {
        case 'merge':
          q = {
            ...this.currentUrlTree.queryParams,
            ...queryParams
          };
          break;
        case 'preserve':
          q = this.currentUrlTree.queryParams;
          break;
        default:
          q = queryParams || null;
      }
      if (q !== null) {
        q = this.removeEmptyProps(q);
      }
      let relativeToUrlSegmentGroup;
      try {
        const relativeToSnapshot = relativeTo ? relativeTo.snapshot : this.routerState.snapshot.root;
        relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeToSnapshot);
      } catch (e) {
        // This is strictly for backwards compatibility with tests that create
        // invalid `ActivatedRoute` mocks.
        // Note: the difference between having this fallback for invalid `ActivatedRoute` setups and
        // just throwing is ~500 test failures. Fixing all of those tests by hand is not feasible at
        // the moment.
        if (typeof commands[0] !== 'string' || commands[0][0] !== '/') {
          // Navigations that were absolute in the old way of creating UrlTrees
          // would still work because they wouldn't attempt to match the
          // segments in the `ActivatedRoute` to the `currentUrlTree` but
          // instead just replace the root segment with the navigation result.
          // Non-absolute navigations would fail to apply the commands because
          // the logic could not find the segment to replace (so they'd act like there were no
          // commands).
          commands = [];
        }
        relativeToUrlSegmentGroup = this.currentUrlTree.root;
      }
      return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, q, f ?? null);
    }
    /**
     * Navigates to a view using an absolute route path.
     *
     * @param url An absolute path for a defined route. The function does not apply any delta to the
     *     current URL.
     * @param extras An object containing properties that modify the navigation strategy.
     *
     * @returns A Promise that resolves to 'true' when navigation succeeds,
     * to 'false' when navigation fails, or is rejected on error.
     *
     * @usageNotes
     *
     * The following calls request navigation to an absolute path.
     *
     * ```
     * router.navigateByUrl("/team/33/user/11");
     *
     * // Navigate without updating the URL
     * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
     * ```
     *
     * @see [Routing and Navigation guide](guide/routing/common-router-tasks)
     *
     */
    navigateByUrl(url, extras = {
      skipLocationChange: false
    }) {
      const urlTree = isUrlTree(url) ? url : this.parseUrl(url);
      const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
      return this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras);
    }
    /**
     * Navigate based on the provided array of commands and a starting point.
     * If no starting route is provided, the navigation is absolute.
     *
     * @param commands An array of URL fragments with which to construct the target URL.
     * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
     * segments, followed by the parameters for each segment.
     * The fragments are applied to the current URL or the one provided  in the `relativeTo` property
     * of the options object, if supplied.
     * @param extras An options object that determines how the URL should be constructed or
     *     interpreted.
     *
     * @returns A Promise that resolves to `true` when navigation succeeds, or `false` when navigation
     *     fails. The Promise is rejected when an error occurs if `resolveNavigationPromiseOnError` is
     * not `true`.
     *
     * @usageNotes
     *
     * The following calls request navigation to a dynamic route path relative to the current URL.
     *
     * ```
     * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
     *
     * // Navigate without updating the URL, overriding the default behavior
     * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
     * ```
     *
     * @see [Routing and Navigation guide](guide/routing/common-router-tasks)
     *
     */
    navigate(commands, extras = {
      skipLocationChange: false
    }) {
      validateCommands(commands);
      return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
    }
    /** Serializes a `UrlTree` into a string */
    serializeUrl(url) {
      return this.urlSerializer.serialize(url);
    }
    /** Parses a string into a `UrlTree` */
    parseUrl(url) {
      try {
        return this.urlSerializer.parse(url);
      } catch {
        return this.urlSerializer.parse('/');
      }
    }
    isActive(url, matchOptions) {
      let options;
      if (matchOptions === true) {
        options = {
          ...exactMatchOptions
        };
      } else if (matchOptions === false) {
        options = {
          ...subsetMatchOptions
        };
      } else {
        options = matchOptions;
      }
      if (isUrlTree(url)) {
        return containsTree(this.currentUrlTree, url, options);
      }
      const urlTree = this.parseUrl(url);
      return containsTree(this.currentUrlTree, urlTree, options);
    }
    removeEmptyProps(params) {
      return Object.entries(params).reduce((result, [key, value]) => {
        if (value !== null && value !== undefined) {
          result[key] = value;
        }
        return result;
      }, {});
    }
    scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) {
      if (this.disposed) {
        return Promise.resolve(false);
      }
      let resolve;
      let reject;
      let promise;
      if (priorPromise) {
        resolve = priorPromise.resolve;
        reject = priorPromise.reject;
        promise = priorPromise.promise;
      } else {
        promise = new Promise((res, rej) => {
          resolve = res;
          reject = rej;
        });
      }
      // Indicate that the navigation is happening.
      const taskId = this.pendingTasks.add();
      afterNextNavigation(this, () => {
        // Remove pending task in a microtask to allow for cancelled
        // initial navigations and redirects within the same task.
        queueMicrotask(() => this.pendingTasks.remove(taskId));
      });
      this.navigationTransitions.handleNavigationRequest({
        source,
        restoredState,
        currentUrlTree: this.currentUrlTree,
        currentRawUrl: this.currentUrlTree,
        rawUrl,
        extras,
        resolve: resolve,
        reject: reject,
        promise,
        currentSnapshot: this.routerState.snapshot,
        currentRouterState: this.routerState
      });
      // Make sure that the error is propagated even though `processNavigations` catch
      // handler does not rethrow
      return promise.catch(e => {
        return Promise.reject(e);
      });
    }
    static ɵfac = (() => function Router_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || Router)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: Router,
      factory: Router.ɵfac,
      providedIn: 'root'
    }))();
  }
  return Router;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function validateCommands(commands) {
  for (let i = 0; i < commands.length; i++) {
    const cmd = commands[i];
    if (cmd == null) {
      throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4008 /* RuntimeErrorCode.NULLISH_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) && `The requested path contains ${cmd} segment at index ${i}`);
    }
  }
}
function isPublicRouterEvent(e) {
  return !(e instanceof BeforeActivateRoutes) && !(e instanceof RedirectRequest);
}

/**
 * @description
 *
 * When applied to an element in a template, makes that element a link
 * that initiates navigation to a route. Navigation opens one or more routed components
 * in one or more `<router-outlet>` locations on the page.
 *
 * Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`,
 * the following creates a static link to the route:
 * `<a routerLink="/user/bob">link to user component</a>`
 *
 * You can use dynamic values to generate the link.
 * For a dynamic link, pass an array of path segments,
 * followed by the params for each segment.
 * For example, `['/team', teamId, 'user', userName, {details: true}]`
 * generates a link to `/team/11/user/bob;details=true`.
 *
 * Multiple static segments can be merged into one term and combined with dynamic segments.
 * For example, `['/team/11/user', userName, {details: true}]`
 *
 * The input that you provide to the link is treated as a delta to the current URL.
 * For instance, suppose the current URL is `/user/(box//aux:team)`.
 * The link `<a [routerLink]="['/user/jim']">Jim</a>` creates the URL
 * `/user/(jim//aux:team)`.
 * See {@link Router#createUrlTree} for more information.
 *
 * @usageNotes
 *
 * You can use absolute or relative paths in a link, set query parameters,
 * control how parameters are handled, and keep a history of navigation states.
 *
 * ### Relative link paths
 *
 * The first segment name can be prepended with `/`, `./`, or `../`.
 * * If the first segment begins with `/`, the router looks up the route from the root of the
 *   app.
 * * If the first segment begins with `./`, or doesn't begin with a slash, the router
 *   looks in the children of the current activated route.
 * * If the first segment begins with `../`, the router goes up one level in the route tree.
 *
 * ### Setting and handling query params and fragments
 *
 * The following link adds a query parameter and a fragment to the generated URL:
 *
 * ```
 * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
 *   link to user component
 * </a>
 * ```
 * By default, the directive constructs the new URL using the given query parameters.
 * The example generates the link: `/user/bob?debug=true#education`.
 *
 * You can instruct the directive to handle query parameters differently
 * by specifying the `queryParamsHandling` option in the link.
 * Allowed values are:
 *
 *  - `'merge'`: Merge the given `queryParams` into the current query params.
 *  - `'preserve'`: Preserve the current query params.
 *
 * For example:
 *
 * ```
 * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
 *   link to user component
 * </a>
 * ```
 *
 * `queryParams`, `fragment`, `queryParamsHandling`, `preserveFragment`, and `relativeTo`
 * cannot be used when the `routerLink` input is a `UrlTree`.
 *
 * See {@link UrlCreationOptions#queryParamsHandling}.
 *
 * ### Preserving navigation history
 *
 * You can provide a `state` value to be persisted to the browser's
 * [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties).
 * For example:
 *
 * ```
 * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">
 *   link to user component
 * </a>
 * ```
 *
 * Use {@link Router#getCurrentNavigation} to retrieve a saved
 * navigation-state value. For example, to capture the `tracingId` during the `NavigationStart`
 * event:
 *
 * ```
 * // Get NavigationStart events
 * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
 *   const navigation = router.getCurrentNavigation();
 *   tracingService.trace({id: navigation.extras.state.tracingId});
 * });
 * ```
 *
 * @ngModule RouterModule
 *
 * @publicApi
 */
let RouterLink = /*#__PURE__*/(() => {
  class RouterLink {
    router;
    route;
    tabIndexAttribute;
    renderer;
    el;
    locationStrategy;
    /**
     * Represents an `href` attribute value applied to a host element,
     * when a host element is `<a>`. For other tags, the value is `null`.
     */
    href = null;
    /**
     * Represents the `target` attribute on a host element.
     * This is only used when the host element is an `<a>` tag.
     */
    target;
    /**
     * Passed to {@link Router#createUrlTree} as part of the
     * `UrlCreationOptions`.
     * @see {@link UrlCreationOptions#queryParams}
     * @see {@link Router#createUrlTree}
     */
    queryParams;
    /**
     * Passed to {@link Router#createUrlTree} as part of the
     * `UrlCreationOptions`.
     * @see {@link UrlCreationOptions#fragment}
     * @see {@link Router#createUrlTree}
     */
    fragment;
    /**
     * Passed to {@link Router#createUrlTree} as part of the
     * `UrlCreationOptions`.
     * @see {@link UrlCreationOptions#queryParamsHandling}
     * @see {@link Router#createUrlTree}
     */
    queryParamsHandling;
    /**
     * Passed to {@link Router#navigateByUrl} as part of the
     * `NavigationBehaviorOptions`.
     * @see {@link NavigationBehaviorOptions#state}
     * @see {@link Router#navigateByUrl}
     */
    state;
    /**
     * Passed to {@link Router#navigateByUrl} as part of the
     * `NavigationBehaviorOptions`.
     * @see {@link NavigationBehaviorOptions#info}
     * @see {@link Router#navigateByUrl}
     */
    info;
    /**
     * Passed to {@link Router#createUrlTree} as part of the
     * `UrlCreationOptions`.
     * Specify a value here when you do not want to use the default value
     * for `routerLink`, which is the current activated route.
     * Note that a value of `undefined` here will use the `routerLink` default.
     * @see {@link UrlCreationOptions#relativeTo}
     * @see {@link Router#createUrlTree}
     */
    relativeTo;
    /** Whether a host element is an `<a>` tag. */
    isAnchorElement;
    subscription;
    /** @internal */
    onChanges = (() => new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject())();
    constructor(router, route, tabIndexAttribute, renderer, el, locationStrategy) {
      this.router = router;
      this.route = route;
      this.tabIndexAttribute = tabIndexAttribute;
      this.renderer = renderer;
      this.el = el;
      this.locationStrategy = locationStrategy;
      const tagName = el.nativeElement.tagName?.toLowerCase();
      this.isAnchorElement = tagName === 'a' || tagName === 'area';
      if (this.isAnchorElement) {
        this.subscription = router.events.subscribe(s => {
          if (s instanceof NavigationEnd) {
            this.updateHref();
          }
        });
      } else {
        this.setTabIndexIfNotOnNativeEl('0');
      }
    }
    /**
     * Passed to {@link Router#createUrlTree} as part of the
     * `UrlCreationOptions`.
     * @see {@link UrlCreationOptions#preserveFragment}
     * @see {@link Router#createUrlTree}
     */
    preserveFragment = false;
    /**
     * Passed to {@link Router#navigateByUrl} as part of the
     * `NavigationBehaviorOptions`.
     * @see {@link NavigationBehaviorOptions#skipLocationChange}
     * @see {@link Router#navigateByUrl}
     */
    skipLocationChange = false;
    /**
     * Passed to {@link Router#navigateByUrl} as part of the
     * `NavigationBehaviorOptions`.
     * @see {@link NavigationBehaviorOptions#replaceUrl}
     * @see {@link Router#navigateByUrl}
     */
    replaceUrl = false;
    /**
     * Modifies the tab index if there was not a tabindex attribute on the element during
     * instantiation.
     */
    setTabIndexIfNotOnNativeEl(newTabIndex) {
      if (this.tabIndexAttribute != null /* both `null` and `undefined` */ || this.isAnchorElement) {
        return;
      }
      this.applyAttributeValue('tabindex', newTabIndex);
    }
    /** @nodoc */
    // TODO(atscott): Remove changes parameter in major version as a breaking change.
    ngOnChanges(changes) {
      if (ngDevMode && isUrlTree(this.routerLinkInput) && (this.fragment !== undefined || this.queryParams || this.queryParamsHandling || this.preserveFragment || this.relativeTo)) {
        throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4016 /* RuntimeErrorCode.INVALID_ROUTER_LINK_INPUTS */, 'Cannot configure queryParams or fragment when using a UrlTree as the routerLink input value.');
      }
      if (this.isAnchorElement) {
        this.updateHref();
      }
      // This is subscribed to by `RouterLinkActive` so that it knows to update when there are changes
      // to the RouterLinks it's tracking.
      this.onChanges.next(this);
    }
    routerLinkInput = null;
    /**
     * Commands to pass to {@link Router#createUrlTree} or a `UrlTree`.
     *   - **array**: commands to pass to {@link Router#createUrlTree}.
     *   - **string**: shorthand for array of commands with just the string, i.e. `['/route']`
     *   - **UrlTree**: a `UrlTree` for this link rather than creating one from the commands
     *     and other inputs that correspond to properties of `UrlCreationOptions`.
     *   - **null|undefined**: effectively disables the `routerLink`
     * @see {@link Router#createUrlTree}
     */
    set routerLink(commandsOrUrlTree) {
      if (commandsOrUrlTree == null) {
        this.routerLinkInput = null;
        this.setTabIndexIfNotOnNativeEl(null);
      } else {
        if (isUrlTree(commandsOrUrlTree)) {
          this.routerLinkInput = commandsOrUrlTree;
        } else {
          this.routerLinkInput = Array.isArray(commandsOrUrlTree) ? commandsOrUrlTree : [commandsOrUrlTree];
        }
        this.setTabIndexIfNotOnNativeEl('0');
      }
    }
    /** @nodoc */
    onClick(button, ctrlKey, shiftKey, altKey, metaKey) {
      const urlTree = this.urlTree;
      if (urlTree === null) {
        return true;
      }
      if (this.isAnchorElement) {
        if (button !== 0 || ctrlKey || shiftKey || altKey || metaKey) {
          return true;
        }
        if (typeof this.target === 'string' && this.target != '_self') {
          return true;
        }
      }
      const extras = {
        skipLocationChange: this.skipLocationChange,
        replaceUrl: this.replaceUrl,
        state: this.state,
        info: this.info
      };
      this.router.navigateByUrl(urlTree, extras);
      // Return `false` for `<a>` elements to prevent default action
      // and cancel the native behavior, since the navigation is handled
      // by the Router.
      return !this.isAnchorElement;
    }
    /** @nodoc */
    ngOnDestroy() {
      this.subscription?.unsubscribe();
    }
    updateHref() {
      const urlTree = this.urlTree;
      this.href = urlTree !== null && this.locationStrategy ? this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree)) : null;
      const sanitizedValue = this.href === null ? null :
      // This class represents a directive that can be added to both `<a>` elements,
      // as well as other elements. As a result, we can't define security context at
      // compile time. So the security context is deferred to runtime.
      // The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function
      // based on the tag and property names. The logic mimics the one from
      // `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time.
      //
      // Note: we should investigate whether we can switch to using `@HostBinding('attr.href')`
      // instead of applying a value via a renderer, after a final merge of the
      // `RouterLinkWithHref` directive.
      (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵsanitizeUrlOrResourceUrl"])(this.href, this.el.nativeElement.tagName.toLowerCase(), 'href');
      this.applyAttributeValue('href', sanitizedValue);
    }
    applyAttributeValue(attrName, attrValue) {
      const renderer = this.renderer;
      const nativeElement = this.el.nativeElement;
      if (attrValue !== null) {
        renderer.setAttribute(nativeElement, attrName, attrValue);
      } else {
        renderer.removeAttribute(nativeElement, attrName);
      }
    }
    get urlTree() {
      if (this.routerLinkInput === null) {
        return null;
      } else if (isUrlTree(this.routerLinkInput)) {
        return this.routerLinkInput;
      }
      return this.router.createUrlTree(this.routerLinkInput, {
        // If the `relativeTo` input is not defined, we want to use `this.route` by default.
        // Otherwise, we should use the value provided by the user in the input.
        relativeTo: this.relativeTo !== undefined ? this.relativeTo : this.route,
        queryParams: this.queryParams,
        fragment: this.fragment,
        queryParamsHandling: this.queryParamsHandling,
        preserveFragment: this.preserveFragment
      });
    }
    static ɵfac = (() => function RouterLink_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterLink)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](ActivatedRoute), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinjectAttribute"]('tabindex'), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_common__WEBPACK_IMPORTED_MODULE_32__.LocationStrategy));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: RouterLink,
      selectors: [["", "routerLink", ""]],
      hostVars: 1,
      hostBindings: function RouterLink_HostBindings(rf, ctx) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵlistener"]("click", function RouterLink_click_HostBindingHandler($event) {
            return ctx.onClick($event.button, $event.ctrlKey, $event.shiftKey, $event.altKey, $event.metaKey);
          });
        }
        if (rf & 2) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵattribute"]("target", ctx.target);
        }
      },
      inputs: {
        target: "target",
        queryParams: "queryParams",
        fragment: "fragment",
        queryParamsHandling: "queryParamsHandling",
        state: "state",
        info: "info",
        relativeTo: "relativeTo",
        preserveFragment: [2, "preserveFragment", "preserveFragment", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        skipLocationChange: [2, "skipLocationChange", "skipLocationChange", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        replaceUrl: [2, "replaceUrl", "replaceUrl", _angular_core__WEBPACK_IMPORTED_MODULE_1__.booleanAttribute],
        routerLink: "routerLink"
      },
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵInputTransformsFeature"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return RouterLink;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 *
 * @description
 *
 * Tracks whether the linked route of an element is currently active, and allows you
 * to specify one or more CSS classes to add to the element when the linked route
 * is active.
 *
 * Use this directive to create a visual distinction for elements associated with an active route.
 * For example, the following code highlights the word "Bob" when the router
 * activates the associated route:
 *
 * ```
 * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
 * ```
 *
 * Whenever the URL is either '/user' or '/user/bob', the "active-link" class is
 * added to the anchor tag. If the URL changes, the class is removed.
 *
 * You can set more than one class using a space-separated string or an array.
 * For example:
 *
 * ```
 * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
 * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
 * ```
 *
 * To add the classes only when the URL matches the link exactly, add the option `exact: true`:
 *
 * ```
 * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
 * true}">Bob</a>
 * ```
 *
 * To directly check the `isActive` status of the link, assign the `RouterLinkActive`
 * instance to a template variable.
 * For example, the following checks the status without assigning any CSS classes:
 *
 * ```
 * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
 *   Bob {{ rla.isActive ? '(already open)' : ''}}
 * </a>
 * ```
 *
 * You can apply the `RouterLinkActive` directive to an ancestor of linked elements.
 * For example, the following sets the active-link class on the `<div>`  parent tag
 * when the URL is either '/user/jim' or '/user/bob'.
 *
 * ```
 * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
 *   <a routerLink="/user/jim">Jim</a>
 *   <a routerLink="/user/bob">Bob</a>
 * </div>
 * ```
 *
 * The `RouterLinkActive` directive can also be used to set the aria-current attribute
 * to provide an alternative distinction for active elements to visually impaired users.
 *
 * For example, the following code adds the 'active' class to the Home Page link when it is
 * indeed active and in such case also sets its aria-current attribute to 'page':
 *
 * ```
 * <a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home Page</a>
 * ```
 *
 * @ngModule RouterModule
 *
 * @publicApi
 */
let RouterLinkActive = /*#__PURE__*/(() => {
  class RouterLinkActive {
    router;
    element;
    renderer;
    cdr;
    link;
    links;
    classes = [];
    routerEventsSubscription;
    linkInputChangesSubscription;
    _isActive = false;
    get isActive() {
      return this._isActive;
    }
    /**
     * Options to configure how to determine if the router link is active.
     *
     * These options are passed to the `Router.isActive()` function.
     *
     * @see {@link Router#isActive}
     */
    routerLinkActiveOptions = {
      exact: false
    };
    /**
     * Aria-current attribute to apply when the router link is active.
     *
     * Possible values: `'page'` | `'step'` | `'location'` | `'date'` | `'time'` | `true` | `false`.
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current}
     */
    ariaCurrentWhenActive;
    /**
     *
     * You can use the output `isActiveChange` to get notified each time the link becomes
     * active or inactive.
     *
     * Emits:
     * true  -> Route is active
     * false -> Route is inactive
     *
     * ```
     * <a
     *  routerLink="/user/bob"
     *  routerLinkActive="active-link"
     *  (isActiveChange)="this.onRouterLinkActive($event)">Bob</a>
     * ```
     */
    isActiveChange = (() => new _angular_core__WEBPACK_IMPORTED_MODULE_1__.EventEmitter())();
    constructor(router, element, renderer, cdr, link) {
      this.router = router;
      this.element = element;
      this.renderer = renderer;
      this.cdr = cdr;
      this.link = link;
      this.routerEventsSubscription = router.events.subscribe(s => {
        if (s instanceof NavigationEnd) {
          this.update();
        }
      });
    }
    /** @nodoc */
    ngAfterContentInit() {
      // `of(null)` is used to force subscribe body to execute once immediately (like `startWith`).
      (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(this.links.changes, (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(null)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_35__.mergeAll)()).subscribe(_ => {
        this.update();
        this.subscribeToEachLinkOnChanges();
      });
    }
    subscribeToEachLinkOnChanges() {
      this.linkInputChangesSubscription?.unsubscribe();
      const allLinkChanges = [...this.links.toArray(), this.link].filter(link => !!link).map(link => link.onChanges);
      this.linkInputChangesSubscription = (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(allLinkChanges).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_35__.mergeAll)()).subscribe(link => {
        if (this._isActive !== this.isLinkActive(this.router)(link)) {
          this.update();
        }
      });
    }
    set routerLinkActive(data) {
      const classes = Array.isArray(data) ? data : data.split(' ');
      this.classes = classes.filter(c => !!c);
    }
    /** @nodoc */
    ngOnChanges(changes) {
      this.update();
    }
    /** @nodoc */
    ngOnDestroy() {
      this.routerEventsSubscription.unsubscribe();
      this.linkInputChangesSubscription?.unsubscribe();
    }
    update() {
      if (!this.links || !this.router.navigated) return;
      queueMicrotask(() => {
        const hasActiveLinks = this.hasActiveLinks();
        this.classes.forEach(c => {
          if (hasActiveLinks) {
            this.renderer.addClass(this.element.nativeElement, c);
          } else {
            this.renderer.removeClass(this.element.nativeElement, c);
          }
        });
        if (hasActiveLinks && this.ariaCurrentWhenActive !== undefined) {
          this.renderer.setAttribute(this.element.nativeElement, 'aria-current', this.ariaCurrentWhenActive.toString());
        } else {
          this.renderer.removeAttribute(this.element.nativeElement, 'aria-current');
        }
        // Only emit change if the active state changed.
        if (this._isActive !== hasActiveLinks) {
          this._isActive = hasActiveLinks;
          this.cdr.markForCheck();
          // Emit on isActiveChange after classes are updated
          this.isActiveChange.emit(hasActiveLinks);
        }
      });
    }
    isLinkActive(router) {
      const options = isActiveMatchOptions(this.routerLinkActiveOptions) ? this.routerLinkActiveOptions :
      // While the types should disallow `undefined` here, it's possible without strict inputs
      this.routerLinkActiveOptions.exact || false;
      return link => {
        const urlTree = link.urlTree;
        return urlTree ? router.isActive(urlTree, options) : false;
      };
    }
    hasActiveLinks() {
      const isActiveCheckFn = this.isLinkActive(this.router);
      return this.link && isActiveCheckFn(this.link) || this.links.some(isActiveCheckFn);
    }
    static ɵfac = (() => function RouterLinkActive_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterLinkActive)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.Renderer2), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.ChangeDetectorRef), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdirectiveInject"](RouterLink, 8));
    })();
    static ɵdir = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineDirective"]({
      type: RouterLinkActive,
      selectors: [["", "routerLinkActive", ""]],
      contentQueries: function RouterLinkActive_ContentQueries(rf, ctx, dirIndex) {
        if (rf & 1) {
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵcontentQuery"](dirIndex, RouterLink, 5);
        }
        if (rf & 2) {
          let _t;
          _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵqueryRefresh"](_t = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵloadQuery"]()) && (ctx.links = _t);
        }
      },
      inputs: {
        routerLinkActiveOptions: "routerLinkActiveOptions",
        ariaCurrentWhenActive: "ariaCurrentWhenActive",
        routerLinkActive: "routerLinkActive"
      },
      outputs: {
        isActiveChange: "isActiveChange"
      },
      exportAs: ["routerLinkActive"],
      features: [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵNgOnChangesFeature"]]
    }))();
  }
  return RouterLinkActive;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Use instead of `'paths' in options` to be compatible with property renaming
 */
function isActiveMatchOptions(options) {
  return !!options.paths;
}

/**
 * @description
 *
 * Provides a preloading strategy.
 *
 * @publicApi
 */
class PreloadingStrategy {}
/**
 * @description
 *
 * Provides a preloading strategy that preloads all modules as quickly as possible.
 *
 * ```
 * RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
 * ```
 *
 * @publicApi
 */
let PreloadAllModules = /*#__PURE__*/(() => {
  class PreloadAllModules {
    preload(route, fn) {
      return fn().pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.catchError)(() => (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(null)));
    }
    static ɵfac = (() => function PreloadAllModules_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || PreloadAllModules)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: PreloadAllModules,
      factory: PreloadAllModules.ɵfac,
      providedIn: 'root'
    }))();
  }
  return PreloadAllModules;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * @description
 *
 * Provides a preloading strategy that does not preload any modules.
 *
 * This strategy is enabled by default.
 *
 * @publicApi
 */
let NoPreloading = /*#__PURE__*/(() => {
  class NoPreloading {
    preload(route, fn) {
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(null);
    }
    static ɵfac = (() => function NoPreloading_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || NoPreloading)();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: NoPreloading,
      factory: NoPreloading.ɵfac,
      providedIn: 'root'
    }))();
  }
  return NoPreloading;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * The preloader optimistically loads all router configurations to
 * make navigations into lazily-loaded sections of the application faster.
 *
 * The preloader runs in the background. When the router bootstraps, the preloader
 * starts listening to all navigation events. After every such event, the preloader
 * will check if any configurations can be loaded lazily.
 *
 * If a route is protected by `canLoad` guards, the preloaded will not load it.
 *
 * @publicApi
 */
let RouterPreloader = /*#__PURE__*/(() => {
  class RouterPreloader {
    router;
    injector;
    preloadingStrategy;
    loader;
    subscription;
    constructor(router, compiler, injector, preloadingStrategy, loader) {
      this.router = router;
      this.injector = injector;
      this.preloadingStrategy = preloadingStrategy;
      this.loader = loader;
    }
    setUpPreloading() {
      this.subscription = this.router.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.filter)(e => e instanceof NavigationEnd), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.concatMap)(() => this.preload())).subscribe(() => {});
    }
    preload() {
      return this.processRoutes(this.injector, this.router.config);
    }
    /** @nodoc */
    ngOnDestroy() {
      if (this.subscription) {
        this.subscription.unsubscribe();
      }
    }
    processRoutes(injector, routes) {
      const res = [];
      for (const route of routes) {
        if (route.providers && !route._injector) {
          route._injector = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.createEnvironmentInjector)(route.providers, injector, `Route: ${route.path}`);
        }
        const injectorForCurrentRoute = route._injector ?? injector;
        const injectorForChildren = route._loadedInjector ?? injectorForCurrentRoute;
        // Note that `canLoad` is only checked as a condition that prevents `loadChildren` and not
        // `loadComponent`. `canLoad` guards only block loading of child routes by design. This
        // happens as a consequence of needing to descend into children for route matching immediately
        // while component loading is deferred until route activation. Because `canLoad` guards can
        // have side effects, we cannot execute them here so we instead skip preloading altogether
        // when present. Lastly, it remains to be decided whether `canLoad` should behave this way
        // at all. Code splitting and lazy loading is separate from client-side authorization checks
        // and should not be used as a security measure to prevent loading of code.
        if (route.loadChildren && !route._loadedRoutes && route.canLoad === undefined || route.loadComponent && !route._loadedComponent) {
          res.push(this.preloadConfig(injectorForCurrentRoute, route));
        }
        if (route.children || route._loadedRoutes) {
          res.push(this.processRoutes(injectorForChildren, route.children ?? route._loadedRoutes));
        }
      }
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(res).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_35__.mergeAll)());
    }
    preloadConfig(injector, route) {
      return this.preloadingStrategy.preload(route, () => {
        let loadedChildren$;
        if (route.loadChildren && route.canLoad === undefined) {
          loadedChildren$ = this.loader.loadChildren(injector, route);
        } else {
          loadedChildren$ = (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(null);
        }
        const recursiveLoadChildren$ = loadedChildren$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.mergeMap)(config => {
          if (config === null) {
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(void 0);
          }
          route._loadedRoutes = config.routes;
          route._loadedInjector = config.injector;
          // If the loaded config was a module, use that as the module/module injector going
          // forward. Otherwise, continue using the current module/module injector.
          return this.processRoutes(config.injector ?? injector, config.routes);
        }));
        if (route.loadComponent && !route._loadedComponent) {
          const loadComponent$ = this.loader.loadComponent(route);
          return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)([recursiveLoadChildren$, loadComponent$]).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_35__.mergeAll)());
        } else {
          return recursiveLoadChildren$;
        }
      });
    }
    static ɵfac = (() => function RouterPreloader_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterPreloader)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](Router), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.Compiler), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.EnvironmentInjector), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](PreloadingStrategy), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](RouterConfigLoader));
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: RouterPreloader,
      factory: RouterPreloader.ɵfac,
      providedIn: 'root'
    }))();
  }
  return RouterPreloader;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const ROUTER_SCROLLER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('');
let RouterScroller = /*#__PURE__*/(() => {
  class RouterScroller {
    urlSerializer;
    transitions;
    viewportScroller;
    zone;
    options;
    routerEventsSubscription;
    scrollEventsSubscription;
    lastId = 0;
    lastSource = 'imperative';
    restoredId = 0;
    store = {};
    /** @nodoc */
    constructor(urlSerializer, transitions, viewportScroller, zone, options = {}) {
      this.urlSerializer = urlSerializer;
      this.transitions = transitions;
      this.viewportScroller = viewportScroller;
      this.zone = zone;
      this.options = options;
      // Default both options to 'disabled'
      options.scrollPositionRestoration ||= 'disabled';
      options.anchorScrolling ||= 'disabled';
    }
    init() {
      // we want to disable the automatic scrolling because having two places
      // responsible for scrolling results race conditions, especially given
      // that browser don't implement this behavior consistently
      if (this.options.scrollPositionRestoration !== 'disabled') {
        this.viewportScroller.setHistoryScrollRestoration('manual');
      }
      this.routerEventsSubscription = this.createScrollEvents();
      this.scrollEventsSubscription = this.consumeScrollEvents();
    }
    createScrollEvents() {
      return this.transitions.events.subscribe(e => {
        if (e instanceof NavigationStart) {
          // store the scroll position of the current stable navigations.
          this.store[this.lastId] = this.viewportScroller.getScrollPosition();
          this.lastSource = e.navigationTrigger;
          this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;
        } else if (e instanceof NavigationEnd) {
          this.lastId = e.id;
          this.scheduleScrollEvent(e, this.urlSerializer.parse(e.urlAfterRedirects).fragment);
        } else if (e instanceof NavigationSkipped && e.code === NavigationSkippedCode.IgnoredSameUrlNavigation) {
          this.lastSource = undefined;
          this.restoredId = 0;
          this.scheduleScrollEvent(e, this.urlSerializer.parse(e.url).fragment);
        }
      });
    }
    consumeScrollEvents() {
      return this.transitions.events.subscribe(e => {
        if (!(e instanceof Scroll)) return;
        // a popstate event. The pop state event will always ignore anchor scrolling.
        if (e.position) {
          if (this.options.scrollPositionRestoration === 'top') {
            this.viewportScroller.scrollToPosition([0, 0]);
          } else if (this.options.scrollPositionRestoration === 'enabled') {
            this.viewportScroller.scrollToPosition(e.position);
          }
          // imperative navigation "forward"
        } else {
          if (e.anchor && this.options.anchorScrolling === 'enabled') {
            this.viewportScroller.scrollToAnchor(e.anchor);
          } else if (this.options.scrollPositionRestoration !== 'disabled') {
            this.viewportScroller.scrollToPosition([0, 0]);
          }
        }
      });
    }
    scheduleScrollEvent(routerEvent, anchor) {
      this.zone.runOutsideAngular(() => {
        // The scroll event needs to be delayed until after change detection. Otherwise, we may
        // attempt to restore the scroll position before the router outlet has fully rendered the
        // component by executing its update block of the template function.
        setTimeout(() => {
          this.zone.run(() => {
            this.transitions.events.next(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));
          });
        }, 0);
      });
    }
    /** @nodoc */
    ngOnDestroy() {
      this.routerEventsSubscription?.unsubscribe();
      this.scrollEventsSubscription?.unsubscribe();
    }
    static ɵfac = (() => function RouterScroller_Factory(__ngFactoryType__) {
      _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinvalidFactory"]();
    })();
    static ɵprov = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: RouterScroller,
      factory: RouterScroller.ɵfac
    }))();
  }
  return RouterScroller;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Sets up providers necessary to enable `Router` functionality for the application.
 * Allows to configure a set of routes as well as extra features that should be enabled.
 *
 * @usageNotes
 *
 * Basic example of how you can add a Router to your application:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent, {
 *   providers: [provideRouter(appRoutes)]
 * });
 * ```
 *
 * You can also enable optional features in the Router by adding functions from the `RouterFeatures`
 * type:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes,
 *         withDebugTracing(),
 *         withRouterConfig({paramsInheritanceStrategy: 'always'}))
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link RouterFeatures}
 *
 * @publicApi
 * @param routes A set of `Route`s to use for the application routing table.
 * @param features Optional features to configure additional router behaviors.
 * @returns A set of providers to setup a Router.
 */
function provideRouter(routes, ...features) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.makeEnvironmentProviders)([{
    provide: ROUTES,
    multi: true,
    useValue: routes
  }, typeof ngDevMode === 'undefined' || ngDevMode ? {
    provide: ROUTER_IS_PROVIDED,
    useValue: true
  } : [], {
    provide: ActivatedRoute,
    useFactory: rootRoute,
    deps: [Router]
  }, {
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_BOOTSTRAP_LISTENER,
    multi: true,
    useFactory: getBootstrapListener
  }, features.map(feature => feature.ɵproviders)]);
}
function rootRoute(router) {
  return router.routerState.root;
}
/**
 * Helper function to create an object that represents a Router feature.
 */
function routerFeature(kind, providers) {
  return {
    ɵkind: kind,
    ɵproviders: providers
  };
}
/**
 * An Injection token used to indicate whether `provideRouter` or `RouterModule.forRoot` was ever
 * called.
 */
const ROUTER_IS_PROVIDED = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('', {
  providedIn: 'root',
  factory: () => false
});
const routerIsProvidedDevModeCheck = {
  provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ENVIRONMENT_INITIALIZER,
  multi: true,
  useFactory() {
    return () => {
      if (!(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTER_IS_PROVIDED)) {
        console.warn('`provideRoutes` was called without `provideRouter` or `RouterModule.forRoot`. ' + 'This is likely a mistake.');
      }
    };
  }
};
/**
 * Registers a DI provider for a set of routes.
 * @param routes The route configuration to provide.
 *
 * @usageNotes
 *
 * ```
 * @NgModule({
 *   providers: [provideRoutes(ROUTES)]
 * })
 * class LazyLoadedChildModule {}
 * ```
 *
 * @deprecated If necessary, provide routes using the `ROUTES` `InjectionToken`.
 * @see {@link ROUTES}
 * @publicApi
 */
function provideRoutes(routes) {
  return [{
    provide: ROUTES,
    multi: true,
    useValue: routes
  }, typeof ngDevMode === 'undefined' || ngDevMode ? routerIsProvidedDevModeCheck : []];
}
/**
 * Enables customizable scrolling behavior for router navigations.
 *
 * @usageNotes
 *
 * Basic example of how you can enable scrolling feature:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withInMemoryScrolling())
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 * @see {@link ViewportScroller}
 *
 * @publicApi
 * @param options Set of configuration parameters to customize scrolling behavior, see
 *     `InMemoryScrollingOptions` for additional information.
 * @returns A set of providers for use with `provideRouter`.
 */
function withInMemoryScrolling(options = {}) {
  const providers = [{
    provide: ROUTER_SCROLLER,
    useFactory: () => {
      const viewportScroller = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_common__WEBPACK_IMPORTED_MODULE_32__.ViewportScroller);
      const zone = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
      const transitions = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(NavigationTransitions);
      const urlSerializer = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlSerializer);
      return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, options);
    }
  }];
  return routerFeature(4 /* RouterFeatureKind.InMemoryScrollingFeature */, providers);
}
function getBootstrapListener() {
  const injector = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.Injector);
  return bootstrappedComponentRef => {
    const ref = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__.ApplicationRef);
    if (bootstrappedComponentRef !== ref.components[0]) {
      return;
    }
    const router = injector.get(Router);
    const bootstrapDone = injector.get(BOOTSTRAP_DONE);
    if (injector.get(INITIAL_NAVIGATION) === 1 /* InitialNavigation.EnabledNonBlocking */) {
      router.initialNavigation();
    }
    injector.get(ROUTER_PRELOADER, null, _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectFlags.Optional)?.setUpPreloading();
    injector.get(ROUTER_SCROLLER, null, _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectFlags.Optional)?.init();
    router.resetRootComponentType(ref.componentTypes[0]);
    if (!bootstrapDone.closed) {
      bootstrapDone.next();
      bootstrapDone.complete();
      bootstrapDone.unsubscribe();
    }
  };
}
/**
 * A subject used to indicate that the bootstrapping phase is done. When initial navigation is
 * `enabledBlocking`, the first navigation waits until bootstrapping is finished before continuing
 * to the activation phase.
 */
const BOOTSTRAP_DONE = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'bootstrap done indicator' : '', {
  factory: () => {
    return new rxjs__WEBPACK_IMPORTED_MODULE_30__.Subject();
  }
});
const INITIAL_NAVIGATION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'initial navigation' : '', {
  providedIn: 'root',
  factory: () => 1 /* InitialNavigation.EnabledNonBlocking */
});
/**
 * Configures initial navigation to start before the root component is created.
 *
 * The bootstrap is blocked until the initial navigation is complete. This should be set in case
 * you use [server-side rendering](guide/ssr), but do not enable [hydration](guide/hydration) for
 * your application.
 *
 * @usageNotes
 *
 * Basic example of how you can enable this navigation behavior:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withEnabledBlockingInitialNavigation())
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 *
 * @publicApi
 * @returns A set of providers for use with `provideRouter`.
 */
function withEnabledBlockingInitialNavigation() {
  const providers = [{
    provide: INITIAL_NAVIGATION,
    useValue: 0 /* InitialNavigation.EnabledBlocking */
  }, {
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_INITIALIZER,
    multi: true,
    deps: [_angular_core__WEBPACK_IMPORTED_MODULE_1__.Injector],
    useFactory: injector => {
      const locationInitialized = injector.get(_angular_common__WEBPACK_IMPORTED_MODULE_32__.LOCATION_INITIALIZED, Promise.resolve());
      return () => {
        return locationInitialized.then(() => {
          return new Promise(resolve => {
            const router = injector.get(Router);
            const bootstrapDone = injector.get(BOOTSTRAP_DONE);
            afterNextNavigation(router, () => {
              // Unblock APP_INITIALIZER in case the initial navigation was canceled or errored
              // without a redirect.
              resolve(true);
            });
            injector.get(NavigationTransitions).afterPreactivation = () => {
              // Unblock APP_INITIALIZER once we get to `afterPreactivation`. At this point, we
              // assume activation will complete successfully (even though this is not
              // guaranteed).
              resolve(true);
              return bootstrapDone.closed ? (0,rxjs__WEBPACK_IMPORTED_MODULE_3__.of)(void 0) : bootstrapDone;
            };
            router.initialNavigation();
          });
        });
      };
    }
  }];
  return routerFeature(2 /* RouterFeatureKind.EnabledBlockingInitialNavigationFeature */, providers);
}
/**
 * Disables initial navigation.
 *
 * Use if there is a reason to have more control over when the router starts its initial navigation
 * due to some complex initialization logic.
 *
 * @usageNotes
 *
 * Basic example of how you can disable initial navigation:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withDisabledInitialNavigation())
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 *
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withDisabledInitialNavigation() {
  const providers = [{
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_INITIALIZER,
    multi: true,
    useFactory: () => {
      const router = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(Router);
      return () => {
        router.setUpLocationChangeListener();
      };
    }
  }, {
    provide: INITIAL_NAVIGATION,
    useValue: 2 /* InitialNavigation.Disabled */
  }];
  return routerFeature(3 /* RouterFeatureKind.DisabledInitialNavigationFeature */, providers);
}
/**
 * Enables logging of all internal navigation events to the console.
 * Extra logging might be useful for debugging purposes to inspect Router event sequence.
 *
 * @usageNotes
 *
 * Basic example of how you can enable debug tracing:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withDebugTracing())
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 *
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withDebugTracing() {
  let providers = [];
  if (typeof ngDevMode === 'undefined' || ngDevMode) {
    providers = [{
      provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.ENVIRONMENT_INITIALIZER,
      multi: true,
      useFactory: () => {
        const router = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(Router);
        return () => router.events.subscribe(e => {
          // tslint:disable:no-console
          console.group?.(`Router Event: ${e.constructor.name}`);
          console.log(stringifyEvent(e));
          console.log(e);
          console.groupEnd?.();
          // tslint:enable:no-console
        });
      }
    }];
  } else {
    providers = [];
  }
  return routerFeature(1 /* RouterFeatureKind.DebugTracingFeature */, providers);
}
const ROUTER_PRELOADER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router preloader' : '');
/**
 * Allows to configure a preloading strategy to use. The strategy is configured by providing a
 * reference to a class that implements a `PreloadingStrategy`.
 *
 * @usageNotes
 *
 * Basic example of how you can configure preloading:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withPreloading(PreloadAllModules))
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 *
 * @param preloadingStrategy A reference to a class that implements a `PreloadingStrategy` that
 *     should be used.
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withPreloading(preloadingStrategy) {
  const providers = [{
    provide: ROUTER_PRELOADER,
    useExisting: RouterPreloader
  }, {
    provide: PreloadingStrategy,
    useExisting: preloadingStrategy
  }];
  return routerFeature(0 /* RouterFeatureKind.PreloadingFeature */, providers);
}
/**
 * Allows to provide extra parameters to configure Router.
 *
 * @usageNotes
 *
 * Basic example of how you can provide extra configuration options:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withRouterConfig({
 *          onSameUrlNavigation: 'reload'
 *       }))
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 *
 * @param options A set of parameters to configure Router, see `RouterConfigOptions` for
 *     additional information.
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withRouterConfig(options) {
  const providers = [{
    provide: ROUTER_CONFIGURATION,
    useValue: options
  }];
  return routerFeature(5 /* RouterFeatureKind.RouterConfigurationFeature */, providers);
}
/**
 * Provides the location strategy that uses the URL fragment instead of the history API.
 *
 * @usageNotes
 *
 * Basic example of how you can use the hash location option:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withHashLocation())
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link provideRouter}
 * @see {@link HashLocationStrategy}
 *
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withHashLocation() {
  const providers = [{
    provide: _angular_common__WEBPACK_IMPORTED_MODULE_32__.LocationStrategy,
    useClass: _angular_common__WEBPACK_IMPORTED_MODULE_32__.HashLocationStrategy
  }];
  return routerFeature(6 /* RouterFeatureKind.RouterHashLocationFeature */, providers);
}
/**
 * Provides a function which is called when a navigation error occurs.
 *
 * This function is run inside application's [injection context](guide/di/dependency-injection-context)
 * so you can use the [`inject`](api/core/inject) function.
 *
 * This function can return a `RedirectCommand` to convert the error to a redirect, similar to returning
 * a `UrlTree` or `RedirectCommand` from a guard. This will also prevent the `Router` from emitting
 * `NavigationError`; it will instead emit `NavigationCancel` with code NavigationCancellationCode.Redirect.
 * Return values other than `RedirectCommand` are ignored and do not change any behavior with respect to
 * how the `Router` handles the error.
 *
 * @usageNotes
 *
 * Basic example of how you can use the error handler option:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) =>
 * inject(MyErrorTracker).trackError(e)))
 *     ]
 *   }
 * );
 * ```
 *
 * @see {@link NavigationError}
 * @see {@link core/inject}
 * @see {@link runInInjectionContext}
 *
 * @returns A set of providers for use with `provideRouter`.
 *
 * @publicApi
 */
function withNavigationErrorHandler(handler) {
  const providers = [{
    provide: NAVIGATION_ERROR_HANDLER,
    useValue: handler
  }];
  return routerFeature(7 /* RouterFeatureKind.NavigationErrorHandlerFeature */, providers);
}
/**
 * Enables binding information from the `Router` state directly to the inputs of the component in
 * `Route` configurations.
 *
 * @usageNotes
 *
 * Basic example of how you can enable the feature:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withComponentInputBinding())
 *     ]
 *   }
 * );
 * ```
 *
 * The router bindings information from any of the following sources:
 *
 *  - query parameters
 *  - path and matrix parameters
 *  - static route data
 *  - data from resolvers
 *
 * Duplicate keys are resolved in the same order from above, from least to greatest,
 * meaning that resolvers have the highest precedence and override any of the other information
 * from the route.
 *
 * Importantly, when an input does not have an item in the route data with a matching key, this
 * input is set to `undefined`. This prevents previous information from being
 * retained if the data got removed from the route (i.e. if a query parameter is removed).
 * Default values can be provided with a resolver on the route to ensure the value is always present
 * or an input and use an input transform in the component.
 *
 * @see {@link guide/components/inputs#input-transforms input transforms}
 * @returns A set of providers for use with `provideRouter`.
 */
function withComponentInputBinding() {
  const providers = [RoutedComponentInputBinder, {
    provide: INPUT_BINDER,
    useExisting: RoutedComponentInputBinder
  }];
  return routerFeature(8 /* RouterFeatureKind.ComponentInputBindingFeature */, providers);
}
/**
 * Enables view transitions in the Router by running the route activation and deactivation inside of
 * `document.startViewTransition`.
 *
 * Note: The View Transitions API is not available in all browsers. If the browser does not support
 * view transitions, the Router will not attempt to start a view transition and continue processing
 * the navigation as usual.
 *
 * @usageNotes
 *
 * Basic example of how you can enable the feature:
 * ```
 * const appRoutes: Routes = [];
 * bootstrapApplication(AppComponent,
 *   {
 *     providers: [
 *       provideRouter(appRoutes, withViewTransitions())
 *     ]
 *   }
 * );
 * ```
 *
 * @returns A set of providers for use with `provideRouter`.
 * @see https://developer.chrome.com/docs/web-platform/view-transitions/
 * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API
 * @developerPreview
 */
function withViewTransitions(options) {
  const providers = [{
    provide: CREATE_VIEW_TRANSITION,
    useValue: createViewTransition
  }, {
    provide: VIEW_TRANSITION_OPTIONS,
    useValue: {
      skipNextTransition: !!options?.skipInitialTransition,
      ...options
    }
  }];
  return routerFeature(9 /* RouterFeatureKind.ViewTransitionsFeature */, providers);
}

/**
 * The directives defined in the `RouterModule`.
 */
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, ɵEmptyOutletComponent];
/**
 * @docsNotRequired
 */
const ROUTER_FORROOT_GUARD = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router duplicate forRoot guard' : 'ROUTER_FORROOT_GUARD');
// TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept
// here to avoid a breaking change whereby the provider order matters based on where the
// `RouterModule`/`RouterTestingModule` is imported. These can/should be removed as a "breaking"
// change in a major version.
const ROUTER_PROVIDERS = [_angular_common__WEBPACK_IMPORTED_MODULE_32__.Location, {
  provide: UrlSerializer,
  useClass: DefaultUrlSerializer
}, Router, ChildrenOutletContexts, {
  provide: ActivatedRoute,
  useFactory: rootRoute,
  deps: [Router]
}, RouterConfigLoader,
// Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can
// be removed when `provideRoutes` is removed.
typeof ngDevMode === 'undefined' || ngDevMode ? {
  provide: ROUTER_IS_PROVIDED,
  useValue: true
} : []];
/**
 * @description
 *
 * Adds directives and providers for in-app navigation among views defined in an application.
 * Use the Angular `Router` service to declaratively specify application states and manage state
 * transitions.
 *
 * You can import this NgModule multiple times, once for each lazy-loaded bundle.
 * However, only one `Router` service can be active.
 * To ensure this, there are two ways to register routes when importing this module:
 *
 * * The `forRoot()` method creates an `NgModule` that contains all the directives, the given
 * routes, and the `Router` service itself.
 * * The `forChild()` method creates an `NgModule` that contains all the directives and the given
 * routes, but does not include the `Router` service.
 *
 * @see [Routing and Navigation guide](guide/routing/common-router-tasks) for an
 * overview of how the `Router` service should be used.
 *
 * @publicApi
 */
let RouterModule = /*#__PURE__*/(() => {
  class RouterModule {
    constructor(guard) {}
    /**
     * Creates and configures a module with all the router providers and directives.
     * Optionally sets up an application listener to perform an initial navigation.
     *
     * When registering the NgModule at the root, import as follows:
     *
     * ```
     * @NgModule({
     *   imports: [RouterModule.forRoot(ROUTES)]
     * })
     * class MyNgModule {}
     * ```
     *
     * @param routes An array of `Route` objects that define the navigation paths for the application.
     * @param config An `ExtraOptions` configuration object that controls how navigation is performed.
     * @return The new `NgModule`.
     *
     */
    static forRoot(routes, config) {
      return {
        ngModule: RouterModule,
        providers: [ROUTER_PROVIDERS, typeof ngDevMode === 'undefined' || ngDevMode ? config?.enableTracing ? withDebugTracing().ɵproviders : [] : [], {
          provide: ROUTES,
          multi: true,
          useValue: routes
        }, {
          provide: ROUTER_FORROOT_GUARD,
          useFactory: provideForRootGuard,
          deps: [[Router, new _angular_core__WEBPACK_IMPORTED_MODULE_1__.Optional(), new _angular_core__WEBPACK_IMPORTED_MODULE_1__.SkipSelf()]]
        }, config?.errorHandler ? {
          provide: NAVIGATION_ERROR_HANDLER,
          useValue: config.errorHandler
        } : [], {
          provide: ROUTER_CONFIGURATION,
          useValue: config ? config : {}
        }, config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(), provideRouterScroller(), config?.preloadingStrategy ? withPreloading(config.preloadingStrategy).ɵproviders : [], config?.initialNavigation ? provideInitialNavigation(config) : [], config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [], config?.enableViewTransitions ? withViewTransitions().ɵproviders : [], provideRouterInitializer()]
      };
    }
    /**
     * Creates a module with all the router directives and a provider registering routes,
     * without creating a new Router service.
     * When registering for submodules and lazy-loaded submodules, create the NgModule as follows:
     *
     * ```
     * @NgModule({
     *   imports: [RouterModule.forChild(ROUTES)]
     * })
     * class MyNgModule {}
     * ```
     *
     * @param routes An array of `Route` objects that define the navigation paths for the submodule.
     * @return The new NgModule.
     *
     */
    static forChild(routes) {
      return {
        ngModule: RouterModule,
        providers: [{
          provide: ROUTES,
          multi: true,
          useValue: routes
        }]
      };
    }
    static ɵfac = (() => function RouterModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || RouterModule)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](ROUTER_FORROOT_GUARD, 8));
    })();
    static ɵmod = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({
      type: RouterModule
    }))();
    static ɵinj = (() => /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({}))();
  }
  return RouterModule;
})();
/*#__PURE__*/(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * For internal use by `RouterModule` only. Note that this differs from `withInMemoryRouterScroller`
 * because it reads from the `ExtraOptions` which should not be used in the standalone world.
 */
function provideRouterScroller() {
  return {
    provide: ROUTER_SCROLLER,
    useFactory: () => {
      const viewportScroller = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_common__WEBPACK_IMPORTED_MODULE_32__.ViewportScroller);
      const zone = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone);
      const config = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(ROUTER_CONFIGURATION);
      const transitions = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(NavigationTransitions);
      const urlSerializer = (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(UrlSerializer);
      if (config.scrollOffset) {
        viewportScroller.setOffset(config.scrollOffset);
      }
      return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, config);
    }
  };
}
// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` should
// provide hash location directly via `{provide: LocationStrategy, useClass: HashLocationStrategy}`.
function provideHashLocationStrategy() {
  return {
    provide: _angular_common__WEBPACK_IMPORTED_MODULE_32__.LocationStrategy,
    useClass: _angular_common__WEBPACK_IMPORTED_MODULE_32__.HashLocationStrategy
  };
}
// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` does not
// need this at all because `PathLocationStrategy` is the default factory for `LocationStrategy`.
function providePathLocationStrategy() {
  return {
    provide: _angular_common__WEBPACK_IMPORTED_MODULE_32__.LocationStrategy,
    useClass: _angular_common__WEBPACK_IMPORTED_MODULE_32__.PathLocationStrategy
  };
}
function provideForRootGuard(router) {
  if ((typeof ngDevMode === 'undefined' || ngDevMode) && router) {
    throw new _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵRuntimeError"](4007 /* RuntimeErrorCode.FOR_ROOT_CALLED_TWICE */, `The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` + ` Lazy loaded modules should use RouterModule.forChild() instead.`);
  }
  return 'guarded';
}
// Note: For internal use only with `RouterModule`. Standalone router setup with `provideRouter`
// users call `withXInitialNavigation` directly.
function provideInitialNavigation(config) {
  return [config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [], config.initialNavigation === 'enabledBlocking' ? withEnabledBlockingInitialNavigation().ɵproviders : []];
}
// TODO(atscott): This should not be in the public API
/**
 * A DI token for the router initializer that
 * is called after the app is bootstrapped.
 *
 * @publicApi
 */
const ROUTER_INITIALIZER = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Router Initializer' : '');
function provideRouterInitializer() {
  return [
  // ROUTER_INITIALIZER token should be removed. It's public API but shouldn't be. We can just
  // have `getBootstrapListener` directly attached to APP_BOOTSTRAP_LISTENER.
  {
    provide: ROUTER_INITIALIZER,
    useFactory: getBootstrapListener
  }, {
    provide: _angular_core__WEBPACK_IMPORTED_MODULE_1__.APP_BOOTSTRAP_LISTENER,
    multi: true,
    useExisting: ROUTER_INITIALIZER
  }];
}

/**
 * Maps an array of injectable classes with canMatch functions to an array of equivalent
 * `CanMatchFn` for use in a `Route` definition.
 *
 * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
 *
 * @publicApi
 * @see {@link Route}
 */
function mapToCanMatch(providers) {
  return providers.map(provider => (...params) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(provider).canMatch(...params));
}
/**
 * Maps an array of injectable classes with canActivate functions to an array of equivalent
 * `CanActivateFn` for use in a `Route` definition.
 *
 * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
 *
 * @publicApi
 * @see {@link Route}
 */
function mapToCanActivate(providers) {
  return providers.map(provider => (...params) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(provider).canActivate(...params));
}
/**
 * Maps an array of injectable classes with canActivateChild functions to an array of equivalent
 * `CanActivateChildFn` for use in a `Route` definition.
 *
 * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
 *
 * @publicApi
 * @see {@link Route}
 */
function mapToCanActivateChild(providers) {
  return providers.map(provider => (...params) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(provider).canActivateChild(...params));
}
/**
 * Maps an array of injectable classes with canDeactivate functions to an array of equivalent
 * `CanDeactivateFn` for use in a `Route` definition.
 *
 * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
 *
 * @publicApi
 * @see {@link Route}
 */
function mapToCanDeactivate(providers) {
  return providers.map(provider => (...params) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(provider).canDeactivate(...params));
}
/**
 * Maps an injectable class with a resolve function to an equivalent `ResolveFn`
 * for use in a `Route` definition.
 *
 * Usage {@example router/utils/functional_guards.ts region='Resolve'}
 *
 * @publicApi
 * @see {@link Route}
 */
function mapToResolve(provider) {
  return (...params) => (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.inject)(provider).resolve(...params);
}

/**
 * @module
 * @description
 * Entry point for all public APIs of the router package.
 */
/**
 * @publicApi
 */
const VERSION = /*#__PURE__*/new _angular_core__WEBPACK_IMPORTED_MODULE_1__.Version('19.0.0');
function getLoadedRoutes(route) {
  return route._loadedRoutes;
}
/*#__PURE__*/(0,_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵpublishExternalGlobalUtil"])('ɵgetLoadedRoutes', getLoadedRoutes);

/**
 * @module
 * @description
 * Entry point for all public APIs of this package.
 */
// This file only reexports content of the `src` folder. Keep it that way.

// This file is not used to build this module. It is only used during editing

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 9643:
/*!****************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/angular-oauth2-oidc-jwks@17.0.2/node_modules/angular-oauth2-oidc-jwks/fesm2022/angular-oauth2-oidc-jwks.mjs ***!
  \****************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   JwksValidationHandler: () => (/* binding */ JwksValidationHandler)
/* harmony export */ });
/* harmony import */ var jsrsasign__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jsrsasign */ 928);
/* harmony import */ var angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular-oauth2-oidc */ 2888);



/**
 * Validates the signature of an id_token against one
 * of the keys of an JSON Web Key Set (jwks).
 *
 * This jwks can be provided by the discovery document.
 */
class JwksValidationHandler extends angular_oauth2_oidc__WEBPACK_IMPORTED_MODULE_1__.AbstractValidationHandler {
  constructor() {
    super(...arguments);
    /**
     * Allowed algorithms
     */
    this.allowedAlgorithms = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'PS256', 'PS384', 'PS512'];
    /**
     * Time period in seconds the timestamp in the signature can
     * differ from the current time.
     */
    this.gracePeriodInSec = 600;
  }
  validateSignature(params, retry = false) {
    if (!params.idToken) throw new Error('Parameter idToken expected!');
    if (!params.idTokenHeader) throw new Error('Parameter idTokenHandler expected.');
    if (!params.jwks) throw new Error('Parameter jwks expected!');
    if (!params.jwks['keys'] || !Array.isArray(params.jwks['keys']) || params.jwks['keys'].length === 0) {
      throw new Error('Array keys in jwks missing!');
    }
    // console.debug('validateSignature: retry', retry);
    let kid = params.idTokenHeader['kid'];
    let keys = params.jwks['keys'];
    let key;
    let alg = params.idTokenHeader['alg'];
    if (kid) {
      key = keys.find(k => k['kid'] === kid /* && k['use'] === 'sig' */);
    } else {
      let kty = this.alg2kty(alg);
      let matchingKeys = keys.filter(k => k['kty'] === kty && k['use'] === 'sig');
      /*
            if (matchingKeys.length == 0) {
                let error = 'No matching key found.';
                console.error(error);
                return Promise.reject(error);
            }*/
      if (matchingKeys.length > 1) {
        let error = 'More than one matching key found. Please specify a kid in the id_token header.';
        console.error(error);
        return Promise.reject(error);
      } else if (matchingKeys.length === 1) {
        key = matchingKeys[0];
      }
    }
    if (!key && !retry && params.loadKeys) {
      return params.loadKeys().then(loadedKeys => params.jwks = loadedKeys).then(_ => this.validateSignature(params, true));
    }
    if (!key && retry && !kid) {
      let error = 'No matching key found.';
      console.error(error);
      return Promise.reject(error);
    }
    if (!key && retry && kid) {
      let error = 'expected key not found in property jwks. ' + 'This property is most likely loaded with the ' + 'discovery document. ' + 'Expected key id (kid): ' + kid;
      console.error(error);
      return Promise.reject(error);
    }
    let keyObj = jsrsasign__WEBPACK_IMPORTED_MODULE_0__.KEYUTIL.getKey(key);
    let validationOptions = {
      alg: this.allowedAlgorithms,
      gracePeriod: this.gracePeriodInSec
    };
    let isValid = jsrsasign__WEBPACK_IMPORTED_MODULE_0__.KJUR.jws.JWS.verifyJWT(params.idToken, keyObj, validationOptions);
    if (isValid) {
      return Promise.resolve();
    } else {
      return Promise.reject('Signature not valid');
    }
  }
  alg2kty(alg) {
    switch (alg.charAt(0)) {
      case 'R':
        return 'RSA';
      case 'E':
        return 'EC';
      default:
        throw new Error('Cannot infer kty from alg: ' + alg);
    }
  }
  calcHash(valueToHash, algorithm) {
    let hashAlg = new jsrsasign__WEBPACK_IMPORTED_MODULE_0__.KJUR.crypto.MessageDigest({
      alg: algorithm
    });
    let result = hashAlg.digestString(valueToHash);
    let byteArrayAsString = this.toByteArrayAsString(result);
    return Promise.resolve(byteArrayAsString);
  }
  toByteArrayAsString(hexString) {
    let result = '';
    for (let i = 0; i < hexString.length; i += 2) {
      let hexDigit = hexString.charAt(i) + hexString.charAt(i + 1);
      let num = parseInt(hexDigit, 16);
      result += String.fromCharCode(num);
    }
    return result;
  }
}

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 2888:
/*!***********************************************************************************************************************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/angular-oauth2-oidc@19.0.0_@angular+common@19.0.0_@angular+core@19.0.0_rxjs@7.8.1_zone._199a800bb313ed182ebdf1fdd2fbe65b/node_modules/angular-oauth2-oidc/fesm2022/angular-oauth2-oidc.mjs ***!
  \***********************************************************************************************************************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AUTH_CONFIG: () => (/* binding */ AUTH_CONFIG),
/* harmony export */   AbstractValidationHandler: () => (/* binding */ AbstractValidationHandler),
/* harmony export */   AuthConfig: () => (/* binding */ AuthConfig),
/* harmony export */   DateTimeProvider: () => (/* binding */ DateTimeProvider),
/* harmony export */   DefaultHashHandler: () => (/* binding */ DefaultHashHandler),
/* harmony export */   DefaultOAuthInterceptor: () => (/* binding */ DefaultOAuthInterceptor),
/* harmony export */   HashHandler: () => (/* binding */ HashHandler),
/* harmony export */   JwksValidationHandler: () => (/* binding */ JwksValidationHandler),
/* harmony export */   LoginOptions: () => (/* binding */ LoginOptions),
/* harmony export */   MemoryStorage: () => (/* binding */ MemoryStorage),
/* harmony export */   NullValidationHandler: () => (/* binding */ NullValidationHandler),
/* harmony export */   OAuthErrorEvent: () => (/* binding */ OAuthErrorEvent),
/* harmony export */   OAuthEvent: () => (/* binding */ OAuthEvent),
/* harmony export */   OAuthInfoEvent: () => (/* binding */ OAuthInfoEvent),
/* harmony export */   OAuthLogger: () => (/* binding */ OAuthLogger),
/* harmony export */   OAuthModule: () => (/* binding */ OAuthModule),
/* harmony export */   OAuthModuleConfig: () => (/* binding */ OAuthModuleConfig),
/* harmony export */   OAuthNoopResourceServerErrorHandler: () => (/* binding */ OAuthNoopResourceServerErrorHandler),
/* harmony export */   OAuthResourceServerConfig: () => (/* binding */ OAuthResourceServerConfig),
/* harmony export */   OAuthResourceServerErrorHandler: () => (/* binding */ OAuthResourceServerErrorHandler),
/* harmony export */   OAuthService: () => (/* binding */ OAuthService),
/* harmony export */   OAuthStorage: () => (/* binding */ OAuthStorage),
/* harmony export */   OAuthSuccessEvent: () => (/* binding */ OAuthSuccessEvent),
/* harmony export */   ReceivedTokens: () => (/* binding */ ReceivedTokens),
/* harmony export */   SystemDateTimeProvider: () => (/* binding */ SystemDateTimeProvider),
/* harmony export */   UrlHelperService: () => (/* binding */ UrlHelperService),
/* harmony export */   ValidationHandler: () => (/* binding */ ValidationHandler),
/* harmony export */   provideOAuthClient: () => (/* binding */ provideOAuthClient)
/* harmony export */ });
/* harmony import */ var _Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */ 4626);
/* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ 4380);
/* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @angular/common */ 6216);
/* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/common/http */ 8143);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ 2714);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ 2049);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! rxjs */ 580);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! rxjs */ 3873);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! rxjs */ 7954);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! rxjs */ 1428);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! rxjs */ 3250);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ 4484);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs/operators */ 4997);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs/operators */ 6128);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs/operators */ 9207);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rxjs/operators */ 462);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! rxjs/operators */ 6634);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! rxjs/operators */ 8898);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! rxjs/operators */ 5685);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! rxjs/operators */ 3439);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! rxjs/operators */ 1969);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! rxjs/operators */ 1292);









/**
 * A validation handler that isn't validating nothing.
 * Can be used to skip validation (at your own risk).
 */
class NullValidationHandler {
  validateSignature(validationParams) {
    return Promise.resolve(null);
  }
  validateAtHash(validationParams) {
    return Promise.resolve(true);
  }
}
class OAuthModuleConfig {}
class OAuthResourceServerConfig {}
class DateTimeProvider {}
let SystemDateTimeProvider = /*#__PURE__*/(() => {
  class SystemDateTimeProvider extends DateTimeProvider {
    now() {
      return Date.now();
    }
    new() {
      return new Date();
    }
    static #_ = (() => this.ɵfac = /* @__PURE__ */(() => {
      let ɵSystemDateTimeProvider_BaseFactory;
      return function SystemDateTimeProvider_Factory(__ngFactoryType__) {
        return (ɵSystemDateTimeProvider_BaseFactory || (ɵSystemDateTimeProvider_BaseFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵgetInheritedFactory"](SystemDateTimeProvider)))(__ngFactoryType__ || SystemDateTimeProvider);
      };
    })())();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: SystemDateTimeProvider,
      factory: SystemDateTimeProvider.ɵfac
    }))();
  }
  return SystemDateTimeProvider;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Additional options that can be passed to tryLogin.
 */
class LoginOptions {
  constructor() {
    /**
     * Set this to true to disable the nonce
     * check which is used to avoid
     * replay attacks.
     * This flag should never be true in
     * production environments.
     */
    this.disableNonceCheck = false;
    /**
     * Normally, you want to clear your hash fragment after
     * the lib read the token(s) so that they are not displayed
     * anymore in the url. If not, set this to true. For code flow
     * this controls removing query string values.
     */
    this.preventClearHashAfterLogin = false;
  }
}
/**
 * Defines the logging interface the OAuthService uses
 * internally. Is compatible with the `console` object,
 * but you can provide your own implementation as well
 * through dependency injection.
 */
class OAuthLogger {}
/**
 * Defines a simple storage that can be used for
 * storing the tokens at client side.
 * Is compatible to localStorage and sessionStorage,
 * but you can also create your own implementations.
 */
class OAuthStorage {}
let MemoryStorage = /*#__PURE__*/(() => {
  class MemoryStorage {
    constructor() {
      this.data = new Map();
    }
    getItem(key) {
      return this.data.get(key);
    }
    removeItem(key) {
      this.data.delete(key);
    }
    setItem(key, data) {
      this.data.set(key, data);
    }
    static #_ = (() => this.ɵfac = function MemoryStorage_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || MemoryStorage)();
    })();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: MemoryStorage,
      factory: MemoryStorage.ɵfac
    }))();
  }
  return MemoryStorage;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
/**
 * Represents the received tokens, the received state
 * and the parsed claims from the id-token.
 */
class ReceivedTokens {}
class OAuthEvent {
  constructor(type) {
    this.type = type;
  }
}
class OAuthSuccessEvent extends OAuthEvent {
  constructor(type, info = null) {
    super(type);
    this.info = info;
  }
}
class OAuthInfoEvent extends OAuthEvent {
  constructor(type, info = null) {
    super(type);
    this.info = info;
  }
}
class OAuthErrorEvent extends OAuthEvent {
  constructor(type, reason, params = null) {
    super(type);
    this.reason = reason;
    this.params = params;
  }
}

// see: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22
function b64DecodeUnicode(str) {
  const base64 = str.replace(/-/g, '+').replace(/_/g, '/');
  return decodeURIComponent(atob(base64).split('').map(function (c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}
function base64UrlEncode(str) {
  const base64 = btoa(str);
  return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
class AuthConfig {
  constructor(json) {
    /**
     * The client's id as registered with the auth server
     */
    this.clientId = '';
    /**
     * The client's redirectUri as registered with the auth server
     */
    this.redirectUri = '';
    /**
     * An optional second redirectUri where the auth server
     * redirects the user to after logging out.
     */
    this.postLogoutRedirectUri = '';
    /**
     * Defines whether to use 'redirectUri' as a replacement
     * of 'postLogoutRedirectUri' if the latter is not set.
     */
    this.redirectUriAsPostLogoutRedirectUriFallback = true;
    /**
     * The auth server's endpoint that allows to log
     * the user in when using implicit flow.
     */
    this.loginUrl = '';
    /**
     * The requested scopes
     */
    this.scope = 'openid profile';
    this.resource = '';
    this.rngUrl = '';
    /**
     * Defines whether to use OpenId Connect during
     * implicit flow.
     */
    this.oidc = true;
    /**
     * Defines whether to request an access token during
     * implicit flow.
     */
    this.requestAccessToken = true;
    this.options = null;
    /**
     * The issuer's uri.
     */
    this.issuer = '';
    /**
     * The logout url.
     */
    this.logoutUrl = '';
    /**
     * Defines whether to clear the hash fragment after logging in.
     */
    this.clearHashAfterLogin = true;
    /**
     * Url of the token endpoint as defined by OpenId Connect and OAuth 2.
     */
    this.tokenEndpoint = null;
    /**
     * Url of the revocation endpoint as defined by OpenId Connect and OAuth 2.
     */
    this.revocationEndpoint = null;
    /**
     * Names of known parameters sent out in the TokenResponse. https://tools.ietf.org/html/rfc6749#section-5.1
     */
    this.customTokenParameters = [];
    /**
     * Url of the userinfo endpoint as defined by OpenId Connect.
     */
    this.userinfoEndpoint = null;
    this.responseType = '';
    /**
     * Defines whether additional debug information should
     * be shown at the console. Note that in certain browsers
     * the verbosity of the console needs to be explicitly set
     * to include Debug level messages.
     */
    this.showDebugInformation = false;
    /**
     * The redirect uri used when doing silent refresh.
     */
    this.silentRefreshRedirectUri = '';
    this.silentRefreshMessagePrefix = '';
    /**
     * Set this to true to display the iframe used for
     * silent refresh for debugging.
     */
    this.silentRefreshShowIFrame = false;
    /**
     * Timeout for silent refresh.
     * @internal
     * @deprecated use silentRefreshTimeout
     */
    this.siletRefreshTimeout = 1000 * 20;
    /**
     * Timeout for silent refresh.
     */
    this.silentRefreshTimeout = 1000 * 20;
    /**
     * Some auth servers don't allow using password flow
     * w/o a client secret while the standards do not
     * demand for it. In this case, you can set a password
     * here. As this password is exposed to the public
     * it does not bring additional security and is therefore
     * as good as using no password.
     */
    this.dummyClientSecret = '';
    /**
     * Defines whether https is required.
     * The default value is remoteOnly which only allows
     * http for localhost, while every other domains need
     * to be used with https.
     */
    this.requireHttps = 'remoteOnly';
    /**
     * Defines whether every url provided by the discovery
     * document has to start with the issuer's url.
     */
    this.strictDiscoveryDocumentValidation = true;
    /**
     * JSON Web Key Set (https://tools.ietf.org/html/rfc7517)
     * with keys used to validate received id_tokens.
     * This is taken out of the disovery document. Can be set manually too.
     */
    this.jwks = null;
    /**
     * Map with additional query parameter that are appended to
     * the request when initializing implicit flow.
     */
    this.customQueryParams = null;
    this.silentRefreshIFrameName = 'angular-oauth-oidc-silent-refresh-iframe';
    /**
     * Defines when the token_timeout event should be raised.
     * If you set this to the default value 0.75, the event
     * is triggered after 75% of the token's life time.
     */
    this.timeoutFactor = 0.75;
    /**
     * If true, the lib will try to check whether the user
     * is still logged in on a regular basis as described
     * in http://openid.net/specs/openid-connect-session-1_0.html#ChangeNotification
     */
    this.sessionChecksEnabled = false;
    /**
     * Interval in msec for checking the session
     * according to http://openid.net/specs/openid-connect-session-1_0.html#ChangeNotification
     */
    this.sessionCheckIntervall = 3 * 1000;
    /**
     * Url for the iframe used for session checks
     */
    this.sessionCheckIFrameUrl = null;
    /**
     * Name of the iframe to use for session checks
     */
    this.sessionCheckIFrameName = 'angular-oauth-oidc-check-session-iframe';
    /**
     * This property has been introduced to disable at_hash checks
     * and is indented for Identity Provider that does not deliver
     * an at_hash EVEN THOUGH its recommended by the OIDC specs.
     * Of course, when disabling these checks then we are bypassing
     * a security check which means we are more vulnerable.
     */
    this.disableAtHashCheck = false;
    /**
     * Defines wether to check the subject of a refreshed token after silent refresh.
     * Normally, it should be the same as before.
     */
    this.skipSubjectCheck = false;
    this.useIdTokenHintForSilentRefresh = false;
    /**
     * Defined whether to skip the validation of the issuer in the discovery document.
     * Normally, the discovey document's url starts with the url of the issuer.
     */
    this.skipIssuerCheck = false;
    /**
     * final state sent to issuer is built as follows:
     * state = nonce + nonceStateSeparator + additional state
     * Default separator is ';' (encoded %3B).
     * In rare cases, this character might be forbidden or inconvenient to use by the issuer so it can be customized.
     */
    this.nonceStateSeparator = ';';
    /**
     * Set this to true to use HTTP BASIC auth for AJAX calls
     */
    this.useHttpBasicAuth = false;
    /**
     * Decreases the Expiration time of tokens by this number of seconds
     */
    this.decreaseExpirationBySec = 0;
    /**
     * The interceptors waits this time span if there is no token
     */
    this.waitForTokenInMsec = 0;
    /**
     * Code Flow is by defauld used together with PKCI which is also higly recommented.
     * You can disbale it here by setting this flag to true.
     * https://tools.ietf.org/html/rfc7636#section-1.1
     */
    this.disablePKCE = false;
    /**
     * Set this to true to preserve the requested route including query parameters after code flow login.
     * This setting enables deep linking for the code flow.
     */
    this.preserveRequestedRoute = false;
    /**
     * Allows to disable the timer for the id_token used
     * for token refresh
     */
    this.disableIdTokenTimer = false;
    /**
     * Blocks other origins requesting a silent refresh
     */
    this.checkOrigin = false;
    /**
     * This property allows you to override the method that is used to open the login url,
     * allowing a way for implementations to specify their own method of routing to new
     * urls.
     */
    this.openUri = uri => {
      location.href = uri;
    };
    if (json) {
      Object.assign(this, json);
    }
  }
}

/**
 * This custom encoder allows charactes like +, % and / to be used in passwords
 */
class WebHttpUrlEncodingCodec {
  encodeKey(k) {
    return encodeURIComponent(k);
  }
  encodeValue(v) {
    return encodeURIComponent(v);
  }
  decodeKey(k) {
    return decodeURIComponent(k);
  }
  decodeValue(v) {
    return decodeURIComponent(v);
  }
}

/**
 * Interface for Handlers that are hooked in to
 * validate tokens.
 */
class ValidationHandler {}
/**
 * This abstract implementation of ValidationHandler already implements
 * the method validateAtHash. However, to make use of it,
 * you have to override the method calcHash.
 */
class AbstractValidationHandler {
  /**
   * Validates the at_hash in an id_token against the received access_token.
   */
  validateAtHash(params) {
    var _this = this;
    return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
      const hashAlg = _this.inferHashAlgorithm(params.idTokenHeader);
      const tokenHash = yield _this.calcHash(params.accessToken, hashAlg); // sha256(accessToken, { asString: true });
      const leftMostHalf = tokenHash.substr(0, tokenHash.length / 2);
      const atHash = base64UrlEncode(leftMostHalf);
      const claimsAtHash = params.idTokenClaims['at_hash'].replace(/=/g, '');
      if (atHash !== claimsAtHash) {
        console.error('exptected at_hash: ' + atHash);
        console.error('actual at_hash: ' + claimsAtHash);
      }
      return atHash === claimsAtHash;
    })();
  }
  /**
   * Infers the name of the hash algorithm to use
   * from the alg field of an id_token.
   *
   * @param jwtHeader the id_token's parsed header
   */
  inferHashAlgorithm(jwtHeader) {
    const alg = jwtHeader['alg'];
    if (!alg.match(/^.S[0-9]{3}$/)) {
      throw new Error('Algorithm not supported: ' + alg);
    }
    return 'sha-' + alg.substr(2);
  }
}
let UrlHelperService = /*#__PURE__*/(() => {
  class UrlHelperService {
    getHashFragmentParams(customHashFragment) {
      let hash = customHashFragment || window.location.hash;
      hash = decodeURIComponent(hash);
      if (hash.indexOf('#') !== 0) {
        return {};
      }
      const questionMarkPosition = hash.indexOf('?');
      if (questionMarkPosition > -1) {
        hash = hash.substr(questionMarkPosition + 1);
      } else {
        hash = hash.substr(1);
      }
      return this.parseQueryString(hash);
    }
    parseQueryString(queryString) {
      const data = {};
      let pair, separatorIndex, escapedKey, escapedValue, key, value;
      if (queryString === null) {
        return data;
      }
      const pairs = queryString.split('&');
      for (let i = 0; i < pairs.length; i++) {
        pair = pairs[i];
        separatorIndex = pair.indexOf('=');
        if (separatorIndex === -1) {
          escapedKey = pair;
          escapedValue = null;
        } else {
          escapedKey = pair.substr(0, separatorIndex);
          escapedValue = pair.substr(separatorIndex + 1);
        }
        key = decodeURIComponent(escapedKey);
        value = decodeURIComponent(escapedValue);
        if (key.substr(0, 1) === '/') {
          key = key.substr(1);
        }
        data[key] = value;
      }
      return data;
    }
    static #_ = (() => this.ɵfac = function UrlHelperService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || UrlHelperService)();
    })();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: UrlHelperService,
      factory: UrlHelperService.ɵfac
    }))();
  }
  return UrlHelperService;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

// Credits: https://github.com/dchest/fast-sha256-js/tree/master/src
// We add this lib directly b/c the published version of fast-sha256-js
// is commonjs and hence leads to a warning about tree-shakability emitted
// by the Angular CLI
// SHA-256 (+ HMAC and PBKDF2) for JavaScript.
//
// Written in 2014-2016 by Dmitry Chestnykh.
// Public domain, no warranty.
//
// Functions (accept and return Uint8Arrays):
//
//   sha256(message) -> hash
//   sha256.hmac(key, message) -> mac
//   sha256.pbkdf2(password, salt, rounds, dkLen) -> dk
//
//  Classes:
//
//   new sha256.Hash()
//   new sha256.HMAC(key)
//
const digestLength = 32;
const blockSize = 64;
// SHA-256 constants
const K = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
function hashBlocks(w, v, p, pos, len) {
  let a, b, c, d, e, f, g, h, u, i, j, t1, t2;
  while (len >= 64) {
    a = v[0];
    b = v[1];
    c = v[2];
    d = v[3];
    e = v[4];
    f = v[5];
    g = v[6];
    h = v[7];
    for (i = 0; i < 16; i++) {
      j = pos + i * 4;
      w[i] = (p[j] & 0xff) << 24 | (p[j + 1] & 0xff) << 16 | (p[j + 2] & 0xff) << 8 | p[j + 3] & 0xff;
    }
    for (i = 16; i < 64; i++) {
      u = w[i - 2];
      t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
      u = w[i - 15];
      t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
      w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
    }
    for (i = 0; i < 64; i++) {
      t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
      t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0;
      h = g;
      g = f;
      f = e;
      e = d + t1 | 0;
      d = c;
      c = b;
      b = a;
      a = t1 + t2 | 0;
    }
    v[0] += a;
    v[1] += b;
    v[2] += c;
    v[3] += d;
    v[4] += e;
    v[5] += f;
    v[6] += g;
    v[7] += h;
    pos += 64;
    len -= 64;
  }
  return pos;
}
// Hash implements SHA256 hash algorithm.
class Hash {
  constructor() {
    this.digestLength = digestLength;
    this.blockSize = blockSize;
    // Note: Int32Array is used instead of Uint32Array for performance reasons.
    this.state = new Int32Array(8); // hash state
    this.temp = new Int32Array(64); // temporary state
    this.buffer = new Uint8Array(128); // buffer for data to hash
    this.bufferLength = 0; // number of bytes in buffer
    this.bytesHashed = 0; // number of total bytes hashed
    this.finished = false; // indicates whether the hash was finalized
    this.reset();
  }
  // Resets hash state making it possible
  // to re-use this instance to hash other data.
  reset() {
    this.state[0] = 0x6a09e667;
    this.state[1] = 0xbb67ae85;
    this.state[2] = 0x3c6ef372;
    this.state[3] = 0xa54ff53a;
    this.state[4] = 0x510e527f;
    this.state[5] = 0x9b05688c;
    this.state[6] = 0x1f83d9ab;
    this.state[7] = 0x5be0cd19;
    this.bufferLength = 0;
    this.bytesHashed = 0;
    this.finished = false;
    return this;
  }
  // Cleans internal buffers and re-initializes hash state.
  clean() {
    for (let i = 0; i < this.buffer.length; i++) {
      this.buffer[i] = 0;
    }
    for (let i = 0; i < this.temp.length; i++) {
      this.temp[i] = 0;
    }
    this.reset();
  }
  // Updates hash state with the given data.
  //
  // Optionally, length of the data can be specified to hash
  // fewer bytes than data.length.
  //
  // Throws error when trying to update already finalized hash:
  // instance must be reset to use it again.
  update(data, dataLength = data.length) {
    if (this.finished) {
      throw new Error("SHA256: can't update because hash was finished.");
    }
    let dataPos = 0;
    this.bytesHashed += dataLength;
    if (this.bufferLength > 0) {
      while (this.bufferLength < 64 && dataLength > 0) {
        this.buffer[this.bufferLength++] = data[dataPos++];
        dataLength--;
      }
      if (this.bufferLength === 64) {
        hashBlocks(this.temp, this.state, this.buffer, 0, 64);
        this.bufferLength = 0;
      }
    }
    if (dataLength >= 64) {
      dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
      dataLength %= 64;
    }
    while (dataLength > 0) {
      this.buffer[this.bufferLength++] = data[dataPos++];
      dataLength--;
    }
    return this;
  }
  // Finalizes hash state and puts hash into out.
  //
  // If hash was already finalized, puts the same value.
  finish(out) {
    if (!this.finished) {
      const bytesHashed = this.bytesHashed;
      const left = this.bufferLength;
      const bitLenHi = bytesHashed / 0x20000000 | 0;
      const bitLenLo = bytesHashed << 3;
      const padLength = bytesHashed % 64 < 56 ? 64 : 128;
      this.buffer[left] = 0x80;
      for (let i = left + 1; i < padLength - 8; i++) {
        this.buffer[i] = 0;
      }
      this.buffer[padLength - 8] = bitLenHi >>> 24 & 0xff;
      this.buffer[padLength - 7] = bitLenHi >>> 16 & 0xff;
      this.buffer[padLength - 6] = bitLenHi >>> 8 & 0xff;
      this.buffer[padLength - 5] = bitLenHi >>> 0 & 0xff;
      this.buffer[padLength - 4] = bitLenLo >>> 24 & 0xff;
      this.buffer[padLength - 3] = bitLenLo >>> 16 & 0xff;
      this.buffer[padLength - 2] = bitLenLo >>> 8 & 0xff;
      this.buffer[padLength - 1] = bitLenLo >>> 0 & 0xff;
      hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
      this.finished = true;
    }
    for (let i = 0; i < 8; i++) {
      out[i * 4 + 0] = this.state[i] >>> 24 & 0xff;
      out[i * 4 + 1] = this.state[i] >>> 16 & 0xff;
      out[i * 4 + 2] = this.state[i] >>> 8 & 0xff;
      out[i * 4 + 3] = this.state[i] >>> 0 & 0xff;
    }
    return this;
  }
  // Returns the final hash digest.
  digest() {
    const out = new Uint8Array(this.digestLength);
    this.finish(out);
    return out;
  }
  // Internal function for use in HMAC for optimization.
  _saveState(out) {
    for (let i = 0; i < this.state.length; i++) {
      out[i] = this.state[i];
    }
  }
  // Internal function for use in HMAC for optimization.
  _restoreState(from, bytesHashed) {
    for (let i = 0; i < this.state.length; i++) {
      this.state[i] = from[i];
    }
    this.bytesHashed = bytesHashed;
    this.finished = false;
    this.bufferLength = 0;
  }
}
// HMAC implements HMAC-SHA256 message authentication algorithm.
class HMAC {
  constructor(key) {
    this.inner = new Hash();
    this.outer = new Hash();
    this.blockSize = this.inner.blockSize;
    this.digestLength = this.inner.digestLength;
    const pad = new Uint8Array(this.blockSize);
    if (key.length > this.blockSize) {
      new Hash().update(key).finish(pad).clean();
    } else {
      for (let i = 0; i < key.length; i++) {
        pad[i] = key[i];
      }
    }
    for (let i = 0; i < pad.length; i++) {
      pad[i] ^= 0x36;
    }
    this.inner.update(pad);
    for (let i = 0; i < pad.length; i++) {
      pad[i] ^= 0x36 ^ 0x5c;
    }
    this.outer.update(pad);
    this.istate = new Uint32Array(8);
    this.ostate = new Uint32Array(8);
    this.inner._saveState(this.istate);
    this.outer._saveState(this.ostate);
    for (let i = 0; i < pad.length; i++) {
      pad[i] = 0;
    }
  }
  // Returns HMAC state to the state initialized with key
  // to make it possible to run HMAC over the other data with the same
  // key without creating a new instance.
  reset() {
    this.inner._restoreState(this.istate, this.inner.blockSize);
    this.outer._restoreState(this.ostate, this.outer.blockSize);
    return this;
  }
  // Cleans HMAC state.
  clean() {
    for (let i = 0; i < this.istate.length; i++) {
      this.ostate[i] = this.istate[i] = 0;
    }
    this.inner.clean();
    this.outer.clean();
  }
  // Updates state with provided data.
  update(data) {
    this.inner.update(data);
    return this;
  }
  // Finalizes HMAC and puts the result in out.
  finish(out) {
    if (this.outer.finished) {
      this.outer.finish(out);
    } else {
      this.inner.finish(out);
      this.outer.update(out, this.digestLength).finish(out);
    }
    return this;
  }
  // Returns message authentication code.
  digest() {
    const out = new Uint8Array(this.digestLength);
    this.finish(out);
    return out;
  }
}
// Returns SHA256 hash of data.
function hash(data) {
  const h = new Hash().update(data);
  const digest = h.digest();
  h.clean();
  return digest;
}
// Returns HMAC-SHA256 of data under the key.
function hmac(key, data) {
  const h = new HMAC(key).update(data);
  const digest = h.digest();
  h.clean();
  return digest;
}
// Fills hkdf buffer like this:
// T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
function fillBuffer(buffer, hmac, info, counter) {
  // Counter is a byte value: check if it overflowed.
  const num = counter[0];
  if (num === 0) {
    throw new Error('hkdf: cannot expand more');
  }
  // Prepare HMAC instance for new data with old key.
  hmac.reset();
  // Hash in previous output if it was generated
  // (i.e. counter is greater than 1).
  if (num > 1) {
    hmac.update(buffer);
  }
  // Hash in info if it exists.
  if (info) {
    hmac.update(info);
  }
  // Hash in the counter.
  hmac.update(counter);
  // Output result to buffer and clean HMAC instance.
  hmac.finish(buffer);
  // Increment counter inside typed array, this works properly.
  counter[0]++;
}
const hkdfSalt = new Uint8Array(digestLength); // Filled with zeroes.
function hkdf(key, salt = hkdfSalt, info, length = 32) {
  const counter = new Uint8Array([1]);
  // HKDF-Extract uses salt as HMAC key, and key as data.
  const okm = hmac(salt, key);
  // Initialize HMAC for expanding with extracted key.
  // Ensure no collisions with `hmac` function.
  const hmac_ = new HMAC(okm);
  // Allocate buffer.
  const buffer = new Uint8Array(hmac_.digestLength);
  let bufpos = buffer.length;
  const out = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    if (bufpos === buffer.length) {
      fillBuffer(buffer, hmac_, info, counter);
      bufpos = 0;
    }
    out[i] = buffer[bufpos++];
  }
  hmac_.clean();
  buffer.fill(0);
  counter.fill(0);
  return out;
}
// Derives a key from password and salt using PBKDF2-HMAC-SHA256
// with the given number of iterations.
//
// The number of bytes returned is equal to dkLen.
//
// (For better security, avoid dkLen greater than hash length - 32 bytes).
function pbkdf2(password, salt, iterations, dkLen) {
  const prf = new HMAC(password);
  const len = prf.digestLength;
  const ctr = new Uint8Array(4);
  const t = new Uint8Array(len);
  const u = new Uint8Array(len);
  const dk = new Uint8Array(dkLen);
  for (let i = 0; i * len < dkLen; i++) {
    const c = i + 1;
    ctr[0] = c >>> 24 & 0xff;
    ctr[1] = c >>> 16 & 0xff;
    ctr[2] = c >>> 8 & 0xff;
    ctr[3] = c >>> 0 & 0xff;
    prf.reset();
    prf.update(salt);
    prf.update(ctr);
    prf.finish(u);
    for (let j = 0; j < len; j++) {
      t[j] = u[j];
    }
    for (let j = 2; j <= iterations; j++) {
      prf.reset();
      prf.update(u).finish(u);
      for (let k = 0; k < len; k++) {
        t[k] ^= u[k];
      }
    }
    for (let j = 0; j < len && i * len + j < dkLen; j++) {
      dk[i * len + j] = t[j];
    }
  }
  for (let i = 0; i < len; i++) {
    t[i] = u[i] = 0;
  }
  for (let i = 0; i < 4; i++) {
    ctr[i] = 0;
  }
  prf.clean();
  return dk;
}

/**
 * Abstraction for crypto algorithms
 */
class HashHandler {}
function decodeUTF8(s) {
  if (typeof s !== 'string') throw new TypeError('expected string');
  const d = s,
    b = new Uint8Array(d.length);
  for (let i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
  return b;
}
function encodeUTF8(arr) {
  const s = [];
  for (let i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
  return s.join('');
}
let DefaultHashHandler = /*#__PURE__*/(() => {
  class DefaultHashHandler {
    calcHash(valueToHash, algorithm) {
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        // const encoder = new TextEncoder();
        // const hashArray = await window.crypto.subtle.digest(algorithm, data);
        // const data = encoder.encode(valueToHash);
        // const fhash = fsha256(valueToHash);
        const candHash = encodeUTF8(hash(decodeUTF8(valueToHash)));
        // const hashArray = (sha256 as any).array(valueToHash);
        // // const hashString = this.toHashString(hashArray);
        // const hashString = this.toHashString2(hashArray);
        // console.debug('hash orig - cand', candHash, hashString);
        // alert(1);
        return candHash;
      })();
    }
    toHashString2(byteArray) {
      let result = '';
      for (const e of byteArray) {
        result += String.fromCharCode(e);
      }
      return result;
    }
    toHashString(buffer) {
      const byteArray = new Uint8Array(buffer);
      let result = '';
      for (const e of byteArray) {
        result += String.fromCharCode(e);
      }
      return result;
    }
    static #_ = (() => this.ɵfac = function DefaultHashHandler_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DefaultHashHandler)();
    })();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DefaultHashHandler,
      factory: DefaultHashHandler.ɵfac
    }))();
  }
  return DefaultHashHandler;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();

/**
 * Service for logging in and logging out with
 * OIDC and OAuth2. Supports implicit flow and
 * password flow.
 */
let OAuthService = /*#__PURE__*/(() => {
  class OAuthService extends AuthConfig {
    constructor(ngZone, http, storage, tokenValidationHandler, config, urlHelper, logger, crypto, document, dateTimeService) {
      super();
      this.ngZone = ngZone;
      this.http = http;
      this.config = config;
      this.urlHelper = urlHelper;
      this.logger = logger;
      this.crypto = crypto;
      this.dateTimeService = dateTimeService;
      /**
       * @internal
       * Deprecated:  use property events instead
       */
      this.discoveryDocumentLoaded = false;
      /**
       * The received (passed around) state, when logging
       * in with implicit flow.
       */
      this.state = '';
      this.eventsSubject = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
      this.discoveryDocumentLoadedSubject = new rxjs__WEBPACK_IMPORTED_MODULE_2__.Subject();
      this.grantTypesSupported = [];
      this.inImplicitFlow = false;
      this.saveNoncesInLocalStorage = false;
      this.debug('angular-oauth2-oidc v10');
      // See https://github.com/manfredsteyer/angular-oauth2-oidc/issues/773 for why this is needed
      this.document = document;
      if (!config) {
        config = {};
      }
      this.discoveryDocumentLoaded$ = this.discoveryDocumentLoadedSubject.asObservable();
      this.events = this.eventsSubject.asObservable();
      if (tokenValidationHandler) {
        this.tokenValidationHandler = tokenValidationHandler;
      }
      if (config) {
        this.configure(config);
      }
      try {
        if (storage) {
          this.setStorage(storage);
        } else if (typeof sessionStorage !== 'undefined') {
          this.setStorage(sessionStorage);
        }
      } catch (e) {
        console.error('No OAuthStorage provided and cannot access default (sessionStorage).' + 'Consider providing a custom OAuthStorage implementation in your module.', e);
      }
      // in IE, sessionStorage does not always survive a redirect
      if (this.checkLocalStorageAccessable()) {
        const ua = window?.navigator?.userAgent;
        const msie = ua?.includes('MSIE ') || ua?.includes('Trident');
        if (msie) {
          this.saveNoncesInLocalStorage = true;
        }
      }
      this.setupRefreshTimer();
    }
    checkLocalStorageAccessable() {
      if (typeof window === 'undefined') return false;
      const test = 'test';
      try {
        if (typeof window['localStorage'] === 'undefined') return false;
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
      } catch (e) {
        return false;
      }
    }
    /**
     * Use this method to configure the service
     * @param config the configuration
     */
    configure(config) {
      // For the sake of downward compatibility with
      // original configuration API
      Object.assign(this, new AuthConfig(), config);
      this.config = Object.assign({}, new AuthConfig(), config);
      if (this.sessionChecksEnabled) {
        this.setupSessionCheck();
      }
      this.configChanged();
    }
    configChanged() {
      this.setupRefreshTimer();
    }
    restartSessionChecksIfStillLoggedIn() {
      if (this.hasValidIdToken()) {
        this.initSessionCheck();
      }
    }
    restartRefreshTimerIfStillLoggedIn() {
      this.setupExpirationTimers();
    }
    setupSessionCheck() {
      this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'token_received')).subscribe(() => {
        this.initSessionCheck();
      });
    }
    /**
     * Will setup up silent refreshing for when the token is
     * about to expire. When the user is logged out via this.logOut method, the
     * silent refreshing will pause and not refresh the tokens until the user is
     * logged back in via receiving a new token.
     * @param params Additional parameter to pass
     * @param listenTo Setup automatic refresh of a specific token type
     */
    setupAutomaticSilentRefresh(params = {}, listenTo, noPrompt = true) {
      let shouldRunSilentRefresh = true;
      this.clearAutomaticRefreshTimer();
      this.automaticRefreshSubscription = this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.tap)(e => {
        if (e.type === 'token_received') {
          shouldRunSilentRefresh = true;
        } else if (e.type === 'logout') {
          shouldRunSilentRefresh = false;
        }
      }), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'token_expires' && (listenTo == null || listenTo === 'any' || e.info === listenTo)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_5__.debounceTime)(1000)).subscribe(() => {
        if (shouldRunSilentRefresh) {
          // this.silentRefresh(params, noPrompt).catch(_ => {
          this.refreshInternal(params, noPrompt).catch(() => {
            this.debug('Automatic silent refresh did not work');
          });
        }
      });
      this.restartRefreshTimerIfStillLoggedIn();
    }
    refreshInternal(params, noPrompt) {
      if (!this.useSilentRefresh && this.responseType === 'code') {
        return this.refreshToken();
      } else {
        return this.silentRefresh(params, noPrompt);
      }
    }
    /**
     * Convenience method that first calls `loadDiscoveryDocument(...)` and
     * directly chains using the `then(...)` part of the promise to call
     * the `tryLogin(...)` method.
     *
     * @param options LoginOptions to pass through to `tryLogin(...)`
     */
    loadDiscoveryDocumentAndTryLogin(options = null) {
      return this.loadDiscoveryDocument().then(() => {
        return this.tryLogin(options);
      });
    }
    /**
     * Convenience method that first calls `loadDiscoveryDocumentAndTryLogin(...)`
     * and if then chains to `initLoginFlow()`, but only if there is no valid
     * IdToken or no valid AccessToken.
     *
     * @param options LoginOptions to pass through to `tryLogin(...)`
     */
    loadDiscoveryDocumentAndLogin(options = null) {
      options = options || {};
      return this.loadDiscoveryDocumentAndTryLogin(options).then(() => {
        if (!this.hasValidIdToken() || !this.hasValidAccessToken()) {
          const state = typeof options.state === 'string' ? options.state : '';
          this.initLoginFlow(state);
          return false;
        } else {
          return true;
        }
      });
    }
    debug(...args) {
      if (this.showDebugInformation) {
        this.logger.debug(...args);
      }
    }
    validateUrlFromDiscoveryDocument(url) {
      const errors = [];
      const httpsCheck = this.validateUrlForHttps(url);
      const issuerCheck = this.validateUrlAgainstIssuer(url);
      if (!httpsCheck) {
        errors.push('https for all urls required. Also for urls received by discovery.');
      }
      if (!issuerCheck) {
        errors.push('Every url in discovery document has to start with the issuer url.' + 'Also see property strictDiscoveryDocumentValidation.');
      }
      return errors;
    }
    validateUrlForHttps(url) {
      if (!url) {
        return true;
      }
      const lcUrl = url.toLowerCase();
      if (this.requireHttps === false) {
        return true;
      }
      if ((lcUrl.match(/^http:\/\/localhost($|[:/])/) || lcUrl.match(/^http:\/\/localhost($|[:/])/)) && this.requireHttps === 'remoteOnly') {
        return true;
      }
      return lcUrl.startsWith('https://');
    }
    assertUrlNotNullAndCorrectProtocol(url, description) {
      if (!url) {
        throw new Error(`'${description}' should not be null`);
      }
      if (!this.validateUrlForHttps(url)) {
        throw new Error(`'${description}' must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).`);
      }
    }
    validateUrlAgainstIssuer(url) {
      if (!this.strictDiscoveryDocumentValidation) {
        return true;
      }
      if (!url) {
        return true;
      }
      return url.toLowerCase().startsWith(this.issuer.toLowerCase());
    }
    setupRefreshTimer() {
      if (typeof window === 'undefined') {
        this.debug('timer not supported on this plattform');
        return;
      }
      if (this.hasValidIdToken() || this.hasValidAccessToken()) {
        this.clearAccessTokenTimer();
        this.clearIdTokenTimer();
        this.setupExpirationTimers();
      }
      if (this.tokenReceivedSubscription) this.tokenReceivedSubscription.unsubscribe();
      this.tokenReceivedSubscription = this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'token_received')).subscribe(() => {
        this.clearAccessTokenTimer();
        this.clearIdTokenTimer();
        this.setupExpirationTimers();
      });
    }
    setupExpirationTimers() {
      if (this.hasValidAccessToken()) {
        this.setupAccessTokenTimer();
      }
      if (!this.disableIdTokenTimer && this.hasValidIdToken()) {
        this.setupIdTokenTimer();
      }
    }
    setupAccessTokenTimer() {
      const expiration = this.getAccessTokenExpiration();
      const storedAt = this.getAccessTokenStoredAt();
      const timeout = this.calcTimeout(storedAt, expiration);
      this.ngZone.runOutsideAngular(() => {
        this.accessTokenTimeoutSubscription = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(new OAuthInfoEvent('token_expires', 'access_token')).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.delay)(timeout)).subscribe(e => {
          this.ngZone.run(() => {
            this.eventsSubject.next(e);
          });
        });
      });
    }
    setupIdTokenTimer() {
      const expiration = this.getIdTokenExpiration();
      const storedAt = this.getIdTokenStoredAt();
      const timeout = this.calcTimeout(storedAt, expiration);
      this.ngZone.runOutsideAngular(() => {
        this.idTokenTimeoutSubscription = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(new OAuthInfoEvent('token_expires', 'id_token')).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.delay)(timeout)).subscribe(e => {
          this.ngZone.run(() => {
            this.eventsSubject.next(e);
          });
        });
      });
    }
    /**
     * Stops timers for automatic refresh.
     * To restart it, call setupAutomaticSilentRefresh again.
     */
    stopAutomaticRefresh() {
      this.clearAccessTokenTimer();
      this.clearIdTokenTimer();
      this.clearAutomaticRefreshTimer();
    }
    clearAccessTokenTimer() {
      if (this.accessTokenTimeoutSubscription) {
        this.accessTokenTimeoutSubscription.unsubscribe();
      }
    }
    clearIdTokenTimer() {
      if (this.idTokenTimeoutSubscription) {
        this.idTokenTimeoutSubscription.unsubscribe();
      }
    }
    clearAutomaticRefreshTimer() {
      if (this.automaticRefreshSubscription) {
        this.automaticRefreshSubscription.unsubscribe();
      }
    }
    calcTimeout(storedAt, expiration) {
      const now = this.dateTimeService.now();
      const delta = (expiration - storedAt) * this.timeoutFactor - (now - storedAt);
      const duration = Math.max(0, delta);
      const maxTimeoutValue = 2_147_483_647;
      return duration > maxTimeoutValue ? maxTimeoutValue : duration;
    }
    /**
     * DEPRECATED. Use a provider for OAuthStorage instead:
     *
     * { provide: OAuthStorage, useFactory: oAuthStorageFactory }
     * export function oAuthStorageFactory(): OAuthStorage { return localStorage; }
     * Sets a custom storage used to store the received
     * tokens on client side. By default, the browser's
     * sessionStorage is used.
     * @ignore
     *
     * @param storage
     */
    setStorage(storage) {
      this._storage = storage;
      this.configChanged();
    }
    /**
     * Loads the discovery document to configure most
     * properties of this service. The url of the discovery
     * document is infered from the issuer's url according
     * to the OpenId Connect spec. To use another url you
     * can pass it to to optional parameter fullUrl.
     *
     * @param fullUrl
     */
    loadDiscoveryDocument(fullUrl = null) {
      return new Promise((resolve, reject) => {
        if (!fullUrl) {
          fullUrl = this.issuer || '';
          if (!fullUrl.endsWith('/')) {
            fullUrl += '/';
          }
          fullUrl += '.well-known/openid-configuration';
        }
        if (!this.validateUrlForHttps(fullUrl)) {
          reject("issuer  must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
          return;
        }
        this.http.get(fullUrl).subscribe(doc => {
          if (!this.validateDiscoveryDocument(doc)) {
            this.eventsSubject.next(new OAuthErrorEvent('discovery_document_validation_error', null));
            reject('discovery_document_validation_error');
            return;
          }
          this.loginUrl = doc.authorization_endpoint;
          this.logoutUrl = doc.end_session_endpoint || this.logoutUrl;
          this.grantTypesSupported = doc.grant_types_supported;
          this.issuer = doc.issuer;
          this.tokenEndpoint = doc.token_endpoint;
          this.userinfoEndpoint = doc.userinfo_endpoint || this.userinfoEndpoint;
          this.jwksUri = doc.jwks_uri;
          this.sessionCheckIFrameUrl = doc.check_session_iframe || this.sessionCheckIFrameUrl;
          this.discoveryDocumentLoaded = true;
          this.discoveryDocumentLoadedSubject.next(doc);
          this.revocationEndpoint = doc.revocation_endpoint || this.revocationEndpoint;
          if (this.sessionChecksEnabled) {
            this.restartSessionChecksIfStillLoggedIn();
          }
          this.loadJwks().then(jwks => {
            const result = {
              discoveryDocument: doc,
              jwks: jwks
            };
            const event = new OAuthSuccessEvent('discovery_document_loaded', result);
            this.eventsSubject.next(event);
            resolve(event);
            return;
          }).catch(err => {
            this.eventsSubject.next(new OAuthErrorEvent('discovery_document_load_error', err));
            reject(err);
            return;
          });
        }, err => {
          this.logger.error('error loading discovery document', err);
          this.eventsSubject.next(new OAuthErrorEvent('discovery_document_load_error', err));
          reject(err);
        });
      });
    }
    loadJwks() {
      return new Promise((resolve, reject) => {
        if (this.jwksUri) {
          this.http.get(this.jwksUri).subscribe(jwks => {
            this.jwks = jwks;
            // this.eventsSubject.next(
            //   new OAuthSuccessEvent('discovery_document_loaded')
            // );
            resolve(jwks);
          }, err => {
            this.logger.error('error loading jwks', err);
            this.eventsSubject.next(new OAuthErrorEvent('jwks_load_error', err));
            reject(err);
          });
        } else {
          resolve(null);
        }
      });
    }
    validateDiscoveryDocument(doc) {
      let errors;
      if (!this.skipIssuerCheck && doc.issuer !== this.issuer) {
        this.logger.error('invalid issuer in discovery document', 'expected: ' + this.issuer, 'current: ' + doc.issuer);
        return false;
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.authorization_endpoint);
      if (errors.length > 0) {
        this.logger.error('error validating authorization_endpoint in discovery document', errors);
        return false;
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.end_session_endpoint);
      if (errors.length > 0) {
        this.logger.error('error validating end_session_endpoint in discovery document', errors);
        return false;
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.token_endpoint);
      if (errors.length > 0) {
        this.logger.error('error validating token_endpoint in discovery document', errors);
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.revocation_endpoint);
      if (errors.length > 0) {
        this.logger.error('error validating revocation_endpoint in discovery document', errors);
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.userinfo_endpoint);
      if (errors.length > 0) {
        this.logger.error('error validating userinfo_endpoint in discovery document', errors);
        return false;
      }
      errors = this.validateUrlFromDiscoveryDocument(doc.jwks_uri);
      if (errors.length > 0) {
        this.logger.error('error validating jwks_uri in discovery document', errors);
        return false;
      }
      if (this.sessionChecksEnabled && !doc.check_session_iframe) {
        this.logger.warn('sessionChecksEnabled is activated but discovery document' + ' does not contain a check_session_iframe field');
      }
      return true;
    }
    /**
     * Uses password flow to exchange userName and password for an
     * access_token. After receiving the access_token, this method
     * uses it to query the userinfo endpoint in order to get information
     * about the user in question.
     *
     * When using this, make sure that the property oidc is set to false.
     * Otherwise stricter validations take place that make this operation
     * fail.
     *
     * @param userName
     * @param password
     * @param headers Optional additional http-headers.
     */
    fetchTokenUsingPasswordFlowAndLoadUserProfile(userName, password, headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders()) {
      return this.fetchTokenUsingPasswordFlow(userName, password, headers).then(() => this.loadUserProfile());
    }
    /**
     * Loads the user profile by accessing the user info endpoint defined by OpenId Connect.
     *
     * When using this with OAuth2 password flow, make sure that the property oidc is set to false.
     * Otherwise stricter validations take place that make this operation fail.
     */
    loadUserProfile() {
      if (!this.hasValidAccessToken()) {
        throw new Error('Can not load User Profile without access_token');
      }
      if (!this.validateUrlForHttps(this.userinfoEndpoint)) {
        throw new Error("userinfoEndpoint must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
      }
      return new Promise((resolve, reject) => {
        const headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders().set('Authorization', 'Bearer ' + this.getAccessToken());
        this.http.get(this.userinfoEndpoint, {
          headers,
          observe: 'response',
          responseType: 'text'
        }).subscribe(response => {
          this.debug('userinfo received', JSON.stringify(response));
          if (response.headers.get('content-type').startsWith('application/json')) {
            let info = JSON.parse(response.body);
            const existingClaims = this.getIdentityClaims() || {};
            if (!this.skipSubjectCheck) {
              if (this.oidc && (!existingClaims['sub'] || info.sub !== existingClaims['sub'])) {
                const err = 'if property oidc is true, the received user-id (sub) has to be the user-id ' + 'of the user that has logged in with oidc.\n' + 'if you are not using oidc but just oauth2 password flow set oidc to false';
                reject(err);
                return;
              }
            }
            info = Object.assign({}, existingClaims, info);
            this._storage.setItem('id_token_claims_obj', JSON.stringify(info));
            this.eventsSubject.next(new OAuthSuccessEvent('user_profile_loaded'));
            resolve({
              info
            });
          } else {
            this.debug('userinfo is not JSON, treating it as JWE/JWS');
            this.eventsSubject.next(new OAuthSuccessEvent('user_profile_loaded'));
            resolve(JSON.parse(response.body));
          }
        }, err => {
          this.logger.error('error loading user info', err);
          this.eventsSubject.next(new OAuthErrorEvent('user_profile_load_error', err));
          reject(err);
        });
      });
    }
    /**
     * Uses password flow to exchange userName and password for an access_token.
     * @param userName
     * @param password
     * @param headers Optional additional http-headers.
     */
    fetchTokenUsingPasswordFlow(userName, password, headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders()) {
      const parameters = {
        username: userName,
        password: password
      };
      return this.fetchTokenUsingGrant('password', parameters, headers);
    }
    /**
     * Uses a custom grant type to retrieve tokens.
     * @param grantType Grant type.
     * @param parameters Parameters to pass.
     * @param headers Optional additional HTTP headers.
     */
    fetchTokenUsingGrant(grantType, parameters, headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders()) {
      this.assertUrlNotNullAndCorrectProtocol(this.tokenEndpoint, 'tokenEndpoint');
      /**
       * A `HttpParameterCodec` that uses `encodeURIComponent` and `decodeURIComponent` to
       * serialize and parse URL parameter keys and values.
       *
       * @stable
       */
      let params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpParams({
        encoder: new WebHttpUrlEncodingCodec()
      }).set('grant_type', grantType).set('scope', this.scope);
      if (this.useHttpBasicAuth) {
        const header = btoa(`${this.clientId}:${this.dummyClientSecret}`);
        headers = headers.set('Authorization', 'Basic ' + header);
      }
      if (!this.useHttpBasicAuth) {
        params = params.set('client_id', this.clientId);
      }
      if (!this.useHttpBasicAuth && this.dummyClientSecret) {
        params = params.set('client_secret', this.dummyClientSecret);
      }
      if (this.customQueryParams) {
        for (const key of Object.getOwnPropertyNames(this.customQueryParams)) {
          params = params.set(key, this.customQueryParams[key]);
        }
      }
      // set explicit parameters last, to allow overwriting
      for (const key of Object.keys(parameters)) {
        params = params.set(key, parameters[key]);
      }
      headers = headers.set('Content-Type', 'application/x-www-form-urlencoded');
      return new Promise((resolve, reject) => {
        this.http.post(this.tokenEndpoint, params, {
          headers
        }).subscribe(tokenResponse => {
          this.debug('tokenResponse', tokenResponse);
          this.storeAccessTokenResponse(tokenResponse.access_token, tokenResponse.refresh_token, tokenResponse.expires_in || this.fallbackAccessTokenExpirationTimeInSec, tokenResponse.scope, this.extractRecognizedCustomParameters(tokenResponse));
          if (this.oidc && tokenResponse.id_token) {
            this.processIdToken(tokenResponse.id_token, tokenResponse.access_token).then(result => {
              this.storeIdToken(result);
              resolve(tokenResponse);
            });
          }
          this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
          resolve(tokenResponse);
        }, err => {
          this.logger.error('Error performing ${grantType} flow', err);
          this.eventsSubject.next(new OAuthErrorEvent('token_error', err));
          reject(err);
        });
      });
    }
    /**
     * Refreshes the token using a refresh_token.
     * This does not work for implicit flow, b/c
     * there is no refresh_token in this flow.
     * A solution for this is provided by the
     * method silentRefresh.
     */
    refreshToken() {
      this.assertUrlNotNullAndCorrectProtocol(this.tokenEndpoint, 'tokenEndpoint');
      return new Promise((resolve, reject) => {
        let params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpParams({
          encoder: new WebHttpUrlEncodingCodec()
        }).set('grant_type', 'refresh_token').set('scope', this.scope).set('refresh_token', this._storage.getItem('refresh_token'));
        let headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
        if (this.useHttpBasicAuth) {
          const header = btoa(`${this.clientId}:${this.dummyClientSecret}`);
          headers = headers.set('Authorization', 'Basic ' + header);
        }
        if (!this.useHttpBasicAuth) {
          params = params.set('client_id', this.clientId);
        }
        if (!this.useHttpBasicAuth && this.dummyClientSecret) {
          params = params.set('client_secret', this.dummyClientSecret);
        }
        if (this.customQueryParams) {
          for (const key of Object.getOwnPropertyNames(this.customQueryParams)) {
            params = params.set(key, this.customQueryParams[key]);
          }
        }
        this.http.post(this.tokenEndpoint, params, {
          headers
        }).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_9__.switchMap)(tokenResponse => {
          if (this.oidc && tokenResponse.id_token) {
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_10__.from)(this.processIdToken(tokenResponse.id_token, tokenResponse.access_token, true)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_4__.tap)(result => this.storeIdToken(result)), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.map)(() => tokenResponse));
          } else {
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(tokenResponse);
          }
        })).subscribe(tokenResponse => {
          this.debug('refresh tokenResponse', tokenResponse);
          this.storeAccessTokenResponse(tokenResponse.access_token, tokenResponse.refresh_token, tokenResponse.expires_in || this.fallbackAccessTokenExpirationTimeInSec, tokenResponse.scope, this.extractRecognizedCustomParameters(tokenResponse));
          this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
          this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed'));
          resolve(tokenResponse);
        }, err => {
          this.logger.error('Error refreshing token', err);
          this.eventsSubject.next(new OAuthErrorEvent('token_refresh_error', err));
          reject(err);
        });
      });
    }
    removeSilentRefreshEventListener() {
      if (this.silentRefreshPostMessageEventListener) {
        window.removeEventListener('message', this.silentRefreshPostMessageEventListener);
        this.silentRefreshPostMessageEventListener = null;
      }
    }
    setupSilentRefreshEventListener() {
      this.removeSilentRefreshEventListener();
      this.silentRefreshPostMessageEventListener = e => {
        const message = this.processMessageEventMessage(e);
        if (this.checkOrigin && e.origin !== location.origin) {
          console.error('wrong origin requested silent refresh!');
        }
        this.tryLogin({
          customHashFragment: message,
          preventClearHashAfterLogin: true,
          customRedirectUri: this.silentRefreshRedirectUri || this.redirectUri
        }).catch(err => this.debug('tryLogin during silent refresh failed', err));
      };
      window.addEventListener('message', this.silentRefreshPostMessageEventListener);
    }
    /**
     * Performs a silent refresh for implicit flow.
     * Use this method to get new tokens when/before
     * the existing tokens expire.
     */
    silentRefresh(params = {}, noPrompt = true) {
      const claims = this.getIdentityClaims() || {};
      if (this.useIdTokenHintForSilentRefresh && this.hasValidIdToken()) {
        params['id_token_hint'] = this.getIdToken();
      }
      if (!this.validateUrlForHttps(this.loginUrl)) {
        throw new Error("loginUrl  must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
      }
      if (typeof this.document === 'undefined') {
        throw new Error('silent refresh is not supported on this platform');
      }
      const existingIframe = this.document.getElementById(this.silentRefreshIFrameName);
      if (existingIframe) {
        this.document.body.removeChild(existingIframe);
      }
      this.silentRefreshSubject = claims['sub'];
      const iframe = this.document.createElement('iframe');
      iframe.id = this.silentRefreshIFrameName;
      this.setupSilentRefreshEventListener();
      const redirectUri = this.silentRefreshRedirectUri || this.redirectUri;
      this.createLoginUrl(null, null, redirectUri, noPrompt, params).then(url => {
        iframe.setAttribute('src', url);
        if (!this.silentRefreshShowIFrame) {
          iframe.style['display'] = 'none';
        }
        this.document.body.appendChild(iframe);
      });
      const errors = this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e instanceof OAuthErrorEvent), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.first)());
      const success = this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'token_received'), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.first)());
      const timeout = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(new OAuthErrorEvent('silent_refresh_timeout', null)).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_7__.delay)(this.silentRefreshTimeout));
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_13__.race)([errors, success, timeout]).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.map)(e => {
        if (e instanceof OAuthErrorEvent) {
          if (e.type === 'silent_refresh_timeout') {
            this.eventsSubject.next(e);
          } else {
            e = new OAuthErrorEvent('silent_refresh_error', e);
            this.eventsSubject.next(e);
          }
          throw e;
        } else if (e.type === 'token_received') {
          e = new OAuthSuccessEvent('silently_refreshed');
          this.eventsSubject.next(e);
        }
        return e;
      })).toPromise();
    }
    /**
     * This method exists for backwards compatibility.
     * {@link OAuthService#initLoginFlowInPopup} handles both code
     * and implicit flows.
     */
    initImplicitFlowInPopup(options) {
      return this.initLoginFlowInPopup(options);
    }
    initLoginFlowInPopup(options) {
      options = options || {};
      return this.createLoginUrl(null, null, this.silentRefreshRedirectUri, false, {
        display: 'popup'
      }).then(url => {
        return new Promise((resolve, reject) => {
          /**
           * Error handling section
           */
          const checkForPopupClosedInterval = 500;
          let windowRef = null;
          // If we got no window reference we open a window
          // else we are using the window already opened
          if (!options.windowRef) {
            windowRef = window.open(url, 'ngx-oauth2-oidc-login', this.calculatePopupFeatures(options));
          } else if (options.windowRef && !options.windowRef.closed) {
            windowRef = options.windowRef;
            windowRef.location.href = url;
          }
          let checkForPopupClosedTimer;
          const tryLogin = hash => {
            this.tryLogin({
              customHashFragment: hash,
              preventClearHashAfterLogin: true,
              customRedirectUri: this.silentRefreshRedirectUri
            }).then(() => {
              cleanup();
              resolve(true);
            }, err => {
              cleanup();
              reject(err);
            });
          };
          const checkForPopupClosed = () => {
            if (!windowRef || windowRef.closed) {
              cleanup();
              reject(new OAuthErrorEvent('popup_closed', {}));
            }
          };
          if (!windowRef) {
            reject(new OAuthErrorEvent('popup_blocked', {}));
          } else {
            checkForPopupClosedTimer = window.setInterval(checkForPopupClosed, checkForPopupClosedInterval);
          }
          const cleanup = () => {
            window.clearInterval(checkForPopupClosedTimer);
            window.removeEventListener('storage', storageListener);
            window.removeEventListener('message', listener);
            if (windowRef !== null) {
              windowRef.close();
            }
            windowRef = null;
          };
          const listener = e => {
            const message = this.processMessageEventMessage(e);
            if (message && message !== null) {
              window.removeEventListener('storage', storageListener);
              tryLogin(message);
            } else {
              console.log('false event firing');
            }
          };
          const storageListener = event => {
            if (event.key === 'auth_hash') {
              window.removeEventListener('message', listener);
              tryLogin(event.newValue);
            }
          };
          window.addEventListener('message', listener);
          window.addEventListener('storage', storageListener);
        });
      });
    }
    calculatePopupFeatures(options) {
      // Specify an static height and width and calculate centered position
      const height = options.height || 470;
      const width = options.width || 500;
      const left = window.screenLeft + (window.outerWidth - width) / 2;
      const top = window.screenTop + (window.outerHeight - height) / 2;
      return `location=no,toolbar=no,width=${width},height=${height},top=${top},left=${left}`;
    }
    processMessageEventMessage(e) {
      let expectedPrefix = '#';
      if (this.silentRefreshMessagePrefix) {
        expectedPrefix += this.silentRefreshMessagePrefix;
      }
      if (!e || !e.data || typeof e.data !== 'string') {
        return;
      }
      const prefixedMessage = e.data;
      if (!prefixedMessage.startsWith(expectedPrefix)) {
        return;
      }
      return '#' + prefixedMessage.substr(expectedPrefix.length);
    }
    canPerformSessionCheck() {
      if (!this.sessionChecksEnabled) {
        return false;
      }
      if (!this.sessionCheckIFrameUrl) {
        console.warn('sessionChecksEnabled is activated but there is no sessionCheckIFrameUrl');
        return false;
      }
      const sessionState = this.getSessionState();
      if (!sessionState) {
        console.warn('sessionChecksEnabled is activated but there is no session_state');
        return false;
      }
      if (typeof this.document === 'undefined') {
        return false;
      }
      return true;
    }
    setupSessionCheckEventListener() {
      this.removeSessionCheckEventListener();
      this.sessionCheckEventListener = e => {
        const origin = e.origin.toLowerCase();
        const issuer = this.issuer.toLowerCase();
        this.debug('sessionCheckEventListener');
        if (!issuer.startsWith(origin)) {
          this.debug('sessionCheckEventListener', 'wrong origin', origin, 'expected', issuer, 'event', e);
          return;
        }
        // only run in Angular zone if it is 'changed' or 'error'
        switch (e.data) {
          case 'unchanged':
            this.ngZone.run(() => {
              this.handleSessionUnchanged();
            });
            break;
          case 'changed':
            this.ngZone.run(() => {
              this.handleSessionChange();
            });
            break;
          case 'error':
            this.ngZone.run(() => {
              this.handleSessionError();
            });
            break;
        }
        this.debug('got info from session check inframe', e);
      };
      // prevent Angular from refreshing the view on every message (runs in intervals)
      this.ngZone.runOutsideAngular(() => {
        window.addEventListener('message', this.sessionCheckEventListener);
      });
    }
    handleSessionUnchanged() {
      this.debug('session check', 'session unchanged');
      this.eventsSubject.next(new OAuthInfoEvent('session_unchanged'));
    }
    handleSessionChange() {
      this.eventsSubject.next(new OAuthInfoEvent('session_changed'));
      this.stopSessionCheckTimer();
      if (!this.useSilentRefresh && this.responseType === 'code') {
        this.refreshToken().then(() => {
          this.debug('token refresh after session change worked');
        }).catch(() => {
          this.debug('token refresh did not work after session changed');
          this.eventsSubject.next(new OAuthInfoEvent('session_terminated'));
          this.logOut(true);
        });
      } else if (this.silentRefreshRedirectUri) {
        this.silentRefresh().catch(() => this.debug('silent refresh failed after session changed'));
        this.waitForSilentRefreshAfterSessionChange();
      } else {
        this.eventsSubject.next(new OAuthInfoEvent('session_terminated'));
        this.logOut(true);
      }
    }
    waitForSilentRefreshAfterSessionChange() {
      this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'silently_refreshed' || e.type === 'silent_refresh_timeout' || e.type === 'silent_refresh_error'), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_12__.first)()).subscribe(e => {
        if (e.type !== 'silently_refreshed') {
          this.debug('silent refresh did not work after session changed');
          this.eventsSubject.next(new OAuthInfoEvent('session_terminated'));
          this.logOut(true);
        }
      });
    }
    handleSessionError() {
      this.stopSessionCheckTimer();
      this.eventsSubject.next(new OAuthInfoEvent('session_error'));
    }
    removeSessionCheckEventListener() {
      if (this.sessionCheckEventListener) {
        window.removeEventListener('message', this.sessionCheckEventListener);
        this.sessionCheckEventListener = null;
      }
    }
    initSessionCheck() {
      if (!this.canPerformSessionCheck()) {
        return;
      }
      const existingIframe = this.document.getElementById(this.sessionCheckIFrameName);
      if (existingIframe) {
        this.document.body.removeChild(existingIframe);
      }
      const iframe = this.document.createElement('iframe');
      iframe.id = this.sessionCheckIFrameName;
      this.setupSessionCheckEventListener();
      const url = this.sessionCheckIFrameUrl;
      iframe.setAttribute('src', url);
      iframe.style.display = 'none';
      this.document.body.appendChild(iframe);
      this.startSessionCheckTimer();
    }
    startSessionCheckTimer() {
      this.stopSessionCheckTimer();
      this.ngZone.runOutsideAngular(() => {
        this.sessionCheckTimer = setInterval(this.checkSession.bind(this), this.sessionCheckIntervall);
      });
    }
    stopSessionCheckTimer() {
      if (this.sessionCheckTimer) {
        clearInterval(this.sessionCheckTimer);
        this.sessionCheckTimer = null;
      }
    }
    checkSession() {
      const iframe = this.document.getElementById(this.sessionCheckIFrameName);
      if (!iframe) {
        this.logger.warn('checkSession did not find iframe', this.sessionCheckIFrameName);
      }
      const sessionState = this.getSessionState();
      if (!sessionState) {
        this.stopSessionCheckTimer();
      }
      const message = this.clientId + ' ' + sessionState;
      iframe.contentWindow.postMessage(message, this.issuer);
    }
    createLoginUrl(state = '', loginHint = '', customRedirectUri = '', noPrompt = false, params = {}) {
      var _this2 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        const that = _this2; // eslint-disable-line @typescript-eslint/no-this-alias
        let redirectUri;
        if (customRedirectUri) {
          redirectUri = customRedirectUri;
        } else {
          redirectUri = _this2.redirectUri;
        }
        const nonce = yield _this2.createAndSaveNonce();
        if (state) {
          state = nonce + _this2.config.nonceStateSeparator + encodeURIComponent(state);
        } else {
          state = nonce;
        }
        if (!_this2.requestAccessToken && !_this2.oidc) {
          throw new Error('Either requestAccessToken or oidc or both must be true');
        }
        if (_this2.config.responseType) {
          _this2.responseType = _this2.config.responseType;
        } else {
          if (_this2.oidc && _this2.requestAccessToken) {
            _this2.responseType = 'id_token token';
          } else if (_this2.oidc && !_this2.requestAccessToken) {
            _this2.responseType = 'id_token';
          } else {
            _this2.responseType = 'token';
          }
        }
        const seperationChar = that.loginUrl.indexOf('?') > -1 ? '&' : '?';
        let scope = that.scope;
        if (_this2.oidc && !scope.match(/(^|\s)openid($|\s)/)) {
          scope = 'openid ' + scope;
        }
        let url = that.loginUrl + seperationChar + 'response_type=' + encodeURIComponent(that.responseType) + '&client_id=' + encodeURIComponent(that.clientId) + '&state=' + encodeURIComponent(state) + '&redirect_uri=' + encodeURIComponent(redirectUri) + '&scope=' + encodeURIComponent(scope);
        if (_this2.responseType.includes('code') && !_this2.disablePKCE) {
          const [challenge, verifier] = yield _this2.createChallangeVerifierPairForPKCE();
          if (_this2.saveNoncesInLocalStorage && typeof window['localStorage'] !== 'undefined') {
            localStorage.setItem('PKCE_verifier', verifier);
          } else {
            _this2._storage.setItem('PKCE_verifier', verifier);
          }
          url += '&code_challenge=' + challenge;
          url += '&code_challenge_method=S256';
        }
        if (loginHint) {
          url += '&login_hint=' + encodeURIComponent(loginHint);
        }
        if (that.resource) {
          url += '&resource=' + encodeURIComponent(that.resource);
        }
        if (that.oidc) {
          url += '&nonce=' + encodeURIComponent(nonce);
        }
        if (noPrompt) {
          url += '&prompt=none';
        }
        for (const key of Object.keys(params)) {
          url += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
        }
        if (_this2.customQueryParams) {
          for (const key of Object.getOwnPropertyNames(_this2.customQueryParams)) {
            url += '&' + key + '=' + encodeURIComponent(_this2.customQueryParams[key]);
          }
        }
        return url;
      })();
    }
    initImplicitFlowInternal(additionalState = '', params = '') {
      if (this.inImplicitFlow) {
        return;
      }
      this.inImplicitFlow = true;
      if (!this.validateUrlForHttps(this.loginUrl)) {
        throw new Error("loginUrl  must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
      }
      let addParams = {};
      let loginHint = null;
      if (typeof params === 'string') {
        loginHint = params;
      } else if (typeof params === 'object') {
        addParams = params;
      }
      this.createLoginUrl(additionalState, loginHint, null, false, addParams).then(this.config.openUri).catch(error => {
        console.error('Error in initImplicitFlow', error);
        this.inImplicitFlow = false;
      });
    }
    /**
     * Starts the implicit flow and redirects to user to
     * the auth servers' login url.
     *
     * @param additionalState Optional state that is passed around.
     *  You'll find this state in the property `state` after `tryLogin` logged in the user.
     * @param params Hash with additional parameter. If it is a string, it is used for the
     *               parameter loginHint (for the sake of compatibility with former versions)
     */
    initImplicitFlow(additionalState = '', params = '') {
      if (this.loginUrl !== '') {
        this.initImplicitFlowInternal(additionalState, params);
      } else {
        this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'discovery_document_loaded')).subscribe(() => this.initImplicitFlowInternal(additionalState, params));
      }
    }
    /**
     * Reset current implicit flow
     *
     * @description This method allows resetting the current implict flow in order to be initialized again.
     */
    resetImplicitFlow() {
      this.inImplicitFlow = false;
    }
    callOnTokenReceivedIfExists(options) {
      const that = this; // eslint-disable-line @typescript-eslint/no-this-alias
      if (options.onTokenReceived) {
        const tokenParams = {
          idClaims: that.getIdentityClaims(),
          idToken: that.getIdToken(),
          accessToken: that.getAccessToken(),
          state: that.state
        };
        options.onTokenReceived(tokenParams);
      }
    }
    storeAccessTokenResponse(accessToken, refreshToken, expiresIn, grantedScopes, customParameters) {
      this._storage.setItem('access_token', accessToken);
      if (grantedScopes && !Array.isArray(grantedScopes)) {
        this._storage.setItem('granted_scopes', JSON.stringify(grantedScopes.split(' ')));
      } else if (grantedScopes && Array.isArray(grantedScopes)) {
        this._storage.setItem('granted_scopes', JSON.stringify(grantedScopes));
      }
      this._storage.setItem('access_token_stored_at', '' + this.dateTimeService.now());
      if (expiresIn) {
        const expiresInMilliSeconds = expiresIn * 1000;
        const now = this.dateTimeService.new();
        const expiresAt = now.getTime() + expiresInMilliSeconds;
        this._storage.setItem('expires_at', '' + expiresAt);
      }
      if (refreshToken) {
        this._storage.setItem('refresh_token', refreshToken);
      }
      if (customParameters) {
        customParameters.forEach((value, key) => {
          this._storage.setItem(key, value);
        });
      }
    }
    /**
     * Delegates to tryLoginImplicitFlow for the sake of competability
     * @param options Optional options.
     */
    tryLogin(options = null) {
      if (this.config.responseType === 'code') {
        return this.tryLoginCodeFlow(options).then(() => true);
      } else {
        return this.tryLoginImplicitFlow(options);
      }
    }
    parseQueryString(queryString) {
      if (!queryString || queryString.length === 0) {
        return {};
      }
      if (queryString.charAt(0) === '?') {
        queryString = queryString.substr(1);
      }
      return this.urlHelper.parseQueryString(queryString);
    }
    tryLoginCodeFlow(options = null) {
      var _this3 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        options = options || {};
        const querySource = options.customHashFragment ? options.customHashFragment.substring(1) : window.location.search;
        const parts = _this3.getCodePartsFromUrl(querySource);
        const code = parts['code'];
        const state = parts['state'];
        const sessionState = parts['session_state'];
        if (!options.preventClearHashAfterLogin) {
          const href = location.origin + location.pathname + location.search.replace(/code=[^&$]*/, '').replace(/scope=[^&$]*/, '').replace(/state=[^&$]*/, '').replace(/session_state=[^&$]*/, '').replace(/^\?&/, '?').replace(/&$/, '').replace(/^\?$/, '').replace(/&+/g, '&').replace(/\?&/, '?').replace(/\?$/, '') + location.hash;
          history.replaceState(null, window.name, href);
        }
        const [nonceInState, userState] = _this3.parseState(state);
        _this3.state = userState;
        if (parts['error']) {
          _this3.debug('error trying to login');
          _this3.handleLoginError(options, parts);
          const err = new OAuthErrorEvent('code_error', {}, parts);
          _this3.eventsSubject.next(err);
          return Promise.reject(err);
        }
        if (!options.disableNonceCheck) {
          if (!nonceInState) {
            _this3.saveRequestedRoute();
            return Promise.resolve();
          }
          if (!options.disableOAuth2StateCheck) {
            const success = _this3.validateNonce(nonceInState);
            if (!success) {
              const event = new OAuthErrorEvent('invalid_nonce_in_state', null);
              _this3.eventsSubject.next(event);
              return Promise.reject(event);
            }
          }
        }
        _this3.storeSessionState(sessionState);
        if (code) {
          yield _this3.getTokenFromCode(code, options);
          _this3.restoreRequestedRoute();
          return Promise.resolve();
        } else {
          return Promise.resolve();
        }
      })();
    }
    saveRequestedRoute() {
      if (this.config.preserveRequestedRoute) {
        this._storage.setItem('requested_route', window.location.pathname + window.location.search);
      }
    }
    restoreRequestedRoute() {
      const requestedRoute = this._storage.getItem('requested_route');
      if (requestedRoute) {
        history.replaceState(null, '', window.location.origin + requestedRoute);
      }
    }
    /**
     * Retrieve the returned auth code from the redirect uri that has been called.
     * If required also check hash, as we could use hash location strategy.
     */
    getCodePartsFromUrl(queryString) {
      if (!queryString || queryString.length === 0) {
        return this.urlHelper.getHashFragmentParams();
      }
      // normalize query string
      if (queryString.charAt(0) === '?') {
        queryString = queryString.substr(1);
      }
      return this.urlHelper.parseQueryString(queryString);
    }
    /**
     * Get token using an intermediate code. Works for the Authorization Code flow.
     */
    getTokenFromCode(code, options) {
      let params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpParams({
        encoder: new WebHttpUrlEncodingCodec()
      }).set('grant_type', 'authorization_code').set('code', code).set('redirect_uri', options.customRedirectUri || this.redirectUri);
      if (!this.disablePKCE) {
        let PKCEVerifier;
        if (this.saveNoncesInLocalStorage && typeof window['localStorage'] !== 'undefined') {
          PKCEVerifier = localStorage.getItem('PKCE_verifier');
        } else {
          PKCEVerifier = this._storage.getItem('PKCE_verifier');
        }
        if (!PKCEVerifier) {
          console.warn('No PKCE verifier found in oauth storage!');
        } else {
          params = params.set('code_verifier', PKCEVerifier);
        }
      }
      return this.fetchAndProcessToken(params, options);
    }
    fetchAndProcessToken(params, options) {
      options = options || {};
      this.assertUrlNotNullAndCorrectProtocol(this.tokenEndpoint, 'tokenEndpoint');
      let headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
      if (this.useHttpBasicAuth) {
        const header = btoa(`${this.clientId}:${this.dummyClientSecret}`);
        headers = headers.set('Authorization', 'Basic ' + header);
      }
      if (!this.useHttpBasicAuth) {
        params = params.set('client_id', this.clientId);
      }
      if (!this.useHttpBasicAuth && this.dummyClientSecret) {
        params = params.set('client_secret', this.dummyClientSecret);
      }
      return new Promise((resolve, reject) => {
        if (this.customQueryParams) {
          for (const key of Object.getOwnPropertyNames(this.customQueryParams)) {
            params = params.set(key, this.customQueryParams[key]);
          }
        }
        this.http.post(this.tokenEndpoint, params, {
          headers
        }).subscribe(tokenResponse => {
          this.debug('refresh tokenResponse', tokenResponse);
          this.storeAccessTokenResponse(tokenResponse.access_token, tokenResponse.refresh_token, tokenResponse.expires_in || this.fallbackAccessTokenExpirationTimeInSec, tokenResponse.scope, this.extractRecognizedCustomParameters(tokenResponse));
          if (this.oidc && tokenResponse.id_token) {
            this.processIdToken(tokenResponse.id_token, tokenResponse.access_token, options.disableNonceCheck).then(result => {
              this.storeIdToken(result);
              this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
              this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed'));
              resolve(tokenResponse);
            }).catch(reason => {
              this.eventsSubject.next(new OAuthErrorEvent('token_validation_error', reason));
              console.error('Error validating tokens');
              console.error(reason);
              reject(reason);
            });
          } else {
            this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
            this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed'));
            resolve(tokenResponse);
          }
        }, err => {
          console.error('Error getting token', err);
          this.eventsSubject.next(new OAuthErrorEvent('token_refresh_error', err));
          reject(err);
        });
      });
    }
    /**
     * Checks whether there are tokens in the hash fragment
     * as a result of the implicit flow. These tokens are
     * parsed, validated and used to sign the user in to the
     * current client.
     *
     * @param options Optional options.
     */
    tryLoginImplicitFlow(options = null) {
      options = options || {};
      let parts;
      if (options.customHashFragment) {
        parts = this.urlHelper.getHashFragmentParams(options.customHashFragment);
      } else {
        parts = this.urlHelper.getHashFragmentParams();
      }
      this.debug('parsed url', parts);
      const state = parts['state'];
      const [nonceInState, userState] = this.parseState(state);
      this.state = userState;
      if (parts['error']) {
        this.debug('error trying to login');
        this.handleLoginError(options, parts);
        const err = new OAuthErrorEvent('token_error', {}, parts);
        this.eventsSubject.next(err);
        return Promise.reject(err);
      }
      const accessToken = parts['access_token'];
      const idToken = parts['id_token'];
      const sessionState = parts['session_state'];
      const grantedScopes = parts['scope'];
      if (!this.requestAccessToken && !this.oidc) {
        return Promise.reject('Either requestAccessToken or oidc (or both) must be true.');
      }
      if (this.requestAccessToken && !accessToken) {
        return Promise.resolve(false);
      }
      if (this.requestAccessToken && !options.disableOAuth2StateCheck && !state) {
        return Promise.resolve(false);
      }
      if (this.oidc && !idToken) {
        return Promise.resolve(false);
      }
      if (this.sessionChecksEnabled && !sessionState) {
        this.logger.warn('session checks (Session Status Change Notification) ' + 'were activated in the configuration but the id_token ' + 'does not contain a session_state claim');
      }
      if (this.requestAccessToken && !options.disableNonceCheck) {
        const success = this.validateNonce(nonceInState);
        if (!success) {
          const event = new OAuthErrorEvent('invalid_nonce_in_state', null);
          this.eventsSubject.next(event);
          return Promise.reject(event);
        }
      }
      if (this.requestAccessToken) {
        this.storeAccessTokenResponse(accessToken, null, parts['expires_in'] || this.fallbackAccessTokenExpirationTimeInSec, grantedScopes);
      }
      if (!this.oidc) {
        this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
        if (this.clearHashAfterLogin && !options.preventClearHashAfterLogin) {
          this.clearLocationHash();
        }
        this.callOnTokenReceivedIfExists(options);
        return Promise.resolve(true);
      }
      return this.processIdToken(idToken, accessToken, options.disableNonceCheck).then(result => {
        if (options.validationHandler) {
          return options.validationHandler({
            accessToken: accessToken,
            idClaims: result.idTokenClaims,
            idToken: result.idToken,
            state: state
          }).then(() => result);
        }
        return result;
      }).then(result => {
        this.storeIdToken(result);
        this.storeSessionState(sessionState);
        if (this.clearHashAfterLogin && !options.preventClearHashAfterLogin) {
          this.clearLocationHash();
        }
        this.eventsSubject.next(new OAuthSuccessEvent('token_received'));
        this.callOnTokenReceivedIfExists(options);
        this.inImplicitFlow = false;
        return true;
      }).catch(reason => {
        this.eventsSubject.next(new OAuthErrorEvent('token_validation_error', reason));
        this.logger.error('Error validating tokens');
        this.logger.error(reason);
        return Promise.reject(reason);
      });
    }
    parseState(state) {
      let nonce = state;
      let userState = '';
      if (state) {
        const idx = state.indexOf(this.config.nonceStateSeparator);
        if (idx > -1) {
          nonce = state.substr(0, idx);
          userState = state.substr(idx + this.config.nonceStateSeparator.length);
        }
      }
      return [nonce, userState];
    }
    validateNonce(nonceInState) {
      let savedNonce;
      if (this.saveNoncesInLocalStorage && typeof window['localStorage'] !== 'undefined') {
        savedNonce = localStorage.getItem('nonce');
      } else {
        savedNonce = this._storage.getItem('nonce');
      }
      if (savedNonce !== nonceInState) {
        const err = 'Validating access_token failed, wrong state/nonce.';
        console.error(err, savedNonce, nonceInState);
        return false;
      }
      return true;
    }
    storeIdToken(idToken) {
      this._storage.setItem('id_token', idToken.idToken);
      this._storage.setItem('id_token_claims_obj', idToken.idTokenClaimsJson);
      this._storage.setItem('id_token_expires_at', '' + idToken.idTokenExpiresAt);
      this._storage.setItem('id_token_stored_at', '' + this.dateTimeService.now());
    }
    storeSessionState(sessionState) {
      this._storage.setItem('session_state', sessionState);
    }
    getSessionState() {
      return this._storage.getItem('session_state');
    }
    handleLoginError(options, parts) {
      if (options.onLoginError) {
        options.onLoginError(parts);
      }
      if (this.clearHashAfterLogin && !options.preventClearHashAfterLogin) {
        this.clearLocationHash();
      }
    }
    getClockSkewInMsec(defaultSkewMsc = 600_000) {
      if (!this.clockSkewInSec && this.clockSkewInSec !== 0) {
        return defaultSkewMsc;
      }
      return this.clockSkewInSec * 1000;
    }
    /**
     * @ignore
     */
    processIdToken(idToken, accessToken, skipNonceCheck = false) {
      const tokenParts = idToken.split('.');
      const headerBase64 = this.padBase64(tokenParts[0]);
      const headerJson = b64DecodeUnicode(headerBase64);
      const header = JSON.parse(headerJson);
      const claimsBase64 = this.padBase64(tokenParts[1]);
      const claimsJson = b64DecodeUnicode(claimsBase64);
      const claims = JSON.parse(claimsJson);
      let savedNonce;
      if (this.saveNoncesInLocalStorage && typeof window['localStorage'] !== 'undefined') {
        savedNonce = localStorage.getItem('nonce');
      } else {
        savedNonce = this._storage.getItem('nonce');
      }
      if (Array.isArray(claims.aud)) {
        if (claims.aud.every(v => v !== this.clientId)) {
          const err = 'Wrong audience: ' + claims.aud.join(',');
          this.logger.warn(err);
          return Promise.reject(err);
        }
      } else {
        if (claims.aud !== this.clientId) {
          const err = 'Wrong audience: ' + claims.aud;
          this.logger.warn(err);
          return Promise.reject(err);
        }
      }
      if (!claims.sub) {
        const err = 'No sub claim in id_token';
        this.logger.warn(err);
        return Promise.reject(err);
      }
      /* For now, we only check whether the sub against
       * silentRefreshSubject when sessionChecksEnabled is on
       * We will reconsider in a later version to do this
       * in every other case too.
       */
      if (this.sessionChecksEnabled && this.silentRefreshSubject && this.silentRefreshSubject !== claims['sub']) {
        const err = 'After refreshing, we got an id_token for another user (sub). ' + `Expected sub: ${this.silentRefreshSubject}, received sub: ${claims['sub']}`;
        this.logger.warn(err);
        return Promise.reject(err);
      }
      if (!claims.iat) {
        const err = 'No iat claim in id_token';
        this.logger.warn(err);
        return Promise.reject(err);
      }
      if (!this.skipIssuerCheck && claims.iss !== this.issuer) {
        const err = 'Wrong issuer: ' + claims.iss;
        this.logger.warn(err);
        return Promise.reject(err);
      }
      if (!skipNonceCheck && claims.nonce !== savedNonce) {
        const err = 'Wrong nonce: ' + claims.nonce;
        this.logger.warn(err);
        return Promise.reject(err);
      }
      // at_hash is not applicable to authorization code flow
      // addressing https://github.com/manfredsteyer/angular-oauth2-oidc/issues/661
      // i.e. Based on spec the at_hash check is only true for implicit code flow on Ping Federate
      // https://www.pingidentity.com/developer/en/resources/openid-connect-developers-guide.html
      if (Object.prototype.hasOwnProperty.call(this, 'responseType') && (this.responseType === 'code' || this.responseType === 'id_token')) {
        this.disableAtHashCheck = true;
      }
      if (!this.disableAtHashCheck && this.requestAccessToken && !claims['at_hash']) {
        const err = 'An at_hash is needed!';
        this.logger.warn(err);
        return Promise.reject(err);
      }
      const now = this.dateTimeService.now();
      const issuedAtMSec = claims.iat * 1000;
      const expiresAtMSec = claims.exp * 1000;
      const clockSkewInMSec = this.getClockSkewInMsec(); // (this.getClockSkewInMsec() || 600) * 1000;
      if (issuedAtMSec - clockSkewInMSec >= now || expiresAtMSec + clockSkewInMSec - this.decreaseExpirationBySec <= now) {
        const err = 'Token has expired';
        console.error(err);
        console.error({
          now: now,
          issuedAtMSec: issuedAtMSec,
          expiresAtMSec: expiresAtMSec
        });
        return Promise.reject(err);
      }
      const validationParams = {
        accessToken: accessToken,
        idToken: idToken,
        jwks: this.jwks,
        idTokenClaims: claims,
        idTokenHeader: header,
        loadKeys: () => this.loadJwks()
      };
      if (this.disableAtHashCheck) {
        return this.checkSignature(validationParams).then(() => {
          const result = {
            idToken: idToken,
            idTokenClaims: claims,
            idTokenClaimsJson: claimsJson,
            idTokenHeader: header,
            idTokenHeaderJson: headerJson,
            idTokenExpiresAt: expiresAtMSec
          };
          return result;
        });
      }
      return this.checkAtHash(validationParams).then(atHashValid => {
        if (!this.disableAtHashCheck && this.requestAccessToken && !atHashValid) {
          const err = 'Wrong at_hash';
          this.logger.warn(err);
          return Promise.reject(err);
        }
        return this.checkSignature(validationParams).then(() => {
          const atHashCheckEnabled = !this.disableAtHashCheck;
          const result = {
            idToken: idToken,
            idTokenClaims: claims,
            idTokenClaimsJson: claimsJson,
            idTokenHeader: header,
            idTokenHeaderJson: headerJson,
            idTokenExpiresAt: expiresAtMSec
          };
          if (atHashCheckEnabled) {
            return this.checkAtHash(validationParams).then(atHashValid => {
              if (this.requestAccessToken && !atHashValid) {
                const err = 'Wrong at_hash';
                this.logger.warn(err);
                return Promise.reject(err);
              } else {
                return result;
              }
            });
          } else {
            return result;
          }
        });
      });
    }
    /**
     * Returns the received claims about the user.
     */
    getIdentityClaims() {
      const claims = this._storage.getItem('id_token_claims_obj');
      if (!claims) {
        return null;
      }
      return JSON.parse(claims);
    }
    /**
     * Returns the granted scopes from the server.
     */
    getGrantedScopes() {
      const scopes = this._storage.getItem('granted_scopes');
      if (!scopes) {
        return null;
      }
      return JSON.parse(scopes);
    }
    /**
     * Returns the current id_token.
     */
    getIdToken() {
      return this._storage ? this._storage.getItem('id_token') : null;
    }
    padBase64(base64data) {
      while (base64data.length % 4 !== 0) {
        base64data += '=';
      }
      return base64data;
    }
    /**
     * Returns the current access_token.
     */
    getAccessToken() {
      return this._storage ? this._storage.getItem('access_token') : null;
    }
    getRefreshToken() {
      return this._storage ? this._storage.getItem('refresh_token') : null;
    }
    /**
     * Returns the expiration date of the access_token
     * as milliseconds since 1970.
     */
    getAccessTokenExpiration() {
      if (!this._storage.getItem('expires_at')) {
        return null;
      }
      return parseInt(this._storage.getItem('expires_at'), 10);
    }
    getAccessTokenStoredAt() {
      return parseInt(this._storage.getItem('access_token_stored_at'), 10);
    }
    getIdTokenStoredAt() {
      return parseInt(this._storage.getItem('id_token_stored_at'), 10);
    }
    /**
     * Returns the expiration date of the id_token
     * as milliseconds since 1970.
     */
    getIdTokenExpiration() {
      if (!this._storage.getItem('id_token_expires_at')) {
        return null;
      }
      return parseInt(this._storage.getItem('id_token_expires_at'), 10);
    }
    /**
     * Checkes, whether there is a valid access_token.
     */
    hasValidAccessToken() {
      if (this.getAccessToken()) {
        const expiresAt = this._storage.getItem('expires_at');
        const now = this.dateTimeService.new();
        if (expiresAt && parseInt(expiresAt, 10) - this.decreaseExpirationBySec < now.getTime() - this.getClockSkewInMsec()) {
          return false;
        }
        return true;
      }
      return false;
    }
    /**
     * Checks whether there is a valid id_token.
     */
    hasValidIdToken() {
      if (this.getIdToken()) {
        const expiresAt = this._storage.getItem('id_token_expires_at');
        const now = this.dateTimeService.new();
        if (expiresAt && parseInt(expiresAt, 10) - this.decreaseExpirationBySec < now.getTime() - this.getClockSkewInMsec()) {
          return false;
        }
        return true;
      }
      return false;
    }
    /**
     * Retrieve a saved custom property of the TokenReponse object. Only if predefined in authconfig.
     */
    getCustomTokenResponseProperty(requestedProperty) {
      return this._storage && this.config.customTokenParameters && this.config.customTokenParameters.indexOf(requestedProperty) >= 0 && this._storage.getItem(requestedProperty) !== null ? JSON.parse(this._storage.getItem(requestedProperty)) : null;
    }
    /**
     * Returns the auth-header that can be used
     * to transmit the access_token to a service
     */
    authorizationHeader() {
      return 'Bearer ' + this.getAccessToken();
    }
    logOut(customParameters = {}, state = '') {
      let noRedirectToLogoutUrl = false;
      if (typeof customParameters === 'boolean') {
        noRedirectToLogoutUrl = customParameters;
        customParameters = {};
      }
      const id_token = this.getIdToken();
      this._storage.removeItem('access_token');
      this._storage.removeItem('id_token');
      this._storage.removeItem('refresh_token');
      if (this.saveNoncesInLocalStorage) {
        localStorage.removeItem('nonce');
        localStorage.removeItem('PKCE_verifier');
      } else {
        this._storage.removeItem('nonce');
        this._storage.removeItem('PKCE_verifier');
      }
      this._storage.removeItem('expires_at');
      this._storage.removeItem('id_token_claims_obj');
      this._storage.removeItem('id_token_expires_at');
      this._storage.removeItem('id_token_stored_at');
      this._storage.removeItem('access_token_stored_at');
      this._storage.removeItem('granted_scopes');
      this._storage.removeItem('session_state');
      if (this.config.customTokenParameters) {
        this.config.customTokenParameters.forEach(customParam => this._storage.removeItem(customParam));
      }
      this.silentRefreshSubject = null;
      this.eventsSubject.next(new OAuthInfoEvent('logout'));
      if (!this.logoutUrl) {
        return;
      }
      if (noRedirectToLogoutUrl) {
        return;
      }
      // if (!id_token && !this.postLogoutRedirectUri) {
      //   return;
      // }
      let logoutUrl;
      if (!this.validateUrlForHttps(this.logoutUrl)) {
        throw new Error("logoutUrl  must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
      }
      // For backward compatibility
      if (this.logoutUrl.indexOf('{{') > -1) {
        logoutUrl = this.logoutUrl.replace(/\{\{id_token\}\}/, encodeURIComponent(id_token)).replace(/\{\{client_id\}\}/, encodeURIComponent(this.clientId));
      } else {
        let params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpParams({
          encoder: new WebHttpUrlEncodingCodec()
        });
        if (id_token) {
          params = params.set('id_token_hint', id_token);
        }
        const postLogoutUrl = this.postLogoutRedirectUri || this.redirectUriAsPostLogoutRedirectUriFallback && this.redirectUri || '';
        if (postLogoutUrl) {
          params = params.set('post_logout_redirect_uri', postLogoutUrl);
          if (state) {
            params = params.set('state', state);
          }
        }
        for (const key in customParameters) {
          params = params.set(key, customParameters[key]);
        }
        logoutUrl = this.logoutUrl + (this.logoutUrl.indexOf('?') > -1 ? '&' : '?') + params.toString();
      }
      this.config.openUri(logoutUrl);
    }
    /**
     * @ignore
     */
    createAndSaveNonce() {
      const that = this; // eslint-disable-line @typescript-eslint/no-this-alias
      return this.createNonce().then(function (nonce) {
        // Use localStorage for nonce if possible
        // localStorage is the only storage who survives a
        // redirect in ALL browsers (also IE)
        // Otherwiese we'd force teams who have to support
        // IE into using localStorage for everything
        if (that.saveNoncesInLocalStorage && typeof window['localStorage'] !== 'undefined') {
          localStorage.setItem('nonce', nonce);
        } else {
          that._storage.setItem('nonce', nonce);
        }
        return nonce;
      });
    }
    /**
     * @ignore
     */
    ngOnDestroy() {
      this.clearAccessTokenTimer();
      this.clearIdTokenTimer();
      this.removeSilentRefreshEventListener();
      const silentRefreshFrame = this.document.getElementById(this.silentRefreshIFrameName);
      if (silentRefreshFrame) {
        silentRefreshFrame.remove();
      }
      this.stopSessionCheckTimer();
      this.removeSessionCheckEventListener();
      const sessionCheckFrame = this.document.getElementById(this.sessionCheckIFrameName);
      if (sessionCheckFrame) {
        sessionCheckFrame.remove();
      }
    }
    createNonce() {
      return new Promise(resolve => {
        if (this.rngUrl) {
          throw new Error('createNonce with rng-web-api has not been implemented so far');
        }
        /*
         * This alphabet is from:
         * https://tools.ietf.org/html/rfc7636#section-4.1
         *
         * [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
         */
        const unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
        let size = 45;
        let id = '';
        const crypto = typeof self === 'undefined' ? null : self.crypto || self['msCrypto'];
        if (crypto) {
          let bytes = new Uint8Array(size);
          crypto.getRandomValues(bytes);
          // Needed for IE
          if (!bytes.map) {
            bytes.map = Array.prototype.map;
          }
          bytes = bytes.map(x => unreserved.charCodeAt(x % unreserved.length));
          id = String.fromCharCode.apply(null, bytes);
        } else {
          while (0 < size--) {
            id += unreserved[Math.random() * unreserved.length | 0];
          }
        }
        resolve(base64UrlEncode(id));
      });
    }
    checkAtHash(params) {
      var _this4 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (!_this4.tokenValidationHandler) {
          _this4.logger.warn('No tokenValidationHandler configured. Cannot check at_hash.');
          return true;
        }
        return _this4.tokenValidationHandler.validateAtHash(params);
      })();
    }
    checkSignature(params) {
      if (!this.tokenValidationHandler) {
        this.logger.warn('No tokenValidationHandler configured. Cannot check signature.');
        return Promise.resolve(null);
      }
      return this.tokenValidationHandler.validateSignature(params);
    }
    /**
     * Start the implicit flow or the code flow,
     * depending on your configuration.
     */
    initLoginFlow(additionalState = '', params = {}) {
      if (this.responseType === 'code') {
        return this.initCodeFlow(additionalState, params);
      } else {
        return this.initImplicitFlow(additionalState, params);
      }
    }
    /**
     * Starts the authorization code flow and redirects to user to
     * the auth servers login url.
     */
    initCodeFlow(additionalState = '', params = {}) {
      if (this.loginUrl !== '') {
        this.initCodeFlowInternal(additionalState, params);
      } else {
        this.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'discovery_document_loaded')).subscribe(() => this.initCodeFlowInternal(additionalState, params));
      }
    }
    initCodeFlowInternal(additionalState = '', params = {}) {
      if (!this.validateUrlForHttps(this.loginUrl)) {
        throw new Error("loginUrl  must use HTTPS (with TLS), or config value for property 'requireHttps' must be set to 'false' and allow HTTP (without TLS).");
      }
      let addParams = {};
      let loginHint = null;
      if (typeof params === 'string') {
        loginHint = params;
      } else if (typeof params === 'object') {
        addParams = params;
      }
      this.createLoginUrl(additionalState, loginHint, null, false, addParams).then(this.config.openUri).catch(error => {
        console.error('Error in initAuthorizationCodeFlow');
        console.error(error);
      });
    }
    createChallangeVerifierPairForPKCE() {
      var _this5 = this;
      return (0,_Users_jeffreywilbur_projects_repipe_unified_app_node_modules_pnpm_babel_runtime_7_26_0_node_modules_babel_runtime_helpers_esm_asyncToGenerator_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function* () {
        if (!_this5.crypto) {
          throw new Error('PKCE support for code flow needs a CryptoHander. Did you import the OAuthModule using forRoot() ?');
        }
        const verifier = yield _this5.createNonce();
        const challengeRaw = yield _this5.crypto.calcHash(verifier, 'sha-256');
        const challenge = base64UrlEncode(challengeRaw);
        return [challenge, verifier];
      })();
    }
    extractRecognizedCustomParameters(tokenResponse) {
      const foundParameters = new Map();
      if (!this.config.customTokenParameters) {
        return foundParameters;
      }
      this.config.customTokenParameters.forEach(recognizedParameter => {
        if (tokenResponse[recognizedParameter]) {
          foundParameters.set(recognizedParameter, JSON.stringify(tokenResponse[recognizedParameter]));
        }
      });
      return foundParameters;
    }
    /**
     * Revokes the auth token to secure the vulnarability
     * of the token issued allowing the authorization server to clean
     * up any security credentials associated with the authorization
     */
    revokeTokenAndLogout(customParameters = {}, ignoreCorsIssues = false) {
      const revokeEndpoint = this.revocationEndpoint;
      const accessToken = this.getAccessToken();
      const refreshToken = this.getRefreshToken();
      if (!accessToken) {
        return Promise.resolve();
      }
      let params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpParams({
        encoder: new WebHttpUrlEncodingCodec()
      });
      let headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
      if (this.useHttpBasicAuth) {
        const header = btoa(`${this.clientId}:${this.dummyClientSecret}`);
        headers = headers.set('Authorization', 'Basic ' + header);
      }
      if (!this.useHttpBasicAuth) {
        params = params.set('client_id', this.clientId);
      }
      if (!this.useHttpBasicAuth && this.dummyClientSecret) {
        params = params.set('client_secret', this.dummyClientSecret);
      }
      if (this.customQueryParams) {
        for (const key of Object.getOwnPropertyNames(this.customQueryParams)) {
          params = params.set(key, this.customQueryParams[key]);
        }
      }
      return new Promise((resolve, reject) => {
        let revokeAccessToken;
        let revokeRefreshToken;
        if (accessToken) {
          const revokationParams = params.set('token', accessToken).set('token_type_hint', 'access_token');
          revokeAccessToken = this.http.post(revokeEndpoint, revokationParams, {
            headers
          });
        } else {
          revokeAccessToken = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(null);
        }
        if (refreshToken) {
          const revokationParams = params.set('token', refreshToken).set('token_type_hint', 'refresh_token');
          revokeRefreshToken = this.http.post(revokeEndpoint, revokationParams, {
            headers
          });
        } else {
          revokeRefreshToken = (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(null);
        }
        if (ignoreCorsIssues) {
          revokeAccessToken = revokeAccessToken.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.catchError)(err => {
            if (err.status === 0) {
              return (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(null);
            }
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_15__.throwError)(err);
          }));
          revokeRefreshToken = revokeRefreshToken.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.catchError)(err => {
            if (err.status === 0) {
              return (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(null);
            }
            return (0,rxjs__WEBPACK_IMPORTED_MODULE_15__.throwError)(err);
          }));
        }
        (0,rxjs__WEBPACK_IMPORTED_MODULE_16__.combineLatest)([revokeAccessToken, revokeRefreshToken]).subscribe(res => {
          this.logOut(customParameters);
          resolve(res);
          this.logger.info('Token successfully revoked');
        }, err => {
          this.logger.error('Error revoking token', err);
          this.eventsSubject.next(new OAuthErrorEvent('token_revoke_error', err));
          reject(err);
        });
      });
    }
    /**
     * Clear location.hash if it's present
     */
    clearLocationHash() {
      // Checking for empty hash is necessary for Firefox
      // as setting an empty hash to an empty string adds # to the URL
      if (location.hash != '') {
        location.hash = '';
      }
    }
    static #_ = (() => this.ɵfac = function OAuthService_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || OAuthService)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_1__.NgZone), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HttpClient), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](OAuthStorage, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](ValidationHandler, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](AuthConfig, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](UrlHelperService), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](OAuthLogger), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](HashHandler, 8), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common__WEBPACK_IMPORTED_MODULE_17__.DOCUMENT), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](DateTimeProvider));
    })();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: OAuthService,
      factory: OAuthService.ɵfac
    }))();
  }
  return OAuthService;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
class OAuthResourceServerErrorHandler {}
class OAuthNoopResourceServerErrorHandler {
  handleError(err) {
    return (0,rxjs__WEBPACK_IMPORTED_MODULE_15__.throwError)(err);
  }
}
let DefaultOAuthInterceptor = /*#__PURE__*/(() => {
  class DefaultOAuthInterceptor {
    constructor(oAuthService, errorHandler, moduleConfig) {
      this.oAuthService = oAuthService;
      this.errorHandler = errorHandler;
      this.moduleConfig = moduleConfig;
    }
    checkUrl(url) {
      if (this.moduleConfig.resourceServer.customUrlValidation) {
        return this.moduleConfig.resourceServer.customUrlValidation(url);
      }
      if (this.moduleConfig.resourceServer.allowedUrls) {
        return !!this.moduleConfig.resourceServer.allowedUrls.find(u => url.toLowerCase().startsWith(u.toLowerCase()));
      }
      return true;
    }
    intercept(req, next) {
      const url = req.url.toLowerCase();
      if (!this.moduleConfig || !this.moduleConfig.resourceServer || !this.checkUrl(url)) {
        return next.handle(req);
      }
      const sendAccessToken = this.moduleConfig.resourceServer.sendAccessToken;
      if (!sendAccessToken) {
        return next.handle(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.catchError)(err => this.errorHandler.handleError(err)));
      }
      return (0,rxjs__WEBPACK_IMPORTED_MODULE_18__.merge)((0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(this.oAuthService.getAccessToken()).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(token => !!token)), this.oAuthService.events.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.filter)(e => e.type === 'token_received'), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_19__.timeout)(this.oAuthService.waitForTokenInMsec || 0), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.catchError)(() => (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.of)(null)),
      // timeout is not an error
      (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_11__.map)(() => this.oAuthService.getAccessToken()))).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_20__.take)(1), (0,rxjs_operators__WEBPACK_IMPORTED_MODULE_21__.mergeMap)(token => {
        if (token) {
          const header = 'Bearer ' + token;
          const headers = req.headers.set('Authorization', header);
          req = req.clone({
            headers
          });
        }
        return next.handle(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_14__.catchError)(err => this.errorHandler.handleError(err)));
      }));
    }
    static #_ = (() => this.ɵfac = function DefaultOAuthInterceptor_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || DefaultOAuthInterceptor)(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](OAuthService), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](OAuthResourceServerErrorHandler), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](OAuthModuleConfig, 8));
    })();
    static #_2 = (() => this.ɵprov = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({
      token: DefaultOAuthInterceptor,
      factory: DefaultOAuthInterceptor.ɵfac
    }))();
  }
  return DefaultOAuthInterceptor;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
function createDefaultLogger() {
  return console;
}
function createDefaultStorage() {
  return typeof sessionStorage !== 'undefined' ? sessionStorage : new MemoryStorage();
}
function provideOAuthClient(config = null, validationHandlerClass = NullValidationHandler) {
  return (0,_angular_core__WEBPACK_IMPORTED_MODULE_1__.makeEnvironmentProviders)([OAuthService, UrlHelperService, {
    provide: OAuthLogger,
    useFactory: createDefaultLogger
  }, {
    provide: OAuthStorage,
    useFactory: createDefaultStorage
  }, {
    provide: ValidationHandler,
    useClass: validationHandlerClass
  }, {
    provide: HashHandler,
    useClass: DefaultHashHandler
  }, {
    provide: OAuthResourceServerErrorHandler,
    useClass: OAuthNoopResourceServerErrorHandler
  }, {
    provide: OAuthModuleConfig,
    useValue: config
  }, {
    provide: _angular_common_http__WEBPACK_IMPORTED_MODULE_8__.HTTP_INTERCEPTORS,
    useClass: DefaultOAuthInterceptor,
    multi: true
  }, {
    provide: DateTimeProvider,
    useClass: SystemDateTimeProvider
  }]);
}
let OAuthModule = /*#__PURE__*/(() => {
  class OAuthModule {
    static forRoot(config = null, validationHandlerClass = NullValidationHandler) {
      return {
        ngModule: OAuthModule,
        providers: [provideOAuthClient(config, validationHandlerClass)]
      };
    }
    static #_ = (() => this.ɵfac = function OAuthModule_Factory(__ngFactoryType__) {
      return new (__ngFactoryType__ || OAuthModule)();
    })();
    static #_2 = (() => this.ɵmod = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({
      type: OAuthModule
    }))();
    static #_3 = (() => this.ɵinj = /* @__PURE__ */_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({
      imports: [_angular_common__WEBPACK_IMPORTED_MODULE_17__.CommonModule]
    }))();
  }
  return OAuthModule;
})();
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && void 0;
})();
const err = `PLEASE READ THIS CAREFULLY:

Beginning with angular-oauth2-oidc version 9, the JwksValidationHandler
has been moved to an library of its own. If you need it for implementing
OAuth2/OIDC **implicit flow**, please install it using npm:

  npm i angular-oauth2-oidc-jwks --save

After that, you can import it into your application:

  import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks';

Please note, that this dependency is not needed for the **code flow**,
which is nowadays the **recommented** one for single page applications.
This also results in smaller bundle sizes.
`;
/**
 * This is just a dummy of the JwksValidationHandler
 * telling the users that the real one has been moved
 * to an library of its own, namely angular-oauth2-oidc-utils
 */
class JwksValidationHandler extends NullValidationHandler {
  constructor() {
    super();
    console.error(err);
  }
}
const AUTH_CONFIG = new _angular_core__WEBPACK_IMPORTED_MODULE_1__.InjectionToken('AUTH_CONFIG');

/**
 * Generated bundle index. Do not edit.
 */



/***/ }),

/***/ 4968:
/*!*****************************************************************************************************!*\
  !*** ./node_modules/.pnpm/awesome-phonenumber@7.2.0/node_modules/awesome-phonenumber/index-esm.mjs ***!
  \*****************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AsYouType: () => (/* binding */ AsYouType),
/* harmony export */   "default": () => (/* binding */ index),
/* harmony export */   findNumbers: () => (/* binding */ findNumbers),
/* harmony export */   getAsYouType: () => (/* binding */ getAsYouType),
/* harmony export */   getCountryCodeForRegionCode: () => (/* binding */ getCountryCodeForRegionCode),
/* harmony export */   getExample: () => (/* binding */ getExample),
/* harmony export */   getNumberFrom: () => (/* binding */ getNumberFrom),
/* harmony export */   getRegionCodeForCountryCode: () => (/* binding */ getRegionCodeForCountryCode),
/* harmony export */   getSupportedCallingCodes: () => (/* binding */ getSupportedCallingCodes),
/* harmony export */   getSupportedRegionCodes: () => (/* binding */ getSupportedRegionCodes),
/* harmony export */   parsePhoneNumber: () => (/* binding */ parsePhoneNumber)
/* harmony export */ });
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var awesomePhonenumber$1 = {
  exports: {}
};
var lib$1 = {
  exports: {}
};
var lib = lib$1.exports;
var hasRequiredLib;
function requireLib() {
  if (hasRequiredLib) return lib$1.exports;
  hasRequiredLib = 1;
  (function (module) {
    (function () {
      /*
      Copyright The Closure Library Authors.
      SPDX-License-Identifier: Apache-2.0
      */
      var aa = this || self;
      function ba(a) {
        a.ra = void 0;
        a.pa = function () {
          return a.ra ? a.ra : a.ra = new a();
        };
      }
      function h(a, b) {
        function c() {}
        c.prototype = b.prototype;
        a.Da = b.prototype;
        a.prototype = new c();
        a.prototype.constructor = a;
        a.Ja = function (d, e, f) {
          for (var g = Array(arguments.length - 2), l = 2; l < arguments.length; l++) g[l - 2] = arguments[l];
          return b.prototype[e].apply(d, g);
        };
      }
      var da = class {
          constructor(a) {
            if (ca !== ca) throw Error("SafeUrl is not meant to be built directly");
            this.g = a;
          }
          toString() {
            return this.g.toString();
          }
        },
        ca = {};
      new da("about:invalid#zClosurez");
      new da("about:blank");
      var ea = {};
      class fa {
        constructor() {
          if (ea !== ea) throw Error("SafeStyle is not meant to be built directly");
        }
        toString() {
          return "".toString();
        }
      }
      new fa();
      function ha(a) {
        var b = [];
        let c = 0;
        for (var d in a) b[c++] = a[d];
        return b;
      }
      var ia = {};
      class ja {
        constructor() {
          if (ia !== ia) throw Error("SafeStyleSheet is not meant to be built directly");
        }
        toString() {
          return "".toString();
        }
      }
      new ja();
      var ka = {};
      class la {
        constructor() {
          var a = aa.trustedTypes && aa.trustedTypes.emptyHTML || "";
          if (ka !== ka) throw Error("SafeHtml is not meant to be built directly");
          this.g = a;
        }
        toString() {
          return this.g.toString();
        }
      }
      new la();
      function ma(a, b) {
        this.h = a;
        this.g = {};
        for (a = 0; a < b.length; a++) {
          var c = b[a];
          this.g[c.g] = c;
        }
      }
      function na(a) {
        a = ha(a.g);
        a.sort(function (b, c) {
          return b.g - c.g;
        });
        return a;
      }
      function oa(a, b) {
        this.g = a;
        this.m = !!b.ga;
        this.h = b.i;
        this.u = b.type;
        this.s = !1;
        switch (this.h) {
          case pa:
          case qa:
          case ra:
          case sa:
          case ta:
          case va:
          case wa:
            this.s = !0;
        }
        this.j = b.defaultValue;
      }
      var wa = 1,
        va = 2,
        pa = 3,
        qa = 4,
        ra = 6,
        sa = 16,
        ta = 18;
      function k() {
        this.h = {};
        this.j = this.o().g;
        this.g = this.m = null;
      }
      k.prototype.has = function (a) {
        return m(this, a.g);
      };
      k.prototype.get = function (a, b) {
        return p(this, a.g, b);
      };
      k.prototype.set = function (a, b) {
        q(this, a.g, b);
      };
      k.prototype.add = function (a, b) {
        xa(this, a.g, b);
      };
      function ya(a, b) {
        for (var c = na(a.o()), d = 0; d < c.length; d++) {
          var e = c[d],
            f = e.g;
          if (m(b, f)) {
            a.g && delete a.g[e.g];
            var g = 11 == e.h || 10 == e.h;
            if (e.m) {
              e = r(b, f);
              for (var l = 0; l < e.length; l++) xa(a, f, g ? e[l].clone() : e[l]);
            } else e = t(b, f), g ? (g = t(a, f)) ? ya(g, e) : q(a, f, e.clone()) : q(a, f, e);
          }
        }
      }
      k.prototype.clone = function () {
        var a = new this.constructor();
        a != this && (a.h = {}, a.g && (a.g = {}), ya(a, this));
        return a;
      };
      function m(a, b) {
        return null != a.h[b];
      }
      function t(a, b) {
        var c = a.h[b];
        if (null == c) return null;
        if (a.m) {
          if (!(b in a.g)) {
            var d = a.m,
              e = a.j[b];
            if (null != c) if (e.m) {
              for (var f = [], g = 0; g < c.length; g++) f[g] = d.h(e, c[g]);
              c = f;
            } else c = d.h(e, c);
            return a.g[b] = c;
          }
          return a.g[b];
        }
        return c;
      }
      function p(a, b, c) {
        var d = t(a, b);
        return a.j[b].m ? d[c || 0] : d;
      }
      function u(a, b) {
        if (m(a, b)) a = p(a, b);else a: {
          a = a.j[b];
          if (void 0 === a.j) if (b = a.u, b === Boolean) a.j = !1;else if (b === Number) a.j = 0;else if (b === String) a.j = a.s ? "0" : "";else {
            a = new b();
            break a;
          }
          a = a.j;
        }
        return a;
      }
      function r(a, b) {
        return t(a, b) || [];
      }
      function v(a, b) {
        return a.j[b].m ? m(a, b) ? a.h[b].length : 0 : m(a, b) ? 1 : 0;
      }
      function q(a, b, c) {
        a.h[b] = c;
        a.g && (a.g[b] = c);
      }
      function xa(a, b, c) {
        a.h[b] || (a.h[b] = []);
        a.h[b].push(c);
        a.g && delete a.g[b];
      }
      function w(a, b) {
        var c = [],
          d;
        for (d in b) 0 != d && c.push(new oa(d, b[d]));
        return new ma(a, c);
      }
      function x() {}
      x.prototype.g = function (a) {
        new a.h();
        throw Error("Unimplemented");
      };
      x.prototype.h = function (a, b) {
        if (11 == a.h || 10 == a.h) return b instanceof k ? b : this.g(a.u.prototype.o(), b);
        if (14 == a.h) return "string" === typeof b && za.test(b) && (a = Number(b), 0 < a) ? a : b;
        if (!a.s) return b;
        a = a.u;
        if (a === String) {
          if ("number" === typeof b) return String(b);
        } else if (a === Number && "string" === typeof b && ("Infinity" === b || "-Infinity" === b || "NaN" === b || za.test(b))) return Number(b);
        return b;
      };
      var za = /^-?[0-9]+$/;
      function Aa() {}
      h(Aa, x);
      Aa.prototype.g = function (a, b) {
        a = new a.h();
        a.m = this;
        a.h = b;
        a.g = {};
        return a;
      };
      function y() {}
      h(y, Aa);
      y.prototype.h = function (a, b) {
        return 8 == a.h ? !!b : x.prototype.h.apply(this, arguments);
      };
      y.prototype.g = function (a, b) {
        return y.Da.g.call(this, a, b);
      };
      function z(a, b) {
        null != a && this.g.apply(this, arguments);
      }
      z.prototype.h = "";
      z.prototype.set = function (a) {
        this.h = "" + a;
      };
      z.prototype.g = function (a, b, c) {
        this.h += String(a);
        if (null != b) for (let d = 1; d < arguments.length; d++) this.h += arguments[d];
        return this;
      };
      function A(a) {
        a.h = "";
      }
      z.prototype.toString = function () {
        return this.h;
      }; /*
         Protocol Buffer 2 Copyright 2008 Google Inc.
         All other code copyright its respective owners.
         Copyright (C) 2010 The Libphonenumber Authors
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
         You may obtain a copy of the License at
         http://www.apache.org/licenses/LICENSE-2.0
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         See the License for the specific language governing permissions and
         limitations under the License.
         */
      function B() {
        k.call(this);
      }
      h(B, k);
      var Ba = null;
      function C() {
        k.call(this);
      }
      h(C, k);
      var Ca = null;
      function D() {
        k.call(this);
      }
      h(D, k);
      var Da = null;
      D.prototype.ia = function () {
        return p(this, 10);
      };
      B.prototype.o = function () {
        var a = Ba;
        a || (Ba = a = w(B, {
          0: {
            name: "NumberFormat",
            na: "i18n.phonenumbers.NumberFormat"
          },
          1: {
            name: "pattern",
            required: !0,
            i: 9,
            type: String
          },
          2: {
            name: "format",
            required: !0,
            i: 9,
            type: String
          },
          3: {
            name: "leading_digits_pattern",
            ga: !0,
            i: 9,
            type: String
          },
          4: {
            name: "national_prefix_formatting_rule",
            i: 9,
            type: String
          },
          6: {
            name: "national_prefix_optional_when_formatting",
            i: 8,
            defaultValue: !1,
            type: Boolean
          },
          5: {
            name: "domestic_carrier_code_formatting_rule",
            i: 9,
            type: String
          }
        }));
        return a;
      };
      B.o = B.prototype.o;
      C.prototype.o = function () {
        var a = Ca;
        a || (Ca = a = w(C, {
          0: {
            name: "PhoneNumberDesc",
            na: "i18n.phonenumbers.PhoneNumberDesc"
          },
          2: {
            name: "national_number_pattern",
            i: 9,
            type: String
          },
          9: {
            name: "possible_length",
            ga: !0,
            i: 5,
            type: Number
          },
          10: {
            name: "possible_length_local_only",
            ga: !0,
            i: 5,
            type: Number
          },
          6: {
            name: "example_number",
            i: 9,
            type: String
          }
        }));
        return a;
      };
      C.o = C.prototype.o;
      D.prototype.o = function () {
        var a = Da;
        a || (Da = a = w(D, {
          0: {
            name: "PhoneMetadata",
            na: "i18n.phonenumbers.PhoneMetadata"
          },
          1: {
            name: "general_desc",
            i: 11,
            type: C
          },
          2: {
            name: "fixed_line",
            i: 11,
            type: C
          },
          3: {
            name: "mobile",
            i: 11,
            type: C
          },
          4: {
            name: "toll_free",
            i: 11,
            type: C
          },
          5: {
            name: "premium_rate",
            i: 11,
            type: C
          },
          6: {
            name: "shared_cost",
            i: 11,
            type: C
          },
          7: {
            name: "personal_number",
            i: 11,
            type: C
          },
          8: {
            name: "voip",
            i: 11,
            type: C
          },
          21: {
            name: "pager",
            i: 11,
            type: C
          },
          25: {
            name: "uan",
            i: 11,
            type: C
          },
          27: {
            name: "emergency",
            i: 11,
            type: C
          },
          28: {
            name: "voicemail",
            i: 11,
            type: C
          },
          29: {
            name: "short_code",
            i: 11,
            type: C
          },
          30: {
            name: "standard_rate",
            i: 11,
            type: C
          },
          31: {
            name: "carrier_specific",
            i: 11,
            type: C
          },
          33: {
            name: "sms_services",
            i: 11,
            type: C
          },
          24: {
            name: "no_international_dialling",
            i: 11,
            type: C
          },
          9: {
            name: "id",
            required: !0,
            i: 9,
            type: String
          },
          10: {
            name: "country_code",
            i: 5,
            type: Number
          },
          11: {
            name: "international_prefix",
            i: 9,
            type: String
          },
          17: {
            name: "preferred_international_prefix",
            i: 9,
            type: String
          },
          12: {
            name: "national_prefix",
            i: 9,
            type: String
          },
          13: {
            name: "preferred_extn_prefix",
            i: 9,
            type: String
          },
          15: {
            name: "national_prefix_for_parsing",
            i: 9,
            type: String
          },
          16: {
            name: "national_prefix_transform_rule",
            i: 9,
            type: String
          },
          18: {
            name: "same_mobile_and_fixed_line_pattern",
            i: 8,
            defaultValue: !1,
            type: Boolean
          },
          19: {
            name: "number_format",
            ga: !0,
            i: 11,
            type: B
          },
          20: {
            name: "intl_number_format",
            ga: !0,
            i: 11,
            type: B
          },
          22: {
            name: "main_country_for_code",
            i: 8,
            defaultValue: !1,
            type: Boolean
          },
          23: {
            name: "leading_digits",
            i: 9,
            type: String
          }
        }));
        return a;
      };
      D.o = D.prototype.o;
      function E() {
        k.call(this);
      }
      h(E, k);
      var Ea = null;
      E.prototype.ia = function () {
        return p(this, 1);
      };
      var Fa = {
        Ia: 0,
        Ha: 1,
        Ga: 5,
        Fa: 10,
        Ea: 20
      };
      E.prototype.o = function () {
        var a = Ea;
        a || (Ea = a = w(E, {
          0: {
            name: "PhoneNumber",
            na: "i18n.phonenumbers.PhoneNumber"
          },
          1: {
            name: "country_code",
            required: !0,
            i: 5,
            type: Number
          },
          2: {
            name: "national_number",
            required: !0,
            i: 4,
            type: Number
          },
          3: {
            name: "extension",
            i: 9,
            type: String
          },
          4: {
            name: "italian_leading_zero",
            i: 8,
            type: Boolean
          },
          8: {
            name: "number_of_leading_zeros",
            i: 5,
            defaultValue: 1,
            type: Number
          },
          5: {
            name: "raw_input",
            i: 9,
            type: String
          },
          6: {
            name: "country_code_source",
            i: 14,
            defaultValue: 0,
            type: Fa
          },
          7: {
            name: "preferred_domestic_carrier_code",
            i: 9,
            type: String
          }
        }));
        return a;
      };
      E.ctor = E;
      E.ctor.o = E.prototype.o; /*
                                Copyright (C) 2010 The Libphonenumber Authors
                                Licensed under the Apache License, Version 2.0 (the "License");
                                you may not use this file except in compliance with the License.
                                You may obtain a copy of the License at
                                http://www.apache.org/licenses/LICENSE-2.0
                                Unless required by applicable law or agreed to in writing, software
                                distributed under the License is distributed on an "AS IS" BASIS,
                                WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                See the License for the specific language governing permissions and
                                limitations under the License.
                                */
      var F = {
          1: "US AG AI AS BB BM BS CA DM DO GD GU JM KN KY LC MP MS PR SX TC TT VC VG VI".split(" "),
          7: ["RU", "KZ"],
          20: ["EG"],
          27: ["ZA"],
          30: ["GR"],
          31: ["NL"],
          32: ["BE"],
          33: ["FR"],
          34: ["ES"],
          36: ["HU"],
          39: ["IT", "VA"],
          40: ["RO"],
          41: ["CH"],
          43: ["AT"],
          44: ["GB", "GG", "IM", "JE"],
          45: ["DK"],
          46: ["SE"],
          47: ["NO", "SJ"],
          48: ["PL"],
          49: ["DE"],
          51: ["PE"],
          52: ["MX"],
          53: ["CU"],
          54: ["AR"],
          55: ["BR"],
          56: ["CL"],
          57: ["CO"],
          58: ["VE"],
          60: ["MY"],
          61: ["AU", "CC", "CX"],
          62: ["ID"],
          63: ["PH"],
          64: ["NZ"],
          65: ["SG"],
          66: ["TH"],
          81: ["JP"],
          82: ["KR"],
          84: ["VN"],
          86: ["CN"],
          90: ["TR"],
          91: ["IN"],
          92: ["PK"],
          93: ["AF"],
          94: ["LK"],
          95: ["MM"],
          98: ["IR"],
          211: ["SS"],
          212: ["MA", "EH"],
          213: ["DZ"],
          216: ["TN"],
          218: ["LY"],
          220: ["GM"],
          221: ["SN"],
          222: ["MR"],
          223: ["ML"],
          224: ["GN"],
          225: ["CI"],
          226: ["BF"],
          227: ["NE"],
          228: ["TG"],
          229: ["BJ"],
          230: ["MU"],
          231: ["LR"],
          232: ["SL"],
          233: ["GH"],
          234: ["NG"],
          235: ["TD"],
          236: ["CF"],
          237: ["CM"],
          238: ["CV"],
          239: ["ST"],
          240: ["GQ"],
          241: ["GA"],
          242: ["CG"],
          243: ["CD"],
          244: ["AO"],
          245: ["GW"],
          246: ["IO"],
          247: ["AC"],
          248: ["SC"],
          249: ["SD"],
          250: ["RW"],
          251: ["ET"],
          252: ["SO"],
          253: ["DJ"],
          254: ["KE"],
          255: ["TZ"],
          256: ["UG"],
          257: ["BI"],
          258: ["MZ"],
          260: ["ZM"],
          261: ["MG"],
          262: ["RE", "YT"],
          263: ["ZW"],
          264: ["NA"],
          265: ["MW"],
          266: ["LS"],
          267: ["BW"],
          268: ["SZ"],
          269: ["KM"],
          290: ["SH", "TA"],
          291: ["ER"],
          297: ["AW"],
          298: ["FO"],
          299: ["GL"],
          350: ["GI"],
          351: ["PT"],
          352: ["LU"],
          353: ["IE"],
          354: ["IS"],
          355: ["AL"],
          356: ["MT"],
          357: ["CY"],
          358: ["FI", "AX"],
          359: ["BG"],
          370: ["LT"],
          371: ["LV"],
          372: ["EE"],
          373: ["MD"],
          374: ["AM"],
          375: ["BY"],
          376: ["AD"],
          377: ["MC"],
          378: ["SM"],
          380: ["UA"],
          381: ["RS"],
          382: ["ME"],
          383: ["XK"],
          385: ["HR"],
          386: ["SI"],
          387: ["BA"],
          389: ["MK"],
          420: ["CZ"],
          421: ["SK"],
          423: ["LI"],
          500: ["FK"],
          501: ["BZ"],
          502: ["GT"],
          503: ["SV"],
          504: ["HN"],
          505: ["NI"],
          506: ["CR"],
          507: ["PA"],
          508: ["PM"],
          509: ["HT"],
          590: ["GP", "BL", "MF"],
          591: ["BO"],
          592: ["GY"],
          593: ["EC"],
          594: ["GF"],
          595: ["PY"],
          596: ["MQ"],
          597: ["SR"],
          598: ["UY"],
          599: ["CW", "BQ"],
          670: ["TL"],
          672: ["NF"],
          673: ["BN"],
          674: ["NR"],
          675: ["PG"],
          676: ["TO"],
          677: ["SB"],
          678: ["VU"],
          679: ["FJ"],
          680: ["PW"],
          681: ["WF"],
          682: ["CK"],
          683: ["NU"],
          685: ["WS"],
          686: ["KI"],
          687: ["NC"],
          688: ["TV"],
          689: ["PF"],
          690: ["TK"],
          691: ["FM"],
          692: ["MH"],
          800: ["001"],
          808: ["001"],
          850: ["KP"],
          852: ["HK"],
          853: ["MO"],
          855: ["KH"],
          856: ["LA"],
          870: ["001"],
          878: ["001"],
          880: ["BD"],
          881: ["001"],
          882: ["001"],
          883: ["001"],
          886: ["TW"],
          888: ["001"],
          960: ["MV"],
          961: ["LB"],
          962: ["JO"],
          963: ["SY"],
          964: ["IQ"],
          965: ["KW"],
          966: ["SA"],
          967: ["YE"],
          968: ["OM"],
          970: ["PS"],
          971: ["AE"],
          972: ["IL"],
          973: ["BH"],
          974: ["QA"],
          975: ["BT"],
          976: ["MN"],
          977: ["NP"],
          979: ["001"],
          992: ["TJ"],
          993: ["TM"],
          994: ["AZ"],
          995: ["GE"],
          996: ["KG"],
          998: ["UZ"]
        },
        H = {
          AC: [, [,, "(?:[01589]\\d|[46])\\d{4}",,,,,,, [5, 6]], [,, "6[2-467]\\d{3}",,,, "62889",,, [5]], [,, "4\\d{4}",,,, "40123",,, [5]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AC", 247, "00",,,,,,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "(?:0[1-9]|[1589]\\d)\\d{4}",,,, "542011",,, [6]],,, [,,,,,,,,, [-1]]],
          AD: [, [,, "(?:1|6\\d)\\d{7}|[135-9]\\d{5}",,,,,,, [6, 8, 9]], [,, "[78]\\d{5}",,,, "712345",,, [6]], [,, "690\\d{6}|[356]\\d{5}",,,, "312345",,, [6, 9]], [,, "180[02]\\d{4}",,,, "18001234",,, [8]], [,, "[19]\\d{5}",,,, "912345",,, [6]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AD", 376, "00",,,,,,,, [[, "(\\d{3})(\\d{3})", "$1 $2", ["[135-9]"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["1"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["6"]]],, [,,,,,,,,, [-1]],,, [,, "1800\\d{4}",,,,,,, [8]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AE: [, [,, "(?:[4-7]\\d|9[0-689])\\d{7}|800\\d{2,9}|[2-4679]\\d{7}",,,,,,, [5, 6, 7, 8, 9, 10, 11, 12]], [,, "[2-4679][2-8]\\d{6}",,,, "22345678",,, [8], [7]], [,, "5[024-68]\\d{7}",,,, "501234567",,, [9]], [,, "400\\d{6}|800\\d{2,9}",,,, "800123456"], [,, "900[02]\\d{5}",,,, "900234567",,, [9]], [,, "700[05]\\d{5}",,,, "700012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AE", 971, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2,9})", "$1 $2", ["60|8"]], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["[236]|[479][2-8]"], "0$1"], [, "(\\d{3})(\\d)(\\d{5})", "$1 $2 $3", ["[479]"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["5"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "600[25]\\d{5}",,,, "600212345",,, [9]],,, [,,,,,,,,, [-1]]],
          AF: [, [,, "[2-7]\\d{8}",,,,,,, [9], [7]], [,, "(?:[25][0-8]|[34][0-4]|6[0-5])[2-9]\\d{6}",,,, "234567890",,,, [7]], [,, "7\\d{8}",,,, "701234567",,,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AF", 93, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[1-9]"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-7]"], "0$1"]], [[, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-7]"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AG: [, [,, "(?:268|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "268(?:4(?:6[0-38]|84)|56[0-2])\\d{4}",,,, "2684601234",,,, [7]], [,, "268(?:464|7(?:1[3-9]|[28]\\d|3[0246]|64|7[0-689]))\\d{4}",,,, "2684641234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,, "26848[01]\\d{4}",,,, "2684801234",,,, [7]], "AG", 1, "011", "1",,, "([457]\\d{6})$|1", "268$1",,,,, [,, "26840[69]\\d{4}",,,, "2684061234",,,, [7]],, "268", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AI: [, [,, "(?:264|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "264(?:292|4(?:6[12]|9[78]))\\d{4}",,,, "2644612345",,,, [7]], [,, "264(?:235|4(?:69|76)|5(?:3[6-9]|8[1-4])|7(?:29|72))\\d{4}",,,, "2642351234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "AI", 1, "011", "1",,, "([2457]\\d{6})$|1", "264$1",,,,, [,, "264724\\d{4}",,,, "2647241234",,,, [7]],, "264", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AL: [, [,, "(?:700\\d\\d|900)\\d{3}|8\\d{5,7}|(?:[2-5]|6\\d)\\d{7}",,,,,,, [6, 7, 8, 9], [5]], [,, "4505[0-2]\\d{3}|(?:[2358][16-9]\\d[2-9]|4410)\\d{4}|(?:[2358][2-5][2-9]|4(?:[2-57-9][2-9]|6\\d))\\d{5}",,,, "22345678",,, [8], [5, 6, 7]], [,, "6(?:[78][2-9]|9\\d)\\d{6}",,,, "672123456",,, [9]], [,, "800\\d{4}",,,, "8001234",,, [7]], [,, "900[1-9]\\d\\d",,,, "900123",,, [6]], [,, "808[1-9]\\d\\d",,,, "808123",,, [6]], [,, "700[2-9]\\d{4}",,,, "70021234",,, [8]], [,,,,,,,,, [-1]], "AL", 355, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3,4})", "$1 $2", ["80|9"], "0$1"], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["4[2-6]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[2358][2-5]|4"], "0$1"], [, "(\\d{3})(\\d{5})", "$1 $2", ["[23578]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["6"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AM: [, [,, "(?:[1-489]\\d|55|60|77)\\d{6}",,,,,,, [8], [5, 6]], [,, "(?:(?:1[0-25]|47)\\d|2(?:2[2-46]|3[1-8]|4[2-69]|5[2-7]|6[1-9]|8[1-7])|3[12]2)\\d{5}",,,, "10123456",,,, [5, 6]], [,, "(?:33|4[1349]|55|77|88|9[13-9])\\d{6}",,,, "77123456"], [,, "800\\d{5}",,,, "80012345"], [,, "90[016]\\d{5}",,,, "90012345"], [,, "80[1-4]\\d{5}",,,, "80112345"], [,,,,,,,,, [-1]], [,, "60(?:2[78]|3[5-9]|4[02-9]|5[0-46-9]|[6-8]\\d|9[0-2])\\d{4}",,,, "60271234"], "AM", 374, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["[89]0"], "0 $1"], [, "(\\d{3})(\\d{5})", "$1 $2", ["2|3[12]"], "(0$1)"], [, "(\\d{2})(\\d{6})", "$1 $2", ["1|47"], "(0$1)"], [, "(\\d{2})(\\d{6})", "$1 $2", ["[3-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AO: [, [,, "[29]\\d{8}",,,,,,, [9]], [,, "2\\d(?:[0134][25-9]|[25-9]\\d)\\d{5}",,,, "222123456"], [,, "9[1-79]\\d{7}",,,, "923123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AO", 244, "00",,,,,,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[29]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AR: [, [,, "(?:11|[89]\\d\\d)\\d{8}|[2368]\\d{9}",,,,,,, [10, 11], [6, 7, 8]], [,, "3(?:7(?:1[15]|81)|8(?:21|4[16]|69|9[12]))[46]\\d{5}|(?:2(?:657|9(?:54|66))|3(?:7(?:55|77)|865))[2-8]\\d{5}|(?:2(?:2(?:2[59]|44|52)|3(?:26|44)|473|9(?:[07]2|2[26]|34|46))|3327)[45]\\d{5}|(?:2(?:284|3(?:02|23)|920)|3(?:4(?:46|8[27]|92)|541|878))[2-7]\\d{5}|(?:2(?:(?:26|62)2|320|477|9(?:42|83))|3(?:329|4(?:62|76|89)|564))[2-6]\\d{5}|(?:(?:11[1-8]|670)\\d|2(?:2(?:0[45]|1[2-6]|3[3-6])|3(?:[06]4|7[45])|494|6(?:04|1[2-8]|[36][45]|4[3-6])|80[45]|9(?:[17][4-6]|[48][45]|9[3-6]))|3(?:364|4(?:1[2-8]|[25][4-6]|3[3-6]|84)|5(?:1[2-9]|[38][4-6])|6(?:2[45]|44)|7[069][45]|8(?:0[45]|[17][2-6]|3[4-6]|5[3-6]|8[3-68])))\\d{6}|2(?:2(?:21|4[23]|6[145]|7[1-4]|8[356]|9[267])|3(?:16|3[13-8]|43|5[346-8]|9[3-5])|475|6(?:2[46]|4[78]|5[1568])|9(?:03|2[1457-9]|3[1356]|4[08]|[56][23]|82))4\\d{5}|(?:2(?:2(?:57|81)|3(?:24|46|92)|9(?:01|23|64))|3(?:4(?:42|71)|5(?:25|37|4[347]|71)|7(?:18|35|5[17])))[3-6]\\d{5}|(?:2(?:2(?:02|2[3467]|4[156]|5[45]|6[6-8]|91)|3(?:1[47]|25|[45][25]|96)|47[48]|625|932)|3(?:38[2578]|4(?:0[0-24-9]|3[78]|4[457]|58|6[03-9]|72|83|9[136-8])|5(?:2[124]|[368][23]|4[2689]|7[2-6])|7(?:16|2[15]|3[14]|4[13]|5[468]|7[2-5]|8[26])|8(?:2[5-7]|3[278]|4[3-5]|5[78]|6[1-378]|[78]7|94)))[4-6]\\d{5}",,,, "1123456789",,, [10], [6, 7, 8]], [,, "93(?:7(?:1[15]|81)|8(?:21|4[16]|69|9[12]))[46]\\d{5}|9(?:2(?:657|9(?:54|66))|3(?:7(?:55|77)|865))[2-8]\\d{5}|9(?:2(?:2(?:2[59]|44|52)|3(?:26|44)|473|9(?:[07]2|2[26]|34|46))|3327)[45]\\d{5}|9(?:2(?:284|3(?:02|23)|920)|3(?:4(?:46|8[27]|92)|541|878))[2-7]\\d{5}|9(?:2(?:(?:26|62)2|320|477|9(?:42|83))|3(?:329|4(?:62|76|89)|564))[2-6]\\d{5}|(?:675\\d|9(?:11[1-8]\\d|2(?:2(?:0[45]|1[2-6]|3[3-6])|3(?:[06]4|7[45])|494|6(?:04|1[2-8]|[36][45]|4[3-6])|80[45]|9(?:[17][4-6]|[48][45]|9[3-6]))|3(?:364|4(?:1[2-8]|[25][4-6]|3[3-6]|84)|5(?:1[2-9]|[38][4-6])|6(?:2[45]|44)|7[069][45]|8(?:0[45]|[17][2-6]|3[4-6]|5[3-6]|8[3-68]))))\\d{6}|92(?:2(?:21|4[23]|6[145]|7[1-4]|8[356]|9[267])|3(?:16|3[13-8]|43|5[346-8]|9[3-5])|475|6(?:2[46]|4[78]|5[1568])|9(?:03|2[1457-9]|3[1356]|4[08]|[56][23]|82))4\\d{5}|9(?:2(?:2(?:57|81)|3(?:24|46|92)|9(?:01|23|64))|3(?:4(?:42|71)|5(?:25|37|4[347]|71)|7(?:18|35|5[17])))[3-6]\\d{5}|9(?:2(?:2(?:02|2[3467]|4[156]|5[45]|6[6-8]|91)|3(?:1[47]|25|[45][25]|96)|47[48]|625|932)|3(?:38[2578]|4(?:0[0-24-9]|3[78]|4[457]|58|6[03-9]|72|83|9[136-8])|5(?:2[124]|[368][23]|4[2689]|7[2-6])|7(?:16|2[15]|3[14]|4[13]|5[468]|7[2-5]|8[26])|8(?:2[5-7]|3[278]|4[3-5]|5[78]|6[1-378]|[78]7|94)))[4-6]\\d{5}",,,, "91123456789",,,, [6, 7, 8]], [,, "800\\d{7,8}",,,, "8001234567"], [,, "60[04579]\\d{7}",,,, "6001234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AR", 54, "00", "0",,, "0?(?:(11|2(?:2(?:02?|[13]|2[13-79]|4[1-6]|5[2457]|6[124-8]|7[1-4]|8[13-6]|9[1267])|3(?:02?|1[467]|2[03-6]|3[13-8]|[49][2-6]|5[2-8]|[67])|4(?:7[3-578]|9)|6(?:[0136]|2[24-6]|4[6-8]?|5[15-8])|80|9(?:0[1-3]|[19]|2\\d|3[1-6]|4[02568]?|5[2-4]|6[2-46]|72?|8[23]?))|3(?:3(?:2[79]|6|8[2578])|4(?:0[0-24-9]|[12]|3[5-8]?|4[24-7]|5[4-68]?|6[02-9]|7[126]|8[2379]?|9[1-36-8])|5(?:1|2[1245]|3[237]?|4[1-46-9]|6[2-4]|7[1-6]|8[2-5]?)|6[24]|7(?:[069]|1[1568]|2[15]|3[145]|4[13]|5[14-8]|7[2-57]|8[126])|8(?:[01]|2[15-7]|3[2578]?|4[13-6]|5[4-8]?|6[1-357-9]|7[36-8]?|8[5-8]?|9[124])))15)?", "9$1",,, [[, "(\\d{3})", "$1", ["0|1(?:0[0-35-7]|1[02-5]|2[015]|3[47]|4[478])|911"]], [, "(\\d{2})(\\d{4})", "$1-$2", ["[1-9]"]], [, "(\\d{3})(\\d{4})", "$1-$2", ["[2-9]"]], [, "(\\d{4})(\\d{4})", "$1-$2", ["[1-8]"]], [, "(\\d{4})(\\d{2})(\\d{4})", "$1 $2-$3", ["2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9])", "2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8]))|2(?:2[24-9]|3[1-59]|47)", "2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5[56][46]|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]", "2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|58|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|54(?:4|5[13-7]|6[89])|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:454|85[56])[46]|3(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"], "0$1",, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2-$3", ["1"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["[68]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2-$3", ["[23]"], "0$1",, 1], [, "(\\d)(\\d{4})(\\d{2})(\\d{4})", "$2 15-$3-$4", ["9(?:2[2-469]|3[3-578])", "9(?:2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9]))", "9(?:2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8])))|92(?:2[24-9]|3[1-59]|47)", "9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5(?:[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]", "9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|5(?:4(?:4|5[13-7]|6[89])|[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"], "0$1"], [, "(\\d)(\\d{2})(\\d{4})(\\d{4})", "$2 15-$3-$4", ["91"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{5})", "$1-$2-$3", ["8"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{4})", "$2 15-$3-$4", ["9"], "0$1"]], [[, "(\\d{4})(\\d{2})(\\d{4})", "$1 $2-$3", ["2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9])", "2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8]))|2(?:2[24-9]|3[1-59]|47)", "2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5[56][46]|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]", "2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|58|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|54(?:4|5[13-7]|6[89])|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:454|85[56])[46]|3(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"], "0$1",, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2-$3", ["1"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["[68]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2-$3", ["[23]"], "0$1",, 1], [, "(\\d)(\\d{4})(\\d{2})(\\d{4})", "$1 $2 $3-$4", ["9(?:2[2-469]|3[3-578])", "9(?:2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9]))", "9(?:2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8])))|92(?:2[24-9]|3[1-59]|47)", "9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5(?:[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]", "9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|5(?:4(?:4|5[13-7]|6[89])|[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"]], [, "(\\d)(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3-$4", ["91"]], [, "(\\d{3})(\\d{3})(\\d{5})", "$1-$2-$3", ["8"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3-$4", ["9"]]], [,,,,,,,,, [-1]],,, [,, "810\\d{7}",,,,,,, [10]], [,, "810\\d{7}",,,, "8101234567",,, [10]],,, [,,,,,,,,, [-1]]],
          AS: [, [,, "(?:[58]\\d\\d|684|900)\\d{7}",,,,,,, [10], [7]], [,, "6846(?:22|33|44|55|77|88|9[19])\\d{4}",,,, "6846221234",,,, [7]], [,, "684(?:2(?:48|5[2468]|7[26])|7(?:3[13]|70|82))\\d{4}",,,, "6847331234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "AS", 1, "011", "1",,, "([267]\\d{6})$|1", "684$1",,,,, [,,,,,,,,, [-1]],, "684", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AT: [, [,, "1\\d{3,12}|2\\d{6,12}|43(?:(?:0\\d|5[02-9])\\d{3,9}|2\\d{4,5}|[3467]\\d{4}|8\\d{4,6}|9\\d{4,7})|5\\d{4,12}|8\\d{7,12}|9\\d{8,12}|(?:[367]\\d|4[0-24-9])\\d{4,11}",,,,,,, [4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [3]], [,, "1(?:11\\d|[2-9]\\d{3,11})|(?:316|463|(?:51|66|73)2)\\d{3,10}|(?:2(?:1[467]|2[13-8]|5[2357]|6[1-46-8]|7[1-8]|8[124-7]|9[1458])|3(?:1[1-578]|3[23568]|4[5-7]|5[1378]|6[1-38]|8[3-68])|4(?:2[1-8]|35|7[1368]|8[2457])|5(?:2[1-8]|3[357]|4[147]|5[12578]|6[37])|6(?:13|2[1-47]|4[135-8]|5[468])|7(?:2[1-8]|35|4[13478]|5[68]|6[16-8]|7[1-6]|9[45]))\\d{4,10}",,,, "1234567890",,,, [3]], [,, "6(?:5[0-3579]|6[013-9]|[7-9]\\d)\\d{4,10}",,,, "664123456",,, [7, 8, 9, 10, 11, 12, 13]], [,, "800\\d{6,10}",,,, "800123456",,, [9, 10, 11, 12, 13]], [,, "(?:8[69][2-68]|9(?:0[01]|3[019]))\\d{6,10}",,,, "900123456",,, [9, 10, 11, 12, 13]], [,, "8(?:10|2[018])\\d{6,10}|828\\d{5}",,,, "810123456",,, [8, 9, 10, 11, 12, 13]], [,,,,,,,,, [-1]], [,, "5(?:0[1-9]|17|[79]\\d)\\d{2,10}|7[28]0\\d{6,10}",,,, "780123456",,, [5, 6, 7, 8, 9, 10, 11, 12, 13]], "AT", 43, "00", "0",,, "0",,,, [[, "(\\d{4})", "$1", ["14"]], [, "(\\d)(\\d{3,12})", "$1 $2", ["1(?:11|[2-9])"], "0$1"], [, "(\\d{3})(\\d{2})", "$1 $2", ["517"], "0$1"], [, "(\\d{2})(\\d{3,5})", "$1 $2", ["5[079]"], "0$1"], [, "(\\d{6})", "$1", ["[18]"]], [, "(\\d{3})(\\d{3,10})", "$1 $2", ["(?:31|4)6|51|6(?:5[0-3579]|[6-9])|7(?:20|32|8)|[89]"], "0$1"], [, "(\\d{4})(\\d{3,9})", "$1 $2", ["[2-467]|5[2-6]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["5"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4,7})", "$1 $2 $3", ["5"], "0$1"]], [[, "(\\d)(\\d{3,12})", "$1 $2", ["1(?:11|[2-9])"], "0$1"], [, "(\\d{3})(\\d{2})", "$1 $2", ["517"], "0$1"], [, "(\\d{2})(\\d{3,5})", "$1 $2", ["5[079]"], "0$1"], [, "(\\d{3})(\\d{3,10})", "$1 $2", ["(?:31|4)6|51|6(?:5[0-3579]|[6-9])|7(?:20|32|8)|[89]"], "0$1"], [, "(\\d{4})(\\d{3,9})", "$1 $2", ["[2-467]|5[2-6]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["5"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4,7})", "$1 $2 $3", ["5"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AU: [, [,, "1(?:[0-79]\\d{7}(?:\\d(?:\\d{2})?)?|8[0-24-9]\\d{7})|[2-478]\\d{8}|1\\d{4,7}",,,,,,, [5, 6, 7, 8, 9, 10, 12]], [,, "(?:(?:(?:2(?:[0-26-9]\\d|3[0-8]|4[02-9]|5[0135-9])|7(?:[013-57-9]\\d|2[0-8]))\\d|3(?:(?:[0-3589]\\d|6[1-9]|7[0-35-9])\\d|4(?:[0-578]\\d|90)))\\d\\d|8(?:51(?:0(?:0[03-9]|[12479]\\d|3[2-9]|5[0-8]|6[1-9]|8[0-7])|1(?:[0235689]\\d|1[0-69]|4[0-589]|7[0-47-9])|2(?:0[0-79]|[18][13579]|2[14-9]|3[0-46-9]|[4-6]\\d|7[89]|9[0-4])|3\\d\\d)|(?:6[0-8]|[78]\\d)\\d{3}|9(?:[02-9]\\d{3}|1(?:(?:[0-58]\\d|6[0135-9])\\d|7(?:0[0-24-9]|[1-9]\\d)|9(?:[0-46-9]\\d|5[0-79])))))\\d{3}",,,, "212345678",,, [9], [8]], [,, "4(?:79[01]|83[0-389]|94[0-4])\\d{5}|4(?:[0-36]\\d|4[047-9]|5[0-25-9]|7[02-8]|8[0-24-9]|9[0-37-9])\\d{6}",,,, "412345678",,, [9]], [,, "180(?:0\\d{3}|2)\\d{3}",,,, "1800123456",,, [7, 10]], [,, "190[0-26]\\d{6}",,,, "1900123456",,, [10]], [,, "13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",,,, "1300123456",,, [6, 8, 10, 12]], [,,,,,,,,, [-1]], [,, "14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",,,, "147101234",,, [9]], "AU", 61, "001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011", "0",,, "(183[12])|0",, "0011",, [[, "(\\d{2})(\\d{3,4})", "$1 $2", ["16"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["13"]], [, "(\\d{3})(\\d{3})", "$1 $2", ["19"]], [, "(\\d{3})(\\d{4})", "$1 $2", ["180", "1802"]], [, "(\\d{4})(\\d{3,4})", "$1 $2", ["19"]], [, "(\\d{2})(\\d{3})(\\d{2,4})", "$1 $2 $3", ["16"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["14|4"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["[2378]"], "(0$1)", "$CC ($1)"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1(?:30|[89])"]], [, "(\\d{4})(\\d{4})(\\d{4})", "$1 $2 $3", ["130"]]], [[, "(\\d{2})(\\d{3,4})", "$1 $2", ["16"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2,4})", "$1 $2 $3", ["16"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["14|4"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["[2378]"], "(0$1)", "$CC ($1)"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1(?:30|[89])"]]], [,, "163\\d{2,6}",,,, "1631234",,, [5, 6, 7, 8, 9]], 1,, [,, "1(?:3(?:00\\d{5}|45[0-4])|802)\\d{3}|1[38]00\\d{6}|13\\d{4}",,,,,,, [6, 7, 8, 10, 12]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AW: [, [,, "(?:[25-79]\\d\\d|800)\\d{4}",,,,,,, [7]], [,, "5(?:2\\d|8[1-9])\\d{4}",,,, "5212345"], [,, "(?:290|5[69]\\d|6(?:[03]0|22|4[0-2]|[69]\\d)|7(?:[34]\\d|7[07])|9(?:6[45]|9[4-8]))\\d{4}",,,, "5601234"], [,, "800\\d{4}",,,, "8001234"], [,, "900\\d{4}",,,, "9001234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:28\\d|501)\\d{4}",,,, "5011234"], "AW", 297, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[25-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          AX: [, [,, "2\\d{4,9}|35\\d{4,5}|(?:60\\d\\d|800)\\d{4,6}|7\\d{5,11}|(?:[14]\\d|3[0-46-9]|50)\\d{4,8}",,,,,,, [5, 6, 7, 8, 9, 10, 11, 12]], [,, "18[1-8]\\d{3,6}",,,, "181234567",,, [6, 7, 8, 9]], [,, "4946\\d{2,6}|(?:4[0-8]|50)\\d{4,8}",,,, "412345678",,, [6, 7, 8, 9, 10]], [,, "800\\d{4,6}",,,, "800123456",,, [7, 8, 9]], [,, "[67]00\\d{5,6}",,,, "600123456",,, [8, 9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AX", 358, "00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))", "0",,, "0",, "00",,,, [,,,,,,,,, [-1]],, "18", [,,,,,,,,, [-1]], [,, "20\\d{4,8}|60[12]\\d{5,6}|7(?:099\\d{4,5}|5[03-9]\\d{3,7})|20[2-59]\\d\\d|(?:606|7(?:0[78]|1|3\\d))\\d{7}|(?:10|29|3[09]|70[1-5]\\d)\\d{4,8}",,,, "10112345"],,, [,,,,,,,,, [-1]]],
          AZ: [, [,, "365\\d{6}|(?:[124579]\\d|60|88)\\d{7}",,,,,,, [9], [7]], [,, "(?:2[12]428|3655[02])\\d{4}|(?:2(?:22[0-79]|63[0-28])|3654)\\d{5}|(?:(?:1[28]|46)\\d|2(?:[014-6]2|[23]3))\\d{6}",,,, "123123456",,,, [7]], [,, "36554\\d{4}|(?:[16]0|4[04]|5[015]|7[07]|99)\\d{7}",,,, "401234567"], [,, "88\\d{7}",,,, "881234567"], [,, "900200\\d{3}",,,, "900200123"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "AZ", 994, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3", ["[1-9]"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["90"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[28]|2|365|46", "1[28]|2|365[45]|46", "1[28]|2|365(?:4|5[02])|46"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[13-9]"], "0$1"]], [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["90"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[28]|2|365|46", "1[28]|2|365[45]|46", "1[28]|2|365(?:4|5[02])|46"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[13-9]"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BA: [, [,, "6\\d{8}|(?:[35689]\\d|49|70)\\d{6}",,,,,,, [8, 9], [6]], [,, "(?:3(?:[05-79][2-9]|1[4579]|[23][24-9]|4[2-4689]|8[2457-9])|49[2-579]|5(?:0[2-49]|[13][2-9]|[268][2-4679]|4[4689]|5[2-79]|7[2-69]|9[2-4689]))\\d{5}",,,, "30212345",,, [8], [6]], [,, "6040\\d{5}|6(?:03|[1-356]|44|7\\d)\\d{6}",,,, "61123456"], [,, "8[08]\\d{6}",,,, "80123456",,, [8]], [,, "9[0246]\\d{6}",,,, "90123456",,, [8]], [,, "8[12]\\d{6}",,,, "82123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BA", 387, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})", "$1-$2", ["[2-9]"]], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["6[1-3]|[7-9]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2-$3", ["[3-5]|6[56]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["6"], "0$1"]], [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["6[1-3]|[7-9]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2-$3", ["[3-5]|6[56]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["6"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "703[235]0\\d{3}|70(?:2[0-5]|3[0146]|[56]0)\\d{4}",,,, "70341234",,, [8]],,, [,,,,,,,,, [-1]]],
          BB: [, [,, "(?:246|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "246521[0369]\\d{3}|246(?:2(?:2[78]|7[0-4])|4(?:1[024-6]|2\\d|3[2-9])|5(?:20|[34]\\d|54|7[1-3])|6(?:2\\d|38)|7[35]7|9(?:1[89]|63))\\d{4}",,,, "2464123456",,,, [7]], [,, "246(?:(?:2(?:[3568]\\d|4[0-57-9])|3(?:5[2-9]|6[0-6])|4(?:46|5\\d)|69[5-7]|8(?:[2-5]\\d|83))\\d|52(?:1[147]|20))\\d{3}",,,, "2462501234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "(?:246976|900[2-9]\\d\\d)\\d{4}",,,, "9002123456",,,, [7]], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,, "24631\\d{5}",,,, "2463101234",,,, [7]], "BB", 1, "011", "1",,, "([2-9]\\d{6})$|1", "246$1",,,,, [,,,,,,,,, [-1]],, "246", [,,,,,,,,, [-1]], [,, "246(?:292|367|4(?:1[7-9]|3[01]|4[47-9]|67)|7(?:1[2-9]|2\\d|3[016]|53))\\d{4}",,,, "2464301234",,,, [7]],,, [,,,,,,,,, [-1]]],
          BD: [, [,, "[1-469]\\d{9}|8[0-79]\\d{7,8}|[2-79]\\d{8}|[2-9]\\d{7}|[3-9]\\d{6}|[57-9]\\d{5}",,,,,,, [6, 7, 8, 9, 10]], [,, "(?:4(?:31\\d\\d|423)|5222)\\d{3}(?:\\d{2})?|8332[6-9]\\d\\d|(?:3(?:03[56]|224)|4(?:22[25]|653))\\d{3,4}|(?:3(?:42[47]|529|823)|4(?:027|525|65(?:28|8))|562|6257|7(?:1(?:5[3-5]|6[12]|7[156]|89)|22[589]56|32|42675|52(?:[25689](?:56|8)|[347]8)|71(?:6[1267]|75|89)|92374)|82(?:2[59]|32)56|9(?:03[23]56|23(?:256|373)|31|5(?:1|2[4589]56)))\\d{3}|(?:3(?:02[348]|22[35]|324|422)|4(?:22[67]|32[236-9]|6(?:2[46]|5[57])|953)|5526|6(?:024|6655)|81)\\d{4,5}|(?:2(?:7(?:1[0-267]|2[0-289]|3[0-29]|4[01]|5[1-3]|6[013]|7[0178]|91)|8(?:0[125]|1[1-6]|2[0157-9]|3[1-69]|41|6[1-35]|7[1-5]|8[1-8]|9[0-6])|9(?:0[0-2]|1[0-4]|2[568]|3[3-6]|5[5-7]|6[0136-9]|7[0-7]|8[014-9]))|3(?:0(?:2[025-79]|3[2-4])|181|22[12]|32[2356]|824)|4(?:02[09]|22[348]|32[045]|523|6(?:27|54))|666(?:22|53)|7(?:22[57-9]|42[56]|82[35])8|8(?:0[124-9]|2(?:181|2[02-4679]8)|4[12]|[5-7]2)|9(?:[04]2|2(?:2|328)|81))\\d{4}|(?:2(?:[23]\\d|[45])\\d\\d|3(?:1(?:2[5-7]|[5-7])|425|822)|4(?:033|1\\d|[257]1|332|4(?:2[246]|5[25])|6(?:2[35]|56|62)|8(?:23|54)|92[2-5])|5(?:02[03489]|22[457]|32[35-79]|42[46]|6(?:[18]|53)|724|826)|6(?:023|2(?:2[2-5]|5[3-5]|8)|32[3478]|42[34]|52[47]|6(?:[18]|6(?:2[34]|5[24]))|[78]2[2-5]|92[2-6])|7(?:02|21\\d|[3-589]1|6[12]|72[24])|8(?:217|3[12]|[5-7]1)|9[24]1)\\d{5}|(?:(?:3[2-8]|5[2-57-9]|6[03-589])1|4[4689][18])\\d{5}|[59]1\\d{5}",,,, "27111234"], [,, "(?:1[13-9]\\d|644)\\d{7}|(?:3[78]|44|66)[02-9]\\d{7}",,,, "1812345678",,, [10]], [,, "80[03]\\d{7}",,,, "8001234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "96(?:0[469]|1[0-47]|3[389]|43|6[69]|7[78])\\d{6}",,,, "9604123456",,, [10]], "BD", 880, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{4,6})", "$1-$2", ["31[5-8]|[459]1"], "0$1"], [, "(\\d{3})(\\d{3,7})", "$1-$2", ["3(?:[67]|8[013-9])|4(?:6[168]|7|[89][18])|5(?:6[128]|9)|6(?:[15]|28|4[14])|7[2-589]|8(?:0[014-9]|[12])|9[358]|(?:3[2-5]|4[235]|5[2-578]|6[0389]|76|8[3-7]|9[24])1|(?:44|66)[01346-9]"], "0$1"], [, "(\\d{4})(\\d{3,6})", "$1-$2", ["[13-9]|2[23]"], "0$1"], [, "(\\d)(\\d{7,8})", "$1-$2", ["2"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BE: [, [,, "4\\d{8}|[1-9]\\d{7}",,,,,,, [8, 9]], [,, "80[2-8]\\d{5}|(?:1[0-69]|[23][2-8]|4[23]|5\\d|6[013-57-9]|71|8[1-79]|9[2-4])\\d{6}",,,, "12345678",,, [8]], [,, "4[5-9]\\d{7}",,,, "470123456",,, [9]], [,, "800[1-9]\\d{4}",,,, "80012345",,, [8]], [,, "(?:70(?:2[0-57]|3[04-7]|44|6[4-69]|7[0579])|90\\d\\d)\\d{4}",,,, "90012345",,, [8]], [,, "7879\\d{4}",,,, "78791234",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BE", 32, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["(?:80|9)0"], "0$1"], [, "(\\d)(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[239]|4[23]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[15-8]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["4"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "78(?:0[57]|1[014-8]|2[25]|3[15-8]|48|[56]0|7[06-8]|9\\d)\\d{4}",,,, "78102345",,, [8]],,, [,,,,,,,,, [-1]]],
          BF: [, [,, "[025-7]\\d{7}",,,,,,, [8]], [,, "2(?:0(?:49|5[23]|6[5-7]|9[016-9])|4(?:4[569]|5[4-6]|6[5-7]|7[0179])|5(?:[34]\\d|50|6[5-7]))\\d{4}",,,, "20491234"], [,, "(?:0[1-7]|5[0-8]|[67]\\d)\\d{6}",,,, "70123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BF", 226, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[025-7]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BG: [, [,, "00800\\d{7}|[2-7]\\d{6,7}|[89]\\d{6,8}|2\\d{5}",,,,,,, [6, 7, 8, 9, 12], [4, 5]], [,, "2\\d{5,7}|(?:43[1-6]|70[1-9])\\d{4,5}|(?:[36]\\d|4[124-7]|[57][1-9]|8[1-6]|9[1-7])\\d{5,6}",,,, "2123456",,, [6, 7, 8], [4, 5]], [,, "(?:43[07-9]|99[69]\\d)\\d{5}|(?:8[7-9]|98)\\d{7}",,,, "43012345",,, [8, 9]], [,, "(?:00800\\d\\d|800)\\d{5}",,,, "80012345",,, [8, 12]], [,, "90\\d{6}",,,, "90123456",,, [8]], [,, "700\\d{5}",,,, "70012345",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BG", 359, "00", "0",,, "0",,,, [[, "(\\d{6})", "$1", ["1"]], [, "(\\d)(\\d)(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["2"], "0$1"], [, "(\\d{3})(\\d{4})", "$1 $2", ["43[1-6]|70[1-9]"], "0$1"], [, "(\\d)(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2,3})", "$1 $2 $3", ["[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["(?:70|8)0"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{2})", "$1 $2 $3", ["43[1-7]|7"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[48]|9[08]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["9"], "0$1"]], [[, "(\\d)(\\d)(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["2"], "0$1"], [, "(\\d{3})(\\d{4})", "$1 $2", ["43[1-6]|70[1-9]"], "0$1"], [, "(\\d)(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2,3})", "$1 $2 $3", ["[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["(?:70|8)0"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{2})", "$1 $2 $3", ["43[1-7]|7"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[48]|9[08]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["9"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BH: [, [,, "[136-9]\\d{7}",,,,,,, [8]], [,, "(?:1(?:3[1356]|6[0156]|7\\d)\\d|6(?:1[16]\\d|500|6(?:0\\d|3[12]|44|55|7[7-9]|88)|9[69][69])|7(?:[07]\\d\\d|1(?:11|78)))\\d{4}",,,, "17001234"], [,, "(?:3(?:[0-79]\\d|8[0-57-9])\\d|6(?:3(?:00|33|6[16])|441|6(?:3[03-9]|[69]\\d|7[0-689])))\\d{4}",,,, "36001234"], [,, "8[02369]\\d{6}",,,, "80123456"], [,, "(?:87|9[0-8])\\d{6}",,,, "90123456"], [,, "84\\d{6}",,,, "84123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BH", 973, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[13679]|8[02-4679]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BI: [, [,, "(?:[267]\\d|31)\\d{6}",,,,,,, [8]], [,, "(?:22|31)\\d{6}",,,, "22201234"], [,, "(?:29|[67][125-9])\\d{6}",,,, "79561234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BI", 257, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2367]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BJ: [, [,, "[24-689]\\d{7}",,,,,,, [8]], [,, "2090\\d{4}|2(?:02|1[037]|2[45]|3[68]|4\\d)\\d{5}",,,, "20211234"], [,, "(?:4[0-8]|[56]\\d|9[013-9])\\d{6}",,,, "90011234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "857[58]\\d{4}",,,, "85751234"], "BJ", 229, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[24-689]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "81\\d{6}",,,, "81123456"],,, [,,,,,,,,, [-1]]],
          BL: [, [,, "590\\d{6}|(?:69|80|9\\d)\\d{7}",,,,,,, [9]], [,, "590(?:2[7-9]|3[3-7]|5[12]|87)\\d{4}",,,, "590271234"], [,, "69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))\\d{4}",,,, "690001234"], [,, "80[0-5]\\d{6}",,,, "800012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:(?:39[5-7]|76[018])\\d|475[0-5])\\d{4}",,,, "976012345"], "BL", 590, "00", "0",,, "0",,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BM: [, [,, "(?:441|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "441(?:[46]\\d\\d|5(?:4\\d|60|89))\\d{4}",,,, "4414123456",,,, [7]], [,, "441(?:[2378]\\d|5[0-39]|9[02])\\d{5}",,,, "4413701234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "BM", 1, "011", "1",,, "([2-9]\\d{6})$|1", "441$1",,,,, [,,,,,,,,, [-1]],, "441", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BN: [, [,, "[2-578]\\d{6}",,,,,,, [7]], [,, "22[0-7]\\d{4}|(?:2[013-9]|[34]\\d|5[0-25-9])\\d{5}",,,, "2345678"], [,, "(?:22[89]|[78]\\d\\d)\\d{4}",,,, "7123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "5[34]\\d{5}",,,, "5345678"], "BN", 673, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-578]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BO: [, [,, "8001\\d{5}|(?:[2-467]\\d|50)\\d{6}",,,,,,, [8, 9], [7]], [,, "(?:2(?:2\\d\\d|5(?:11|[258]\\d|9[67])|6(?:12|2\\d|9[34])|8(?:2[34]|39|62))|3(?:3\\d\\d|4(?:6\\d|8[24])|8(?:25|42|5[257]|86|9[25])|9(?:[27]\\d|3[2-4]|4[248]|5[24]|6[2-6]))|4(?:4\\d\\d|6(?:11|[24689]\\d|72)))\\d{4}",,,, "22123456",,, [8], [7]], [,, "[67]\\d{7}",,,, "71234567",,, [8]], [,, "8001[07]\\d{4}",,,, "800171234",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "50\\d{6}",,,, "50123456",,, [8], [7]], "BO", 591, "00(?:1\\d)?", "0",,, "0(1\\d)?",,,, [[, "(\\d)(\\d{7})", "$1 $2", ["[235]|4[46]"],, "0$CC $1"], [, "(\\d{8})", "$1", ["[67]"],, "0$CC $1"], [, "(\\d{3})(\\d{2})(\\d{4})", "$1 $2 $3", ["8"],, "0$CC $1"]],, [,,,,,,,,, [-1]],,, [,, "8001[07]\\d{4}",,,,,,, [9]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BQ: [, [,, "(?:[34]1|7\\d)\\d{5}",,,,,,, [7]], [,, "(?:318[023]|41(?:6[023]|70)|7(?:1[578]|2[05]|50)\\d)\\d{3}",,,, "7151234"], [,, "(?:31(?:8[14-8]|9[14578])|416[14-9]|7(?:0[01]|7[07]|8\\d|9[056])\\d)\\d{3}",,,, "3181234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BQ", 599, "00",,,,,,,,,, [,,,,,,,,, [-1]],, "[347]", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BR: [, [,, "(?:[1-46-9]\\d\\d|5(?:[0-46-9]\\d|5[0-46-9]))\\d{8}|[1-9]\\d{9}|[3589]\\d{8}|[34]\\d{7}",,,,,,, [8, 9, 10, 11]], [,, "(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-5]\\d{7}",,,, "1123456789",,, [10], [8]], [,, "(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])(?:7|9\\d)\\d{7}",,,, "11961234567",,, [10, 11], [8, 9]], [,, "800\\d{6,7}",,,, "800123456",,, [9, 10]], [,, "300\\d{6}|[59]00\\d{6,7}",,,, "300123456",,, [9, 10]], [,, "(?:30[03]\\d{3}|4(?:0(?:0\\d|20)|370))\\d{4}|300\\d{5}",,,, "40041234",,, [8, 10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BR", 55, "00(?:1[245]|2[1-35]|31|4[13]|[56]5|99)", "0",,, "(?:0|90)(?:(1[245]|2[1-35]|31|4[13]|[56]5|99)(\\d{10,11}))?", "$2",,, [[, "(\\d{3,6})", "$1", ["1(?:1[25-8]|2[357-9]|3[02-68]|4[12568]|5|6[0-8]|8[015]|9[0-47-9])|321|610"]], [, "(\\d{4})(\\d{4})", "$1-$2", ["300|4(?:0[02]|37)", "4(?:02|37)0|[34]00"]], [, "(\\d{4})(\\d{4})", "$1-$2", ["[2-57]", "[2357]|4(?:[0-24-9]|3(?:[0-689]|7[1-9]))"]], [, "(\\d{3})(\\d{2,3})(\\d{4})", "$1 $2 $3", ["(?:[358]|90)0"], "0$1"], [, "(\\d{5})(\\d{4})", "$1-$2", ["9"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2-$3", ["(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-57]"], "($1)", "0 $CC ($1)"], [, "(\\d{2})(\\d{5})(\\d{4})", "$1 $2-$3", ["[16][1-9]|[2-57-9]"], "($1)", "0 $CC ($1)"]], [[, "(\\d{4})(\\d{4})", "$1-$2", ["300|4(?:0[02]|37)", "4(?:02|37)0|[34]00"]], [, "(\\d{3})(\\d{2,3})(\\d{4})", "$1 $2 $3", ["(?:[358]|90)0"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2-$3", ["(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-57]"], "($1)", "0 $CC ($1)"], [, "(\\d{2})(\\d{5})(\\d{4})", "$1 $2-$3", ["[16][1-9]|[2-57-9]"], "($1)", "0 $CC ($1)"]], [,,,,,,,,, [-1]],,, [,, "30(?:0\\d{5,7}|3\\d{7})|40(?:0\\d|20)\\d{4}|800\\d{6,7}",,,,,,, [8, 9, 10]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BS: [, [,, "(?:242|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "242(?:3(?:02|[236][1-9]|4[0-24-9]|5[0-68]|7[347]|8[0-4]|9[2-467])|461|502|6(?:0[1-5]|12|2[013]|[45]0|7[67]|8[78]|9[89])|7(?:02|88))\\d{4}",,,, "2423456789",,,, [7]], [,, "242(?:3(?:5[79]|7[56]|95)|4(?:[23][1-9]|4[1-35-9]|5[1-8]|6[2-8]|7\\d|81)|5(?:2[45]|3[35]|44|5[1-46-9]|65|77)|6[34]6|7(?:27|38)|8(?:0[1-9]|1[02-9]|2\\d|3[0-4]|[89]9))\\d{4}",,,, "2423591234",,,, [7]], [,, "242300\\d{4}|8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456",,,, [7]], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "BS", 1, "011", "1",,, "([3-8]\\d{6})$|1", "242$1",,,,, [,,,,,,,,, [-1]],, "242", [,,,,,,,,, [-1]], [,, "242225\\d{4}",,,, "2422250123"],,, [,,,,,,,,, [-1]]],
          BT: [, [,, "[17]\\d{7}|[2-8]\\d{6}",,,,,,, [7, 8], [6]], [,, "(?:2[3-6]|[34][5-7]|5[236]|6[2-46]|7[246]|8[2-4])\\d{5}",,,, "2345678",,, [7], [6]], [,, "(?:1[67]|77)\\d{6}",,,, "17123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BT", 975, "00",,,,,,,, [[, "(\\d{3})(\\d{3})", "$1 $2", ["[2-7]"]], [, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-68]|7[246]"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[67]|7"]]], [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-68]|7[246]"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[67]|7"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BW: [, [,, "(?:0800|(?:[37]|800)\\d)\\d{6}|(?:[2-6]\\d|90)\\d{5}",,,,,,, [7, 8, 10]], [,, "(?:2(?:4[0-48]|6[0-24]|9[0578])|3(?:1[0-35-9]|55|[69]\\d|7[013]|81)|4(?:6[03]|7[1267]|9[0-5])|5(?:3[03489]|4[0489]|7[1-47]|88|9[0-49])|6(?:2[1-35]|5[149]|8[013467]))\\d{4}",,,, "2401234",,, [7]], [,, "(?:321|7[1-8]\\d)\\d{5}",,,, "71123456",,, [8]], [,, "(?:0800|800\\d)\\d{6}",,,, "0800012345",,, [10]], [,, "90\\d{5}",,,, "9012345",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "79(?:1(?:[0-2]\\d|3[0-3])|2[0-7]\\d)\\d{3}",,,, "79101234",,, [8]], "BW", 267, "00",,,,,,,, [[, "(\\d{2})(\\d{5})", "$1 $2", ["90"]], [, "(\\d{3})(\\d{4})", "$1 $2", ["[24-6]|3[15-9]"]], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[37]"]], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["0"]], [, "(\\d{3})(\\d{4})(\\d{3})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BY: [, [,, "(?:[12]\\d|33|44|902)\\d{7}|8(?:0[0-79]\\d{5,7}|[1-7]\\d{9})|8(?:1[0-489]|[5-79]\\d)\\d{7}|8[1-79]\\d{6,7}|8[0-79]\\d{5}|8\\d{5}",,,,,,, [6, 7, 8, 9, 10, 11], [5]], [,, "(?:1(?:5(?:1[1-5]|[24]\\d|6[2-4]|9[1-7])|6(?:[235]\\d|4[1-7])|7\\d\\d)|2(?:1(?:[246]\\d|3[0-35-9]|5[1-9])|2(?:[235]\\d|4[0-8])|3(?:[26]\\d|3[02-79]|4[024-7]|5[03-7])))\\d{5}",,,, "152450911",,, [9], [5, 6, 7]], [,, "(?:2(?:5[5-79]|9[1-9])|(?:33|44)\\d)\\d{6}",,,, "294911911",,, [9]], [,, "800\\d{3,7}|8(?:0[13]|20\\d)\\d{7}",,,, "8011234567"], [,, "(?:810|902)\\d{7}",,,, "9021234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "249\\d{6}",,,, "249123456",,, [9]], "BY", 375, "810", "8",,, "0|80?",, "8~10",, [[, "(\\d{3})(\\d{3})", "$1 $2", ["800"], "8 $1"], [, "(\\d{3})(\\d{2})(\\d{2,4})", "$1 $2 $3", ["800"], "8 $1"], [, "(\\d{4})(\\d{2})(\\d{3})", "$1 $2-$3", ["1(?:5[169]|6[3-5]|7[179])|2(?:1[35]|2[34]|3[3-5])", "1(?:5[169]|6(?:3[1-3]|4|5[125])|7(?:1[3-9]|7[0-24-6]|9[2-7]))|2(?:1[35]|2[34]|3[3-5])"], "8 0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["1(?:[56]|7[467])|2[1-3]"], "8 0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["[1-4]"], "8 0$1"], [, "(\\d{3})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["[89]"], "8 $1"]],, [,,,,,,,,, [-1]],,, [,, "800\\d{3,7}|(?:8(?:0[13]|10|20\\d)|902)\\d{7}"], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          BZ: [, [,, "(?:0800\\d|[2-8])\\d{6}",,,,,,, [7, 11]], [,, "(?:2(?:[02]\\d|36|[68]0)|[3-58](?:[02]\\d|[68]0)|7(?:[02]\\d|32|[68]0))\\d{4}",,,, "2221234",,, [7]], [,, "6[0-35-7]\\d{5}",,,, "6221234",,, [7]], [,, "0800\\d{7}",,,, "08001234123",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "BZ", 501, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1-$2", ["[2-8]"]], [, "(\\d)(\\d{3})(\\d{4})(\\d{3})", "$1-$2-$3-$4", ["0"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CA: [, [,, "(?:[2-8]\\d|90)\\d{8}|3\\d{6}",,,,,,, [7, 10]], [,, "(?:2(?:04|[23]6|[48]9|50|63)|3(?:06|43|54|6[578]|82)|4(?:03|1[68]|[26]8|3[178]|50|74)|5(?:06|1[49]|48|79|8[147])|6(?:04|[18]3|39|47|72)|7(?:0[59]|42|53|78|8[02])|8(?:[06]7|19|25|7[39])|90[25])[2-9]\\d{6}",,,, "5062345678",,, [10], [7]], [,, "(?:2(?:04|[23]6|[48]9|50|63)|3(?:06|43|54|6[578]|82)|4(?:03|1[68]|[26]8|3[178]|50|74)|5(?:06|1[49]|48|79|8[147])|6(?:04|[18]3|39|47|72)|7(?:0[59]|42|53|78|8[02])|8(?:[06]7|19|25|7[39])|90[25])[2-9]\\d{6}",,,, "5062345678",,, [10], [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456",,, [10]], [,, "900[2-9]\\d{6}",,,, "9002123456",,, [10]], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|(?:5(?:00|2[125-9]|33|44|66|77|88)|622)[2-9]\\d{6}",,,, "5002345678",,, [10]], [,, "600[2-9]\\d{6}",,,, "6002012345",,, [10]], "CA", 1, "011", "1",,, "1",,, 1,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "310\\d{4}",,,, "3101234",,, [7]],,, [,,,,,,,,, [-1]]],
          CC: [, [,, "1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",,,,,,, [6, 7, 8, 9, 10, 12]], [,, "8(?:51(?:0(?:02|31|60|89)|1(?:18|76)|223)|91(?:0(?:1[0-2]|29)|1(?:[28]2|50|79)|2(?:10|64)|3(?:[06]8|22)|4[29]8|62\\d|70[23]|959))\\d{3}",,,, "891621234",,, [9], [8]], [,, "4(?:79[01]|83[0-389]|94[0-4])\\d{5}|4(?:[0-36]\\d|4[047-9]|5[0-25-9]|7[02-8]|8[0-24-9]|9[0-37-9])\\d{6}",,,, "412345678",,, [9]], [,, "180(?:0\\d{3}|2)\\d{3}",,,, "1800123456",,, [7, 10]], [,, "190[0-26]\\d{6}",,,, "1900123456",,, [10]], [,, "13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",,,, "1300123456",,, [6, 8, 10, 12]], [,,,,,,,,, [-1]], [,, "14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",,,, "147101234",,, [9]], "CC", 61, "001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011", "0",,, "([59]\\d{7})$|0", "8$1", "0011",,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CD: [, [,, "(?:(?:[189]|5\\d)\\d|2)\\d{7}|[1-68]\\d{6}",,,,,,, [7, 8, 9, 10]], [,, "(?:(?:12|573)\\d\\d|276)\\d{5}|[1-6]\\d{6}",,,, "1234567"], [,, "88\\d{5}|(?:8[0-69]|9[017-9])\\d{7}",,,, "991234567",,, [7, 9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CD", 243, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3", ["88"], "0$1"], [, "(\\d{2})(\\d{5})", "$1 $2", ["[1-6]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[89]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["5"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CF: [, [,, "(?:[27]\\d{3}|8776)\\d{4}",,,,,,, [8]], [,, "2[12]\\d{6}",,,, "21612345"], [,, "7[024-7]\\d{6}",,,, "70012345"], [,,,,,,,,, [-1]], [,, "8776\\d{4}",,,, "87761234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CF", 236, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[278]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CG: [, [,, "222\\d{6}|(?:0\\d|80)\\d{7}",,,,,,, [9]], [,, "222[1-589]\\d{5}",,,, "222123456"], [,, "026(?:1[0-5]|6[6-9])\\d{4}|0(?:[14-6]\\d\\d|2(?:40|5[5-8]|6[07-9]))\\d{5}",,,, "061234567"], [,,,,,,,,, [-1]], [,, "80[0-2]\\d{6}",,,, "800123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CG", 242, "00",,,,,,,, [[, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["8"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[02]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CH: [, [,, "8\\d{11}|[2-9]\\d{8}",,,,,,, [9, 12]], [,, "(?:2[12467]|3[1-4]|4[134]|5[256]|6[12]|[7-9]1)\\d{7}",,,, "212345678",,, [9]], [,, "(?:6[89]|7[235-9])\\d{7}",,,, "781234567",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "90[016]\\d{6}",,,, "900123456",,, [9]], [,, "84[0248]\\d{6}",,,, "840123456",,, [9]], [,, "878\\d{6}",,,, "878123456",,, [9]], [,,,,,,,,, [-1]], "CH", 41, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["8[047]|90"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2-79]|81"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["8"], "0$1"]],, [,, "74[0248]\\d{6}",,,, "740123456",,, [9]],,, [,,,,,,,,, [-1]], [,, "5[18]\\d{7}",,,, "581234567",,, [9]],,, [,, "860\\d{9}",,,, "860123456789",,, [12]]],
          CI: [, [,, "[02]\\d{9}",,,,,,, [10]], [,, "2(?:[15]\\d{3}|7(?:2(?:0[23]|1[2357]|2[245]|3[45]|4[3-5])|3(?:06|1[69]|[2-6]7)))\\d{5}",,,, "2123456789"], [,, "0[157]\\d{8}",,,, "0123456789"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CI", 225, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d)(\\d{5})", "$1 $2 $3 $4", ["2"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3 $4", ["0"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CK: [, [,, "[2-578]\\d{4}",,,,,,, [5]], [,, "(?:2\\d|3[13-7]|4[1-5])\\d{3}",,,, "21234"], [,, "[578]\\d{4}",,,, "71234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CK", 682, "00",,,,,,,, [[, "(\\d{2})(\\d{3})", "$1 $2", ["[2-578]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CL: [, [,, "12300\\d{6}|6\\d{9,10}|[2-9]\\d{8}",,,,,,, [9, 10, 11]], [,, "2(?:1982[0-6]|3314[05-9])\\d{3}|(?:2(?:1(?:160|962)|3(?:2\\d\\d|3(?:[03467]\\d|1[0-35-9]|2[1-9]|5[0-24-9]|8[0-3])|600)|646[59])|80[1-9]\\d\\d|9(?:3(?:[0-57-9]\\d\\d|6(?:0[02-9]|[1-9]\\d))|6(?:[0-8]\\d\\d|9(?:[02-79]\\d|1[05-9]))|7[1-9]\\d\\d|9(?:[03-9]\\d\\d|1(?:[0235-9]\\d|4[0-24-9])|2(?:[0-79]\\d|8[0-46-9]))))\\d{4}|(?:22|3[2-5]|[47][1-35]|5[1-3578]|6[13-57]|8[1-9]|9[2458])\\d{7}",,,, "221234567",,, [9]], [,, "2(?:1982[0-6]|3314[05-9])\\d{3}|(?:2(?:1(?:160|962)|3(?:2\\d\\d|3(?:[03467]\\d|1[0-35-9]|2[1-9]|5[0-24-9]|8[0-3])|600)|646[59])|80[1-9]\\d\\d|9(?:3(?:[0-57-9]\\d\\d|6(?:0[02-9]|[1-9]\\d))|6(?:[0-8]\\d\\d|9(?:[02-79]\\d|1[05-9]))|7[1-9]\\d\\d|9(?:[03-9]\\d\\d|1(?:[0235-9]\\d|4[0-24-9])|2(?:[0-79]\\d|8[0-46-9]))))\\d{4}|(?:22|3[2-5]|[47][1-35]|5[1-3578]|6[13-57]|8[1-9]|9[2458])\\d{7}",,,, "221234567",,, [9]], [,, "(?:123|8)00\\d{6}",,,, "800123456",,, [9, 11]], [,,,,,,,,, [-1]], [,, "600\\d{7,8}",,,, "6001234567",,, [10, 11]], [,,,,,,,,, [-1]], [,, "44\\d{7}",,,, "441234567",,, [9]], "CL", 56, "(?:0|1(?:1[0-69]|2[02-5]|5[13-58]|69|7[0167]|8[018]))0",,,,,,, 1, [[, "(\\d{4})", "$1", ["1(?:[03-589]|21)|[29]0|78"]], [, "(\\d{5})(\\d{4})", "$1 $2", ["219", "2196"], "($1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["44"]], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["2[1-36]"], "($1)"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["9[2-9]"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["3[2-5]|[47]|5[1-3578]|6[13-57]|8(?:0[1-9]|[1-9])"], "($1)"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["60|8"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["60"]]], [[, "(\\d{5})(\\d{4})", "$1 $2", ["219", "2196"], "($1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["44"]], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["2[1-36]"], "($1)"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["9[2-9]"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["3[2-5]|[47]|5[1-3578]|6[13-57]|8(?:0[1-9]|[1-9])"], "($1)"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["60|8"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["60"]]], [,,,,,,,,, [-1]],,, [,, "600\\d{7,8}",,,,,,, [10, 11]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CM: [, [,, "[26]\\d{8}|88\\d{6,7}",,,,,,, [8, 9]], [,, "2(?:22|33)\\d{6}",,,, "222123456",,, [9]], [,, "(?:24[23]|6(?:[25-9]\\d|40))\\d{6}",,,, "671234567",,, [9]], [,, "88\\d{6,7}",,,, "88012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CM", 237, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["88"]], [, "(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["[26]|88"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CN: [, [,, "(?:(?:1[03-689]|2\\d)\\d\\d|6)\\d{8}|1\\d{10}|[126]\\d{6}(?:\\d(?:\\d{2})?)?|86\\d{5,6}|(?:[3-579]\\d|8[0-57-9])\\d{5,9}",,,,,,, [7, 8, 9, 10, 11, 12], [5, 6]], [,, "(?:10(?:[02-79]\\d\\d|[18](?:0[1-9]|[1-9]\\d))|2(?:[02-57-9]\\d{3}|1(?:[18](?:0[1-9]|[1-9]\\d)|[2-79]\\d\\d))|(?:41[03]|8078|9(?:78|94))\\d\\d)\\d{5}|(?:10|2[0-57-9])(?:1(?:00|23)\\d\\d|95\\d{3,4})|(?:41[03]|9(?:78|94))(?:100\\d\\d|95\\d{3,4})|8078123|(?:43[35]|754|851)\\d{7,8}|(?:43[35]|754|851)(?:1(?:00\\d|23)\\d|95\\d{3,4})|(?:3(?:11|7[179])|4(?:[15]1|3[12])|5(?:1\\d|2[37]|3[12]|51|7[13-79]|9[15])|7(?:[39]1|5[57]|6[09])|8(?:71|98))(?:[02-8]\\d{7}|1(?:0(?:0\\d\\d(?:\\d{3})?|[1-9]\\d{5})|[13-9]\\d{6}|2(?:[0-24-9]\\d{5}|3\\d(?:\\d{4})?))|9(?:[0-46-9]\\d{6}|5\\d{3}(?:\\d(?:\\d{2})?)?))|(?:3(?:1[02-9]|35|49|5\\d|7[02-68]|9[1-68])|4(?:1[24-9]|2[179]|3[46-9]|5[2-9]|6[47-9]|7\\d|8[23])|5(?:3[03-9]|4[36]|5[02-9]|6[1-46]|7[028]|80|9[2-46-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[17]\\d|2[248]|3[04-9]|4[3-6]|5[0-3689]|6[2368]|9[02-9])|8(?:1[236-8]|2[5-7]|3\\d|5[2-9]|7[02-9]|8[36-8]|9[1-7])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))(?:[02-8]\\d{6}|1(?:0(?:0\\d\\d(?:\\d{2})?|[1-9]\\d{4})|[13-9]\\d{5}|2(?:[0-24-9]\\d{4}|3\\d(?:\\d{3})?))|9(?:[0-46-9]\\d{5}|5\\d{3,5}))",,,, "1012345678",,, [7, 8, 9, 10, 11], [5, 6]], [,, "1740[0-5]\\d{6}|1(?:[38]\\d|4[57]|[59][0-35-9]|6[25-7]|7[0-35-8])\\d{8}",,,, "13123456789",,, [11]], [,, "(?:(?:10|21)8|8)00\\d{7}",,,, "8001234567",,, [10, 12]], [,, "16[08]\\d{5}",,,, "16812345",,, [8]], [,, "10(?:10\\d{4}|96\\d{3,4})|400\\d{7}|950\\d{7,8}|(?:2[0-57-9]|3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))96\\d{3,4}",,,, "4001234567",,, [7, 8, 9, 10, 11], [5, 6]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CN", 86, "00|1(?:[12]\\d|79)\\d\\d00", "0",,, "(1(?:[12]\\d|79)\\d\\d)|0",, "00",, [[, "(\\d{5,6})", "$1", ["1(?:00|2[13])|9[56]", "1(?:00|2(?:1|39))|9[56]", "1(?:00|2(?:1|395))|9[56]"]], [, "(\\d{5,6})", "$1", ["1(?:0|23)|781|[1-9]12", "1(?:0|23)|7812|[1-9]123", "1(?:0|23(?:[0-8]|9[0-46-9]))|78123|[1-9]123"]], [, "(\\d{2})(\\d{5,6})", "$1 $2", ["(?:10|2[0-57-9])[19]|3(?:[157]|35|49|9[1-68])|4(?:1[124-9]|2[179]|6[47-9]|7|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:07|1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3|4[13]|5[1-5]|7[0-79]|9[0-35-9])|(?:4[35]|59|85)[1-9]", "(?:10|2[0-57-9])(?:1[02]|9[56])|8078|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))1", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|80781|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))12", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|807812|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123"], "0$1", "$CC $1"], [, "(\\d{3})(\\d{4})", "$1 $2", ["[1-9]", "1[1-9]|26|[3-9]|(?:10|2[0-57-9])(?:[0-8]|9[0-47-9])", "1(?:0(?:[02-8]|1(?:[013-9]|2[0-24-9])|9[0-47-9])|[1-9])|2(?:[0-57-9](?:[02-8]|1(?:0[1-9]|[13-9]|2[0-24-9])|9[0-47-9])|6)|[3-9]", "1(?:0(?:[02-8]|1(?:[013-9]|2[0-24-9])|9[0-47-9])|[1-9])|2(?:[0-57-9](?:[02-8]|1(?:0[1-9]|[13-9]|2[0-24-9])|9[0-47-9])|6)|3(?:[0268]|3[0-46-9]|4[0-8]|9[079])|4(?:[049]|1[03]|2[02-68]|[35]0|6[0-356]|8[014-9])|5(?:0|2[0-24-689]|4[0-2457-9]|6[057-9]|8[1-9]|90)|6(?:[0-24578]|3[06-9]|6[14-79]|9[03-9])|7(?:0[02-9]|2[0135-79]|3[23]|4[0-27-9]|6[1457]|8)|8(?:[046]|1[01459]|2[0-489]|50|8[0-2459]|9[09])|9(?:0[0457]|1[08]|[268]|4[024-9]|5[06-9]|78|94)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))(?:[02-9]|1(?:[013-9]|2[0-24-9]))", "1(?:0(?:[02-8]|1(?:[013-9]|2[0-24-9])|9[0-47-9])|[1-9])|2(?:[0-57-9](?:[02-8]|1(?:0[1-9]|[13-9]|2[0-24-9])|9[0-47-9])|6)|3(?:[0268]|3[0-46-9]|4[0-8]|9[079])|4(?:[049]|1[03]|2[02-68]|[35]0|6[0-356]|8[014-9])|5(?:0|2[0-24-689]|4[0-2457-9]|6[057-9]|8[1-9]|90)|6(?:[0-24578]|3[06-9]|6[14-79]|9[03-9])|7(?:0[02-9]|2[0135-79]|3[23]|4[0-27-9]|6[1457]|8)|8(?:0(?:[0-689]|7[0-79])|1[01459]|2[0-489]|[46]|50|8[0-2459]|9[09])|9(?:0[0457]|1[08]|[268]|4[024-9]|5[06-9]|78|94)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))(?:[02-9]|1(?:[013-9]|2[0-24-9]))"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["16[08]"]], [, "(\\d{3})(\\d{5,6})", "$1 $2", ["3(?:[157]|35|49|9[1-68])|4(?:[17]|2[179]|6[47-9]|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]|4[13]|5[1-5])|(?:4[35]|59|85)[1-9]", "(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))[19]", "85[23](?:10|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:10|9[56])", "85[23](?:100|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:100|9[56])"], "0$1", "$CC $1"], [, "(\\d{4})(\\d{4})", "$1 $2", ["[1-9]", "1(?:0(?:[02-8]|1[1-9]|9[0-47-9])|[1-9])|2(?:[0-57-9](?:[0-8]|9[0-47-9])|6)|[3-9]", "1(?:0(?:[02-8]|1[1-9]|9[0-47-9])|[1-9])|26|3(?:[0268]|4[0-8]|9[079])|4(?:[049]|2[02-68]|[35]0|6[0-356]|8[014-9])|5(?:0|2[0-24-689]|4[0-2457-9]|6[057-9]|8[1-9]|90)|6(?:[0-24578]|3[06-9]|6[14-79]|9[03-9])|7(?:0[02-9]|2[0135-79]|3[23]|4[0-27-9]|6[1457]|8)|8(?:[046]|1[01459]|2[0-489]|5(?:0|[23][0-8])|8[0-2459]|9[09])|9(?:0[0457]|1[08]|[268]|4[024-9]|5[06-9])|(?:33|85[23]9)[0-46-9]|(?:2[0-57-9]|3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:[0-8]|9[0-47-9])", "1(?:0[02-8]|[1-9])|2(?:[0-57-9][0-8]|6)|3(?:[0268]|3[0-46-9]|4[0-8]|9[079])|4(?:[049]|2[02-68]|[35]0|6[0-356]|8[014-9])|5(?:0|2[0-24-689]|4[0-2457-9]|6[057-9]|90)|6(?:[0-24578]|3[06-9]|6[14-79]|9[03-9])|7(?:0[02-9]|2[0135-79]|3[23]|4[0-27-9]|6[1457]|8)|8(?:[046]|1[01459]|2[0-489]|5(?:0|[23](?:[02-8]|1[1-9]|9[0-46-9]))|8[0-2459]|9[09])|9(?:0[0457]|1[08]|[268]|4[024-9]|5[06-9])|(?:10|2[0-57-9])9[0-47-9]|(?:101|58|85[23]10)[1-9]|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:[02-8]|1(?:0[1-9]|[1-9])|9[0-47-9])"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["(?:4|80)0"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["10|2(?:[02-57-9]|1[1-9])", "10|2(?:[02-57-9]|1[1-9])", "10[0-79]|2(?:[02-57-9]|1[1-79])|(?:10|21)8(?:0[1-9]|[1-9])"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["3(?:[3-59]|7[02-68])|4(?:[26-8]|3[3-9]|5[2-9])|5(?:3[03-9]|[468]|7[028]|9[2-46-9])|6|7(?:[0-247]|3[04-9]|5[0-4689]|6[2368])|8(?:[1-358]|9[1-7])|9(?:[013479]|5[1-5])|(?:[34]1|55|79|87)[02-9]"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{7,8})", "$1 $2", ["9"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["80"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["[3-578]"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["1[3-9]"],, "$CC $1"], [, "(\\d{2})(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["[12]"], "0$1",, 1]], [[, "(\\d{2})(\\d{5,6})", "$1 $2", ["(?:10|2[0-57-9])[19]|3(?:[157]|35|49|9[1-68])|4(?:1[124-9]|2[179]|6[47-9]|7|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:07|1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3|4[13]|5[1-5]|7[0-79]|9[0-35-9])|(?:4[35]|59|85)[1-9]", "(?:10|2[0-57-9])(?:1[02]|9[56])|8078|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))1", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|80781|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))12", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|807812|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123", "10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123"], "0$1", "$CC $1"], [, "(\\d{3})(\\d{5,6})", "$1 $2", ["3(?:[157]|35|49|9[1-68])|4(?:[17]|2[179]|6[47-9]|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]|4[13]|5[1-5])|(?:4[35]|59|85)[1-9]", "(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))[19]", "85[23](?:10|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:10|9[56])", "85[23](?:100|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:100|9[56])"], "0$1", "$CC $1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["(?:4|80)0"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["10|2(?:[02-57-9]|1[1-9])", "10|2(?:[02-57-9]|1[1-9])", "10[0-79]|2(?:[02-57-9]|1[1-79])|(?:10|21)8(?:0[1-9]|[1-9])"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["3(?:[3-59]|7[02-68])|4(?:[26-8]|3[3-9]|5[2-9])|5(?:3[03-9]|[468]|7[028]|9[2-46-9])|6|7(?:[0-247]|3[04-9]|5[0-4689]|6[2368])|8(?:[1-358]|9[1-7])|9(?:[013479]|5[1-5])|(?:[34]1|55|79|87)[02-9]"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{7,8})", "$1 $2", ["9"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["80"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["[3-578]"], "0$1", "$CC $1", 1], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["1[3-9]"],, "$CC $1"], [, "(\\d{2})(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["[12]"], "0$1",, 1]], [,,,,,,,,, [-1]],,, [,, "(?:(?:10|21)8|[48])00\\d{7}|950\\d{7,8}",,,,,,, [10, 11, 12]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CO: [, [,, "60\\d{8}|(?:1\\d|[39])\\d{9}",,,,,,, [10, 11], [7]], [,, "601055(?:[0-4]\\d|50)\\d\\d|6010(?:[0-4]\\d|5[0-4])\\d{4}|60(?:[124-7][2-9]|8[1-9])\\d{6}",,,, "6012345678",,, [10], [7]], [,, "333301[0-5]\\d{3}|3333(?:00|2[5-9]|[3-9]\\d)\\d{4}|(?:3(?:24[1-9]|3(?:00|3[0-24-9]))|9101)\\d{6}|3(?:0[0-5]|1\\d|2[0-3]|5[01]|70)\\d{7}",,,, "3211234567",,, [10]], [,, "1800\\d{7}",,,, "18001234567",,, [11]], [,, "(?:19(?:0[01]|4[78])|901)\\d{7}",,,, "19001234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CO", 57, "00(?:4(?:[14]4|56)|[579])", "0",,, "0([3579]|4(?:[14]4|56))?",,,, [[, "(\\d{3})(\\d{7})", "$1 $2", ["6|90"], "($1)", "0$CC $1"], [, "(\\d{3})(\\d{7})", "$1 $2", ["3[0-357]|91"],, "0$CC $1"], [, "(\\d)(\\d{3})(\\d{7})", "$1-$2-$3", ["1"], "0$1"]], [[, "(\\d{3})(\\d{7})", "$1 $2", ["6|90"], "($1)", "0$CC $1"], [, "(\\d{3})(\\d{7})", "$1 $2", ["3[0-357]|91"],, "0$CC $1"], [, "(\\d)(\\d{3})(\\d{7})", "$1 $2 $3", ["1"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CR: [, [,, "(?:8\\d|90)\\d{8}|(?:[24-8]\\d{3}|3005)\\d{4}",,,,,,, [8, 10]], [,, "210[7-9]\\d{4}|2(?:[024-7]\\d|1[1-9])\\d{5}",,,, "22123456",,, [8]], [,, "(?:3005\\d|6500[01])\\d{3}|(?:5[07]|6[0-4]|7[0-3]|8[3-9])\\d{6}",,,, "83123456",,, [8]], [,, "800\\d{7}",,,, "8001234567",,, [10]], [,, "90[059]\\d{7}",,,, "9001234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:210[0-6]|4\\d{3}|5100)\\d{4}",,,, "40001234",,, [8]], "CR", 506, "00",,,, "(19(?:0[0-2468]|1[09]|20|66|77|99))",,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[2-7]|8[3-9]"],, "$CC $1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["[89]"],, "$CC $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CU: [, [,, "(?:[2-7]|8\\d\\d)\\d{7}|[2-47]\\d{6}|[34]\\d{5}",,,,,,, [6, 7, 8, 10], [4, 5]], [,, "(?:3[23]|4[89])\\d{4,6}|(?:31|4[36]|8(?:0[25]|78)\\d)\\d{6}|(?:2[1-4]|4[1257]|7\\d)\\d{5,6}",,,, "71234567",,,, [4, 5]], [,, "(?:5\\d|6[2-4])\\d{6}",,,, "51234567",,, [8]], [,, "800\\d{7}",,,, "8001234567",,, [10]], [,,,,,,,,, [-1]], [,, "807\\d{7}",,,, "8071234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CU", 53, "119", "0",,, "0",,,, [[, "(\\d{2})(\\d{4,6})", "$1 $2", ["2[1-4]|[34]"], "(0$1)"], [, "(\\d)(\\d{6,7})", "$1 $2", ["7"], "(0$1)"], [, "(\\d)(\\d{7})", "$1 $2", ["[56]"], "0$1"], [, "(\\d{3})(\\d{7})", "$1 $2", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CV: [, [,, "(?:[2-59]\\d\\d|800)\\d{4}",,,,,,, [7]], [,, "2(?:2[1-7]|3[0-8]|4[12]|5[1256]|6\\d|7[1-3]|8[1-5])\\d{4}",,,, "2211234"], [,, "(?:36|5[1-389]|9\\d)\\d{5}",,,, "9911234"], [,, "800\\d{4}",,,, "8001234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:3[3-5]|4[356])\\d{5}",,,, "3401234"], "CV", 238, "0",,,,,,,, [[, "(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3", ["[2-589]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CW: [, [,, "(?:[34]1|60|(?:7|9\\d)\\d)\\d{5}",,,,,,, [7, 8]], [,, "9(?:4(?:3[0-5]|4[14]|6\\d)|50\\d|7(?:2[014]|3[02-9]|4[4-9]|6[357]|77|8[7-9])|8(?:3[39]|[46]\\d|7[01]|8[57-9]))\\d{4}",,,, "94351234"], [,, "953[01]\\d{4}|9(?:5[12467]|6[5-9])\\d{5}",,,, "95181234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "60[0-2]\\d{4}",,,, "6001234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "CW", 599, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[3467]"]], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["9[4-8]"]]],, [,, "955\\d{5}",,,, "95581234",,, [8]], 1, "[69]", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CX: [, [,, "1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",,,,,,, [6, 7, 8, 9, 10, 12]], [,, "8(?:51(?:0(?:01|30|59|88)|1(?:17|46|75)|2(?:22|35))|91(?:00[6-9]|1(?:[28]1|49|78)|2(?:09|63)|3(?:12|26|75)|4(?:56|97)|64\\d|7(?:0[01]|1[0-2])|958))\\d{3}",,,, "891641234",,, [9], [8]], [,, "4(?:79[01]|83[0-389]|94[0-4])\\d{5}|4(?:[0-36]\\d|4[047-9]|5[0-25-9]|7[02-8]|8[0-24-9]|9[0-37-9])\\d{6}",,,, "412345678",,, [9]], [,, "180(?:0\\d{3}|2)\\d{3}",,,, "1800123456",,, [7, 10]], [,, "190[0-26]\\d{6}",,,, "1900123456",,, [10]], [,, "13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",,,, "1300123456",,, [6, 8, 10, 12]], [,,,,,,,,, [-1]], [,, "14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",,,, "147101234",,, [9]], "CX", 61, "001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011", "0",,, "([59]\\d{7})$|0", "8$1", "0011",,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          CY: [, [,, "(?:[279]\\d|[58]0)\\d{6}",,,,,,, [8]], [,, "2[2-6]\\d{6}",,,, "22345678"], [,, "9(?:10|[4-79]\\d)\\d{5}",,,, "96123456"], [,, "800\\d{5}",,,, "80001234"], [,, "90[09]\\d{5}",,,, "90012345"], [,, "80[1-9]\\d{5}",,,, "80112345"], [,, "700\\d{5}",,,, "70012345"], [,,,,,,,,, [-1]], "CY", 357, "00",,,,,,,, [[, "(\\d{2})(\\d{6})", "$1 $2", ["[257-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "(?:50|77)\\d{6}",,,, "77123456"],,, [,,,,,,,,, [-1]]],
          CZ: [, [,, "(?:[2-578]\\d|60)\\d{7}|9\\d{8,11}",,,,,,, [9, 10, 11, 12]], [,, "(?:2\\d|3[1257-9]|4[16-9]|5[13-9])\\d{7}",,,, "212345678",,, [9]], [,, "(?:60[1-8]\\d|7(?:0(?:[2-5]\\d|60)|19[01]|[2379]\\d\\d))\\d{5}",,,, "601123456",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "9(?:0[05689]|76)\\d{6}",,,, "900123456",,, [9]], [,, "8[134]\\d{7}",,,, "811234567",,, [9]], [,, "70[01]\\d{6}",,,, "700123456",,, [9]], [,, "9[17]0\\d{6}",,,, "910123456",,, [9]], "CZ", 420, "00",,,,,,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-8]|9[015-7]"]], [, "(\\d{2})(\\d{3})(\\d{3})(\\d{2})", "$1 $2 $3 $4", ["96"]], [, "(\\d{2})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["9"]], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["9"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "9(?:5\\d|7[2-4])\\d{6}",,,, "972123456",,, [9]],,, [,, "9(?:3\\d{9}|6\\d{7,10})",,,, "93123456789"]],
          DE: [, [,, "[2579]\\d{5,14}|49(?:[34]0|69|8\\d)\\d\\d?|49(?:37|49|60|7[089]|9\\d)\\d{1,3}|49(?:2[024-9]|3[2-689]|7[1-7])\\d{1,8}|(?:1|[368]\\d|4[0-8])\\d{3,13}|49(?:[015]\\d|2[13]|31|[46][1-8])\\d{1,9}",,,,,,, [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [2, 3]], [,, "32\\d{9,11}|49[1-6]\\d{10}|322\\d{6}|49[0-7]\\d{3,9}|(?:[34]0|[68]9)\\d{3,13}|(?:2(?:0[1-689]|[1-3569]\\d|4[0-8]|7[1-7]|8[0-7])|3(?:[3569]\\d|4[0-79]|7[1-7]|8[1-8])|4(?:1[02-9]|[2-48]\\d|5[0-6]|6[0-8]|7[0-79])|5(?:0[2-8]|[124-6]\\d|[38][0-8]|[79][0-7])|6(?:0[02-9]|[1-358]\\d|[47][0-8]|6[1-9])|7(?:0[2-8]|1[1-9]|[27][0-7]|3\\d|[4-6][0-8]|8[0-5]|9[013-7])|8(?:0[2-9]|1[0-79]|2\\d|3[0-46-9]|4[0-6]|5[013-9]|6[1-8]|7[0-8]|8[0-24-6])|9(?:0[6-9]|[1-4]\\d|[589][0-7]|6[0-8]|7[0-467]))\\d{3,12}",,,, "30123456",,, [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [2, 3, 4]], [,, "15310\\d{6}|1(?:6[023]|7[0-57-9])\\d{7,8}|1(?:5[0-25-9]|76)\\d{8}",,,, "15123456789",,, [10, 11]], [,, "800\\d{7,12}",,,, "8001234567890",,, [10, 11, 12, 13, 14, 15]], [,, "(?:137[7-9]|900(?:[135]|9\\d))\\d{6}",,,, "9001234567",,, [10, 11]], [,, "180\\d{5,11}|13(?:7[1-6]\\d\\d|8)\\d{4}",,,, "18012345",,, [7, 8, 9, 10, 11, 12, 13, 14]], [,, "700\\d{8}",,,, "70012345678",,, [11]], [,,,,,,,,, [-1]], "DE", 49, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3,13})", "$1 $2", ["3[02]|40|[68]9"], "0$1"], [, "(\\d{3})(\\d{3,12})", "$1 $2", ["2(?:0[1-389]|1[124]|2[18]|3[14])|3(?:[35-9][15]|4[015])|906|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1", "2(?:0[1-389]|12[0-8])|3(?:[35-9][15]|4[015])|906|2(?:[13][14]|2[18])|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1"], "0$1"], [, "(\\d{4})(\\d{2,11})", "$1 $2", ["[24-6]|3(?:[3569][02-46-9]|4[2-4679]|7[2-467]|8[2-46-8])|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]", "[24-6]|3(?:3(?:0[1-467]|2[127-9]|3[124578]|7[1257-9]|8[1256]|9[145])|4(?:2[135]|4[13578]|9[1346])|5(?:0[14]|2[1-3589]|6[1-4]|7[13468]|8[13568])|6(?:2[1-489]|3[124-6]|6[13]|7[12579]|8[1-356]|9[135])|7(?:2[1-7]|4[145]|6[1-5]|7[1-4])|8(?:21|3[1468]|6|7[1467]|8[136])|9(?:0[12479]|2[1358]|4[134679]|6[1-9]|7[136]|8[147]|9[1468]))|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]|3[68]4[1347]|3(?:47|60)[1356]|3(?:3[46]|46|5[49])[1246]|3[4579]3[1357]"], "0$1"], [, "(\\d{3})(\\d{4})", "$1 $2", ["138"], "0$1"], [, "(\\d{5})(\\d{2,10})", "$1 $2", ["3"], "0$1"], [, "(\\d{3})(\\d{5,11})", "$1 $2", ["181"], "0$1"], [, "(\\d{3})(\\d)(\\d{4,10})", "$1 $2 $3", ["1(?:3|80)|9"], "0$1"], [, "(\\d{3})(\\d{7,8})", "$1 $2", ["1[67]"], "0$1"], [, "(\\d{3})(\\d{7,12})", "$1 $2", ["8"], "0$1"], [, "(\\d{5})(\\d{6})", "$1 $2", ["185", "1850", "18500"], "0$1"], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["7"], "0$1"], [, "(\\d{4})(\\d{7})", "$1 $2", ["18[68]"], "0$1"], [, "(\\d{4})(\\d{7})", "$1 $2", ["15[1279]"], "0$1"], [, "(\\d{5})(\\d{6})", "$1 $2", ["15[03568]", "15(?:[0568]|31)"], "0$1"], [, "(\\d{3})(\\d{8})", "$1 $2", ["18"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{7,8})", "$1 $2 $3", ["1(?:6[023]|7)"], "0$1"], [, "(\\d{4})(\\d{2})(\\d{7})", "$1 $2 $3", ["15[279]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{8})", "$1 $2 $3", ["15"], "0$1"]],, [,, "16(?:4\\d{1,10}|[89]\\d{1,11})",,,, "16412345",,, [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]],,, [,,,,,,,,, [-1]], [,, "18(?:1\\d{5,11}|[2-9]\\d{8})",,,, "18500123456",,, [8, 9, 10, 11, 12, 13, 14]],,, [,, "1(?:6(?:013|255|399)|7(?:(?:[015]1|[69]3)3|[2-4]55|[78]99))\\d{7,8}|15(?:(?:[03-68]00|113)\\d|2\\d55|7\\d99|9\\d33)\\d{7}",,,, "177991234567",,, [12, 13]]],
          DJ: [, [,, "(?:2\\d|77)\\d{6}",,,,,,, [8]], [,, "2(?:1[2-5]|7[45])\\d{5}",,,, "21360003"], [,, "77\\d{6}",,,, "77831001"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "DJ", 253, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[27]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          DK: [, [,, "[2-9]\\d{7}",,,,,,, [8]], [,, "(?:(?:2\\d|9[1-46-9])\\d|3(?:[0-37]\\d|4[013]|5[0-58]|6[01347-9]|8[0-8]|9[0-79])|4(?:[0-25]\\d|[34][02-9]|6[013-579]|7[013579]|8[0-47]|9[0-27])|5(?:[0-36]\\d|4[0146-9]|5[03-57-9]|7[0568]|8[0-358]|9[0-69])|6(?:[013578]\\d|2[0-68]|4[02-8]|6[01689]|9[015689])|7(?:[0-69]\\d|7[03-9]|8[0147])|8(?:[16-9]\\d|2[0-58]))\\d{5}",,,, "32123456"], [,, "(?:[2-7]\\d|8[126-9]|9[1-46-9])\\d{6}",,,, "34412345"], [,, "80\\d{6}",,,, "80123456"], [,, "90\\d{6}",,,, "90123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "DK", 45, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          DM: [, [,, "(?:[58]\\d\\d|767|900)\\d{7}",,,,,,, [10], [7]], [,, "767(?:2(?:55|66)|4(?:2[01]|4[0-25-9])|50[0-4])\\d{4}",,,, "7674201234",,,, [7]], [,, "767(?:2(?:[2-4689]5|7[5-7])|31[5-7]|61[1-8]|70[1-6])\\d{4}",,,, "7672251234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "DM", 1, "011", "1",,, "([2-7]\\d{6})$|1", "767$1",,,,, [,,,,,,,,, [-1]],, "767", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          DO: [, [,, "(?:[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "8(?:[04]9[2-9]\\d\\d|29(?:2(?:[0-59]\\d|6[04-9]|7[0-27]|8[0237-9])|3(?:[0-35-9]\\d|4[7-9])|[45]\\d\\d|6(?:[0-27-9]\\d|[3-5][1-9]|6[0135-8])|7(?:0[013-9]|[1-37]\\d|4[1-35689]|5[1-4689]|6[1-57-9]|8[1-79]|9[1-8])|8(?:0[146-9]|1[0-48]|[248]\\d|3[1-79]|5[01589]|6[013-68]|7[124-8]|9[0-8])|9(?:[0-24]\\d|3[02-46-9]|5[0-79]|60|7[0169]|8[57-9]|9[02-9])))\\d{4}",,,, "8092345678",,,, [7]], [,, "8[024]9[2-9]\\d{6}",,,, "8092345678",,,, [7]], [,, "8(?:00(?:14|[2-9]\\d)|(?:33|44|55|66|77|88)[2-9]\\d)\\d{5}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "DO", 1, "011", "1",,, "1",,,,,, [,,,,,,,,, [-1]],, "8001|8[024]9", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          DZ: [, [,, "(?:[1-4]|[5-79]\\d|80)\\d{7}",,,,,,, [8, 9]], [,, "9619\\d{5}|(?:1\\d|2[013-79]|3[0-8]|4[013-689])\\d{6}",,,, "12345678"], [,, "(?:5(?:4[0-29]|5\\d|6[0-3])|6(?:[569]\\d|7[0-6])|7[7-9]\\d)\\d{6}",,,, "551234567",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "80[3-689]1\\d{5}",,,, "808123456",,, [9]], [,, "80[12]1\\d{5}",,,, "801123456",,, [9]], [,,,,,,,,, [-1]], [,, "98[23]\\d{6}",,,, "983123456",,, [9]], "DZ", 213, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[1-4]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["9"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[5-8]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          EC: [, [,, "1\\d{9,10}|(?:[2-7]|9\\d)\\d{7}",,,,,,, [8, 9, 10, 11], [7]], [,, "[2-7][2-7]\\d{6}",,,, "22123456",,, [8], [7]], [,, "964[0-2]\\d{5}|9(?:39|[57][89]|6[0-36-9]|[89]\\d)\\d{6}",,,, "991234567",,, [9]], [,, "1800\\d{7}|1[78]00\\d{6}",,,, "18001234567",,, [10, 11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "[2-7]890\\d{4}",,,, "28901234",,, [8]], "EC", 593, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{4})", "$1-$2", ["[2-7]"]], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2-$3", ["[2-7]"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["9"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["1"]]], [[, "(\\d)(\\d{3})(\\d{4})", "$1-$2-$3", ["[2-7]"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["9"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["1"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          EE: [, [,, "8\\d{9}|[4578]\\d{7}|(?:[3-8]\\d|90)\\d{5}",,,,,,, [7, 8, 10]], [,, "(?:3[23589]|4[3-8]|6\\d|7[1-9]|88)\\d{5}",,,, "3212345",,, [7]], [,, "(?:5\\d{5}|8(?:1(?:0(?:0(?:00|[178]\\d)|[3-9]\\d\\d)|(?:1(?:0[236]|1\\d)|(?:2[0-59]|[3-79]\\d)\\d)\\d)|2(?:0(?:0(?:00|4\\d)|(?:19|[2-7]\\d)\\d)|(?:(?:[124-6]\\d|3[5-9])\\d|7(?:[0-79]\\d|8[13-9])|8(?:[2-6]\\d|7[01]))\\d)|[349]\\d{4}))\\d\\d|5(?:(?:[02]\\d|5[0-478])\\d|1(?:[0-8]\\d|95)|6(?:4[0-4]|5[1-589]))\\d{3}",,,, "51234567",,, [7, 8]], [,, "800(?:(?:0\\d\\d|1)\\d|[2-9])\\d{3}",,,, "80012345"], [,, "(?:40\\d\\d|900)\\d{4}",,,, "9001234",,, [7, 8]], [,,,,,,,,, [-1]], [,, "70[0-2]\\d{5}",,,, "70012345",,, [8]], [,,,,,,,,, [-1]], "EE", 372, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[369]|4[3-8]|5(?:[0-2]|5[0-478]|6[45])|7[1-9]|88", "[369]|4[3-8]|5(?:[02]|1(?:[0-8]|95)|5[0-478]|6(?:4[0-4]|5[1-589]))|7[1-9]|88"]], [, "(\\d{4})(\\d{3,4})", "$1 $2", ["[45]|8(?:00|[1-49])", "[45]|8(?:00[1-9]|[1-49])"]], [, "(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3", ["7"]], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,, "800[2-9]\\d{3}",,,,,,, [7]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          EG: [, [,, "[189]\\d{8,9}|[24-6]\\d{8}|[135]\\d{7}",,,,,,, [8, 9, 10], [6, 7]], [,, "13[23]\\d{6}|(?:15|57)\\d{6,7}|(?:2\\d|3|4[05-8]|5[05]|6[24-689]|8[2468]|9[235-7])\\d{7}",,,, "234567890",,, [8, 9], [6, 7]], [,, "1[0-25]\\d{8}",,,, "1001234567",,, [10]], [,, "800\\d{7}",,,, "8001234567",,, [10]], [,, "900\\d{7}",,,, "9001234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "EG", 20, "00", "0",,, "0",,,, [[, "(\\d)(\\d{7,8})", "$1 $2", ["[23]"], "0$1"], [, "(\\d{2})(\\d{6,7})", "$1 $2", ["1[35]|[4-6]|8[2468]|9[235-7]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[89]"], "0$1"], [, "(\\d{2})(\\d{8})", "$1 $2", ["1"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          EH: [, [,, "[5-8]\\d{8}",,,,,,, [9]], [,, "528[89]\\d{5}",,,, "528812345"], [,, "(?:6(?:[0-79]\\d|8[0-247-9])|7(?:[0167]\\d|2[0-4]|5[01]|8[0-3]))\\d{6}",,,, "650123456"], [,, "80[0-7]\\d{6}",,,, "801234567"], [,, "89\\d{7}",,,, "891234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:592(?:4[0-2]|93)|80[89]\\d\\d)\\d{4}",,,, "592401234"], "EH", 212, "00", "0",,, "0",,,,,, [,,,,,,,,, [-1]],, "528[89]", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ER: [, [,, "[178]\\d{6}",,,,,,, [7], [6]], [,, "(?:1(?:1[12568]|[24]0|55|6[146])|8\\d\\d)\\d{4}",,,, "8370362",,,, [6]], [,, "(?:17[1-3]|7\\d\\d)\\d{4}",,,, "7123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "ER", 291, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["[178]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ES: [, [,, "[5-9]\\d{8}",,,,,,, [9]], [,, "96906(?:0[0-8]|1[1-9]|[2-9]\\d)\\d\\d|9(?:69(?:0[0-57-9]|[1-9]\\d)|73(?:[0-8]\\d|9[1-9]))\\d{4}|(?:8(?:[1356]\\d|[28][0-8]|[47][1-9])|9(?:[135]\\d|[268][0-8]|4[1-9]|7[124-9]))\\d{6}",,,, "810123456"], [,, "(?:590[16]00\\d|9(?:6906(?:09|10)|7390\\d\\d))\\d\\d|(?:6\\d|7[1-48])\\d{7}",,,, "612345678"], [,, "[89]00\\d{6}",,,, "800123456"], [,, "80[367]\\d{6}",,,, "803123456"], [,, "90[12]\\d{6}",,,, "901123456"], [,, "70\\d{7}",,,, "701234567"], [,,,,,,,,, [-1]], "ES", 34, "00",,,,,,,, [[, "(\\d{4})", "$1", ["905"]], [, "(\\d{6})", "$1", ["[79]9"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[89]00"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[5-9]"]]], [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[89]00"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[5-9]"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "51\\d{7}",,,, "511234567"],,, [,,,,,,,,, [-1]]],
          ET: [, [,, "(?:11|[2-579]\\d)\\d{7}",,,,,,, [9], [7]], [,, "11667[01]\\d{3}|(?:11(?:1(?:1[124]|2[2-7]|3[1-5]|5[5-8]|8[6-8])|2(?:13|3[6-8]|5[89]|7[05-9]|8[2-6])|3(?:2[01]|3[0-289]|4[1289]|7[1-4]|87)|4(?:1[69]|3[2-49]|4[0-3]|6[5-8]|7\\d)|5(?:1[578]|44|5[0-4])|6(?:1[578]|2[69]|39|4[5-7]|5[0-5]|6[0-59]|8[015-8]))|2(?:2(?:11[1-9]|22[0-7]|33\\d|44[1467]|66[1-68])|5(?:11[124-6]|33[2-8]|44[1467]|55[14]|66[1-3679]|77[124-79]|880))|3(?:3(?:11[0-46-8]|(?:22|55)[0-6]|33[0134689]|44[04]|66[01467])|4(?:44[0-8]|55[0-69]|66[0-3]|77[1-5]))|4(?:6(?:119|22[0-24-7]|33[1-5]|44[13-69]|55[14-689]|660|88[1-4])|7(?:(?:11|22)[1-9]|33[13-7]|44[13-6]|55[1-689]))|5(?:7(?:227|55[05]|(?:66|77)[14-8])|8(?:11[149]|22[013-79]|33[0-68]|44[013-8]|550|66[1-5]|77\\d)))\\d{4}",,,, "111112345",,,, [7]], [,, "700[1-9]\\d{5}|(?:7(?:0[1-9]|1[0-8]|22|77|86|99)|9\\d\\d)\\d{6}",,,, "911234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "ET", 251, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[1-579]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          FI: [, [,, "[1-35689]\\d{4}|7\\d{10,11}|(?:[124-7]\\d|3[0-46-9])\\d{8}|[1-9]\\d{5,8}",,,,,,, [5, 6, 7, 8, 9, 10, 11, 12]], [,, "1[35-7][1-8]\\d{3,6}|(?:1[49][1-8]|[23568][1-8]\\d|9(?:00|[1-8]\\d))\\d{2,6}",,,, "131234567",,, [5, 6, 7, 8, 9]], [,, "4946\\d{2,6}|(?:4[0-8]|50)\\d{4,8}",,,, "412345678",,, [6, 7, 8, 9, 10]], [,, "800\\d{4,6}",,,, "800123456",,, [7, 8, 9]], [,, "[67]00\\d{5,6}",,,, "600123456",,, [8, 9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "FI", 358, "00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))", "0",,, "0",, "00",, [[, "(\\d{5})", "$1", ["75[12]"], "0$1"], [, "(\\d{5})", "$1", ["20[2-59]"], "0$1"], [, "(\\d{6})", "$1", ["11"]], [, "(\\d{3})(\\d{3,7})", "$1 $2", ["(?:[1-3]0|[68])0|70[07-9]"], "0$1"], [, "(\\d{2})(\\d{4,8})", "$1 $2", ["[14]|2[09]|50|7[135]"], "0$1"], [, "(\\d{2})(\\d{6,10})", "$1 $2", ["7"], "0$1"], [, "(\\d)(\\d{4,9})", "$1 $2", ["(?:1[49]|[2568])[1-8]|3(?:0[1-9]|[1-9])|9"], "0$1"]], [[, "(\\d{5})", "$1", ["20[2-59]"], "0$1"], [, "(\\d{3})(\\d{3,7})", "$1 $2", ["(?:[1-3]0|[68])0|70[07-9]"], "0$1"], [, "(\\d{2})(\\d{4,8})", "$1 $2", ["[14]|2[09]|50|7[135]"], "0$1"], [, "(\\d{2})(\\d{6,10})", "$1 $2", ["7"], "0$1"], [, "(\\d)(\\d{4,9})", "$1 $2", ["(?:1[49]|[2568])[1-8]|3(?:0[1-9]|[1-9])|9"], "0$1"]], [,,,,,,,,, [-1]], 1, "1[03-79]|[2-9]", [,, "20(?:2[023]|9[89])\\d{1,6}|(?:60[12]\\d|7099)\\d{4,5}|(?:606|7(?:0[78]|1|3\\d))\\d{7}|(?:[1-3]00|7(?:0[1-5]\\d\\d|5[03-9]))\\d{3,7}"], [,, "20\\d{4,8}|60[12]\\d{5,6}|7(?:099\\d{4,5}|5[03-9]\\d{3,7})|20[2-59]\\d\\d|(?:606|7(?:0[78]|1|3\\d))\\d{7}|(?:10|29|3[09]|70[1-5]\\d)\\d{4,8}",,,, "10112345"],,, [,,,,,,,,, [-1]]],
          FJ: [, [,, "45\\d{5}|(?:0800\\d|[235-9])\\d{6}",,,,,,, [7, 11]], [,, "603\\d{4}|(?:3[0-5]|6[25-7]|8[58])\\d{5}",,,, "3212345",,, [7]], [,, "(?:[279]\\d|45|5[01568]|8[034679])\\d{5}",,,, "7012345",,, [7]], [,, "0800\\d{7}",,,, "08001234567",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "FJ", 679, "0(?:0|52)",,,,,, "00",, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[235-9]|45"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["0"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          FK: [, [,, "[2-7]\\d{4}",,,,,,, [5]], [,, "[2-47]\\d{4}",,,, "31234"], [,, "[56]\\d{4}",,,, "51234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "FK", 500, "00",,,,,,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          FM: [, [,, "(?:[39]\\d\\d|820)\\d{4}",,,,,,, [7]], [,, "31(?:00[67]|208|309)\\d\\d|(?:3(?:[2357]0[1-9]|602|804|905)|(?:820|9[2-6]\\d)\\d)\\d{3}",,,, "3201234"], [,, "31(?:00[67]|208|309)\\d\\d|(?:3(?:[2357]0[1-9]|602|804|905)|(?:820|9[2-7]\\d)\\d)\\d{3}",,,, "3501234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "FM", 691, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[389]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          FO: [, [,, "[2-9]\\d{5}",,,,,,, [6]], [,, "(?:20|[34]\\d|8[19])\\d{4}",,,, "201234"], [,, "(?:[27][1-9]|5\\d|9[16])\\d{4}",,,, "211234"], [,, "80[257-9]\\d{3}",,,, "802123"], [,, "90(?:[13-5][15-7]|2[125-7]|9\\d)\\d\\d",,,, "901123"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:6[0-36]|88)\\d{4}",,,, "601234"], "FO", 298, "00",,,, "(10(?:01|[12]0|88))",,,, [[, "(\\d{6})", "$1", ["[2-9]"],, "$CC $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          FR: [, [,, "[1-9]\\d{8}",,,,,,, [9]], [,, "(?:26[013-9]|59[1-35-9])\\d{6}|(?:[13]\\d|2[0-57-9]|4[1-9]|5[0-8])\\d{7}",,,, "123456789"], [,, "(?:6(?:[0-24-8]\\d|3[0-8]|9[589])|7[3-9]\\d)\\d{6}",,,, "612345678"], [,, "80[0-5]\\d{6}",,,, "801234567"], [,, "836(?:0[0-36-9]|[1-9]\\d)\\d{4}|8(?:1[2-9]|2[2-47-9]|3[0-57-9]|[569]\\d|8[0-35-9])\\d{6}",,,, "891123456"], [,, "8(?:1[01]|2[0156]|4[024]|84)\\d{6}",,,, "884012345"], [,,,,,,,,, [-1]], [,, "9\\d{8}",,,, "912345678"], "FR", 33, "00", "0",,, "0",,,, [[, "(\\d{4})", "$1", ["10"]], [, "(\\d{3})(\\d{3})", "$1 $2", ["1"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"], "0 $1"], [, "(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["[1-79]"], "0$1"]], [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"], "0 $1"], [, "(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["[1-79]"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "80[6-9]\\d{6}",,,, "806123456"],,, [,,,,,,,,, [-1]]],
          GA: [, [,, "(?:[067]\\d|11)\\d{6}|[2-7]\\d{6}",,,,,,, [7, 8]], [,, "[01]1\\d{6}",,,, "01441234",,, [8]], [,, "(?:(?:0[2-7]|7[467])\\d|6(?:0[0-4]|10|[256]\\d))\\d{5}|[2-7]\\d{6}",,,, "06031234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GA", 241, "00",,,, "0(11\\d{6}|60\\d{6}|61\\d{6}|6[256]\\d{6}|7[467]\\d{6})", "$1",,, [[, "(\\d)(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2-7]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["0"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["11|[67]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GB: [, [,, "[1-357-9]\\d{9}|[18]\\d{8}|8\\d{6}",,,,,,, [7, 9, 10], [4, 5, 6, 8]], [,, "(?:1(?:1(?:3(?:[0-58]\\d\\d|73[0-35])|4(?:(?:[0-5]\\d|70)\\d|69[7-9])|(?:(?:5[0-26-9]|[78][0-49])\\d|6(?:[0-4]\\d|50))\\d)|(?:2(?:(?:0[024-9]|2[3-9]|3[3-79]|4[1-689]|[58][02-9]|6[0-47-9]|7[013-9]|9\\d)\\d|1(?:[0-7]\\d|8[0-3]))|(?:3(?:0\\d|1[0-8]|[25][02-9]|3[02-579]|[468][0-46-9]|7[1-35-79]|9[2-578])|4(?:0[03-9]|[137]\\d|[28][02-57-9]|4[02-69]|5[0-8]|[69][0-79])|5(?:0[1-35-9]|[16]\\d|2[024-9]|3[015689]|4[02-9]|5[03-9]|7[0-35-9]|8[0-468]|9[0-57-9])|6(?:0[034689]|1\\d|2[0-35689]|[38][013-9]|4[1-467]|5[0-69]|6[13-9]|7[0-8]|9[0-24578])|7(?:0[0246-9]|2\\d|3[0236-8]|4[03-9]|5[0-46-9]|6[013-9]|7[0-35-9]|8[024-9]|9[02-9])|8(?:0[35-9]|2[1-57-9]|3[02-578]|4[0-578]|5[124-9]|6[2-69]|7\\d|8[02-9]|9[02569])|9(?:0[02-589]|[18]\\d|2[02-689]|3[1-57-9]|4[2-9]|5[0-579]|6[2-47-9]|7[0-24578]|9[2-57]))\\d)\\d)|2(?:0[013478]|3[0189]|4[017]|8[0-46-9]|9[0-2])\\d{3})\\d{4}|1(?:2(?:0(?:46[1-4]|87[2-9])|545[1-79]|76(?:2\\d|3[1-8]|6[1-6])|9(?:7(?:2[0-4]|3[2-5])|8(?:2[2-8]|7[0-47-9]|8[3-5])))|3(?:6(?:38[2-5]|47[23])|8(?:47[04-9]|64[0157-9]))|4(?:044[1-7]|20(?:2[23]|8\\d)|6(?:0(?:30|5[2-57]|6[1-8]|7[2-8])|140)|8(?:052|87[1-3]))|5(?:2(?:4(?:3[2-79]|6\\d)|76\\d)|6(?:26[06-9]|686))|6(?:06(?:4\\d|7[4-79])|295[5-7]|35[34]\\d|47(?:24|61)|59(?:5[08]|6[67]|74)|9(?:55[0-4]|77[23]))|7(?:26(?:6[13-9]|7[0-7])|(?:442|688)\\d|50(?:2[0-3]|[3-68]2|76))|8(?:27[56]\\d|37(?:5[2-5]|8[239])|843[2-58])|9(?:0(?:0(?:6[1-8]|85)|52\\d)|3583|4(?:66[1-8]|9(?:2[01]|81))|63(?:23|3[1-4])|9561))\\d{3}",,,, "1212345678",,, [9, 10], [4, 5, 6, 7, 8]], [,, "7(?:457[0-57-9]|700[01]|911[028])\\d{5}|7(?:[1-3]\\d\\d|4(?:[0-46-9]\\d|5[0-689])|5(?:0[0-8]|[13-9]\\d|2[0-35-9])|7(?:0[1-9]|[1-7]\\d|8[02-9]|9[0-689])|8(?:[014-9]\\d|[23][0-8])|9(?:[024-9]\\d|1[02-9]|3[0-689]))\\d{6}",,,, "7400123456",,, [10]], [,, "80[08]\\d{7}|800\\d{6}|8001111",,,, "8001234567"], [,, "(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[2-49]))\\d{7}|845464\\d",,,, "9012345678",,, [7, 10]], [,,,,,,,,, [-1]], [,, "70\\d{8}",,,, "7012345678",,, [10]], [,, "56\\d{8}",,,, "5612345678",,, [10]], "GB", 44, "00", "0", " x",, "0",,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["800", "8001", "80011", "800111", "8001111"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3", ["845", "8454", "84546", "845464"], "0$1"], [, "(\\d{3})(\\d{6})", "$1 $2", ["800"], "0$1"], [, "(\\d{5})(\\d{4,5})", "$1 $2", ["1(?:38|5[23]|69|76|94)", "1(?:(?:38|69)7|5(?:24|39)|768|946)", "1(?:3873|5(?:242|39[4-6])|(?:697|768)[347]|9467)"], "0$1"], [, "(\\d{4})(\\d{5,6})", "$1 $2", ["1(?:[2-69][02-9]|[78])"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["[25]|7(?:0|6[02-9])", "[25]|7(?:0|6(?:[03-9]|2[356]))"], "0$1"], [, "(\\d{4})(\\d{6})", "$1 $2", ["7"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[1389]"], "0$1"]],, [,, "76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",,,, "7640123456",,, [10]], 1,, [,,,,,,,,, [-1]], [,, "(?:3[0347]|55)\\d{8}",,,, "5512345678",,, [10]],,, [,,,,,,,,, [-1]]],
          GD: [, [,, "(?:473|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "473(?:2(?:3[0-2]|69)|3(?:2[89]|86)|4(?:[06]8|3[5-9]|4[0-4]|5[579]|73|90)|63[68]|7(?:58|84)|800|938)\\d{4}",,,, "4732691234",,,, [7]], [,, "473(?:4(?:0[2-79]|1[04-9]|2[0-5]|49|5[68])|5(?:2[01]|3[3-8])|901)\\d{4}",,,, "4734031234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "GD", 1, "011", "1",,, "([2-9]\\d{6})$|1", "473$1",,,,, [,,,,,,,,, [-1]],, "473", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GE: [, [,, "(?:[3-57]\\d\\d|800)\\d{6}",,,,,,, [9], [6, 7]], [,, "(?:3(?:[256]\\d|4[124-9]|7[0-4])|4(?:1\\d|2[2-7]|3[1-79]|4[2-8]|7[239]|9[1-7]))\\d{6}",,,, "322123456",,,, [6, 7]], [,, "5(?:(?:(?:0555|1(?:[17]77|555))[5-9]|757(?:7[7-9]|8[01]))\\d|22252[0-4])\\d\\d|5(?:0(?:0[17]0|505)|1(?:0[01]0|1(?:07|33|51))|2(?:0[02]0|2[25]2)|3(?:0[03]0|3[35]3)|(?:40[04]|900)0|5222)[0-4]\\d{3}|(?:5(?:0(?:0(?:0\\d|11|22|3[0-6]|44|5[05]|77|88|9[09])|111|22[02]|77\\d)|1(?:1(?:[03][01]|[124]\\d|5[2-6]|7[0-4])|4\\d\\d)|[23]555|4(?:4\\d\\d|555)|5(?:[0157-9]\\d\\d|200)|6[89]\\d\\d|7(?:[0147-9]\\d\\d|5(?:00|[57]5))|8(?:0(?:[018]\\d|2[0-4])|5(?:55|8[89])|8(?:55|88))|9(?:090|[1-35-9]\\d\\d))|790\\d\\d)\\d{4}",,,, "555123456"], [,, "800\\d{6}",,,, "800123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "70[67]\\d{6}",,,, "706123456"], "GE", 995, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["70"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["32"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[57]"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[348]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,, "70[67]\\d{6}"], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GF: [, [,, "[56]94\\d{6}|(?:80|9\\d)\\d{7}",,,,,,, [9]], [,, "594(?:[02-49]\\d|1[0-5]|5[6-9]|6[0-3]|80)\\d{4}",,,, "594101234"], [,, "694(?:[0-249]\\d|3[0-8])\\d{4}",,,, "694201234"], [,, "80[0-5]\\d{6}",,,, "800012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:(?:396|76\\d)\\d|476[0-5])\\d{4}",,,, "976012345"], "GF", 594, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[56]|9[47]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[89]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GG: [, [,, "(?:1481|[357-9]\\d{3})\\d{6}|8\\d{6}(?:\\d{2})?",,,,,,, [7, 9, 10], [6]], [,, "1481[25-9]\\d{5}",,,, "1481256789",,, [10], [6]], [,, "7(?:(?:781|839)\\d|911[17])\\d{5}",,,, "7781123456",,, [10]], [,, "80[08]\\d{7}|800\\d{6}|8001111",,,, "8001234567"], [,, "(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[0-3]))\\d{7}|845464\\d",,,, "9012345678",,, [7, 10]], [,,,,,,,,, [-1]], [,, "70\\d{8}",,,, "7012345678",,, [10]], [,, "56\\d{8}",,,, "5612345678",,, [10]], "GG", 44, "00", "0",,, "([25-9]\\d{5})$|0", "1481$1",,,,, [,, "76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",,,, "7640123456",,, [10]],,, [,,,,,,,,, [-1]], [,, "(?:3[0347]|55)\\d{8}",,,, "5512345678",,, [10]],,, [,,,,,,,,, [-1]]],
          GH: [, [,, "(?:[235]\\d{3}|800)\\d{5}",,,,,,, [8, 9], [7]], [,, "3082[0-5]\\d{4}|3(?:0(?:[237]\\d|8[01])|[167](?:2[0-6]|7\\d|80)|2(?:2[0-5]|7\\d|80)|3(?:2[0-3]|7\\d|80)|4(?:2[013-9]|3[01]|7\\d|80)|5(?:2[0-7]|7\\d|80)|8(?:2[0-2]|7\\d|80)|9(?:[28]0|7\\d))\\d{5}",,,, "302345678",,, [9], [7]], [,, "(?:2(?:[0346-9]\\d|5[67])|5(?:[03-7]\\d|9[1-9]))\\d{6}",,,, "231234567",,, [9]], [,, "800\\d{5}",,,, "80012345",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GH", 233, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[237]|8[0-2]"]], [, "(\\d{3})(\\d{5})", "$1 $2", ["8"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[235]"], "0$1"]], [[, "(\\d{3})(\\d{5})", "$1 $2", ["8"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[235]"], "0$1"]], [,,,,,,,,, [-1]],,, [,, "800\\d{5}",,,,,,, [8]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GI: [, [,, "(?:[25]\\d|60)\\d{6}",,,,,,, [8]], [,, "2190[0-2]\\d{3}|2(?:0(?:[02]\\d|3[01])|16[24-9]|2[2-5]\\d)\\d{4}",,,, "20012345"], [,, "5251[0-4]\\d{3}|(?:5(?:[146-8]\\d\\d|250)|60(?:1[01]|6\\d))\\d{4}",,,, "57123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GI", 350, "00",,,,,,,, [[, "(\\d{3})(\\d{5})", "$1 $2", ["2"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GL: [, [,, "(?:19|[2-689]\\d|70)\\d{4}",,,,,,, [6]], [,, "(?:19|3[1-7]|[68][1-9]|70|9\\d)\\d{4}",,,, "321000"], [,, "[245]\\d{5}",,,, "221234"], [,, "80\\d{4}",,,, "801234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "3[89]\\d{4}",,,, "381234"], "GL", 299, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["19|[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GM: [, [,, "[2-9]\\d{6}",,,,,,, [7]], [,, "(?:4(?:[23]\\d\\d|4(?:1[024679]|[6-9]\\d))|5(?:5(?:3\\d|4[0-7])|6[67]\\d|7(?:1[04]|2[035]|3[58]|48))|8\\d{3})\\d{3}",,,, "5661234"], [,, "(?:[23679]\\d|4[015]|5[0-489])\\d{5}",,,, "3012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GM", 220, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GN: [, [,, "722\\d{6}|(?:3|6\\d)\\d{7}",,,,,,, [8, 9]], [,, "3(?:0(?:24|3[12]|4[1-35-7]|5[13]|6[189]|[78]1|9[1478])|1\\d\\d)\\d{4}",,,, "30241234",,, [8]], [,, "6[0-356]\\d{7}",,,, "601123456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "722\\d{6}",,,, "722123456",,, [9]], "GN", 224, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["3"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[67]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GP: [, [,, "590\\d{6}|(?:69|80|9\\d)\\d{7}",,,,,,, [9]], [,, "590(?:0[1-68]|[14][0-24-9]|2[0-68]|3[1-9]|5[3-579]|[68][0-689]|7[08]|9\\d)\\d{4}",,,, "590201234"], [,, "69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))\\d{4}",,,, "690001234"], [,, "80[0-5]\\d{6}",,,, "800012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:(?:39[5-7]|76[018])\\d|475[0-5])\\d{4}",,,, "976012345"], "GP", 590, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[569]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"], "0$1"]],, [,,,,,,,,, [-1]], 1,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GQ: [, [,, "222\\d{6}|(?:3\\d|55|[89]0)\\d{7}",,,,,,, [9]], [,, "33[0-24-9]\\d[46]\\d{4}|3(?:33|5\\d)\\d[7-9]\\d{4}",,,, "333091234"], [,, "(?:222|55\\d)\\d{6}",,,, "222123456"], [,, "80\\d[1-9]\\d{5}",,,, "800123456"], [,, "90\\d[1-9]\\d{5}",,,, "900123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GQ", 240, "00",,,,,,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[235]"]], [, "(\\d{3})(\\d{6})", "$1 $2", ["[89]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GR: [, [,, "5005000\\d{3}|8\\d{9,11}|(?:[269]\\d|70)\\d{8}",,,,,,, [10, 11, 12]], [,, "2(?:1\\d\\d|2(?:2[1-46-9]|[36][1-8]|4[1-7]|5[1-4]|7[1-5]|[89][1-9])|3(?:1\\d|2[1-57]|[35][1-3]|4[13]|7[1-7]|8[124-6]|9[1-79])|4(?:1\\d|2[1-8]|3[1-4]|4[13-5]|6[1-578]|9[1-5])|5(?:1\\d|[29][1-4]|3[1-5]|4[124]|5[1-6])|6(?:1\\d|[269][1-6]|3[1245]|4[1-7]|5[13-9]|7[14]|8[1-5])|7(?:1\\d|2[1-5]|3[1-6]|4[1-7]|5[1-57]|6[135]|9[125-7])|8(?:1\\d|2[1-5]|[34][1-4]|9[1-57]))\\d{6}",,,, "2123456789",,, [10]], [,, "68[57-9]\\d{7}|(?:69|94)\\d{8}",,,, "6912345678",,, [10]], [,, "800\\d{7,9}",,,, "8001234567"], [,, "90[19]\\d{7}",,,, "9091234567",,, [10]], [,, "8(?:0[16]|12|[27]5|50)\\d{7}",,,, "8011234567",,, [10]], [,, "70\\d{8}",,,, "7012345678",,, [10]], [,,,,,,,,, [-1]], "GR", 30, "00",,,,,,,, [[, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["21|7"]], [, "(\\d{4})(\\d{6})", "$1 $2", ["2(?:2|3[2-57-9]|4[2-469]|5[2-59]|6[2-9]|7[2-69]|8[2-49])|5"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2689]"]], [, "(\\d{3})(\\d{3,4})(\\d{5})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "5005000\\d{3}",,,, "5005000123",,, [10]],,, [,,,,,,,,, [-1]]],
          GT: [, [,, "80\\d{6}|(?:1\\d{3}|[2-7])\\d{7}",,,,,,, [8, 11]], [,, "[267][2-9]\\d{6}",,,, "22456789",,, [8]], [,, "(?:[3-5]\\d\\d|80[0-4])\\d{5}",,,, "51234567",,, [8]], [,, "18[01]\\d{8}",,,, "18001112222",,, [11]], [,, "19\\d{9}",,,, "19001112222",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "GT", 502, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[2-8]"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GU: [, [,, "(?:[58]\\d\\d|671|900)\\d{7}",,,,,,, [10], [7]], [,, "671(?:2\\d\\d|3(?:00|3[39]|4[349]|55|6[26])|4(?:00|56|7[1-9]|8[02-46-9])|5(?:55|6[2-5]|88)|6(?:3[2-578]|4[24-9]|5[34]|78|8[235-9])|7(?:[0479]7|2[0167]|3[45]|8[7-9])|8(?:[2-57-9]8|6[48])|9(?:2[29]|6[79]|7[1279]|8[7-9]|9[78]))\\d{4}",,,, "6713001234",,,, [7]], [,, "671(?:2\\d\\d|3(?:00|3[39]|4[349]|55|6[26])|4(?:00|56|7[1-9]|8[02-46-9])|5(?:55|6[2-5]|88)|6(?:3[2-578]|4[24-9]|5[34]|78|8[235-9])|7(?:[0479]7|2[0167]|3[45]|8[7-9])|8(?:[2-57-9]8|6[48])|9(?:2[29]|6[79]|7[1279]|8[7-9]|9[78]))\\d{4}",,,, "6713001234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "GU", 1, "011", "1",,, "([2-9]\\d{6})$|1", "671$1",, 1,,, [,,,,,,,,, [-1]],, "671", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GW: [, [,, "[49]\\d{8}|4\\d{6}",,,,,,, [7, 9]], [,, "443\\d{6}",,,, "443201234",,, [9]], [,, "9(?:5\\d|6[569]|77)\\d{6}",,,, "955012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "40\\d{5}",,,, "4012345",,, [7]], "GW", 245, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["40"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[49]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          GY: [, [,, "(?:[2-8]\\d{3}|9008)\\d{3}",,,,,,, [7]], [,, "(?:2(?:1[6-9]|2[0-35-9]|3[1-4]|5[3-9]|6\\d|7[0-79])|3(?:2[25-9]|3\\d)|4(?:4[0-24]|5[56])|50[0-6]|77[1-57])\\d{4}",,,, "2201234"], [,, "510\\d{4}|(?:6\\d|7[0-5])\\d{5}",,,, "6091234"], [,, "(?:289|8(?:00|6[28]|88|99))\\d{4}",,,, "2891234"], [,, "9008\\d{3}",,,, "9008123"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "515\\d{4}",,,, "5151234"], "GY", 592, "001",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          HK: [, [,, "8[0-46-9]\\d{6,7}|9\\d{4,7}|(?:[2-7]|9\\d{3})\\d{7}",,,,,,, [5, 6, 7, 8, 9, 11]], [,, "(?:2(?:[13-9]\\d|2[013-9])\\d|3(?:(?:[1569][0-24-9]|4[0-246-9]|7[0-24-69])\\d|8(?:4[0-8]|[579]\\d|6[0-2]))|58(?:0[1-9]|1[2-9]))\\d{4}",,,, "21234567",,, [8]], [,, "(?:4(?:44[0-25-9]|6(?:1[0-7]|4[0-57-9]|6[0-4])|74[0-2])|5(?:73[0-6]|95[0-8])|6(?:26[013-8]|66[0-3])|70(?:7[1-8]|8[0-4])|84(?:4[0-2]|8[0-35-9])|9(?:29[013-9]|39[01]|59[0-4]|899))\\d{4}|(?:4(?:4[0-35-9]|6[02357-9]|7[05])|5(?:[1-59][0-46-9]|6[0-4689]|7[0-246-9])|6(?:0[1-9]|[13-59]\\d|[268][0-57-9]|7[0-79])|70[1-49]|84[0-39]|9(?:0[1-9]|1[02-9]|[2358][0-8]|[467]\\d))\\d{5}",,,, "51234567",,, [8]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "900(?:[0-24-9]\\d{7}|3\\d{1,4})",,,, "90012345678",,, [5, 6, 7, 8, 11]], [,,,,,,,,, [-1]], [,, "8(?:1[0-4679]\\d|2(?:[0-36]\\d|7[0-4])|3(?:[034]\\d|2[09]|70))\\d{4}",,,, "81123456",,, [8]], [,,,,,,,,, [-1]], "HK", 852, "00(?:30|5[09]|[126-9]?)",,,,,, "00",, [[, "(\\d{3})(\\d{2,5})", "$1 $2", ["900", "9003"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[2-7]|8[1-4]|9(?:0[1-9]|[1-8])"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"]], [, "(\\d{3})(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["9"]]],, [,, "7(?:1(?:0[0-38]|1[0-3679]|3[013]|69|9[0136])|2(?:[02389]\\d|1[18]|7[27-9])|3(?:[0-38]\\d|7[0-369]|9[2357-9])|47\\d|5(?:[178]\\d|5[0-5])|6(?:0[0-7]|2[236-9]|[35]\\d)|7(?:[27]\\d|8[7-9])|8(?:[23689]\\d|7[1-9])|9(?:[025]\\d|6[0-246-8]|7[0-36-9]|8[238]))\\d{4}",,,, "71123456",,, [8]],,, [,,,,,,,,, [-1]], [,, "30(?:0[1-9]|[15-7]\\d|2[047]|89)\\d{4}",,,, "30161234",,, [8]],,, [,,,,,,,,, [-1]]],
          HN: [, [,, "8\\d{10}|[237-9]\\d{7}",,,,,,, [8, 11]], [,, "2(?:2(?:0[0-59]|1[1-9]|[23]\\d|4[02-6]|5[57]|6[245]|7[0135689]|8[01346-9]|9[0-2])|4(?:0[578]|2[3-59]|3[13-9]|4[0-68]|5[1-3589])|5(?:0[2357-9]|1[1-356]|4[03-5]|5\\d|6[014-69]|7[04]|80)|6(?:[056]\\d|17|2[067]|3[047]|4[0-378]|[78][0-8]|9[01])|7(?:0[5-79]|6[46-9]|7[02-9]|8[034]|91)|8(?:79|8[0-357-9]|9[1-57-9]))\\d{4}",,,, "22123456",,, [8]], [,, "[37-9]\\d{7}",,,, "91234567",,, [8]], [,, "8002\\d{7}",,,, "80021234567",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "HN", 504, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1-$2", ["[237-9]"]], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["8"]]], [[, "(\\d{4})(\\d{4})", "$1-$2", ["[237-9]"]]], [,,,,,,,,, [-1]],,, [,, "8002\\d{7}",,,,,,, [11]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          HR: [, [,, "(?:[24-69]\\d|3[0-79])\\d{7}|80\\d{5,7}|[1-79]\\d{7}|6\\d{5,6}",,,,,,, [6, 7, 8, 9]], [,, "1\\d{7}|(?:2[0-3]|3[1-5]|4[02-47-9]|5[1-3])\\d{6,7}",,,, "12345678",,, [8, 9], [6, 7]], [,, "9(?:(?:0[1-9]|[12589]\\d)\\d\\d|7(?:[0679]\\d\\d|5(?:[01]\\d|44|55|77|9[5-7])))\\d{4}|98\\d{6}",,,, "921234567",,, [8, 9]], [,, "80\\d{5,7}",,,, "800123456",,, [7, 8, 9]], [,, "6[01459]\\d{6}|6[01]\\d{4,5}",,,, "611234",,, [6, 7, 8]], [,,,,,,,,, [-1]], [,, "7[45]\\d{6}",,,, "74123456",,, [8]], [,,,,,,,,, [-1]], "HR", 385, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["6[01]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["8"], "0$1"], [, "(\\d)(\\d{4})(\\d{3})", "$1 $2 $3", ["1"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["6|7[245]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["9"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[2-57]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "62\\d{6,7}|72\\d{6}",,,, "62123456",,, [8, 9]],,, [,,,,,,,,, [-1]]],
          HT: [, [,, "(?:[2-489]\\d|55)\\d{6}",,,,,,, [8]], [,, "2(?:2\\d|5[1-5]|81|9[149])\\d{5}",,,, "22453300"], [,, "(?:[34]\\d|55)\\d{6}",,,, "34101234"], [,, "8\\d{7}",,,, "80012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:[67][0-4]|8[0-3589]|9\\d)\\d{5}",,,, "98901234"], "HT", 509, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3", ["[2-589]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          HU: [, [,, "[235-7]\\d{8}|[1-9]\\d{7}",,,,,,, [8, 9], [6, 7]], [,, "(?:1\\d|[27][2-9]|3[2-7]|4[24-9]|5[2-79]|6[23689]|8[2-57-9]|9[2-69])\\d{6}",,,, "12345678",,, [8], [6, 7]], [,, "(?:[257]0|3[01])\\d{7}",,,, "201234567",,, [9]], [,, "(?:[48]0\\d|680[29])\\d{5}",,,, "80123456"], [,, "9[01]\\d{6}",,,, "90123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "21\\d{7}",,,, "211234567",,, [9]], "HU", 36, "00", "06",,, "06",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["1"], "(06 $1)"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[27][2-9]|3[2-7]|4[24-9]|5[2-79]|6|8[2-57-9]|9[2-69]"], "(06 $1)"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[2-9]"], "06 $1"]],, [,,,,,,,,, [-1]],,, [,, "(?:[48]0\\d|680[29])\\d{5}"], [,, "38\\d{7}",,,, "381234567",,, [9]],,, [,,,,,,,,, [-1]]],
          ID: [, [,, "00[1-9]\\d{9,14}|(?:[1-36]|8\\d{5})\\d{6}|00\\d{9}|[1-9]\\d{8,10}|[2-9]\\d{7}",,,,,,, [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [5, 6]], [,, "2[124]\\d{7,8}|619\\d{8}|2(?:1(?:14|500)|2\\d{3})\\d{3}|61\\d{5,8}|(?:2(?:[35][1-4]|6[0-8]|7[1-6]|8\\d|9[1-8])|3(?:1|[25][1-8]|3[1-68]|4[1-3]|6[1-3568]|7[0-469]|8\\d)|4(?:0[1-589]|1[01347-9]|2[0-36-8]|3[0-24-68]|43|5[1-378]|6[1-5]|7[134]|8[1245])|5(?:1[1-35-9]|2[25-8]|3[124-9]|4[1-3589]|5[1-46]|6[1-8])|6(?:[25]\\d|3[1-69]|4[1-6])|7(?:02|[125][1-9]|[36]\\d|4[1-8]|7[0-36-9])|9(?:0[12]|1[013-8]|2[0-479]|5[125-8]|6[23679]|7[159]|8[01346]))\\d{5,8}",,,, "218350123",,, [7, 8, 9, 10, 11], [5, 6]], [,, "8[1-35-9]\\d{7,10}",,,, "812345678",,, [9, 10, 11, 12]], [,, "00(?:1803\\d{5,11}|7803\\d{7})|(?:177\\d|800)\\d{5,7}",,,, "8001234567",,, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], [,, "809\\d{7}",,,, "8091234567",,, [10]], [,, "804\\d{7}",,,, "8041234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "ID", 62, "00[89]", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["15"]], [, "(\\d{2})(\\d{5,9})", "$1 $2", ["2[124]|[36]1"], "(0$1)"], [, "(\\d{3})(\\d{5,7})", "$1 $2", ["800"], "0$1"], [, "(\\d{3})(\\d{5,8})", "$1 $2", ["[2-79]"], "(0$1)"], [, "(\\d{3})(\\d{3,4})(\\d{3})", "$1-$2-$3", ["8[1-35-9]"], "0$1"], [, "(\\d{3})(\\d{6,8})", "$1 $2", ["1"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["804"], "0$1"], [, "(\\d{3})(\\d)(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["80"], "0$1"], [, "(\\d{3})(\\d{4})(\\d{4,5})", "$1-$2-$3", ["8"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{2,8})", "$1 $2 $3 $4", ["001"]], [, "(\\d{2})(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["0"]]], [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["15"]], [, "(\\d{2})(\\d{5,9})", "$1 $2", ["2[124]|[36]1"], "(0$1)"], [, "(\\d{3})(\\d{5,7})", "$1 $2", ["800"], "0$1"], [, "(\\d{3})(\\d{5,8})", "$1 $2", ["[2-79]"], "(0$1)"], [, "(\\d{3})(\\d{3,4})(\\d{3})", "$1-$2-$3", ["8[1-35-9]"], "0$1"], [, "(\\d{3})(\\d{6,8})", "$1 $2", ["1"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["804"], "0$1"], [, "(\\d{3})(\\d)(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["80"], "0$1"], [, "(\\d{3})(\\d{4})(\\d{4,5})", "$1-$2-$3", ["8"], "0$1"]], [,,,,,,,,, [-1]],,, [,, "001803\\d{5,11}|(?:007803\\d|8071)\\d{6}",,,,,,, [10, 11, 12, 13, 14, 15, 16, 17]], [,, "(?:1500|8071\\d{3})\\d{3}",,,, "8071123456",,, [7, 10]],,, [,,,,,,,,, [-1]]],
          IE: [, [,, "(?:1\\d|[2569])\\d{6,8}|4\\d{6,9}|7\\d{8}|8\\d{8,9}",,,,,,, [7, 8, 9, 10], [5, 6]], [,, "(?:1\\d|21)\\d{6,7}|(?:2[24-9]|4(?:0[24]|5\\d|7)|5(?:0[45]|1\\d|8)|6(?:1\\d|[237-9])|9(?:1\\d|[35-9]))\\d{5}|(?:23|4(?:[1-469]|8\\d)|5[23679]|6[4-6]|7[14]|9[04])\\d{7}",,,, "2212345",,,, [5, 6]], [,, "8(?:22|[35-9]\\d)\\d{6}",,,, "850123456",,, [9]], [,, "1800\\d{6}",,,, "1800123456",,, [10]], [,, "15(?:1[2-8]|[2-8]0|9[089])\\d{6}",,,, "1520123456",,, [10]], [,, "18[59]0\\d{6}",,,, "1850123456",,, [10]], [,, "700\\d{6}",,,, "700123456",,, [9]], [,, "76\\d{7}",,,, "761234567",,, [9]], "IE", 353, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{5})", "$1 $2", ["2[24-9]|47|58|6[237-9]|9[35-9]"], "(0$1)"], [, "(\\d{3})(\\d{5})", "$1 $2", ["[45]0"], "(0$1)"], [, "(\\d)(\\d{3,4})(\\d{4})", "$1 $2 $3", ["1"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[2569]|4[1-69]|7[14]"], "(0$1)"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["70"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["81"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[78]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["4"], "(0$1)"], [, "(\\d{2})(\\d)(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,, "18[59]0\\d{6}",,,,,,, [10]], [,, "818\\d{6}",,,, "818123456",,, [9]],,, [,, "88210[1-9]\\d{4}|8(?:[35-79]5\\d\\d|8(?:[013-9]\\d\\d|2(?:[01][1-9]|[2-9]\\d)))\\d{5}",,,, "8551234567",,, [10]]],
          IL: [, [,, "1\\d{6}(?:\\d{3,5})?|[57]\\d{8}|[1-489]\\d{7}",,,,,,, [7, 8, 9, 10, 11, 12]], [,, "153\\d{8,9}|29[1-9]\\d{5}|(?:2[0-8]|[3489]\\d)\\d{6}",,,, "21234567",,, [8, 11, 12], [7]], [,, "55(?:410|57[0-289])\\d{4}|5(?:(?:[0-2][02-9]|[36]\\d|[49][2-9]|8[3-7])\\d|5(?:01|2\\d|3[0-3]|4[34]|5[0-25689]|6[6-8]|7[0-267]|8[7-9]|9[1-9]))\\d{5}",,,, "502345678",,, [9]], [,, "1(?:255|80[019]\\d{3})\\d{3}",,,, "1800123456",,, [7, 10]], [,, "1212\\d{4}|1(?:200|9(?:0[0-2]|19))\\d{6}",,,, "1919123456",,, [8, 10]], [,, "1700\\d{6}",,,, "1700123456",,, [10]], [,,,,,,,,, [-1]], [,, "7(?:38(?:0\\d|5[0-2569]|88)|8(?:33|55|77|81)\\d)\\d{4}|7(?:18|2[23]|3[237]|47|6[258]|7\\d|82|9[2-9])\\d{6}",,,, "771234567",,, [9]], "IL", 972, "0(?:0|1[2-9])", "0",,, "0",,,, [[, "(\\d{4})(\\d{3})", "$1-$2", ["125"]], [, "(\\d{4})(\\d{2})(\\d{2})", "$1-$2-$3", ["121"]], [, "(\\d)(\\d{3})(\\d{4})", "$1-$2-$3", ["[2-489]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["[57]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1-$2-$3", ["12"]], [, "(\\d{4})(\\d{6})", "$1-$2", ["159"]], [, "(\\d)(\\d{3})(\\d{3})(\\d{3})", "$1-$2-$3-$4", ["1[7-9]"]], [, "(\\d{3})(\\d{1,2})(\\d{3})(\\d{4})", "$1-$2 $3-$4", ["15"]]],, [,,,,,,,,, [-1]],,, [,, "1700\\d{6}",,,,,,, [10]], [,, "1599\\d{6}",,,, "1599123456",,, [10]],,, [,, "151\\d{8,9}",,,, "15112340000",,, [11, 12]]],
          IM: [, [,, "1624\\d{6}|(?:[3578]\\d|90)\\d{8}",,,,,,, [10], [6]], [,, "1624(?:230|[5-8]\\d\\d)\\d{3}",,,, "1624756789",,,, [6]], [,, "76245[06]\\d{4}|7(?:4576|[59]24\\d|624[0-4689])\\d{5}",,,, "7924123456"], [,, "808162\\d{4}",,,, "8081624567"], [,, "8(?:440[49]06|72299\\d)\\d{3}|(?:8(?:45|70)|90[0167])624\\d{4}",,,, "9016247890"], [,,,,,,,,, [-1]], [,, "70\\d{8}",,,, "7012345678"], [,, "56\\d{8}",,,, "5612345678"], "IM", 44, "00", "0",,, "([25-8]\\d{5})$|0", "1624$1",,,,, [,,,,,,,,, [-1]],, "74576|(?:16|7[56])24", [,,,,,,,,, [-1]], [,, "3440[49]06\\d{3}|(?:3(?:08162|3\\d{4}|45624|7(?:0624|2299))|55\\d{4})\\d{4}",,,, "5512345678"],,, [,,,,,,,,, [-1]]],
          IN: [, [,, "(?:000800|[2-9]\\d\\d)\\d{7}|1\\d{7,12}",,,,,,, [8, 9, 10, 11, 12, 13], [6, 7]], [,, "2717(?:[2-7]\\d|95)\\d{4}|(?:271[0-689]|782[0-6])[2-7]\\d{5}|(?:170[24]|2(?:(?:[02][2-79]|90)\\d|80[13468])|(?:3(?:23|80)|683|79[1-7])\\d|4(?:20[24]|72[2-8])|552[1-7])\\d{6}|(?:11|33|4[04]|80)[2-7]\\d{7}|(?:342|674|788)(?:[0189][2-7]|[2-7]\\d)\\d{5}|(?:1(?:2[0-249]|3[0-25]|4[145]|[59][14]|6[014]|7[1257]|8[01346])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568]|9[14])|3(?:26|4[13]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[014-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|2[14]|3[134]|4[47]|5[15]|[67]1)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91))[2-7]\\d{6}|(?:1(?:2[35-8]|3[346-9]|4[236-9]|[59][0235-9]|6[235-9]|7[34689]|8[257-9])|2(?:1[134689]|3[24-8]|4[2-8]|5[25689]|6[2-4679]|7[3-79]|8[2-479]|9[235-9])|3(?:01|1[79]|2[1245]|4[5-8]|5[125689]|6[235-7]|7[157-9]|8[2-46-8])|4(?:1[14578]|2[5689]|3[2-467]|5[4-7]|6[35]|73|8[2689]|9[2389])|5(?:[16][146-9]|2[14-8]|3[1346]|4[14-69]|5[46]|7[2-4]|8[2-8]|9[246])|6(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[124-6])|7(?:1[013-9]|2[0235-9]|3[2679]|4[1-35689]|5[2-46-9]|[67][02-9]|8[013-7]|9[089])|8(?:1[1357-9]|2[235-8]|3[03-57-9]|4[0-24-9]|5\\d|6[2457-9]|7[1-6]|8[1256]|9[2-4]))\\d[2-7]\\d{5}",,,, "7410410123",,, [10], [6, 7, 8]], [,, "(?:61279|7(?:887[02-9]|9(?:313|79[07-9]))|8(?:079[04-9]|(?:84|91)7[02-8]))\\d{5}|(?:6(?:12|[2-47]1|5[17]|6[13]|80)[0189]|7(?:1(?:2[0189]|9[0-5])|2(?:[14][017-9]|8[0-59])|3(?:2[5-8]|[34][017-9]|9[016-9])|4(?:1[015-9]|[29][89]|39|8[389])|5(?:[15][017-9]|2[04-9]|9[7-9])|6(?:0[0-47]|1[0-257-9]|2[0-4]|3[19]|5[4589])|70[0289]|88[089]|97[02-8])|8(?:0(?:6[67]|7[02-8])|70[017-9]|84[01489]|91[0-289]))\\d{6}|(?:7(?:31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[0189]\\d|7[02-8])\\d{5}|(?:6(?:[09]\\d|1[04679]|2[03689]|3[05-9]|4[0489]|50|6[069]|7[07]|8[7-9])|7(?:0\\d|2[0235-79]|3[05-8]|40|5[0346-8]|6[6-9]|7[1-9]|8[0-79]|9[089])|8(?:0[01589]|1[0-57-9]|2[235-9]|3[03-57-9]|[45]\\d|6[02457-9]|7[1-69]|8[0-25-9]|9[02-9])|9\\d\\d)\\d{7}|(?:6(?:(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|8[124-6])\\d|7(?:[235689]\\d|4[0189]))|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-5])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]|881))[0189]\\d{5}",,,, "8123456789",,, [10]], [,, "000800\\d{7}|1(?:600\\d{6}|80(?:0\\d{4,9}|3\\d{9}))",,,, "1800123456"], [,, "186[12]\\d{9}",,,, "1861123456789",,, [13]], [,, "1860\\d{7}",,,, "18603451234",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "IN", 91, "00", "0",,, "0",,,, [[, "(\\d{7})", "$1", ["575"]], [, "(\\d{8})", "$1", ["5(?:0|2[23]|3[03]|[67]1|88)", "5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|888)", "5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|8888)"],,, 1], [, "(\\d{4})(\\d{4,5})", "$1 $2", ["180", "1800"],,, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["140"],,, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["11|2[02]|33|4[04]|79[1-7]|80[2-46]", "11|2[02]|33|4[04]|79(?:[1-6]|7[19])|80(?:[2-4]|6[0-589])", "11|2[02]|33|4[04]|79(?:[124-6]|3(?:[02-9]|1[0-24-9])|7(?:1|9[1-6]))|80(?:[2-4]|6[0-589])"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["1(?:2[0-249]|3[0-25]|4[145]|[68]|7[1257])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|5[12]|[78]1)|6(?:12|[2-4]1|5[17]|6[13]|80)|7(?:12|3[134]|4[47]|61|88)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91)|(?:43|59|75)[15]|(?:1[59]|29|67|72)[14]", "1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|674|7(?:(?:2[14]|3[34]|5[15])[2-6]|61[346]|88[0-8])|8(?:70[2-6]|84[235-7]|91[3-7])|(?:1(?:29|60|8[06])|261|552|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))[2-7]", "1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12(?:[2-6]|7[0-8])|74[2-7])|7(?:(?:2[14]|5[15])[2-6]|3171|61[346]|88(?:[2-7]|82))|8(?:70[2-6]|84(?:[2356]|7[19])|91(?:[3-6]|7[19]))|73[134][2-6]|(?:74[47]|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[2-6]|7[19])|(?:1(?:29|60|8[06])|261|552|6(?:[2-4]1|5[17]|6[13]|7(?:1|4[0189])|80)|7(?:12|88[01]))[2-7]"], "0$1",, 1], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2[2457-9]|3[2-5]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1[013-9]|28|3[129]|4[1-35689]|5[29]|6[02-5]|70)|807", "1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2(?:[2457]|84|95)|3(?:[2-4]|55)|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1(?:[013-8]|9[6-9])|28[6-8]|3(?:17|2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4|5[0-367])|70[13-7])|807[19]", "1(?:[2-479]|5(?:[0236-9]|5[013-9]))|[2-5]|6(?:2(?:84|95)|355|83)|73179|807(?:1|9[1-3])|(?:1552|6(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[124-6])\\d|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]))[2-7]"], "0$1",, 1], [, "(\\d{5})(\\d{5})", "$1 $2", ["[6-9]"], "0$1",, 1], [, "(\\d{4})(\\d{2,4})(\\d{4})", "$1 $2 $3", ["1(?:6|8[06])", "1(?:6|8[06]0)"],,, 1], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["0"]], [, "(\\d{4})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["18"],,, 1]], [[, "(\\d{8})", "$1", ["5(?:0|2[23]|3[03]|[67]1|88)", "5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|888)", "5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|8888)"],,, 1], [, "(\\d{4})(\\d{4,5})", "$1 $2", ["180", "1800"],,, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["140"],,, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["11|2[02]|33|4[04]|79[1-7]|80[2-46]", "11|2[02]|33|4[04]|79(?:[1-6]|7[19])|80(?:[2-4]|6[0-589])", "11|2[02]|33|4[04]|79(?:[124-6]|3(?:[02-9]|1[0-24-9])|7(?:1|9[1-6]))|80(?:[2-4]|6[0-589])"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["1(?:2[0-249]|3[0-25]|4[145]|[68]|7[1257])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|5[12]|[78]1)|6(?:12|[2-4]1|5[17]|6[13]|80)|7(?:12|3[134]|4[47]|61|88)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91)|(?:43|59|75)[15]|(?:1[59]|29|67|72)[14]", "1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|674|7(?:(?:2[14]|3[34]|5[15])[2-6]|61[346]|88[0-8])|8(?:70[2-6]|84[235-7]|91[3-7])|(?:1(?:29|60|8[06])|261|552|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))[2-7]", "1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12(?:[2-6]|7[0-8])|74[2-7])|7(?:(?:2[14]|5[15])[2-6]|3171|61[346]|88(?:[2-7]|82))|8(?:70[2-6]|84(?:[2356]|7[19])|91(?:[3-6]|7[19]))|73[134][2-6]|(?:74[47]|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[2-6]|7[19])|(?:1(?:29|60|8[06])|261|552|6(?:[2-4]1|5[17]|6[13]|7(?:1|4[0189])|80)|7(?:12|88[01]))[2-7]"], "0$1",, 1], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2[2457-9]|3[2-5]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1[013-9]|28|3[129]|4[1-35689]|5[29]|6[02-5]|70)|807", "1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2(?:[2457]|84|95)|3(?:[2-4]|55)|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1(?:[013-8]|9[6-9])|28[6-8]|3(?:17|2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4|5[0-367])|70[13-7])|807[19]", "1(?:[2-479]|5(?:[0236-9]|5[013-9]))|[2-5]|6(?:2(?:84|95)|355|83)|73179|807(?:1|9[1-3])|(?:1552|6(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[124-6])\\d|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]))[2-7]"], "0$1",, 1], [, "(\\d{5})(\\d{5})", "$1 $2", ["[6-9]"], "0$1",, 1], [, "(\\d{4})(\\d{2,4})(\\d{4})", "$1 $2 $3", ["1(?:6|8[06])", "1(?:6|8[06]0)"],,, 1], [, "(\\d{4})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["18"],,, 1]], [,,,,,,,,, [-1]],,, [,, "1(?:600\\d{6}|800\\d{4,9})|(?:000800|18(?:03\\d\\d|6(?:0|[12]\\d\\d)))\\d{7}"], [,, "140\\d{7}",,,, "1409305260",,, [10]],,, [,,,,,,,,, [-1]]],
          IO: [, [,, "3\\d{6}",,,,,,, [7]], [,, "37\\d{5}",,,, "3709100"], [,, "38\\d{5}",,,, "3801234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "IO", 246, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["3"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          IQ: [, [,, "(?:1|7\\d\\d)\\d{7}|[2-6]\\d{7,8}",,,,,,, [8, 9, 10], [6, 7]], [,, "1\\d{7}|(?:2[13-5]|3[02367]|4[023]|5[03]|6[026])\\d{6,7}",,,, "12345678",,, [8, 9], [6, 7]], [,, "7[3-9]\\d{8}",,,, "7912345678",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "IQ", 964, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["1"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[2-6]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["7"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          IR: [, [,, "[1-9]\\d{9}|(?:[1-8]\\d\\d|9)\\d{3,4}",,,,,,, [4, 5, 6, 7, 10], [8]], [,, "(?:1[137]|2[13-68]|3[1458]|4[145]|5[1468]|6[16]|7[1467]|8[13467])(?:[03-57]\\d{7}|[16]\\d{3}(?:\\d{4})?|[289]\\d{3}(?:\\d(?:\\d{3})?)?)|94(?:000[09]|(?:12\\d|30[0-2])\\d|2(?:121|[2689]0\\d)|4(?:111|40\\d))\\d{4}",,,, "2123456789",,, [6, 7, 10], [4, 5, 8]], [,, "9(?:(?:0(?:[0-35]\\d|4[4-6])|(?:[13]\\d|2[0-3])\\d)\\d|9(?:[0-46]\\d\\d|5[15]0|8(?:[12]\\d|88)|9(?:0[0-3]|[19]\\d|21|69|77|8[7-9])))\\d{5}",,,, "9123456789",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "IR", 98, "00", "0",,, "0",,,, [[, "(\\d{4,5})", "$1", ["96"], "0$1"], [, "(\\d{2})(\\d{4,5})", "$1 $2", ["(?:1[137]|2[13-68]|3[1458]|4[145]|5[1468]|6[16]|7[1467]|8[13467])[12689]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["9"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["[1-8]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,, "9(?:4440\\d{5}|6(?:0[12]|2[16-8]|3(?:08|[14]5|[23]|66)|4(?:0|80)|5[01]|6[89]|86|9[19]))",,,,,,, [4, 5, 10]], [,, "96(?:0[12]|2[16-8]|3(?:08|[14]5|[23]|66)|4(?:0|80)|5[01]|6[89]|86|9[19])",,,, "9601",,, [4, 5]],,, [,,,,,,,,, [-1]]],
          IS: [, [,, "(?:38\\d|[4-9])\\d{6}",,,,,,, [7, 9]], [,, "(?:4(?:1[0-24-69]|2[0-7]|[37][0-8]|4[0-24589]|5[0-68]|6\\d|8[0-36-8])|5(?:05|[156]\\d|2[02578]|3[0-579]|4[03-7]|7[0-2578]|8[0-35-9]|9[013-689])|872)\\d{4}",,,, "4101234",,, [7]], [,, "(?:38[589]\\d\\d|6(?:1[1-8]|2[0-6]|3[026-9]|4[014679]|5[0159]|6[0-69]|70|8[06-8]|9\\d)|7(?:5[057]|[6-9]\\d)|8(?:2[0-59]|[3-69]\\d|8[238]))\\d{4}",,,, "6111234"], [,, "80[0-8]\\d{4}",,,, "8001234",,, [7]], [,, "90(?:0\\d|1[5-79]|2[015-79]|3[135-79]|4[125-7]|5[25-79]|7[1-37]|8[0-35-7])\\d{3}",,,, "9001234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "49[0-24-79]\\d{4}",,,, "4921234",,, [7]], "IS", 354, "00|1(?:0(?:01|[12]0)|100)",,,,,, "00",, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[4-9]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["3"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "809\\d{4}",,,, "8091234",,, [7]],,, [,, "(?:689|8(?:7[18]|80)|95[48])\\d{4}",,,, "6891234",,, [7]]],
          IT: [, [,, "0\\d{5,10}|1\\d{8,10}|3(?:[0-8]\\d{7,10}|9\\d{7,8})|(?:43|55|70)\\d{8}|8\\d{5}(?:\\d{2,4})?",,,,,,, [6, 7, 8, 9, 10, 11, 12]], [,, "0669[0-79]\\d{1,6}|0(?:1(?:[0159]\\d|[27][1-5]|31|4[1-4]|6[1356]|8[2-57])|2\\d\\d|3(?:[0159]\\d|2[1-4]|3[12]|[48][1-6]|6[2-59]|7[1-7])|4(?:[0159]\\d|[23][1-9]|4[245]|6[1-5]|7[1-4]|81)|5(?:[0159]\\d|2[1-5]|3[2-6]|4[1-79]|6[4-6]|7[1-578]|8[3-8])|6(?:[0-57-9]\\d|6[0-8])|7(?:[0159]\\d|2[12]|3[1-7]|4[2-46]|6[13569]|7[13-6]|8[1-59])|8(?:[0159]\\d|2[3-578]|3[1-356]|[6-8][1-5])|9(?:[0159]\\d|[238][1-5]|4[12]|6[1-8]|7[1-6]))\\d{2,7}",,,, "0212345678",,, [6, 7, 8, 9, 10, 11]], [,, "3[2-9]\\d{7,8}|(?:31|43)\\d{8}",,,, "3123456789",,, [9, 10]], [,, "80(?:0\\d{3}|3)\\d{3}",,,, "800123456",,, [6, 9]], [,, "(?:0878\\d{3}|89(?:2\\d|3[04]|4(?:[0-4]|[5-9]\\d\\d)|5[0-4]))\\d\\d|(?:1(?:44|6[346])|89(?:38|5[5-9]|9))\\d{6}",,,, "899123456",,, [6, 8, 9, 10]], [,, "84(?:[08]\\d{3}|[17])\\d{3}",,,, "848123456",,, [6, 9]], [,, "1(?:78\\d|99)\\d{6}",,,, "1781234567",,, [9, 10]], [,, "55\\d{8}",,,, "5512345678",,, [10]], "IT", 39, "00",,,,,,,, [[, "(\\d{4,5})", "$1", ["1(?:0|9[246])", "1(?:0|9(?:2[2-9]|[46]))"]], [, "(\\d{6})", "$1", ["1(?:1|92)"]], [, "(\\d{2})(\\d{4,6})", "$1 $2", ["0[26]"]], [, "(\\d{3})(\\d{3,6})", "$1 $2", ["0[13-57-9][0159]|8(?:03|4[17]|9[2-5])", "0[13-57-9][0159]|8(?:03|4[17]|9(?:2|3[04]|[45][0-4]))"]], [, "(\\d{4})(\\d{2,6})", "$1 $2", ["0(?:[13-579][2-46-8]|8[236-8])"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["894"]], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["0[26]|5"]], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["1(?:44|[679])|[378]|43"]], [, "(\\d{3})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["0[13-57-9][0159]|14"]], [, "(\\d{2})(\\d{4})(\\d{5})", "$1 $2 $3", ["0[26]"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["0"]], [, "(\\d{3})(\\d{4})(\\d{4,5})", "$1 $2 $3", ["3"]]], [[, "(\\d{2})(\\d{4,6})", "$1 $2", ["0[26]"]], [, "(\\d{3})(\\d{3,6})", "$1 $2", ["0[13-57-9][0159]|8(?:03|4[17]|9[2-5])", "0[13-57-9][0159]|8(?:03|4[17]|9(?:2|3[04]|[45][0-4]))"]], [, "(\\d{4})(\\d{2,6})", "$1 $2", ["0(?:[13-579][2-46-8]|8[236-8])"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["894"]], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["0[26]|5"]], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["1(?:44|[679])|[378]|43"]], [, "(\\d{3})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["0[13-57-9][0159]|14"]], [, "(\\d{2})(\\d{4})(\\d{5})", "$1 $2 $3", ["0[26]"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["0"]], [, "(\\d{3})(\\d{4})(\\d{4,5})", "$1 $2 $3", ["3"]]], [,,,,,,,,, [-1]], 1,, [,, "848\\d{6}",,,,,,, [9]], [,,,,,,,,, [-1]],,, [,, "3[2-8]\\d{9,10}",,,, "33101234501",,, [11, 12]]],
          JE: [, [,, "1534\\d{6}|(?:[3578]\\d|90)\\d{8}",,,,,,, [10], [6]], [,, "1534[0-24-8]\\d{5}",,,, "1534456789",,,, [6]], [,, "7(?:(?:(?:50|82)9|937)\\d|7(?:00[378]|97\\d))\\d{5}",,,, "7797712345"], [,, "80(?:07(?:35|81)|8901)\\d{4}",,,, "8007354567"], [,, "(?:8(?:4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|90(?:066[59]|1810|71(?:07|55)))\\d{4}",,,, "9018105678"], [,,,,,,,,, [-1]], [,, "701511\\d{4}",,,, "7015115678"], [,, "56\\d{8}",,,, "5612345678"], "JE", 44, "00", "0",,, "([0-24-8]\\d{5})$|0", "1534$1",,,,, [,, "76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",,,, "7640123456"],,, [,,,,,,,,, [-1]], [,, "(?:3(?:0(?:07(?:35|81)|8901)|3\\d{4}|4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|55\\d{4})\\d{4}",,,, "5512345678"],,, [,,,,,,,,, [-1]]],
          JM: [, [,, "(?:[58]\\d\\d|658|900)\\d{7}",,,,,,, [10], [7]], [,, "8766060\\d{3}|(?:658(?:2(?:[0-8]\\d|9[0-46-9])|[3-9]\\d\\d)|876(?:52[35]|6(?:0[1-3579]|1[0235-9]|[23]\\d|40|5[06]|6[2-589]|7[0-25-9]|8[04]|9[4-9])|7(?:0[2-689]|[1-6]\\d|8[056]|9[45])|9(?:0[1-8]|1[02378]|[2-8]\\d|9[2-468])))\\d{4}",,,, "8765230123",,,, [7]], [,, "(?:658295|876(?:2(?:0[1-9]|[13-9]\\d|2[013-9])|[348]\\d\\d|5(?:0[1-9]|[1-9]\\d)|6(?:4[89]|6[67])|7(?:0[07]|7\\d|8[1-47-9]|9[0-36-9])|9(?:[01]9|9[0579])))\\d{4}",,,, "8762101234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "JM", 1, "011", "1",,, "1",,,,,, [,,,,,,,,, [-1]],, "658|876", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          JO: [, [,, "(?:(?:[2689]|7\\d)\\d|32|53)\\d{6}",,,,,,, [8, 9]], [,, "87(?:000|90[01])\\d{3}|(?:2(?:6(?:2[0-35-9]|3[0-578]|4[24-7]|5[0-24-8]|[6-8][023]|9[0-3])|7(?:0[1-79]|10|2[014-7]|3[0-689]|4[019]|5[0-3578]))|32(?:0[1-69]|1[1-35-7]|2[024-7]|3\\d|4[0-3]|[5-7][023])|53(?:0[0-3]|[13][023]|2[0-59]|49|5[0-35-9]|6[15]|7[45]|8[1-6]|9[0-36-9])|6(?:2(?:[05]0|22)|3(?:00|33)|4(?:0[0-25]|1[2-7]|2[0569]|[38][07-9]|4[025689]|6[0-589]|7\\d|9[0-2])|5(?:[01][056]|2[034]|3[0-57-9]|4[178]|5[0-69]|6[0-35-9]|7[1-379]|8[0-68]|9[0239]))|87(?:20|7[078]|99))\\d{4}",,,, "62001234",,, [8]], [,, "7(?:[78][0-25-9]|9\\d)\\d{6}",,,, "790123456",,, [9]], [,, "80\\d{6}",,,, "80012345",,, [8]], [,, "9\\d{7}",,,, "90012345",,, [8]], [,, "85\\d{6}",,,, "85012345",,, [8]], [,, "70\\d{7}",,,, "700123456",,, [9]], [,,,,,,,,, [-1]], "JO", 962, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["[2356]|87"], "(0$1)"], [, "(\\d{3})(\\d{5,6})", "$1 $2", ["[89]"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["70"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["7"], "0$1"]],, [,, "74(?:66|77)\\d{5}",,,, "746612345",,, [9]],,, [,,,,,,,,, [-1]], [,, "8(?:10|8\\d)\\d{5}",,,, "88101234",,, [8]],,, [,,,,,,,,, [-1]]],
          JP: [, [,, "00[1-9]\\d{6,14}|[257-9]\\d{9}|(?:00|[1-9]\\d\\d)\\d{6}",,,,,,, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], [,, "(?:1(?:1[235-8]|2[3-6]|3[3-9]|4[2-6]|[58][2-8]|6[2-7]|7[2-9]|9[1-9])|(?:2[2-9]|[36][1-9])\\d|4(?:[2-578]\\d|6[02-8]|9[2-59])|5(?:[2-589]\\d|6[1-9]|7[2-8])|7(?:[25-9]\\d|3[4-9]|4[02-9])|8(?:[2679]\\d|3[2-9]|4[5-9]|5[1-9]|8[03-9])|9(?:[2-58]\\d|[679][1-9]))\\d{6}",,,, "312345678",,, [9]], [,, "[7-9]0[1-9]\\d{7}",,,, "9012345678",,, [10]], [,, "00777(?:[01]|5\\d)\\d\\d|(?:00(?:7778|882[1245])|(?:120|800\\d)\\d\\d)\\d{4}|00(?:37|66|78)\\d{6,13}",,,, "120123456"], [,, "990\\d{6}",,,, "990123456",,, [9]], [,,,,,,,,, [-1]], [,, "60\\d{7}",,,, "601234567",,, [9]], [,, "50[1-9]\\d{7}",,,, "5012345678",,, [10]], "JP", 81, "010", "0",,, "(000[259]\\d{6})$|(?:(?:003768)0?)|0", "$1",,, [[, "(\\d{4})(\\d{4})", "$1-$2", ["007", "0077", "00777", "00777[01]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1-$2-$3", ["(?:12|57|99)0"], "0$1"], [, "(\\d{4})(\\d)(\\d{4})", "$1-$2-$3", ["1(?:26|3[79]|4[56]|5[4-68]|6[3-5])|499|5(?:76|97)|746|8(?:3[89]|47|51)|9(?:80|9[16])", "1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:76|97)9|7468|8(?:3(?:8[7-9]|96)|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]", "1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:769|979[2-69])|7468|8(?:3(?:8[7-9]|96[2457-9])|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["60"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1-$2-$3", ["[36]|4(?:2[09]|7[01])", "[36]|4(?:2(?:0|9[02-69])|7(?:0[019]|1))"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["1(?:1|5[45]|77|88|9[69])|2(?:2[1-37]|3[0-269]|4[59]|5|6[24]|7[1-358]|8[1369]|9[0-38])|4(?:[28][1-9]|3[0-57]|[45]|6[248]|7[2-579]|9[29])|5(?:2|3[0459]|4[0-369]|5[29]|8[02389]|9[0-389])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9[2-6])|8(?:2[124589]|3[26-9]|49|51|6|7[0-468]|8[68]|9[019])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9[1-489])", "1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2(?:[127]|3[014-9])|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9[19])|62|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|8[1-9]|9[29])|5(?:2|3(?:[045]|9[0-8])|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0-2469])|3(?:[29]|60)|49|51|6(?:[0-24]|36|5[0-3589]|7[23]|9[01459])|7[0-468]|8[68])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9(?:[1289]|3[34]|4[0178]))|(?:264|837)[016-9]|2(?:57|93)[015-9]|(?:25[0468]|422|838)[01]|(?:47[59]|59[89]|8(?:6[68]|9))[019]", "1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2[127]|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9(?:17|99))|6(?:2|4[016-9])|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|9[29])|5(?:2|3(?:[045]|9(?:[0-58]|6[4-9]|7[0-35689]))|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0169])|3(?:[29]|60|7(?:[017-9]|6[6-8]))|49|51|6(?:[0-24]|36[2-57-9]|5(?:[0-389]|5[23])|6(?:[01]|9[178])|7(?:2[2-468]|3[78])|9[0145])|7[0-468]|8[68])|9(?:4[15]|5[138]|7[156]|8[189]|9(?:[1289]|3(?:31|4[357])|4[0178]))|(?:8294|96)[1-3]|2(?:57|93)[015-9]|(?:223|8699)[014-9]|(?:25[0468]|422|838)[01]|(?:48|8292|9[23])[1-9]|(?:47[59]|59[89]|8(?:68|9))[019]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{4})", "$1-$2-$3", ["[14]|[289][2-9]|5[3-9]|7[2-4679]"], "0$1"], [, "(\\d{4})(\\d{2})(\\d{3,4})", "$1-$2-$3", ["007", "0077"]], [, "(\\d{4})(\\d{2})(\\d{4})", "$1-$2-$3", ["008"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["800"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1-$2-$3", ["[257-9]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3,4})", "$1-$2-$3", ["0"]], [, "(\\d{4})(\\d{4})(\\d{4,5})", "$1-$2-$3", ["0"]], [, "(\\d{4})(\\d{5})(\\d{5,6})", "$1-$2-$3", ["0"]], [, "(\\d{4})(\\d{6})(\\d{6,7})", "$1-$2-$3", ["0"]]], [[, "(\\d{3})(\\d{3})(\\d{3})", "$1-$2-$3", ["(?:12|57|99)0"], "0$1"], [, "(\\d{4})(\\d)(\\d{4})", "$1-$2-$3", ["1(?:26|3[79]|4[56]|5[4-68]|6[3-5])|499|5(?:76|97)|746|8(?:3[89]|47|51)|9(?:80|9[16])", "1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:76|97)9|7468|8(?:3(?:8[7-9]|96)|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]", "1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:769|979[2-69])|7468|8(?:3(?:8[7-9]|96[2457-9])|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["60"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1-$2-$3", ["[36]|4(?:2[09]|7[01])", "[36]|4(?:2(?:0|9[02-69])|7(?:0[019]|1))"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["1(?:1|5[45]|77|88|9[69])|2(?:2[1-37]|3[0-269]|4[59]|5|6[24]|7[1-358]|8[1369]|9[0-38])|4(?:[28][1-9]|3[0-57]|[45]|6[248]|7[2-579]|9[29])|5(?:2|3[0459]|4[0-369]|5[29]|8[02389]|9[0-389])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9[2-6])|8(?:2[124589]|3[26-9]|49|51|6|7[0-468]|8[68]|9[019])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9[1-489])", "1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2(?:[127]|3[014-9])|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9[19])|62|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|8[1-9]|9[29])|5(?:2|3(?:[045]|9[0-8])|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0-2469])|3(?:[29]|60)|49|51|6(?:[0-24]|36|5[0-3589]|7[23]|9[01459])|7[0-468]|8[68])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9(?:[1289]|3[34]|4[0178]))|(?:264|837)[016-9]|2(?:57|93)[015-9]|(?:25[0468]|422|838)[01]|(?:47[59]|59[89]|8(?:6[68]|9))[019]", "1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2[127]|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9(?:17|99))|6(?:2|4[016-9])|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|9[29])|5(?:2|3(?:[045]|9(?:[0-58]|6[4-9]|7[0-35689]))|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0169])|3(?:[29]|60|7(?:[017-9]|6[6-8]))|49|51|6(?:[0-24]|36[2-57-9]|5(?:[0-389]|5[23])|6(?:[01]|9[178])|7(?:2[2-468]|3[78])|9[0145])|7[0-468]|8[68])|9(?:4[15]|5[138]|7[156]|8[189]|9(?:[1289]|3(?:31|4[357])|4[0178]))|(?:8294|96)[1-3]|2(?:57|93)[015-9]|(?:223|8699)[014-9]|(?:25[0468]|422|838)[01]|(?:48|8292|9[23])[1-9]|(?:47[59]|59[89]|8(?:68|9))[019]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{4})", "$1-$2-$3", ["[14]|[289][2-9]|5[3-9]|7[2-4679]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["800"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1-$2-$3", ["[257-9]"], "0$1"]], [,, "20\\d{8}",,,, "2012345678",,, [10]],,, [,, "00(?:777(?:[01]|(?:5|8\\d)\\d)|882[1245]\\d\\d)\\d\\d|00(?:37|66|78)\\d{6,13}"], [,, "570\\d{6}",,,, "570123456",,, [9]],,, [,,,,,,,,, [-1]]],
          KE: [, [,, "(?:[17]\\d\\d|900)\\d{6}|(?:2|80)0\\d{6,7}|[4-6]\\d{6,8}",,,,,,, [7, 8, 9, 10]], [,, "(?:4[245]|5[1-79]|6[01457-9])\\d{5,7}|(?:4[136]|5[08]|62)\\d{7}|(?:[24]0|66)\\d{6,7}",,,, "202012345",,, [7, 8, 9]], [,, "(?:1(?:0[0-8]|1[0-7]|2[014]|30)|7\\d\\d)\\d{6}",,,, "712123456",,, [9]], [,, "800[02-8]\\d{5,6}",,,, "800223456",,, [9, 10]], [,, "900[02-9]\\d{5}",,,, "900223456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KE", 254, "000", "0",,, "0",,,, [[, "(\\d{2})(\\d{5,7})", "$1 $2", ["[24-6]"], "0$1"], [, "(\\d{3})(\\d{6})", "$1 $2", ["[17]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[89]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KG: [, [,, "8\\d{9}|[235-9]\\d{8}",,,,,,, [9, 10], [5, 6]], [,, "312(?:5[0-79]\\d|9(?:[0-689]\\d|7[0-24-9]))\\d{3}|(?:3(?:1(?:2[0-46-8]|3[1-9]|47|[56]\\d)|2(?:22|3[0-479]|6[0-7])|4(?:22|5[6-9]|6\\d)|5(?:22|3[4-7]|59|6\\d)|6(?:22|5[35-7]|6\\d)|7(?:22|3[468]|4[1-9]|59|[67]\\d)|9(?:22|4[1-8]|6\\d))|6(?:09|12|2[2-4])\\d)\\d{5}",,,, "312123456",,, [9], [5, 6]], [,, "312(?:58\\d|973)\\d{3}|(?:2(?:0[0-35]|2\\d)|5[0-24-7]\\d|600|7(?:[07]\\d|55)|88[08]|9(?:12|9[05-9]))\\d{6}",,,, "700123456",,, [9]], [,, "800\\d{6,7}",,,, "800123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KG", 996, "00", "0",,, "0",,,, [[, "(\\d{4})(\\d{5})", "$1 $2", ["3(?:1[346]|[24-79])"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[235-79]|88"], "0$1"], [, "(\\d{3})(\\d{3})(\\d)(\\d{2,3})", "$1 $2 $3 $4", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KH: [, [,, "1\\d{9}|[1-9]\\d{7,8}",,,,,,, [8, 9, 10], [6, 7]], [,, "23(?:4(?:[2-4]|[56]\\d)|[568]\\d\\d)\\d{4}|23[236-9]\\d{5}|(?:2[4-6]|3[2-6]|4[2-4]|[5-7][2-5])(?:(?:[237-9]|4[56]|5\\d)\\d{5}|6\\d{5,6})",,,, "23756789",,, [8, 9], [6, 7]], [,, "(?:(?:1[28]|3[18]|9[67])\\d|6[016-9]|7(?:[07-9]|[16]\\d)|8(?:[013-79]|8\\d))\\d{6}|(?:1\\d|9[0-57-9])\\d{6}|(?:2[3-6]|3[2-6]|4[2-4]|[5-7][2-5])48\\d{5}",,,, "91234567",,, [8, 9]], [,, "1800(?:1\\d|2[019])\\d{4}",,,, "1800123456",,, [10]], [,, "1900(?:1\\d|2[09])\\d{4}",,,, "1900123456",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KH", 855, "00[14-9]", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[1-9]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KI: [, [,, "(?:[37]\\d|6[0-79])\\d{6}|(?:[2-48]\\d|50)\\d{3}",,,,,,, [5, 8]], [,, "(?:[24]\\d|3[1-9]|50|65(?:02[12]|12[56]|22[89]|[3-5]00)|7(?:27\\d\\d|3100|5(?:02[12]|12[56]|22[89]|[34](?:00|81)|500))|8[0-5])\\d{3}",,,, "31234"], [,, "(?:6200[01]|7(?:310[1-9]|5(?:02[03-9]|12[0-47-9]|22[0-7]|[34](?:0[1-9]|8[02-9])|50[1-9])))\\d{3}|(?:63\\d\\d|7(?:(?:[0146-9]\\d|2[0-689])\\d|3(?:[02-9]\\d|1[1-9])|5(?:[0-2][013-9]|[34][1-79]|5[1-9]|[6-9]\\d)))\\d{4}",,,, "72001234",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "30(?:0[01]\\d\\d|12(?:11|20))\\d\\d",,,, "30010000",,, [8]], "KI", 686, "00", "0",,, "0",,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KM: [, [,, "[3478]\\d{6}",,,,,,, [7], [4]], [,, "7[4-7]\\d{5}",,,, "7712345",,,, [4]], [,, "[34]\\d{6}",,,, "3212345"], [,,,,,,,,, [-1]], [,, "8\\d{6}",,,, "8001234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KM", 269, "00",,,,,,,, [[, "(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3", ["[3478]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KN: [, [,, "(?:[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "869(?:2(?:29|36)|302|4(?:6[015-9]|70)|56[5-7])\\d{4}",,,, "8692361234",,,, [7]], [,, "869(?:48[89]|55[6-8]|66\\d|76[02-7])\\d{4}",,,, "8697652917",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "KN", 1, "011", "1",,, "([2-7]\\d{6})$|1", "869$1",,,,, [,,,,,,,,, [-1]],, "869", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KP: [, [,, "85\\d{6}|(?:19\\d|[2-7])\\d{7}",,,,,,, [8, 10], [6, 7]], [,, "(?:(?:195|2)\\d|3[19]|4[159]|5[37]|6[17]|7[39]|85)\\d{6}",,,, "21234567",,,, [6, 7]], [,, "19[1-3]\\d{7}",,,, "1921234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KP", 850, "00|99", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"], "0$1"], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-7]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"], "0$1"]],, [,,,,,,,,, [-1]],,, [,, "238[02-9]\\d{4}|2(?:[0-24-9]\\d|3[0-79])\\d{5}",,,,,,, [8]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KR: [, [,, "00[1-9]\\d{8,11}|(?:[12]|5\\d{3})\\d{7}|[13-6]\\d{9}|(?:[1-6]\\d|80)\\d{7}|[3-6]\\d{4,5}|(?:00|7)0\\d{8}",,,,,,, [5, 6, 8, 9, 10, 11, 12, 13, 14], [3, 4, 7]], [,, "(?:2|3[1-3]|[46][1-4]|5[1-5])[1-9]\\d{6,7}|(?:3[1-3]|[46][1-4]|5[1-5])1\\d{2,3}",,,, "22123456",,, [5, 6, 8, 9, 10], [3, 4, 7]], [,, "1(?:05(?:[0-8]\\d|9[0-6])|22[13]\\d)\\d{4,5}|1(?:0[0-46-9]|[16-9]\\d|2[013-9])\\d{6,7}",,,, "1020000000",,, [9, 10]], [,, "00(?:308\\d{6,7}|798\\d{7,9})|(?:00368|[38]0)\\d{7}",,,, "801234567",,, [9, 11, 12, 13, 14]], [,, "60[2-9]\\d{6}",,,, "602345678",,, [9]], [,,,,,,,,, [-1]], [,, "50\\d{8,9}",,,, "5012345678",,, [10, 11]], [,, "70\\d{8}",,,, "7012345678",,, [10]], "KR", 82, "00(?:[125689]|3(?:[46]5|91)|7(?:00|27|3|55|6[126]))", "0",,, "0(8(?:[1-46-8]|5\\d\\d))?",,,, [[, "(\\d{5})", "$1", ["1[016-9]1", "1[016-9]11", "1[016-9]114"], "0$1"], [, "(\\d{2})(\\d{3,4})", "$1-$2", ["(?:3[1-3]|[46][1-4]|5[1-5])1"], "0$1", "0$CC-$1"], [, "(\\d{4})(\\d{4})", "$1-$2", ["1"]], [, "(\\d)(\\d{3,4})(\\d{4})", "$1-$2-$3", ["2"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["[36]0|8"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1-$2-$3", ["[1346]|5[1-5]"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1-$2-$3", ["[57]"], "0$1", "0$CC-$1"], [, "(\\d{5})(\\d{3})(\\d{3})", "$1 $2 $3", ["003", "0030"]], [, "(\\d{2})(\\d{5})(\\d{4})", "$1-$2-$3", ["5"], "0$1", "0$CC-$1"], [, "(\\d{5})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["0"]], [, "(\\d{5})(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["0"]]], [[, "(\\d{2})(\\d{3,4})", "$1-$2", ["(?:3[1-3]|[46][1-4]|5[1-5])1"], "0$1", "0$CC-$1"], [, "(\\d{4})(\\d{4})", "$1-$2", ["1"]], [, "(\\d)(\\d{3,4})(\\d{4})", "$1-$2-$3", ["2"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1-$2-$3", ["[36]0|8"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1-$2-$3", ["[1346]|5[1-5]"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1-$2-$3", ["[57]"], "0$1", "0$CC-$1"], [, "(\\d{2})(\\d{5})(\\d{4})", "$1-$2-$3", ["5"], "0$1", "0$CC-$1"]], [,, "15\\d{7,8}",,,, "1523456789",,, [9, 10]],,, [,, "00(?:3(?:08\\d{6,7}|68\\d{7})|798\\d{7,9})",,,,,,, [11, 12, 13, 14]], [,, "1(?:5(?:22|33|44|66|77|88|99)|6(?:[07]0|44|6[0168]|88)|8(?:00|33|55|77|99))\\d{4}",,,, "15441234",,, [8]],,, [,,,,,,,,, [-1]]],
          KW: [, [,, "18\\d{5}|(?:[2569]\\d|41)\\d{6}",,,,,,, [7, 8]], [,, "2(?:[23]\\d\\d|4(?:[1-35-9]\\d|44)|5(?:0[034]|[2-46]\\d|5[1-3]|7[1-7]))\\d{4}",,,, "22345678",,, [8]], [,, "(?:41\\d\\d|5(?:(?:[05]\\d|1[0-7]|6[56])\\d|2(?:22|5[25])|7(?:55|77)|88[58])|6(?:(?:0[034679]|5[015-9]|6\\d)\\d|1(?:00|11|6[16])|2[26]2|3[36]3|4[46]4|7(?:0[013-9]|[67]\\d)|8[68]8|9(?:[069]\\d|3[039]))|9(?:(?:[04679]\\d|8[057-9])\\d|1(?:1[01]|99)|2(?:00|2\\d)|3(?:00|3[03])|5(?:00|5\\d)))\\d{4}",,,, "50012345",,, [8]], [,, "18\\d{5}",,,, "1801234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "KW", 965, "00",,,,,,,, [[, "(\\d{4})(\\d{3,4})", "$1 $2", ["[169]|2(?:[235]|4[1-35-9])|52"]], [, "(\\d{3})(\\d{5})", "$1 $2", ["[245]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KY: [, [,, "(?:345|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "345(?:2(?:22|3[23]|44|66)|333|444|6(?:23|38|40)|7(?:30|4[35-79]|6[6-9]|77)|8(?:00|1[45]|[48]8)|9(?:14|4[035-9]))\\d{4}",,,, "3452221234",,,, [7]], [,, "345(?:32[1-9]|42[0-4]|5(?:1[67]|2[5-79]|4[6-9]|50|76)|649|82[56]|9(?:1[679]|2[2-9]|3[06-9]|90))\\d{4}",,,, "3453231234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "(?:345976|900[2-9]\\d\\d)\\d{4}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "KY", 1, "011", "1",,, "([2-9]\\d{6})$|1", "345$1",,,,, [,, "345849\\d{4}",,,, "3458491234"],, "345", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          KZ: [, [,, "(?:33622|8\\d{8})\\d{5}|[78]\\d{9}",,,,,,, [10, 14], [5, 6, 7]], [,, "(?:33622|7(?:1(?:0(?:[23]\\d|4[0-3]|59|63)|1(?:[23]\\d|4[0-79]|59)|2(?:[23]\\d|59)|3(?:2\\d|3[0-79]|4[0-35-9]|59)|4(?:[24]\\d|3[013-9]|5[1-9]|97)|5(?:2\\d|3[1-9]|4[0-7]|59)|6(?:[2-4]\\d|5[19]|61)|72\\d|8(?:[27]\\d|3[1-46-9]|4[0-5]|59))|2(?:1(?:[23]\\d|4[46-9]|5[3469])|2(?:2\\d|3[0679]|46|5[12679])|3(?:[2-4]\\d|5[139])|4(?:2\\d|3[1-35-9]|59)|5(?:[23]\\d|4[0-8]|59|61)|6(?:2\\d|3[1-9]|4[0-4]|59)|7(?:[2379]\\d|40|5[279])|8(?:[23]\\d|4[0-3]|59)|9(?:2\\d|3[124578]|59))))\\d{5}",,,, "7123456789",,, [10], [5, 6, 7]], [,, "7(?:0[0-25-8]|47|6[0-4]|7[15-8]|85)\\d{7}",,,, "7710009998",,, [10]], [,, "8(?:00|108\\d{3})\\d{7}",,,, "8001234567"], [,, "809\\d{7}",,,, "8091234567",,, [10]], [,,,,,,,,, [-1]], [,, "808\\d{7}",,,, "8081234567",,, [10]], [,, "751\\d{7}",,,, "7511234567",,, [10]], "KZ", 7, "810", "8",,, "8",, "8~10",,,, [,,,,,,,,, [-1]],, "33|7", [,, "751\\d{7}",,,,,,, [10]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LA: [, [,, "[23]\\d{9}|3\\d{8}|(?:[235-8]\\d|41)\\d{6}",,,,,,, [8, 9, 10], [6]], [,, "(?:2[13]|[35-7][14]|41|8[1468])\\d{6}",,,, "21212862",,, [8], [6]], [,, "208[78]\\d{6}|(?:20[23579]|30[24])\\d{7}",,,, "2023123456",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LA", 856, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["2[13]|3[14]|[4-8]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["30[0135-9]"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["[23]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "30[0135-9]\\d{6}",,,, "301234567",,, [9]],,, [,,,,,,,,, [-1]]],
          LB: [, [,, "[27-9]\\d{7}|[13-9]\\d{6}",,,,,,, [7, 8]], [,, "7(?:62|8[0-7]|9[04-9])\\d{4}|(?:[14-69]\\d|2(?:[14-69]\\d|[78][1-9])|7[2-57]|8[02-9])\\d{5}",,,, "1123456"], [,, "793(?:[01]\\d|2[0-4])\\d{3}|(?:(?:3|81)\\d|7(?:[01]\\d|6[013-9]|8[89]|9[12]))\\d{5}",,,, "71123456"], [,,,,,,,,, [-1]], [,, "9[01]\\d{6}",,,, "90123456",,, [8]], [,, "80\\d{6}",,,, "80123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LB", 961, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["[13-69]|7(?:[2-57]|62|8[0-7]|9[04-9])|8[02-9]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[27-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LC: [, [,, "(?:[58]\\d\\d|758|900)\\d{7}",,,,,,, [10], [7]], [,, "758(?:234|4(?:30|5\\d|6[2-9]|8[0-2])|57[0-2]|(?:63|75)8)\\d{4}",,,, "7584305678",,,, [7]], [,, "758(?:28[4-7]|384|4(?:6[01]|8[4-9])|5(?:1[89]|20|84)|7(?:1[2-9]|2\\d|3[0-3])|812)\\d{4}",,,, "7582845678",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "LC", 1, "011", "1",,, "([2-8]\\d{6})$|1", "758$1",,,,, [,,,,,,,,, [-1]],, "758", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LI: [, [,, "[68]\\d{8}|(?:[2378]\\d|90)\\d{5}",,,,,,, [7, 9]], [,, "(?:2(?:01|1[27]|2[02]|3\\d|6[02-578]|96)|3(?:[24]0|33|7[0135-7]|8[048]|9[0269]))\\d{4}",,,, "2345678",,, [7]], [,, "(?:6(?:(?:4[5-9]|5[0-469])\\d|6(?:[024-6]\\d|[17]0|3[7-9]))\\d|7(?:[37-9]\\d|42|56))\\d{4}",,,, "660234567"], [,, "8002[28]\\d\\d|80(?:05\\d|9)\\d{4}",,,, "8002222"], [,, "90(?:02[258]|1(?:23|3[14])|66[136])\\d\\d",,,, "9002222",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LI", 423, "00", "0",,, "(1001)|0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3", ["[2379]|8(?:0[09]|7)", "[2379]|8(?:0(?:02|9)|7)"],, "$CC $1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["69"],, "$CC $1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["6"],, "$CC $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "870(?:28|87)\\d\\d",,,, "8702812",,, [7]],,, [,, "697(?:42|56|[78]\\d)\\d{4}",,,, "697861234",,, [9]]],
          LK: [, [,, "[1-9]\\d{8}",,,,,,, [9], [7]], [,, "(?:12[2-9]|602|8[12]\\d|9(?:1\\d|22|9[245]))\\d{6}|(?:11|2[13-7]|3[1-8]|4[157]|5[12457]|6[35-7])[2-57]\\d{6}",,,, "112345678",,,, [7]], [,, "7(?:[0-25-8]\\d|4[0-4])\\d{6}",,,, "712345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LK", 94, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["7"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[1-689]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "1973\\d{5}",,,, "197312345"],,, [,,,,,,,,, [-1]]],
          LR: [, [,, "(?:[245]\\d|33|77|88)\\d{7}|(?:2\\d|[4-6])\\d{6}",,,,,,, [7, 8, 9]], [,, "2\\d{7}",,,, "21234567",,, [8]], [,, "(?:(?:(?:22|33)0|555|(?:77|88)\\d)\\d|4(?:240|[67]))\\d{5}|[56]\\d{6}",,,, "770123456",,, [7, 9]], [,,,,,,,,, [-1]], [,, "332(?:02|[34]\\d)\\d{4}",,,, "332021234",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LR", 231, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["4[67]|[56]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-578]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LS: [, [,, "(?:[256]\\d\\d|800)\\d{5}",,,,,,, [8]], [,, "2\\d{7}",,,, "22123456"], [,, "[56]\\d{7}",,,, "50123456"], [,, "800[1256]\\d{4}",,,, "80021234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LS", 266, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[2568]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LT: [, [,, "(?:[3469]\\d|52|[78]0)\\d{6}",,,,,,, [8]], [,, "(?:3[1478]|4[124-6]|52)\\d{6}",,,, "31234567"], [,, "6\\d{7}",,,, "61234567"], [,, "80[02]\\d{5}",,,, "80012345"], [,, "9(?:0[0239]|10)\\d{5}",,,, "90012345"], [,, "808\\d{5}",,,, "80812345"], [,, "70[05]\\d{5}",,,, "70012345"], [,, "[89]01\\d{5}",,,, "80123456"], "LT", 370, "00", "0",,, "[08]",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["52[0-7]"], "(0-$1)",, 1], [, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["[7-9]"], "0 $1",, 1], [, "(\\d{2})(\\d{6})", "$1 $2", ["37|4(?:[15]|6[1-8])"], "(0-$1)",, 1], [, "(\\d{3})(\\d{5})", "$1 $2", ["[3-6]"], "(0-$1)",, 1]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "70[67]\\d{5}",,,, "70712345"],,, [,,,,,,,,, [-1]]],
          LU: [, [,, "35[013-9]\\d{4,8}|6\\d{8}|35\\d{2,4}|(?:[2457-9]\\d|3[0-46-9])\\d{2,9}",,,,,,, [4, 5, 6, 7, 8, 9, 10, 11]], [,, "(?:35[013-9]|80[2-9]|90[89])\\d{1,8}|(?:2[2-9]|3[0-46-9]|[457]\\d|8[13-9]|9[2-579])\\d{2,9}",,,, "27123456"], [,, "6(?:[269][18]|5[1568]|7[189]|81)\\d{6}",,,, "628123456",,, [9]], [,, "800\\d{5}",,,, "80012345",,, [8]], [,, "90[015]\\d{5}",,,, "90012345",,, [8]], [,, "801\\d{5}",,,, "80112345",,, [8]], [,,,,,,,,, [-1]], [,, "20(?:1\\d{5}|[2-689]\\d{1,7})",,,, "20201234",,, [4, 5, 6, 7, 8, 9, 10]], "LU", 352, "00",,,, "(15(?:0[06]|1[12]|[35]5|4[04]|6[26]|77|88|99)\\d)",,,, [[, "(\\d{2})(\\d{3})", "$1 $2", ["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3", ["20[2-689]"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})", "$1 $2 $3 $4", ["2(?:[0367]|4[3-8])"],, "$CC $1"], [, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["80[01]|90[015]"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["20"],, "$CC $1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["6"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})", "$1 $2 $3 $4 $5", ["2(?:[0367]|4[3-8])"],, "$CC $1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{1,5})", "$1 $2 $3 $4", ["[3-57]|8[13-9]|9(?:0[89]|[2-579])|(?:2|80)[2-9]"],, "$CC $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LV: [, [,, "(?:[268]\\d|90)\\d{6}",,,,,,, [8]], [,, "6\\d{7}",,,, "63123456"], [,, "23(?:23[0-57-9]|33[0238])\\d{3}|2(?:[0-24-9]\\d\\d|3(?:0[07]|[14-9]\\d|2[024-9]|3[0-24-9]))\\d{4}",,,, "21234567"], [,, "80\\d{6}",,,, "80123456"], [,, "90\\d{6}",,,, "90123456"], [,, "81\\d{6}",,,, "81123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LV", 371, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[269]|8[01]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          LY: [, [,, "[2-9]\\d{8}",,,,,,, [9], [7]], [,, "(?:2(?:0[56]|[1-6]\\d|7[124579]|8[124])|3(?:1\\d|2[2356])|4(?:[17]\\d|2[1-357]|5[2-4]|8[124])|5(?:[1347]\\d|2[1-469]|5[13-5]|8[1-4])|6(?:[1-479]\\d|5[2-57]|8[1-5])|7(?:[13]\\d|2[13-79])|8(?:[124]\\d|5[124]|84))\\d{6}",,,, "212345678",,,, [7]], [,, "9[1-6]\\d{7}",,,, "912345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "LY", 218, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{7})", "$1-$2", ["[2-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MA: [, [,, "[5-8]\\d{8}",,,,,,, [9]], [,, "5(?:2(?:[0-25-79]\\d|3[1-578]|4[02-46-8]|8[0235-7])|3(?:[0-47]\\d|5[02-9]|6[02-8]|8[014-9]|9[3-9])|(?:4[067]|5[03])\\d)\\d{5}",,,, "520123456"], [,, "(?:6(?:[0-79]\\d|8[0-247-9])|7(?:[0167]\\d|2[0-4]|5[01]|8[0-3]))\\d{6}",,,, "650123456"], [,, "80[0-7]\\d{6}",,,, "801234567"], [,, "89\\d{7}",,,, "891234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:592(?:4[0-2]|93)|80[89]\\d\\d)\\d{4}",,,, "592401234"], "MA", 212, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["5[45]"], "0$1"], [, "(\\d{4})(\\d{5})", "$1-$2", ["5(?:2[2-46-9]|3[3-9]|9)|8(?:0[89]|92)"], "0$1"], [, "(\\d{2})(\\d{7})", "$1-$2", ["8"], "0$1"], [, "(\\d{3})(\\d{6})", "$1-$2", ["[5-7]"], "0$1"]],, [,,,,,,,,, [-1]], 1,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MC: [, [,, "(?:[3489]|6\\d)\\d{7}",,,,,,, [8, 9]], [,, "(?:870|9[2-47-9]\\d)\\d{5}",,,, "99123456",,, [8]], [,, "4(?:[469]\\d|5[1-9])\\d{5}|(?:3|6\\d)\\d{7}",,,, "612345678"], [,, "(?:800|90\\d)\\d{5}",,,, "90123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MC", 377, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})(\\d{2})", "$1 $2 $3", ["87"]], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["4"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[389]"]], [, "(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["6"], "0$1"]], [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["4"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[389]"]], [, "(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["6"], "0$1"]], [,,,,,,,,, [-1]],,, [,, "8[07]0\\d{5}",,,,,,, [8]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MD: [, [,, "(?:[235-7]\\d|[89]0)\\d{6}",,,,,,, [8]], [,, "(?:(?:2[1-9]|3[1-79])\\d|5(?:33|5[257]))\\d{5}",,,, "22212345"], [,, "562\\d{5}|(?:6\\d|7[16-9])\\d{6}",,,, "62112345"], [,, "800\\d{5}",,,, "80012345"], [,, "90[056]\\d{5}",,,, "90012345"], [,, "808\\d{5}",,,, "80812345"], [,,,,,,,,, [-1]], [,, "3[08]\\d{6}",,,, "30123456"], "MD", 373, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{5})", "$1 $2", ["[89]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["22|3"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["[25-7]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "803\\d{5}",,,, "80312345"],,, [,,,,,,,,, [-1]]],
          ME: [, [,, "(?:20|[3-79]\\d)\\d{6}|80\\d{6,7}",,,,,,, [8, 9], [6]], [,, "(?:20[2-8]|3(?:[0-2][2-7]|3[24-7])|4(?:0[2-467]|1[2467])|5(?:0[2467]|1[24-7]|2[2-467]))\\d{5}",,,, "30234567",,, [8], [6]], [,, "6(?:[07-9]\\d|3[024]|6[0-25])\\d{5}",,,, "67622901",,, [8]], [,, "80(?:[0-2578]|9\\d)\\d{5}",,,, "80080002"], [,, "9(?:4[1568]|5[178])\\d{5}",,,, "94515151",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "78[1-49]\\d{5}",,,, "78108780",,, [8]], "ME", 382, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[2-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "77[1-9]\\d{5}",,,, "77273012",,, [8]],,, [,,,,,,,,, [-1]]],
          MF: [, [,, "590\\d{6}|(?:69|80|9\\d)\\d{7}",,,,,,, [9]], [,, "590(?:0[079]|[14]3|[27][79]|3[03-7]|5[0-268]|87)\\d{4}",,,, "590271234"], [,, "69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))\\d{4}",,,, "690001234"], [,, "80[0-5]\\d{6}",,,, "800012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:(?:39[5-7]|76[018])\\d|475[0-5])\\d{4}",,,, "976012345"], "MF", 590, "00", "0",,, "0",,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MG: [, [,, "[23]\\d{8}",,,,,,, [9], [7]], [,, "2072[29]\\d{4}|20(?:2\\d|4[47]|5[3467]|6[279]|7[356]|8[268]|9[245])\\d{5}",,,, "202123456",,,, [7]], [,, "3[2-47-9]\\d{7}",,,, "321234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "22\\d{7}",,,, "221234567"], "MG", 261, "00", "0",,, "([24-9]\\d{6})$|0", "20$1",,, [[, "(\\d{2})(\\d{2})(\\d{3})(\\d{2})", "$1 $2 $3 $4", ["[23]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MH: [, [,, "329\\d{4}|(?:[256]\\d|45)\\d{5}",,,,,,, [7]], [,, "(?:247|528|625)\\d{4}",,,, "2471234"], [,, "(?:(?:23|54)5|329|45[35-8])\\d{4}",,,, "2351234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "635\\d{4}",,,, "6351234"], "MH", 692, "011", "1",,, "1",,,, [[, "(\\d{3})(\\d{4})", "$1-$2", ["[2-6]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MK: [, [,, "[2-578]\\d{7}",,,,,,, [8], [6, 7]], [,, "(?:(?:2(?:62|77)0|3444)\\d|4[56]440)\\d{3}|(?:34|4[357])700\\d{3}|(?:2(?:[0-3]\\d|5[0-578]|6[01]|82)|3(?:1[3-68]|[23][2-68]|4[23568])|4(?:[23][2-68]|4[3-68]|5[2568]|6[25-8]|7[24-68]|8[4-68]))\\d{5}",,,, "22012345",,,, [6, 7]], [,, "7(?:3555|(?:474|9[019]7)7)\\d{3}|7(?:[0-25-8]\\d\\d|3(?:[1-48]\\d|6[01]|7[01578])|4(?:2\\d|60|7[01578])|9(?:[2-4]\\d|5[01]|7[015]))\\d{4}",,,, "72345678"], [,, "800\\d{5}",,,, "80012345"], [,, "5\\d{7}",,,, "50012345"], [,, "8(?:0[1-9]|[1-9]\\d)\\d{5}",,,, "80123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MK", 389, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["2|34[47]|4(?:[37]7|5[47]|64)"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[347]"], "0$1"], [, "(\\d{3})(\\d)(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[58]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ML: [, [,, "[24-9]\\d{7}",,,,,,, [8]], [,, "2(?:07[0-8]|12[67])\\d{4}|(?:2(?:02|1[4-689])|4(?:0[0-4]|4[1-39]))\\d{5}",,,, "20212345"], [,, "2(?:0(?:01|79)|17\\d)\\d{4}|(?:5[01]|[679]\\d|8[2-49])\\d{6}",,,, "65012345"], [,, "80\\d{6}",,,, "80012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "ML", 223, "00",,,,,,,, [[, "(\\d{4})", "$1", ["67[057-9]|74[045]", "67(?:0[09]|[59]9|77|8[89])|74(?:0[02]|44|55)"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[24-9]"]]], [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[24-9]"]]], [,,,,,,,,, [-1]],,, [,, "80\\d{6}"], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MM: [, [,, "1\\d{5,7}|95\\d{6}|(?:[4-7]|9[0-46-9])\\d{6,8}|(?:2|8\\d)\\d{5,8}",,,,,,, [6, 7, 8, 9, 10], [5]], [,, "(?:1(?:(?:12|[28]\\d|3[56]|7[3-6]|9[0-6])\\d|4(?:2[29]|62|7[0-2]|83)|6)|2(?:2(?:00|8[34])|4(?:0\\d|[26]2|7[0-2]|83)|51\\d\\d)|4(?:2(?:2\\d\\d|48[013])|3(?:20\\d|4(?:70|83)|56)|420\\d|5(?:2\\d|470))|6(?:0(?:[23]|88\\d)|(?:124|[56]2\\d)\\d|2472|3(?:20\\d|470)|4(?:2[04]\\d|472)|7(?:3\\d\\d|4[67]0|8(?:[01459]\\d|8))))\\d{4}|5(?:2(?:2\\d{5,6}|47[02]\\d{4})|(?:3472|4(?:2(?:1|86)|470)|522\\d|6(?:20\\d|483)|7(?:20\\d|48[01])|8(?:20\\d|47[02])|9(?:20\\d|470))\\d{4})|7(?:(?:0470|4(?:25\\d|470)|5(?:202|470|96\\d))\\d{4}|1(?:20\\d{4,5}|4(?:70|83)\\d{4}))|8(?:1(?:2\\d{5,6}|4(?:10|7[01]\\d)\\d{3})|2(?:2\\d{5,6}|(?:320|490\\d)\\d{3})|(?:3(?:2\\d\\d|470)|4[24-7]|5(?:(?:2\\d|51)\\d|4(?:[1-35-9]\\d|4[0-57-9]))|6[23])\\d{4})|(?:1[2-6]\\d|4(?:2[24-8]|3[2-7]|[46][2-6]|5[3-5])|5(?:[27][2-8]|3[2-68]|4[24-8]|5[23]|6[2-4]|8[24-7]|9[2-7])|6(?:[19]20|42[03-6]|(?:52|7[45])\\d)|7(?:[04][24-8]|[15][2-7]|22|3[2-4])|8(?:1[2-689]|2[2-8]|(?:[35]2|64)\\d))\\d{4}|25\\d{5,6}|(?:2[2-9]|6(?:1[2356]|[24][2-6]|3[24-6]|5[2-4]|6[2-8]|7[235-7]|8[245]|9[24])|8(?:3[24]|5[245]))\\d{4}",,,, "1234567",,, [6, 7, 8, 9], [5]], [,, "(?:17[01]|9(?:2(?:[0-4]|[56]\\d\\d)|(?:3(?:[0-36]|4\\d)|(?:6\\d|8[89]|9[4-8])\\d|7(?:3|40|[5-9]\\d))\\d|4(?:(?:[0245]\\d|[1379])\\d|88)|5[0-6])\\d)\\d{4}|9[69]1\\d{6}|9(?:[68]\\d|9[089])\\d{5}",,,, "92123456",,, [7, 8, 9, 10]], [,, "80080(?:0[1-9]|2\\d)\\d{3}",,,, "8008001234",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "1333\\d{4}|[12]468\\d{4}",,,, "13331234",,, [8]], "MM", 95, "00", "0",,, "0",,,, [[, "(\\d)(\\d{2})(\\d{3})", "$1 $2 $3", ["16|2"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3", ["4(?:[2-46]|5[3-5])|5|6(?:[1-689]|7[235-7])|7(?:[0-4]|5[2-7])|8[1-5]|(?:60|86)[23]"], "0$1"], [, "(\\d)(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[12]|452|678|86", "[12]|452|6788|86"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[4-7]|8[1-35]"], "0$1"], [, "(\\d)(\\d{3})(\\d{4,6})", "$1 $2 $3", ["9(?:2[0-4]|[35-9]|4[137-9])"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["92"], "0$1"], [, "(\\d)(\\d{5})(\\d{4})", "$1 $2 $3", ["9"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MN: [, [,, "[12]\\d{7,9}|[5-9]\\d{7}",,,,,,, [8, 9, 10], [4, 5, 6]], [,, "[12]2[1-3]\\d{5,6}|(?:(?:[12](?:1|27)|5[368])\\d\\d|7(?:0(?:[0-5]\\d|7[078]|80)|128))\\d{4}|[12](?:3[2-8]|4[2-68]|5[1-4689])\\d{6,7}",,,, "53123456",,,, [4, 5, 6]], [,, "(?:83[01]|92[039])\\d{5}|(?:5[05]|6[069]|8[015689]|9[013-9])\\d{6}",,,, "88123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "712[0-79]\\d{4}|7(?:1[013-9]|[25-9]\\d)\\d{5}",,,, "75123456",,, [8]], "MN", 976, "001", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3", ["[12]1"], "0$1"], [, "(\\d{4})(\\d{4})", "$1 $2", ["[5-9]"]], [, "(\\d{3})(\\d{5,6})", "$1 $2", ["[12]2[1-3]"], "0$1"], [, "(\\d{4})(\\d{5,6})", "$1 $2", ["[12](?:27|3[2-8]|4[2-68]|5[1-4689])", "[12](?:27|3[2-8]|4[2-68]|5[1-4689])[0-3]"], "0$1"], [, "(\\d{5})(\\d{4,5})", "$1 $2", ["[12]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MO: [, [,, "0800\\d{3}|(?:28|[68]\\d)\\d{6}",,,,,,, [7, 8]], [,, "(?:28[2-9]|8(?:11|[2-57-9]\\d))\\d{5}",,,, "28212345",,, [8]], [,, "6800[0-79]\\d{3}|6(?:[235]\\d\\d|6(?:0[0-5]|[1-9]\\d)|8(?:0[1-9]|[14-8]\\d|2[5-9]|[39][0-4]))\\d{4}",,,, "66123456",,, [8]], [,, "0800\\d{3}",,,, "0800501",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MO", 853, "00",,,,,,,, [[, "(\\d{4})(\\d{3})", "$1 $2", ["0"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[268]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MP: [, [,, "[58]\\d{9}|(?:67|90)0\\d{7}",,,,,,, [10], [7]], [,, "670(?:2(?:3[3-7]|56|8[4-8])|32[1-38]|4(?:33|8[348])|5(?:32|55|88)|6(?:64|70|82)|78[3589]|8[3-9]8|989)\\d{4}",,,, "6702345678",,,, [7]], [,, "670(?:2(?:3[3-7]|56|8[4-8])|32[1-38]|4(?:33|8[348])|5(?:32|55|88)|6(?:64|70|82)|78[3589]|8[3-9]8|989)\\d{4}",,,, "6702345678",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "MP", 1, "011", "1",,, "([2-9]\\d{6})$|1", "670$1",, 1,,, [,,,,,,,,, [-1]],, "670", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MQ: [, [,, "596\\d{6}|(?:69|80|9\\d)\\d{7}",,,,,,, [9]], [,, "596(?:[03-7]\\d|1[05]|2[7-9]|8[0-39]|9[04-9])\\d{4}",,,, "596301234"], [,, "69(?:6(?:[0-46-9]\\d|5[0-6])|727)\\d{4}",,,, "696201234"], [,, "80[0-5]\\d{6}",,,, "800012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:397[0-3]|477[0-5]|76(?:6\\d|7[0-367]))\\d{4}",,,, "976612345"], "MQ", 596, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[569]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MR: [, [,, "(?:[2-4]\\d\\d|800)\\d{5}",,,,,,, [8]], [,, "(?:25[08]|35\\d|45[1-7])\\d{5}",,,, "35123456"], [,, "[2-4][0-46-9]\\d{6}",,,, "22123456"], [,, "800\\d{5}",,,, "80012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MR", 222, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2-48]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MS: [, [,, "(?:[58]\\d\\d|664|900)\\d{7}",,,,,,, [10], [7]], [,, "6644(?:1[0-3]|91)\\d{4}",,,, "6644912345",,,, [7]], [,, "664(?:3(?:49|9[1-6])|49[2-6])\\d{4}",,,, "6644923456",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "MS", 1, "011", "1",,, "([34]\\d{6})$|1", "664$1",,,,, [,,,,,,,,, [-1]],, "664", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MT: [, [,, "3550\\d{4}|(?:[2579]\\d\\d|800)\\d{5}",,,,,,, [8]], [,, "20(?:3[1-4]|6[059])\\d{4}|2(?:0[19]|[1-357]\\d|60)\\d{5}",,,, "21001234"], [,, "(?:7(?:210|[79]\\d\\d)|9(?:[29]\\d\\d|69[67]|8(?:1[1-3]|89|97)))\\d{4}",,,, "96961234"], [,, "800(?:02|[3467]\\d)\\d{3}",,,, "80071234"], [,, "5(?:0(?:0(?:37|43)|(?:6\\d|70|9[0168])\\d)|[12]\\d0[1-5])\\d{3}",,,, "50037123"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "3550\\d{4}",,,, "35501234"], "MT", 356, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[2357-9]"]]],, [,, "7117\\d{4}",,,, "71171234"],,, [,,,,,,,,, [-1]], [,, "501\\d{5}",,,, "50112345"],,, [,,,,,,,,, [-1]]],
          MU: [, [,, "(?:[57]|8\\d\\d)\\d{7}|[2-468]\\d{6}",,,,,,, [7, 8, 10]], [,, "(?:2(?:[0346-8]\\d|1[0-7])|4(?:[013568]\\d|2[4-8]|71)|54(?:[3-5]\\d|71)|6\\d\\d|8(?:14|3[129]))\\d{4}",,,, "54480123",,, [7, 8]], [,, "5(?:4(?:2[1-389]|7[1-9])|87[15-8])\\d{4}|(?:5(?:2[5-9]|4[3-689]|[57]\\d|8[0-689]|9[0-8])|7(?:0[0-4]|3[013]))\\d{5}",,,, "52512345",,, [8]], [,, "802\\d{7}|80[0-2]\\d{4}",,,, "8001234",,, [7, 10]], [,, "30\\d{5}",,,, "3012345",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "3(?:20|9\\d)\\d{4}",,,, "3201234",,, [7]], "MU", 230, "0(?:0|[24-7]0|3[03])",,,,,, "020",, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-46]|8[013]"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[57]"]], [, "(\\d{5})(\\d{5})", "$1 $2", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MV: [, [,, "(?:800|9[0-57-9]\\d)\\d{7}|[34679]\\d{6}",,,,,,, [7, 10]], [,, "(?:3(?:0[0-3]|3[0-59])|6(?:[58][024689]|6[024-68]|7[02468]))\\d{4}",,,, "6701234",,, [7]], [,, "(?:46[46]|[79]\\d\\d)\\d{4}",,,, "7712345",,, [7]], [,, "800\\d{7}",,,, "8001234567",,, [10]], [,, "900\\d{7}",,,, "9001234567",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MV", 960, "0(?:0|19)",,,,,, "00",, [[, "(\\d{3})(\\d{4})", "$1-$2", ["[34679]"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[89]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "4(?:0[01]|50)\\d{4}",,,, "4001234",,, [7]],,, [,,,,,,,,, [-1]]],
          MW: [, [,, "(?:[1289]\\d|31|77)\\d{7}|1\\d{6}",,,,,,, [7, 9]], [,, "(?:1[2-9]|2[12]\\d\\d)\\d{5}",,,, "1234567"], [,, "111\\d{6}|(?:31|77|[89][89])\\d{7}",,,, "991234567",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MW", 265, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["1[2-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[137-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MX: [, [,, "[2-9]\\d{9}",,,,,,, [10], [7, 8]], [,, "657[12]\\d{6}|(?:2(?:0[01]|2\\d|3[1-35-8]|4[13-9]|7[1-689]|8[1-578]|9[467])|3(?:1[1-79]|[2458][1-9]|3\\d|7[1-8]|9[1-5])|4(?:1[1-57-9]|[267][1-9]|3[1-8]|[45]\\d|8[1-35-9]|9[2-689])|5(?:[56]\\d|88|9[1-79])|6(?:1[2-68]|[2-4][1-9]|5[1-3689]|6[0-57-9]|7[1-7]|8[67]|9[4-8])|7(?:[1346][1-9]|[27]\\d|5[13-9]|8[1-69]|9[17])|8(?:1\\d|2[13-689]|3[1-6]|4[124-6]|6[1246-9]|7[0-378]|9[12479])|9(?:1[346-9]|2[1-4]|3[2-46-8]|5[1348]|[69]\\d|7[12]|8[1-8]))\\d{7}",,,, "2001234567",,,, [7, 8]], [,, "657[12]\\d{6}|(?:2(?:2\\d|3[1-35-8]|4[13-9]|7[1-689]|8[1-578]|9[467])|3(?:1[1-79]|[2458][1-9]|3\\d|7[1-8]|9[1-5])|4(?:1[1-57-9]|[267][1-9]|3[1-8]|[45]\\d|8[1-35-9]|9[2-689])|5(?:[56]\\d|88|9[1-79])|6(?:1[2-68]|[2-4][1-9]|5[1-3689]|6[0-57-9]|7[1-7]|8[67]|9[4-8])|7(?:[1346][1-9]|[27]\\d|5[13-9]|8[1-69]|9[17])|8(?:1\\d|2[13-689]|3[1-6]|4[124-6]|6[1246-9]|7[0-378]|9[12479])|9(?:1[346-9]|2[1-4]|3[2-46-8]|5[1348]|[69]\\d|7[12]|8[1-8]))\\d{7}",,,, "2221234567",,,, [7, 8]], [,, "8(?:00|88)\\d{7}",,,, "8001234567"], [,, "900\\d{7}",,,, "9001234567"], [,, "300\\d{7}",,,, "3001234567"], [,, "500\\d{7}",,,, "5001234567"], [,,,,,,,,, [-1]], "MX", 52, "0[09]",,,,,, "00",, [[, "(\\d{5})", "$1", ["53"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["33|5[56]|81"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-9]"]]], [[, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["33|5[56]|81"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[2-9]"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MY: [, [,, "1\\d{8,9}|(?:3\\d|[4-9])\\d{7}",,,,,,, [8, 9, 10], [6, 7]], [,, "4270\\d{4}|(?:3(?:2[0-36-9]|3[0-368]|4[0-278]|5[0-24-8]|6[0-467]|7[1246-9]|8\\d|9[0-57])\\d|4(?:2[0-689]|[3-79]\\d|8[1-35689])|5(?:2[0-589]|[3468]\\d|5[0-489]|7[1-9]|9[23])|6(?:2[2-9]|3[1357-9]|[46]\\d|5[0-6]|7[0-35-9]|85|9[015-8])|7(?:[2579]\\d|3[03-68]|4[0-8]|6[5-9]|8[0-35-9])|8(?:[24][2-8]|3[2-5]|5[2-7]|6[2-589]|7[2-578]|[89][2-9])|9(?:0[57]|13|[25-7]\\d|[3489][0-8]))\\d{5}",,,, "323856789",,, [8, 9], [6, 7]], [,, "1(?:1888[689]|4400|8(?:47|8[27])[0-4])\\d{4}|1(?:0(?:[23568]\\d|4[0-6]|7[016-9]|9[0-8])|1(?:[1-5]\\d\\d|6(?:0[5-9]|[1-9]\\d)|7(?:[0-4]\\d|5[0-7]))|(?:[269]\\d|[37][1-9]|4[235-9])\\d|5(?:31|9\\d\\d)|8(?:1[23]|[236]\\d|4[06]|5(?:46|[7-9])|7[016-9]|8[01]|9[0-8]))\\d{5}",,,, "123456789",,, [9, 10]], [,, "1[378]00\\d{6}",,,, "1300123456",,, [10]], [,, "1600\\d{6}",,,, "1600123456",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "15(?:4(?:6[0-4]\\d|8(?:0[125]|[17]\\d|21|3[01]|4[01589]|5[014]|6[02]))|6(?:32[0-6]|78\\d))\\d{4}",,,, "1546012345",,, [10]], "MY", 60, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1-$2 $3", ["[4-79]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1-$2 $3", ["1(?:[02469]|[378][1-9]|53)|8", "1(?:[02469]|[37][1-9]|53|8(?:[1-46-9]|5[7-9]))|8"], "0$1"], [, "(\\d)(\\d{4})(\\d{4})", "$1-$2 $3", ["3"], "0$1"], [, "(\\d)(\\d{3})(\\d{2})(\\d{4})", "$1-$2-$3-$4", ["1(?:[367]|80)"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2 $3", ["15"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4})", "$1-$2 $3", ["1"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          MZ: [, [,, "(?:2|8\\d)\\d{7}",,,,,,, [8, 9]], [,, "2(?:[1346]\\d|5[0-2]|[78][12]|93)\\d{5}",,,, "21123456",,, [8]], [,, "8[2-79]\\d{7}",,,, "821234567",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "MZ", 258, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2|8[2-79]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NA: [, [,, "[68]\\d{7,8}",,,,,,, [8, 9]], [,, "64426\\d{3}|6(?:1(?:2[2-7]|3[01378]|4[0-4])|254|32[0237]|4(?:27|41|5[25])|52[236-8]|626|7(?:2[2-4]|30))\\d{4,5}|6(?:1(?:(?:0\\d|2[0189]|3[24-69]|4[5-9])\\d|17|69|7[014])|2(?:17|5[0-36-8]|69|70)|3(?:17|2[14-689]|34|6[289]|7[01]|81)|4(?:17|2[0-2]|4[06]|5[0137]|69|7[01])|5(?:17|2[0459]|69|7[01])|6(?:17|25|38|42|69|7[01])|7(?:17|2[569]|3[13]|6[89]|7[01]))\\d{4}",,,, "61221234"], [,, "(?:60|8[1245])\\d{7}",,,, "811234567",,, [9]], [,, "80\\d{7}",,,, "800123456",,, [9]], [,, "8701\\d{5}",,,, "870123456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "8(?:3\\d\\d|86)\\d{5}",,,, "88612345"], "NA", 264, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["88"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["6"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["87"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NC: [, [,, "(?:050|[2-57-9]\\d\\d)\\d{3}",,,,,,, [6]], [,, "(?:2[03-9]|3[0-5]|4[1-7]|88)\\d{4}",,,, "201234"], [,, "(?:5[0-4]|[79]\\d|8[0-79])\\d{4}",,,, "751234"], [,, "050\\d{3}",,,, "050012"], [,, "36\\d{4}",,,, "366711"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NC", 687, "00",,,,,,,, [[, "(\\d{3})", "$1", ["5[6-8]"]], [, "(\\d{2})(\\d{2})(\\d{2})", "$1.$2.$3", ["[02-57-9]"]]], [[, "(\\d{2})(\\d{2})(\\d{2})", "$1.$2.$3", ["[02-57-9]"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NE: [, [,, "[027-9]\\d{7}",,,,,,, [8]], [,, "2(?:0(?:20|3[1-8]|4[13-5]|5[14]|6[14578]|7[1-578])|1(?:4[145]|5[14]|6[14-68]|7[169]|88))\\d{4}",,,, "20201234"], [,, "(?:23|7[0467]|[89]\\d)\\d{6}",,,, "93123456"], [,, "08\\d{6}",,,, "08123456"], [,, "09\\d{6}",,,, "09123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NE", 227, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["08"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[089]|2[013]|7[0467]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NF: [, [,, "[13]\\d{5}",,,,,,, [6], [5]], [,, "(?:1(?:06|17|28|39)|3[0-2]\\d)\\d{3}",,,, "106609",,,, [5]], [,, "(?:14|3[58])\\d{4}",,,, "381234",,,, [5]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NF", 672, "00",,,, "([0-258]\\d{4})$", "3$1",,, [[, "(\\d{2})(\\d{4})", "$1 $2", ["1[0-3]"]], [, "(\\d)(\\d{5})", "$1 $2", ["[13]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NG: [, [,, "38\\d{6}|[78]\\d{9,13}|(?:20|9\\d)\\d{8}",,,,,,, [8, 10, 11, 12, 13, 14], [6, 7]], [,, "(?:20(?:[1259]\\d|3[013-9]|4[1-8]|6[024-689]|7[1-79]|8[2-9])|38)\\d{6}",,,, "2033123456",,, [8, 10], [6, 7]], [,, "(?:702[0-24-9]|819[01])\\d{6}|(?:7(?:0[13-9]|[12]\\d)|8(?:0[1-9]|1[0-8])|9(?:0[1-9]|1[1-6]))\\d{7}",,,, "8021234567",,, [10]], [,, "800\\d{7,11}",,,, "80017591759",,, [10, 11, 12, 13, 14]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NG", 234, "009", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{2,3})", "$1 $2 $3", ["3"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[7-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["20[129]"], "0$1"], [, "(\\d{4})(\\d{2})(\\d{4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{3})(\\d{4})(\\d{4,5})", "$1 $2 $3", ["[78]"], "0$1"], [, "(\\d{3})(\\d{5})(\\d{5,6})", "$1 $2 $3", ["[78]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "700\\d{7,11}",,,, "7001234567",,, [10, 11, 12, 13, 14]],,, [,,,,,,,,, [-1]]],
          NI: [, [,, "(?:1800|[25-8]\\d{3})\\d{4}",,,,,,, [8]], [,, "2\\d{7}",,,, "21234567"], [,, "(?:5(?:5[0-7]|[78]\\d)|6(?:20|3[035]|4[045]|5[05]|77|8[1-9]|9[059])|(?:7[5-8]|8\\d)\\d)\\d{5}",,,, "81234567"], [,, "1800\\d{4}",,,, "18001234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NI", 505, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[125-8]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NL: [, [,, "(?:[124-7]\\d\\d|3(?:[02-9]\\d|1[0-8]))\\d{6}|8\\d{6,9}|9\\d{6,10}|1\\d{4,5}",,,,,,, [5, 6, 7, 8, 9, 10, 11]], [,, "(?:1(?:[035]\\d|1[13-578]|6[124-8]|7[24]|8[0-467])|2(?:[0346]\\d|2[2-46-9]|5[125]|9[479])|3(?:[03568]\\d|1[3-8]|2[01]|4[1-8])|4(?:[0356]\\d|1[1-368]|7[58]|8[15-8]|9[23579])|5(?:[0358]\\d|[19][1-9]|2[1-57-9]|4[13-8]|6[126]|7[0-3578])|7\\d\\d)\\d{6}",,,, "101234567",,, [9]], [,, "(?:6[1-58]|970\\d)\\d{7}",,,, "612345678",,, [9, 11]], [,, "800\\d{4,7}",,,, "8001234",,, [7, 8, 9, 10]], [,, "90[069]\\d{4,7}",,,, "9061234",,, [7, 8, 9, 10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:85|91)\\d{7}",,,, "851234567",,, [9]], "NL", 31, "00", "0",,, "0",,,, [[, "(\\d{4})", "$1", ["1[238]|[34]"]], [, "(\\d{2})(\\d{3,4})", "$1 $2", ["14"]], [, "(\\d{6})", "$1", ["1"]], [, "(\\d{3})(\\d{4,7})", "$1 $2", ["[89]0"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["66"], "0$1"], [, "(\\d)(\\d{8})", "$1 $2", ["6"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["1[16-8]|2[259]|3[124]|4[17-9]|5[124679]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[1-578]|91"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{5})", "$1 $2 $3", ["9"], "0$1"]], [[, "(\\d{3})(\\d{4,7})", "$1 $2", ["[89]0"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["66"], "0$1"], [, "(\\d)(\\d{8})", "$1 $2", ["6"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["1[16-8]|2[259]|3[124]|4[17-9]|5[124679]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[1-578]|91"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{5})", "$1 $2 $3", ["9"], "0$1"]], [,, "66\\d{7}",,,, "662345678",,, [9]],,, [,, "140(?:1[035]|2[0346]|3[03568]|4[0356]|5[0358]|8[458])|140(?:1[16-8]|2[259]|3[124]|4[17-9]|5[124679]|7)\\d",,,,,,, [5, 6]], [,, "140(?:1[035]|2[0346]|3[03568]|4[0356]|5[0358]|8[458])|(?:140(?:1[16-8]|2[259]|3[124]|4[17-9]|5[124679]|7)|8[478]\\d{6})\\d",,,, "14020",,, [5, 6, 9]],,, [,,,,,,,,, [-1]]],
          NO: [, [,, "(?:0|[2-9]\\d{3})\\d{4}",,,,,,, [5, 8]], [,, "(?:2[1-4]|3[1-3578]|5[1-35-7]|6[1-4679]|7[0-8])\\d{6}",,,, "21234567",,, [8]], [,, "(?:4[015-8]|9\\d)\\d{6}",,,, "40612345",,, [8]], [,, "80[01]\\d{5}",,,, "80012345",,, [8]], [,, "82[09]\\d{5}",,,, "82012345",,, [8]], [,, "810(?:0[0-6]|[2-8]\\d)\\d{3}",,,, "81021234",,, [8]], [,, "880\\d{5}",,,, "88012345",,, [8]], [,, "85[0-5]\\d{5}",,,, "85012345",,, [8]], "NO", 47, "00",,,,,,,, [[, "(\\d{3})(\\d{2})(\\d{3})", "$1 $2 $3", ["8"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2-79]"]]],, [,,,,,,,,, [-1]], 1, "[02-689]|7[0-8]", [,,,,,,,,, [-1]], [,, "(?:0[235-9]|81(?:0(?:0[7-9]|1\\d)|5\\d\\d))\\d{3}",,,, "02000"],,, [,, "81[23]\\d{5}",,,, "81212345",,, [8]]],
          NP: [, [,, "(?:1\\d|9)\\d{9}|[1-9]\\d{7}",,,,,,, [8, 10, 11], [6, 7]], [,, "(?:1[0-6]\\d|99[02-6])\\d{5}|(?:2[13-79]|3[135-8]|4[146-9]|5[135-7]|6[13-9]|7[15-9]|8[1-46-9]|9[1-7])[2-6]\\d{5}",,,, "14567890",,, [8], [6, 7]], [,, "9(?:00|6[0-3]|7[024-6]|8[0-24-68])\\d{7}",,,, "9841234567",,, [10]], [,, "1(?:66001|800\\d\\d)\\d{5}",,,, "16600101234",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NP", 977, "00", "0",,, "0",,,, [[, "(\\d)(\\d{7})", "$1-$2", ["1[2-6]"], "0$1"], [, "(\\d{2})(\\d{6})", "$1-$2", ["1[01]|[2-8]|9(?:[1-59]|[67][2-6])"], "0$1"], [, "(\\d{3})(\\d{7})", "$1-$2", ["9"]], [, "(\\d{4})(\\d{2})(\\d{5})", "$1-$2-$3", ["1"]]], [[, "(\\d)(\\d{7})", "$1-$2", ["1[2-6]"], "0$1"], [, "(\\d{2})(\\d{6})", "$1-$2", ["1[01]|[2-8]|9(?:[1-59]|[67][2-6])"], "0$1"], [, "(\\d{3})(\\d{7})", "$1-$2", ["9"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NR: [, [,, "(?:444|(?:55|8\\d)\\d|666)\\d{4}",,,,,,, [7]], [,, "444\\d{4}",,,, "4441234"], [,, "(?:55[3-9]|666|8\\d\\d)\\d{4}",,,, "5551234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NR", 674, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[4-68]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NU: [, [,, "(?:[4-7]|888\\d)\\d{3}",,,,,,, [4, 7]], [,, "[47]\\d{3}",,,, "7012",,, [4]], [,, "(?:[56]|888[1-9])\\d{3}",,,, "8884012"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "NU", 683, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          NZ: [, [,, "[1289]\\d{9}|50\\d{5}(?:\\d{2,3})?|[27-9]\\d{7,8}|(?:[34]\\d|6[0-35-9])\\d{6}|8\\d{4,6}",,,,,,, [5, 6, 7, 8, 9, 10]], [,, "240\\d{5}|(?:3[2-79]|[49][2-9]|6[235-9]|7[2-57-9])\\d{6}",,,, "32345678",,, [8], [7]], [,, "2(?:[0-27-9]\\d|6)\\d{6,7}|2(?:1\\d|75)\\d{5}",,,, "211234567",,, [8, 9, 10]], [,, "508\\d{6,7}|80\\d{6,8}",,,, "800123456",,, [8, 9, 10]], [,, "(?:1[13-57-9]\\d{5}|50(?:0[08]|30|66|77|88))\\d{3}|90\\d{6,8}",,,, "900123456",,, [7, 8, 9, 10]], [,,,,,,,,, [-1]], [,, "70\\d{7}",,,, "701234567",,, [9]], [,,,,,,,,, [-1]], "NZ", 64, "0(?:0|161)", "0",,, "0",, "00",, [[, "(\\d{2})(\\d{3,8})", "$1 $2", ["8[1-79]"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["50[036-8]|8|90", "50(?:[0367]|88)|8|90"], "0$1"], [, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["24|[346]|7[2-57-9]|9[2-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2(?:10|74)|[589]"], "0$1"], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["1|2[028]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,5})", "$1 $2 $3", ["2(?:[169]|7[0-35-9])|7"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "8(?:1[16-9]|22|3\\d|4[045]|5[459]|6[235-9]|7[0-3579]|90)\\d{2,7}",,,, "83012378"],,, [,,,,,,,,, [-1]]],
          OM: [, [,, "(?:1505|[279]\\d{3}|500)\\d{4}|800\\d{5,6}",,,,,,, [7, 8, 9]], [,, "2[1-6]\\d{6}",,,, "23123456",,, [8]], [,, "(?:1505|90[1-9]\\d)\\d{4}|(?:7[126-9]|9[1-9])\\d{6}",,,, "92123456",,, [8]], [,, "8007\\d{4,5}|(?:500|800[05])\\d{4}",,,, "80071234"], [,, "900\\d{5}",,,, "90012345",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "OM", 968, "00",,,,,,,, [[, "(\\d{3})(\\d{4,6})", "$1 $2", ["[58]"]], [, "(\\d{2})(\\d{6})", "$1 $2", ["2"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[179]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PA: [, [,, "(?:00800|8\\d{3})\\d{6}|[68]\\d{7}|[1-57-9]\\d{6}",,,,,,, [7, 8, 10, 11]], [,, "(?:1(?:0\\d|1[479]|2[37]|3[0137]|4[17]|5[05]|6[058]|7[0167]|8[2358]|9[1389])|2(?:[0235-79]\\d|1[0-7]|4[013-9]|8[02-9])|3(?:[07-9]\\d|1[0-7]|2[0-5]|33|4[0-79]|5[0-35]|6[068])|4(?:00|3[0-579]|4\\d|7[0-57-9])|5(?:[01]\\d|2[0-7]|[56]0|79)|7(?:0[09]|2[0-26-8]|3[03]|4[04]|5[05-9]|6[0156]|7[0-24-9]|8[5-9]|90)|8(?:09|2[89]|3\\d|4[0-24-689]|5[014]|8[02])|9(?:0[5-9]|1[0135-8]|2[036-9]|3[35-79]|40|5[0457-9]|6[05-9]|7[04-9]|8[35-8]|9\\d))\\d{4}",,,, "2001234",,, [7]], [,, "(?:1[16]1|21[89]|6\\d{3}|8(?:1[01]|7[23]))\\d{4}",,,, "61234567",,, [7, 8]], [,, "800\\d{4,5}|(?:00800|800\\d)\\d{6}",,,, "8001234"], [,, "(?:8(?:22|55|60|7[78]|86)|9(?:00|81))\\d{4}",,,, "8601234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "PA", 507, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1-$2", ["[1-57-9]"]], [, "(\\d{4})(\\d{4})", "$1-$2", ["[68]"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PE: [, [,, "(?:[14-8]|9\\d)\\d{7}",,,,,,, [8, 9], [6, 7]], [,, "(?:(?:(?:4[34]|5[14])[0-8]|687)\\d|7(?:173|(?:3[0-8]|55)\\d)|8(?:10[05689]|6(?:0[06-9]|1[6-9]|29)|7(?:0[0569]|[56]0)))\\d{4}|(?:1[0-8]|4[12]|5[236]|6[1-7]|7[246]|8[2-4])\\d{6}",,,, "11234567",,, [8], [6, 7]], [,, "9\\d{8}",,,, "912345678",,, [9]], [,, "800\\d{5}",,,, "80012345",,, [8]], [,, "805\\d{5}",,,, "80512345",,, [8]], [,, "801\\d{5}",,,, "80112345",,, [8]], [,, "80[24]\\d{5}",,,, "80212345",,, [8]], [,,,,,,,,, [-1]], "PE", 51, "00|19(?:1[124]|77|90)00", "0", " Anexo ",, "0",, "00",, [[, "(\\d{3})(\\d{5})", "$1 $2", ["80"], "(0$1)"], [, "(\\d)(\\d{7})", "$1 $2", ["1"], "(0$1)"], [, "(\\d{2})(\\d{6})", "$1 $2", ["[4-8]"], "(0$1)"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["9"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PF: [, [,, "4\\d{5}(?:\\d{2})?|8\\d{7,8}",,,,,,, [6, 8, 9]], [,, "4(?:0[4-689]|9[4-68])\\d{5}",,,, "40412345",,, [8]], [,, "8[7-9]\\d{6}",,,, "87123456",,, [8]], [,, "80[0-5]\\d{6}",,,, "800012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "499\\d{5}",,,, "49901234",,, [8]], "PF", 689, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["44"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["4|8[7-9]"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"]]],, [,,,,,,,,, [-1]],,, [,, "44\\d{4}",,,,,,, [6]], [,, "44\\d{4}",,,, "440123",,, [6]],,, [,,,,,,,,, [-1]]],
          PG: [, [,, "(?:180|[78]\\d{3})\\d{4}|(?:[2-589]\\d|64)\\d{5}",,,,,,, [7, 8]], [,, "(?:(?:3[0-2]|4[257]|5[34]|9[78])\\d|64[1-9]|85[02-46-9])\\d{4}",,,, "3123456",,, [7]], [,, "(?:7\\d|8[1-38])\\d{6}",,,, "70123456",,, [8]], [,, "180\\d{4}",,,, "1801234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "2(?:0[0-57]|7[568])\\d{4}",,,, "2751234",,, [7]], "PG", 675, "00|140[1-3]",,,,,, "00",, [[, "(\\d{3})(\\d{4})", "$1 $2", ["18|[2-69]|85"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[78]"]]],, [,, "27[01]\\d{4}",,,, "2700123",,, [7]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PH: [, [,, "(?:[2-7]|9\\d)\\d{8}|2\\d{5}|(?:1800|8)\\d{7,9}",,,,,,, [6, 8, 9, 10, 11, 12, 13], [4, 5, 7]], [,, "(?:(?:2[3-8]|3[2-68]|4[2-9]|5[2-6]|6[2-58]|7[24578])\\d{3}|88(?:22\\d\\d|42))\\d{4}|(?:2|8[2-8]\\d\\d)\\d{5}",,,, "232345678",,, [6, 8, 9, 10], [4, 5, 7]], [,, "(?:8(?:1[37]|9[5-8])|9(?:0[5-9]|1[0-24-9]|[235-7]\\d|4[2-9]|8[135-9]|9[1-9]))\\d{7}",,,, "9051234567",,, [10]], [,, "1800\\d{7,9}",,,, "180012345678",,, [11, 12, 13]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "PH", 63, "00", "0",,, "0",,,, [[, "(\\d)(\\d{5})", "$1 $2", ["2"], "(0$1)"], [, "(\\d{4})(\\d{4,6})", "$1 $2", ["3(?:23|39|46)|4(?:2[3-6]|[35]9|4[26]|76)|544|88[245]|(?:52|64|86)2", "3(?:230|397|461)|4(?:2(?:35|[46]4|51)|396|4(?:22|63)|59[347]|76[15])|5(?:221|446)|642[23]|8(?:622|8(?:[24]2|5[13]))"], "(0$1)"], [, "(\\d{5})(\\d{4})", "$1 $2", ["346|4(?:27|9[35])|883", "3469|4(?:279|9(?:30|56))|8834"], "(0$1)"], [, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["2"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[3-7]|8[2-8]"], "(0$1)"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["[89]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]], [, "(\\d{4})(\\d{1,2})(\\d{3})(\\d{4})", "$1 $2 $3 $4", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PK: [, [,, "122\\d{6}|[24-8]\\d{10,11}|9(?:[013-9]\\d{8,10}|2(?:[01]\\d\\d|2(?:[06-8]\\d|1[01]))\\d{7})|(?:[2-8]\\d{3}|92(?:[0-7]\\d|8[1-9]))\\d{6}|[24-9]\\d{8}|[89]\\d{7}",,,,,,, [8, 9, 10, 11, 12], [5, 6, 7]], [,, "(?:(?:21|42)[2-9]|58[126])\\d{7}|(?:2[25]|4[0146-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91)[2-9]\\d{6,7}|(?:2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:2[2-8]|3[27-9]|4[2-6]|6[3569]|9[25-8]))[2-9]\\d{5,6}",,,, "2123456789",,, [9, 10], [5, 6, 7, 8]], [,, "3(?:[0-247]\\d|3[0-79]|55|64)\\d{7}",,,, "3012345678",,, [10]], [,, "800\\d{5}(?:\\d{3})?",,,, "80012345",,, [8, 11]], [,, "900\\d{5}",,,, "90012345",,, [8]], [,,,,,,,,, [-1]], [,, "122\\d{6}",,,, "122044444",,, [9]], [,,,,,,,,, [-1]], "PK", 92, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})(\\d{2,7})", "$1 $2 $3", ["[89]0"], "0$1"], [, "(\\d{4})(\\d{5})", "$1 $2", ["1"]], [, "(\\d{3})(\\d{6,7})", "$1 $2", ["2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:2[2-8]|3[27-9]|4[2-6]|6[3569]|9[25-8])", "9(?:2[3-8]|98)|(?:2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:22|3[27-9]|4[2-6]|6[3569]|9[25-7]))[2-9]"], "(0$1)"], [, "(\\d{2})(\\d{7,8})", "$1 $2", ["(?:2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91)[2-9]"], "(0$1)"], [, "(\\d{5})(\\d{5})", "$1 $2", ["58"], "(0$1)"], [, "(\\d{3})(\\d{7})", "$1 $2", ["3"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91"], "(0$1)"], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["[24-9]"], "(0$1)"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "(?:2(?:[125]|3[2358]|4[2-4]|9[2-8])|4(?:[0-246-9]|5[3479])|5(?:[1-35-7]|4[2-467])|6(?:0[468]|[1-8])|7(?:[14]|2[236])|8(?:[16]|2[2-689]|3[23578]|4[3478]|5[2356])|9(?:1|22|3[27-9]|4[2-6]|6[3569]|9[2-7]))111\\d{6}",,,, "21111825888",,, [11, 12]],,, [,,,,,,,,, [-1]]],
          PL: [, [,, "(?:6|8\\d\\d)\\d{7}|[1-9]\\d{6}(?:\\d{2})?|[26]\\d{5}",,,,,,, [6, 7, 8, 9, 10]], [,, "47\\d{7}|(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])(?:[02-9]\\d{6}|1(?:[0-8]\\d{5}|9\\d{3}(?:\\d{2})?))",,,, "123456789",,, [7, 9]], [,, "21(?:1[013-5]|2\\d)\\d{5}|(?:45|5[0137]|6[069]|7[2389]|88)\\d{7}",,,, "512345678",,, [9]], [,, "800\\d{6,7}",,,, "800123456",,, [9, 10]], [,, "70[01346-8]\\d{6}",,,, "701234567",,, [9]], [,, "801\\d{6}",,,, "801234567",,, [9]], [,,,,,,,,, [-1]], [,, "39\\d{7}",,,, "391234567",,, [9]], "PL", 48, "00",,,,,,,, [[, "(\\d{5})", "$1", ["19"]], [, "(\\d{3})(\\d{3})", "$1 $2", ["11|20|64"]], [, "(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3", ["(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])1", "(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])19"]], [, "(\\d{3})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["64"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["21|39|45|5[0137]|6[0469]|7[02389]|8(?:0[14]|8)"]], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[2-8]|[2-7]|8[1-79]|9[145]"]], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["8"]]],, [,, "64\\d{4,7}",,,, "641234567",,, [6, 7, 8, 9]],,, [,,,,,,,,, [-1]], [,, "804\\d{6}",,,, "804123456",,, [9]],,, [,,,,,,,,, [-1]]],
          PM: [, [,, "[45]\\d{5}|(?:708|80\\d)\\d{6}",,,,,,, [6, 9]], [,, "(?:4[1-35-7]|5[01])\\d{4}",,,, "430123",,, [6]], [,, "(?:4[02-4]|5[056]|708[45][0-5])\\d{4}",,,, "551234"], [,, "80[0-5]\\d{6}",,,, "800012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "PM", 508, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["[45]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["7"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PR: [, [,, "(?:[589]\\d\\d|787)\\d{7}",,,,,,, [10], [7]], [,, "(?:787|939)[2-9]\\d{6}",,,, "7872345678",,,, [7]], [,, "(?:787|939)[2-9]\\d{6}",,,, "7872345678",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "PR", 1, "011", "1",,, "1",,, 1,,, [,,,,,,,,, [-1]],, "787|939", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PS: [, [,, "[2489]2\\d{6}|(?:1\\d|5)\\d{8}",,,,,,, [8, 9, 10], [7]], [,, "(?:22[2-47-9]|42[45]|82[014-68]|92[3569])\\d{5}",,,, "22234567",,, [8], [7]], [,, "5[69]\\d{7}",,,, "599123456",,, [9]], [,, "1800\\d{6}",,,, "1800123456",,, [10]], [,,,,,,,,, [-1]], [,, "1700\\d{6}",,,, "1700123456",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "PS", 970, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["[2489]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["5"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PT: [, [,, "1693\\d{5}|(?:[26-9]\\d|30)\\d{7}",,,,,,, [9]], [,, "2(?:[12]\\d|3[1-689]|4[1-59]|[57][1-9]|6[1-35689]|8[1-69]|9[1256])\\d{6}",,,, "212345678"], [,, "6(?:[06]92(?:30|9\\d)|[35]92(?:[049]\\d|3[034]))\\d{3}|(?:(?:16|6[0356])93|9(?:[1-36]\\d\\d|480))\\d{5}",,,, "912345678"], [,, "80[02]\\d{6}",,,, "800123456"], [,, "(?:6(?:0[178]|4[68])\\d|76(?:0[1-57]|1[2-47]|2[237]))\\d{5}",,,, "760123456"], [,, "80(?:8\\d|9[1579])\\d{5}",,,, "808123456"], [,, "884[0-4689]\\d{5}",,,, "884123456"], [,, "30\\d{7}",,,, "301234567"], "PT", 351, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["2[12]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["16|[236-9]"]]],, [,, "6(?:222\\d|8988)\\d{4}",,,, "622212345"],,, [,,,,,,,,, [-1]], [,, "70(?:38[01]|596|(?:7\\d|8[17])\\d)\\d{4}",,,, "707123456"],,, [,, "600\\d{6}|6[06]92(?:0\\d|3[349]|49)\\d{3}",,,, "600110000"]],
          PW: [, [,, "(?:[24-8]\\d\\d|345|900)\\d{4}",,,,,,, [7]], [,, "(?:2(?:55|77)|345|488|5(?:35|44|87)|6(?:22|54|79)|7(?:33|47)|8(?:24|55|76)|900)\\d{4}",,,, "2771234"], [,, "(?:(?:46|83)[0-5]|6[2-4689]0)\\d{4}|(?:45|77|88)\\d{5}",,,, "6201234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "PW", 680, "01[12]",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          PY: [, [,, "59\\d{4,6}|9\\d{5,10}|(?:[2-46-8]\\d|5[0-8])\\d{4,7}",,,,,,, [6, 7, 8, 9, 10, 11], [5]], [,, "(?:[26]1|3[289]|4[1246-8]|7[1-3]|8[1-36])\\d{5,7}|(?:2(?:2[4-68]|[4-68]\\d|7[15]|9[1-5])|3(?:18|3[167]|4[2357]|51|[67]\\d)|4(?:3[12]|5[13]|9[1-47])|5(?:[1-4]\\d|5[02-4])|6(?:3[1-3]|44|7[1-8])|7(?:4[0-4]|5\\d|6[1-578]|75|8[0-8])|858)\\d{5,6}",,,, "212345678",,, [7, 8, 9], [5, 6]], [,, "9(?:51|6[129]|7[1-6]|8[1-7]|9[1-5])\\d{6}",,,, "961456789",,, [9]], [,, "9800\\d{5,7}",,,, "98000123456",,, [9, 10, 11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "8700[0-4]\\d{4}",,,, "870012345",,, [9]], "PY", 595, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3,6})", "$1 $2", ["[2-9]0"], "0$1"], [, "(\\d{2})(\\d{5})", "$1 $2", ["[26]1|3[289]|4[1246-8]|7[1-3]|8[1-36]"], "(0$1)"], [, "(\\d{3})(\\d{4,5})", "$1 $2", ["2[279]|3[13-5]|4[359]|5|6(?:[34]|7[1-46-8])|7[46-8]|85"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2[14-68]|3[26-9]|4[1246-8]|6(?:1|75)|7[1-35]|8[1-36]"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["87"]], [, "(\\d{3})(\\d{6})", "$1 $2", ["9(?:[5-79]|8[1-7])"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-8]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["9"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "[2-9]0\\d{4,7}",,,, "201234567",,, [6, 7, 8, 9]],,, [,,,,,,,,, [-1]]],
          QA: [, [,, "800\\d{4}|(?:2|800)\\d{6}|(?:0080|[3-7])\\d{7}",,,,,,, [7, 8, 9, 11]], [,, "4(?:1111|2022)\\d{3}|4(?:[04]\\d\\d|14[0-6]|999)\\d{4}",,,, "44123456",,, [8]], [,, "[35-7]\\d{7}",,,, "33123456",,, [8]], [,, "800\\d{4}|(?:0080[01]|800)\\d{6}",,,, "8001234",,, [7, 9, 11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "QA", 974, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["2[16]|8"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[3-7]"]]],, [,, "2[16]\\d{5}",,,, "2123456",,, [7]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          RE: [, [,, "(?:26|[689]\\d)\\d{7}",,,,,,, [9]], [,, "26(?:2\\d\\d|3(?:0\\d|1[0-6]))\\d{4}",,,, "262161234"], [,, "69(?:2\\d\\d|3(?:[06][0-6]|1[013]|2[0-2]|3[0-39]|4\\d|5[0-5]|7[0-37]|8[0-8]|9[0-479]))\\d{4}",,,, "692123456"], [,, "80\\d{7}",,,, "801234567"], [,, "89[1-37-9]\\d{6}",,,, "891123456"], [,, "8(?:1[019]|2[0156]|84|90)\\d{6}",,,, "810123456"], [,,,,,,,,, [-1]], [,, "9(?:399[0-3]|479[0-5]|76(?:2[278]|3[0-37]))\\d{4}",,,, "939901234"], "RE", 262, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[2689]"], "0$1"]],, [,,,,,,,,, [-1]], 1,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          RO: [, [,, "(?:[236-8]\\d|90)\\d{7}|[23]\\d{5}",,,,,,, [6, 9]], [,, "[23][13-6]\\d{7}|(?:2(?:19\\d|[3-6]\\d9)|31\\d\\d)\\d\\d",,,, "211234567"], [,, "(?:630|702)0\\d{5}|(?:6(?:00|2\\d)|7(?:0[013-9]|1[0-3]|[2-7]\\d|8[03-8]|9[0-39]))\\d{6}",,,, "712034567",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "90[0136]\\d{6}",,,, "900123456",,, [9]], [,, "801\\d{6}",,,, "801123456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "RO", 40, "00", "0", " int ",, "0",,,, [[, "(\\d{3})(\\d{3})", "$1 $2", ["2[3-6]", "2[3-6]\\d9"], "0$1"], [, "(\\d{2})(\\d{4})", "$1 $2", ["219|31"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[23]1"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[236-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "(?:37\\d|80[578])\\d{6}",,,, "372123456",,, [9]],,, [,,,,,,,,, [-1]]],
          RS: [, [,, "38[02-9]\\d{6,9}|6\\d{7,9}|90\\d{4,8}|38\\d{5,6}|(?:7\\d\\d|800)\\d{3,9}|(?:[12]\\d|3[0-79])\\d{5,10}",,,,,,, [6, 7, 8, 9, 10, 11, 12], [4, 5]], [,, "(?:11[1-9]\\d|(?:2[389]|39)(?:0[2-9]|[2-9]\\d))\\d{3,8}|(?:1[02-9]|2[0-24-7]|3[0-8])[2-9]\\d{4,9}",,,, "10234567",,, [7, 8, 9, 10, 11, 12], [4, 5, 6]], [,, "6(?:[0-689]|7\\d)\\d{6,7}",,,, "601234567",,, [8, 9, 10]], [,, "800\\d{3,9}",,,, "80012345"], [,, "(?:78\\d|90[0169])\\d{3,7}",,,, "90012345",,, [6, 7, 8, 9, 10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "RS", 381, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3,9})", "$1 $2", ["(?:2[389]|39)0|[7-9]"], "0$1"], [, "(\\d{2})(\\d{5,10})", "$1 $2", ["[1-36]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "7[06]\\d{4,10}",,,, "700123456"],,, [,,,,,,,,, [-1]]],
          RU: [, [,, "8\\d{13}|[347-9]\\d{9}",,,,,,, [10, 14], [7]], [,, "(?:3(?:0[12]|4[1-35-79]|5[1-3]|65|8[1-58]|9[0145])|4(?:01|1[1356]|2[13467]|7[1-5]|8[1-7]|9[1-689])|8(?:1[1-8]|2[01]|3[13-6]|4[0-8]|5[15]|6[1-35-79]|7[1-37-9]))\\d{7}",,,, "3011234567",,, [10], [7]], [,, "9\\d{9}",,,, "9123456789",,, [10]], [,, "8(?:0[04]|108\\d{3})\\d{7}",,,, "8001234567"], [,, "80[39]\\d{7}",,,, "8091234567",,, [10]], [,,,,,,,,, [-1]], [,, "808\\d{7}",,,, "8081234567",,, [10]], [,,,,,,,,, [-1]], "RU", 7, "810", "8",,, "8",, "8~10",, [[, "(\\d{3})(\\d{2})(\\d{2})", "$1-$2-$3", ["[0-79]"]], [, "(\\d{4})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["7(?:1[0-8]|2[1-9])", "7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:1[23]|[2-9]2))", "7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:13[03-69]|62[013-9]))|72[1-57-9]2"], "8 ($1)",, 1], [, "(\\d{5})(\\d)(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["7(?:1[0-68]|2[1-9])", "7(?:1(?:[06][3-6]|[18]|2[35]|[3-5][3-5])|2(?:[13][3-5]|[24-689]|7[457]))", "7(?:1(?:0(?:[356]|4[023])|[18]|2(?:3[013-9]|5)|3[45]|43[013-79]|5(?:3[1-8]|4[1-7]|5)|6(?:3[0-35-9]|[4-6]))|2(?:1(?:3[178]|[45])|[24-689]|3[35]|7[457]))|7(?:14|23)4[0-8]|71(?:33|45)[1-79]"], "8 ($1)",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["7"], "8 ($1)",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["[349]|8(?:[02-7]|1[1-8])"], "8 ($1)",, 1], [, "(\\d{4})(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["8"], "8 ($1)"]], [[, "(\\d{4})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["7(?:1[0-8]|2[1-9])", "7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:1[23]|[2-9]2))", "7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:13[03-69]|62[013-9]))|72[1-57-9]2"], "8 ($1)",, 1], [, "(\\d{5})(\\d)(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["7(?:1[0-68]|2[1-9])", "7(?:1(?:[06][3-6]|[18]|2[35]|[3-5][3-5])|2(?:[13][3-5]|[24-689]|7[457]))", "7(?:1(?:0(?:[356]|4[023])|[18]|2(?:3[013-9]|5)|3[45]|43[013-79]|5(?:3[1-8]|4[1-7]|5)|6(?:3[0-35-9]|[4-6]))|2(?:1(?:3[178]|[45])|[24-689]|3[35]|7[457]))|7(?:14|23)4[0-8]|71(?:33|45)[1-79]"], "8 ($1)",, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["7"], "8 ($1)",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["[349]|8(?:[02-7]|1[1-8])"], "8 ($1)",, 1], [, "(\\d{4})(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["8"], "8 ($1)"]], [,,,,,,,,, [-1]], 1, "3[04-689]|[489]", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          RW: [, [,, "(?:06|[27]\\d\\d|[89]00)\\d{6}",,,,,,, [8, 9]], [,, "(?:06|2[23568]\\d)\\d{6}",,,, "250123456"], [,, "7[237-9]\\d{7}",,,, "720123456",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "900\\d{6}",,,, "900123456",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "RW", 250, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["0"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["2"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[7-9]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SA: [, [,, "92\\d{7}|(?:[15]|8\\d)\\d{8}",,,,,,, [9, 10], [7]], [,, "1(?:1\\d|2[24-8]|3[35-8]|4[3-68]|6[2-5]|7[235-7])\\d{6}",,,, "112345678",,, [9], [7]], [,, "579[01]\\d{5}|5(?:[013-689]\\d|7[0-8])\\d{6}",,,, "512345678",,, [9]], [,, "800\\d{7}",,,, "8001234567",,, [10]], [,, "925\\d{6}",,,, "925012345",,, [9]], [,, "920\\d{6}",,,, "920012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SA", 966, "00", "0",,, "0",,,, [[, "(\\d{4})(\\d{5})", "$1 $2", ["9"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["5"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["81"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "811\\d{7}",,,, "8110123456",,, [10]],,, [,,,,,,,,, [-1]]],
          SB: [, [,, "[6-9]\\d{6}|[1-6]\\d{4}",,,,,,, [5, 7]], [,, "(?:1[4-79]|[23]\\d|4[0-2]|5[03]|6[0-37])\\d{3}",,,, "40123",,, [5]], [,, "48\\d{3}|(?:(?:6[89]|7[1-9]|8[4-9])\\d|9(?:1[2-9]|2[013-9]|3[0-2]|[46]\\d|5[0-46-9]|7[0-689]|8[0-79]|9[0-8]))\\d{4}",,,, "7421234"], [,, "1[38]\\d{3}",,,, "18123",,, [5]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "5[12]\\d{3}",,,, "51123",,, [5]], "SB", 677, "0[01]",,,,,,,, [[, "(\\d{2})(\\d{5})", "$1 $2", ["6[89]|7|8[4-9]|9(?:[1-8]|9[0-8])"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SC: [, [,, "(?:[2489]\\d|64)\\d{5}",,,,,,, [7]], [,, "4[2-46]\\d{5}",,,, "4217123"], [,, "2[125-8]\\d{5}",,,, "2510123"], [,, "800[08]\\d{3}",,,, "8000000"], [,, "85\\d{5}",,,, "8512345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "971\\d{4}|(?:64|95)\\d{5}",,,, "6412345"], "SC", 248, "010|0[0-2]",,,,,, "00",, [[, "(\\d)(\\d{3})(\\d{3})", "$1 $2 $3", ["[246]|9[57]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SD: [, [,, "[19]\\d{8}",,,,,,, [9]], [,, "1(?:5\\d|8[35-7])\\d{6}",,,, "153123456"], [,, "(?:1[0-2]|9[0-3569])\\d{7}",,,, "911231234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SD", 249, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[19]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SE: [, [,, "(?:[26]\\d\\d|9)\\d{9}|[1-9]\\d{8}|[1-689]\\d{7}|[1-4689]\\d{6}|2\\d{5}",,,,,,, [6, 7, 8, 9, 10, 12]], [,, "(?:(?:[12][136]|3[356]|4[0246]|6[03]|8\\d)\\d|90[1-9])\\d{4,6}|(?:1(?:2[0-35]|4[0-4]|5[0-25-9]|7[13-6]|[89]\\d)|2(?:2[0-7]|4[0136-8]|5[0138]|7[018]|8[01]|9[0-57])|3(?:0[0-4]|1\\d|2[0-25]|4[056]|7[0-2]|8[0-3]|9[023])|4(?:1[013-8]|3[0135]|5[14-79]|7[0-246-9]|8[0156]|9[0-689])|5(?:0[0-6]|[15][0-5]|2[0-68]|3[0-4]|4\\d|6[03-5]|7[013]|8[0-79]|9[01])|6(?:1[1-3]|2[0-4]|4[02-57]|5[0-37]|6[0-3]|7[0-2]|8[0247]|9[0-356])|9(?:1[0-68]|2\\d|3[02-5]|4[0-3]|5[0-4]|[68][01]|7[0135-8]))\\d{5,6}",,,, "8123456",,, [7, 8, 9]], [,, "7[02369]\\d{7}",,,, "701234567",,, [9]], [,, "20\\d{4,7}",,,, "20123456",,, [6, 7, 8, 9]], [,, "649\\d{6}|99[1-59]\\d{4}(?:\\d{3})?|9(?:00|39|44)[1-8]\\d{3,6}",,,, "9001234567",,, [7, 8, 9, 10]], [,, "77[0-7]\\d{6}",,,, "771234567",,, [9]], [,, "75[1-8]\\d{6}",,,, "751234567",,, [9]], [,,,,,,,,, [-1]], "SE", 46, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{2,3})(\\d{2})", "$1-$2 $3", ["20"], "0$1"], [, "(\\d{3})(\\d{4})", "$1-$2", ["9(?:00|39|44|9)"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})", "$1-$2 $3", ["[12][136]|3[356]|4[0246]|6[03]|90[1-9]"], "0$1"], [, "(\\d)(\\d{2,3})(\\d{2})(\\d{2})", "$1-$2 $3 $4", ["8"], "0$1"], [, "(\\d{3})(\\d{2,3})(\\d{2})", "$1-$2 $3", ["1[2457]|2(?:[247-9]|5[0138])|3[0247-9]|4[1357-9]|5[0-35-9]|6(?:[125689]|4[02-57]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"], "0$1"], [, "(\\d{3})(\\d{2,3})(\\d{3})", "$1-$2 $3", ["9(?:00|39|44)"], "0$1"], [, "(\\d{2})(\\d{2,3})(\\d{2})(\\d{2})", "$1-$2 $3 $4", ["1[13689]|2[0136]|3[1356]|4[0246]|54|6[03]|90[1-9]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1-$2 $3 $4", ["10|7"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{2})", "$1-$2 $3 $4", ["8"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1-$2 $3 $4", ["[13-5]|2(?:[247-9]|5[0138])|6(?:[124-689]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{3})", "$1-$2 $3 $4", ["9"], "0$1"], [, "(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1-$2 $3 $4 $5", ["[26]"], "0$1"]], [[, "(\\d{2})(\\d{2,3})(\\d{2})", "$1 $2 $3", ["20"]], [, "(\\d{3})(\\d{4})", "$1 $2", ["9(?:00|39|44|9)"]], [, "(\\d{2})(\\d{3})(\\d{2})", "$1 $2 $3", ["[12][136]|3[356]|4[0246]|6[03]|90[1-9]"]], [, "(\\d)(\\d{2,3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"]], [, "(\\d{3})(\\d{2,3})(\\d{2})", "$1 $2 $3", ["1[2457]|2(?:[247-9]|5[0138])|3[0247-9]|4[1357-9]|5[0-35-9]|6(?:[125689]|4[02-57]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"]], [, "(\\d{3})(\\d{2,3})(\\d{3})", "$1 $2 $3", ["9(?:00|39|44)"]], [, "(\\d{2})(\\d{2,3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["1[13689]|2[0136]|3[1356]|4[0246]|54|6[03]|90[1-9]"]], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["10|7"]], [, "(\\d)(\\d{3})(\\d{3})(\\d{2})", "$1 $2 $3 $4", ["8"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[13-5]|2(?:[247-9]|5[0138])|6(?:[124-689]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{3})", "$1 $2 $3 $4", ["9"]], [, "(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4 $5", ["[26]"]]], [,, "74[02-9]\\d{6}",,,, "740123456",,, [9]],,, [,,,,,,,,, [-1]], [,, "10[1-8]\\d{6}",,,, "102345678",,, [9]],,, [,, "(?:25[245]|67[3-68])\\d{9}",,,, "254123456789",,, [12]]],
          SG: [, [,, "(?:(?:1\\d|8)\\d\\d|7000)\\d{7}|[3689]\\d{7}",,,,,,, [8, 10, 11]], [,, "662[0-24-9]\\d{4}|6(?:[0-578]\\d|6[013-57-9]|9[0-35-9])\\d{5}",,,, "61234567",,, [8]], [,, "(?:8(?:0(?:[1-8]\\d|9[0-689])|[1-8]\\d\\d|9(?:[0-4]\\d|5[0-3]|62))|9[0-8]\\d\\d)\\d{4}",,,, "81234567",,, [8]], [,, "(?:18|8)00\\d{7}",,,, "18001234567",,, [10, 11]], [,, "1900\\d{7}",,,, "19001234567",,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:3[12]\\d|666)\\d{5}",,,, "31234567",,, [8]], "SG", 65, "0[0-3]\\d",,,,,,,, [[, "(\\d{4,5})", "$1", ["1[013-9]|77", "1(?:[013-8]|9(?:0[1-9]|[1-9]))|77"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[369]|8(?:0[1-9]|[1-9])"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"]], [, "(\\d{4})(\\d{4})(\\d{3})", "$1 $2 $3", ["7"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]]], [[, "(\\d{4})(\\d{4})", "$1 $2", ["[369]|8(?:0[1-9]|[1-9])"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"]], [, "(\\d{4})(\\d{4})(\\d{3})", "$1 $2 $3", ["7"]], [, "(\\d{4})(\\d{3})(\\d{4})", "$1 $2 $3", ["1"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "7000\\d{7}",,,, "70001234567",,, [11]],,, [,,,,,,,,, [-1]]],
          SH: [, [,, "(?:[256]\\d|8)\\d{3}",,,,,,, [4, 5]], [,, "2(?:[0-57-9]\\d|6[4-9])\\d\\d",,,, "22158"], [,, "[56]\\d{4}",,,, "51234",,, [5]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "262\\d\\d",,,, "26212",,, [5]], "SH", 290, "00",,,,,,,,,, [,,,,,,,,, [-1]], 1, "[256]", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SI: [, [,, "[1-7]\\d{7}|8\\d{4,7}|90\\d{4,6}",,,,,,, [5, 6, 7, 8]], [,, "(?:[1-357][2-8]|4[24-8])\\d{6}",,,, "12345678",,, [8], [7]], [,, "65(?:[178]\\d|5[56]|6[01])\\d{4}|(?:[37][01]|4[0139]|51|6[489])\\d{6}",,,, "31234567",,, [8]], [,, "80\\d{4,6}",,,, "80123456",,, [6, 7, 8]], [,, "89[1-3]\\d{2,5}|90\\d{4,6}",,,, "90123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:59\\d\\d|8(?:1(?:[67]\\d|8[0-589])|2(?:0\\d|2[0-37-9]|8[0-2489])|3[389]\\d))\\d{4}",,,, "59012345",,, [8]], "SI", 386, "00|10(?:22|66|88|99)", "0",,, "0",, "00",, [[, "(\\d{2})(\\d{3,6})", "$1 $2", ["8[09]|9"], "0$1"], [, "(\\d{3})(\\d{5})", "$1 $2", ["59|8"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[37][01]|4[0139]|51|6"], "0$1"], [, "(\\d)(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[1-57]"], "(0$1)"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SJ: [, [,, "0\\d{4}|(?:[489]\\d|79)\\d{6}",,,,,,, [5, 8]], [,, "79\\d{6}",,,, "79123456",,, [8]], [,, "(?:4[015-8]|9\\d)\\d{6}",,,, "41234567",,, [8]], [,, "80[01]\\d{5}",,,, "80012345",,, [8]], [,, "82[09]\\d{5}",,,, "82012345",,, [8]], [,, "810(?:0[0-6]|[2-8]\\d)\\d{3}",,,, "81021234",,, [8]], [,, "880\\d{5}",,,, "88012345",,, [8]], [,, "85[0-5]\\d{5}",,,, "85012345",,, [8]], "SJ", 47, "00",,,,,,,,,, [,,,,,,,,, [-1]],, "79", [,,,,,,,,, [-1]], [,, "(?:0[235-9]|81(?:0(?:0[7-9]|1\\d)|5\\d\\d))\\d{3}",,,, "02000"],,, [,, "81[23]\\d{5}",,,, "81212345",,, [8]]],
          SK: [, [,, "[2-689]\\d{8}|[2-59]\\d{6}|[2-5]\\d{5}",,,,,,, [6, 7, 9]], [,, "(?:2(?:16|[2-9]\\d{3})|(?:(?:[3-5][1-8]\\d|819)\\d|601[1-5])\\d)\\d{4}|(?:2|[3-5][1-8])1[67]\\d{3}|[3-5][1-8]16\\d\\d",,,, "221234567"], [,, "909[1-9]\\d{5}|9(?:0[1-8]|1[0-24-9]|4[03-57-9]|5\\d)\\d{6}",,,, "912123456",,, [9]], [,, "800\\d{6}",,,, "800123456",,, [9]], [,, "9(?:00|[78]\\d)\\d{6}",,,, "900123456",,, [9]], [,, "8[5-9]\\d{7}",,,, "850123456",,, [9]], [,,,,,,,,, [-1]], [,, "6(?:02|5[0-4]|9[0-6])\\d{6}",,,, "690123456",,, [9]], "SK", 421, "00", "0",,, "0",,,, [[, "(\\d)(\\d{2})(\\d{3,4})", "$1 $2 $3", ["21"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["[3-5][1-8]1", "[3-5][1-8]1[67]"], "0$1"], [, "(\\d{4})(\\d{3})", "$1 $2", ["909", "9090"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{2})", "$1/$2 $3 $4", ["2"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[689]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1/$2 $3 $4", ["[3-5]"], "0$1"]], [[, "(\\d)(\\d{2})(\\d{3,4})", "$1 $2 $3", ["21"], "0$1"], [, "(\\d{2})(\\d{2})(\\d{2,3})", "$1 $2 $3", ["[3-5][1-8]1", "[3-5][1-8]1[67]"], "0$1"], [, "(\\d)(\\d{3})(\\d{3})(\\d{2})", "$1/$2 $3 $4", ["2"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[689]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1/$2 $3 $4", ["[3-5]"], "0$1"]], [,, "9090\\d{3}",,,, "9090123",,, [7]],,, [,, "9090\\d{3}|(?:602|8(?:00|[5-9]\\d)|9(?:00|[78]\\d))\\d{6}",,,,,,, [7, 9]], [,, "96\\d{7}",,,, "961234567",,, [9]],,, [,,,,,,,,, [-1]]],
          SL: [, [,, "(?:[237-9]\\d|66)\\d{6}",,,,,,, [8], [6]], [,, "22[2-4][2-9]\\d{4}",,,, "22221234",,,, [6]], [,, "(?:25|3[0-5]|66|7[2-9]|8[08]|9[09])\\d{6}",,,, "25123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SL", 232, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{6})", "$1 $2", ["[236-9]"], "(0$1)"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SM: [, [,, "(?:0549|[5-7]\\d)\\d{6}",,,,,,, [8, 10], [6]], [,, "0549(?:8[0157-9]|9\\d)\\d{4}",,,, "0549886377",,, [10], [6]], [,, "6[16]\\d{6}",,,, "66661212",,, [8]], [,,,,,,,,, [-1]], [,, "7[178]\\d{6}",,,, "71123456",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "5[158]\\d{6}",,,, "58001110",,, [8]], "SM", 378, "00",,,, "([89]\\d{5})$", "0549$1",,, [[, "(\\d{6})", "$1", ["[89]"]], [, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[5-7]"]], [, "(\\d{4})(\\d{6})", "$1 $2", ["0"]]], [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[5-7]"]], [, "(\\d{4})(\\d{6})", "$1 $2", ["0"]]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SN: [, [,, "(?:[378]\\d|93)\\d{7}",,,,,,, [9]], [,, "3(?:0(?:1[0-2]|80)|282|3(?:8[1-9]|9[3-9])|611)\\d{5}",,,, "301012345"], [,, "7(?:(?:[06-8]\\d|[19]0|21)\\d|5(?:0[01]|[19]0|2[25]|[38]3|[4-7]\\d))\\d{5}",,,, "701234567"], [,, "800\\d{6}",,,, "800123456"], [,, "88[4689]\\d{6}",,,, "884123456"], [,, "81[02468]\\d{6}",,,, "810123456"], [,,,,,,,,, [-1]], [,, "(?:3(?:392|9[01]\\d)\\d|93(?:3[13]0|929))\\d{4}",,,, "933301234"], "SN", 221, "00",,,,,,,, [[, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"]], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[379]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SO: [, [,, "[346-9]\\d{8}|[12679]\\d{7}|[1-5]\\d{6}|[1348]\\d{5}",,,,,,, [6, 7, 8, 9]], [,, "(?:1\\d|2[0-79]|3[0-46-8]|4[0-7]|5[57-9])\\d{5}|(?:[134]\\d|8[125])\\d{4}",,,, "4012345",,, [6, 7]], [,, "(?:(?:15|(?:3[59]|4[89]|6\\d|7[79]|8[08])\\d|9(?:0\\d|[2-9]))\\d|2(?:4\\d|8))\\d{5}|(?:[67]\\d\\d|904)\\d{5}",,,, "71123456",,, [7, 8, 9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SO", 252, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{4})", "$1 $2", ["8[125]"]], [, "(\\d{6})", "$1", ["[134]"]], [, "(\\d)(\\d{6})", "$1 $2", ["[15]|2[0-79]|3[0-46-8]|4[0-7]"]], [, "(\\d)(\\d{7})", "$1 $2", ["(?:2|90)4|[67]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[348]|64|79|90"]], [, "(\\d{2})(\\d{5,7})", "$1 $2", ["1|28|6[0-35-9]|77|9[2-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SR: [, [,, "(?:[2-5]|68|[78]\\d)\\d{5}",,,,,,, [6, 7]], [,, "(?:2[1-3]|3[0-7]|(?:4|68)\\d|5[2-58])\\d{4}",,,, "211234"], [,, "(?:7[124-7]|8[124-9])\\d{5}",,,, "7412345",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "56\\d{4}",,,, "561234",,, [6]], "SR", 597, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})", "$1-$2-$3", ["56"]], [, "(\\d{3})(\\d{3})", "$1-$2", ["[2-5]"]], [, "(\\d{3})(\\d{4})", "$1-$2", ["[6-8]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SS: [, [,, "[19]\\d{8}",,,,,,, [9]], [,, "1[89]\\d{7}",,,, "181234567"], [,, "(?:12|9[1257-9])\\d{7}",,,, "977123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SS", 211, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[19]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ST: [, [,, "(?:22|9\\d)\\d{5}",,,,,,, [7]], [,, "22\\d{5}",,,, "2221234"], [,, "900[5-9]\\d{3}|9(?:0[1-9]|[89]\\d)\\d{4}",,,, "9812345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "ST", 239, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[29]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SV: [, [,, "[267]\\d{7}|(?:80\\d|900)\\d{4}(?:\\d{4})?",,,,,,, [7, 8, 11]], [,, "2(?:79(?:0[0347-9]|[1-9]\\d)|89(?:0[024589]|[1-9]\\d))\\d{3}|2(?:[1-69]\\d|[78][0-8])\\d{5}",,,, "21234567",,, [8]], [,, "[67]\\d{7}",,,, "70123456",,, [8]], [,, "800\\d{8}|80[01]\\d{4}",,,, "8001234",,, [7, 11]], [,, "900\\d{4}(?:\\d{4})?",,,, "9001234",,, [7, 11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SV", 503, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[89]"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["[267]"]], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["[89]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SX: [, [,, "7215\\d{6}|(?:[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "7215(?:4[2-8]|8[239]|9[056])\\d{4}",,,, "7215425678",,,, [7]], [,, "7215(?:1[02]|2\\d|5[034679]|8[014-8])\\d{4}",,,, "7215205678",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002123456"], [,, "900[2-9]\\d{6}",,,, "9002123456"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "SX", 1, "011", "1",,, "(5\\d{6})$|1", "721$1",,,,, [,,,,,,,,, [-1]],, "721", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SY: [, [,, "[1-39]\\d{8}|[1-5]\\d{7}",,,,,,, [8, 9], [6, 7]], [,, "21\\d{6,7}|(?:1(?:[14]\\d|[2356])|2[235]|3(?:[13]\\d|4)|4[134]|5[1-3])\\d{6}",,,, "112345678",,,, [6, 7]], [,, "9[1-689]\\d{7}",,,, "944567890",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "SY", 963, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[1-5]"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["9"], "0$1",, 1]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          SZ: [, [,, "0800\\d{4}|(?:[237]\\d|900)\\d{6}",,,,,,, [8, 9]], [,, "[23][2-5]\\d{6}",,,, "22171234",,, [8]], [,, "7[6-9]\\d{6}",,,, "76123456",,, [8]], [,, "0800\\d{4}",,,, "08001234",,, [8]], [,, "900\\d{6}",,,, "900012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "70\\d{6}",,,, "70012345",,, [8]], "SZ", 268, "00",,,,,,,, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[0237]"]], [, "(\\d{5})(\\d{4})", "$1 $2", ["9"]]],, [,,,,,,,,, [-1]],,, [,, "0800\\d{4}",,,,,,, [8]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TA: [, [,, "8\\d{3}",,,,,,, [4]], [,, "8\\d{3}",,,, "8999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TA", 290, "00",,,,,,,,,, [,,,,,,,,, [-1]],, "8", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TC: [, [,, "(?:[58]\\d\\d|649|900)\\d{7}",,,,,,, [10], [7]], [,, "649(?:266|712|9(?:4\\d|50))\\d{4}",,,, "6497121234",,,, [7]], [,, "649(?:2(?:3[129]|4[1-79])|3\\d\\d|4[34][1-3])\\d{4}",,,, "6492311234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,, "649(?:71[01]|966)\\d{4}",,,, "6497101234",,,, [7]], "TC", 1, "011", "1",,, "([2-479]\\d{6})$|1", "649$1",,,,, [,,,,,,,,, [-1]],, "649", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TD: [, [,, "(?:22|[689]\\d|77)\\d{6}",,,,,,, [8]], [,, "22(?:[37-9]0|5[0-5]|6[89])\\d{4}",,,, "22501234"], [,, "(?:[69]\\d|77|8[56])\\d{6}",,,, "63012345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TD", 235, "00|16",,,,,, "00",, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[26-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TG: [, [,, "[279]\\d{7}",,,,,,, [8]], [,, "2(?:2[2-7]|3[23]|4[45]|55|6[67]|77)\\d{5}",,,, "22212345"], [,, "(?:7[019]|9[0-36-9])\\d{6}",,,, "90112345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TG", 228, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[279]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TH: [, [,, "(?:001800|[2-57]|[689]\\d)\\d{7}|1\\d{7,9}",,,,,,, [8, 9, 10, 13]], [,, "(?:1[0689]|2\\d|3[2-9]|4[2-5]|5[2-6]|7[3-7])\\d{6}",,,, "21234567",,, [8]], [,, "67(?:1[0-8]|2[4-7])\\d{5}|(?:14|6[1-6]|[89]\\d)\\d{7}",,,, "812345678",,, [9]], [,, "(?:001800\\d|1800)\\d{6}",,,, "1800123456",,, [10, 13]], [,, "1900\\d{6}",,,, "1900123456",,, [10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "6[08]\\d{7}",,,, "601234567",,, [9]], "TH", 66, "00[1-9]", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{4})", "$1 $2 $3", ["2"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[13-9]"], "0$1"], [, "(\\d{4})(\\d{3})(\\d{3})", "$1 $2 $3", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TJ: [, [,, "[0-57-9]\\d{8}",,,,,,, [9], [3, 5, 6, 7]], [,, "(?:3(?:1[3-5]|2[245]|3[12]|4[24-7]|5[25]|72)|4(?:46|74|87))\\d{6}",,,, "372123456",,,, [3, 5, 6, 7]], [,, "(?:33[03-9]|4(?:1[18]|4[02-479])|81[1-9])\\d{6}|(?:[09]\\d|1[017]|2[02]|[34]0|5[05]|7[01578]|8[078])\\d{7}",,,, "917123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TJ", 992, "810",,,,,, "8~10",, [[, "(\\d{6})(\\d)(\\d{2})", "$1 $2 $3", ["331", "3317"]], [, "(\\d{3})(\\d{2})(\\d{4})", "$1 $2 $3", ["44[02-479]|[34]7"]], [, "(\\d{4})(\\d)(\\d{4})", "$1 $2 $3", ["3(?:[1245]|3[12])"]], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[0-57-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TK: [, [,, "[2-47]\\d{3,6}",,,,,,, [4, 5, 6, 7]], [,, "(?:2[2-4]|[34]\\d)\\d{2,5}",,,, "3101"], [,, "7[2-4]\\d{2,5}",,,, "7290"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TK", 690, "00",,,,,,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TL: [, [,, "7\\d{7}|(?:[2-47]\\d|[89]0)\\d{5}",,,,,,, [7, 8]], [,, "(?:2[1-5]|3[1-9]|4[1-4])\\d{5}",,,, "2112345",,, [7]], [,, "7[2-8]\\d{6}",,,, "77212345",,, [8]], [,, "80\\d{5}",,,, "8012345",,, [7]], [,, "90\\d{5}",,,, "9012345",,, [7]], [,,,,,,,,, [-1]], [,, "70\\d{5}",,,, "7012345",,, [7]], [,,,,,,,,, [-1]], "TL", 670, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[2-489]|70"]], [, "(\\d{4})(\\d{4})", "$1 $2", ["7"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TM: [, [,, "(?:[1-6]\\d|71)\\d{6}",,,,,,, [8]], [,, "(?:1(?:2\\d|3[1-9])|2(?:22|4[0-35-8])|3(?:22|4[03-9])|4(?:22|3[128]|4\\d|6[15])|5(?:22|5[7-9]|6[014-689]))\\d{5}",,,, "12345678"], [,, "(?:6\\d|71)\\d{6}",,,, "66123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TM", 993, "810", "8",,, "8",, "8~10",, [[, "(\\d{2})(\\d{2})(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["12"], "(8 $1)"], [, "(\\d{3})(\\d)(\\d{2})(\\d{2})", "$1 $2-$3-$4", ["[1-5]"], "(8 $1)"], [, "(\\d{2})(\\d{6})", "$1 $2", ["[67]"], "8 $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TN: [, [,, "[2-57-9]\\d{7}",,,,,,, [8]], [,, "81200\\d{3}|(?:3[0-2]|7\\d)\\d{6}",,,, "30010123"], [,, "3(?:001|[12]40)\\d{4}|(?:(?:[259]\\d|4[0-8])\\d|3(?:1[1-35]|6[0-4]|91))\\d{5}",,,, "20123456"], [,, "8010\\d{4}",,,, "80101234"], [,, "88\\d{6}",,,, "88123456"], [,, "8[12]10\\d{4}",,,, "81101234"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TN", 216, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-57-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TO: [, [,, "(?:0800|(?:[5-8]\\d\\d|999)\\d)\\d{3}|[2-8]\\d{4}",,,,,,, [5, 7]], [,, "(?:2\\d|3[0-8]|4[0-4]|50|6[09]|7[0-24-69]|8[05])\\d{3}",,,, "20123",,, [5]], [,, "(?:5(?:4[0-5]|5[4-6])|6(?:[09]\\d|3[02]|8[15-9])|(?:7\\d|8[46-9])\\d|999)\\d{4}",,,, "7715123",,, [7]], [,, "0800\\d{3}",,,, "0800222",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "55[0-37-9]\\d{4}",,,, "5510123",,, [7]], "TO", 676, "00",,,,,,,, [[, "(\\d{2})(\\d{3})", "$1-$2", ["[2-4]|50|6[09]|7[0-24-69]|8[05]"]], [, "(\\d{4})(\\d{3})", "$1 $2", ["0"]], [, "(\\d{3})(\\d{4})", "$1 $2", ["[5-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TR: [, [,, "4\\d{6}|8\\d{11,12}|(?:[2-58]\\d\\d|900)\\d{7}",,,,,,, [7, 10, 12, 13]], [,, "(?:2(?:[13][26]|[28][2468]|[45][268]|[67][246])|3(?:[13][28]|[24-6][2468]|[78][02468]|92)|4(?:[16][246]|[23578][2468]|4[26]))\\d{7}",,,, "2123456789",,, [10]], [,, "561(?:011|61\\d)\\d{4}|5(?:0[15-7]|1[06]|24|[34]\\d|5[1-59]|9[46])\\d{7}",,,, "5012345678",,, [10]], [,, "8(?:00\\d{7}(?:\\d{2,3})?|11\\d{7})",,,, "8001234567",,, [10, 12, 13]], [,, "(?:8[89]8|900)\\d{7}",,,, "9001234567",,, [10]], [,,,,,,,,, [-1]], [,, "592(?:21[12]|461)\\d{4}",,,, "5922121234",,, [10]], [,, "850\\d{7}",,,, "8500123456",,, [10]], "TR", 90, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d)(\\d{3})", "$1 $2 $3", ["444"],,, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["512|8[01589]|90"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["5(?:[0-59]|61)", "5(?:[0-59]|61[06])", "5(?:[0-59]|61[06]1)"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[24][1-8]|3[1-9]"], "(0$1)",, 1], [, "(\\d{3})(\\d{3})(\\d{6,7})", "$1 $2 $3", ["80"], "0$1",, 1]], [[, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["512|8[01589]|90"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["5(?:[0-59]|61)", "5(?:[0-59]|61[06])", "5(?:[0-59]|61[06]1)"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[24][1-8]|3[1-9]"], "(0$1)",, 1], [, "(\\d{3})(\\d{3})(\\d{6,7})", "$1 $2 $3", ["80"], "0$1",, 1]], [,, "512\\d{7}",,,, "5123456789",,, [10]],,, [,, "(?:444|811\\d{3})\\d{4}",,,,,,, [7, 10]], [,, "444\\d{4}",,,, "4441444",,, [7]],,, [,,,,,,,,, [-1]]],
          TT: [, [,, "(?:[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "868(?:2(?:01|1[5-9]|[23]\\d|4[0-2])|6(?:0[7-9]|1[02-8]|2[1-9]|[3-69]\\d|7[0-79])|82[124])\\d{4}",,,, "8682211234",,,, [7]], [,, "868(?:(?:2[5-9]|3\\d)\\d|4(?:3[0-6]|[6-9]\\d)|6(?:20|78|8\\d)|7(?:0[1-9]|1[02-9]|[2-9]\\d))\\d{4}",,,, "8682911234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "TT", 1, "011", "1",,, "([2-46-8]\\d{6})$|1", "868$1",,,,, [,,,,,,,,, [-1]],, "868", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,, "868619\\d{4}",,,, "8686191234",,,, [7]]],
          TV: [, [,, "(?:2|7\\d\\d|90)\\d{4}",,,,,,, [5, 6, 7]], [,, "2[02-9]\\d{3}",,,, "20123",,, [5]], [,, "(?:7[01]\\d|90)\\d{4}",,,, "901234",,, [6, 7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "TV", 688, "00",,,,,,,, [[, "(\\d{2})(\\d{3})", "$1 $2", ["2"]], [, "(\\d{2})(\\d{4})", "$1 $2", ["90"]], [, "(\\d{2})(\\d{5})", "$1 $2", ["7"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          TW: [, [,, "[2-689]\\d{8}|7\\d{9,10}|[2-8]\\d{7}|2\\d{6}",,,,,,, [7, 8, 9, 10, 11]], [,, "(?:2[2-8]\\d|370|55[01]|7[1-9])\\d{6}|4(?:(?:0(?:0[1-9]|[2-48]\\d)|1[023]\\d)\\d{4,5}|(?:[239]\\d\\d|4(?:0[56]|12|49))\\d{5})|6(?:[01]\\d{7}|4(?:0[56]|12|24|4[09])\\d{4,5})|8(?:(?:2(?:3\\d|4[0-269]|[578]0|66)|36[24-9]|90\\d\\d)\\d{4}|4(?:0[56]|12|24|4[09])\\d{4,5})|(?:2(?:2(?:0\\d\\d|4(?:0[68]|[249]0|3[0-467]|5[0-25-9]|6[0235689]))|(?:3(?:[09]\\d|1[0-4])|(?:4\\d|5[0-49]|6[0-29]|7[0-5])\\d)\\d)|(?:(?:3[2-9]|5[2-8]|6[0-35-79]|8[7-9])\\d\\d|4(?:2(?:[089]\\d|7[1-9])|(?:3[0-4]|[78]\\d|9[01])\\d))\\d)\\d{3}",,,, "221234567",,, [8, 9]], [,, "(?:40001[0-2]|9[0-8]\\d{4})\\d{3}",,,, "912345678",,, [9]], [,, "80[0-79]\\d{6}|800\\d{5}",,,, "800123456",,, [8, 9]], [,, "20(?:[013-9]\\d\\d|2)\\d{4}",,,, "203123456",,, [7, 9]], [,,,,,,,,, [-1]], [,, "99\\d{7}",,,, "990123456",,, [9]], [,, "7010(?:[0-2679]\\d|3[0-7]|8[0-5])\\d{5}|70\\d{8}",,,, "7012345678",,, [10, 11]], "TW", 886, "0(?:0[25-79]|19)", "0", "#",, "0",,,, [[, "(\\d{2})(\\d)(\\d{4})", "$1 $2 $3", ["202"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[258]0"], "0$1"], [, "(\\d)(\\d{3,4})(\\d{4})", "$1 $2 $3", ["[23568]|4(?:0[02-48]|[1-47-9])|7[1-9]", "[23568]|4(?:0[2-48]|[1-47-9])|(?:400|7)[1-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[49]"], "0$1"], [, "(\\d{2})(\\d{4})(\\d{4,5})", "$1 $2 $3", ["7"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "50[0-46-9]\\d{6}",,,, "500123456",,, [9]],,, [,,,,,,,,, [-1]]],
          TZ: [, [,, "(?:[25-8]\\d|41|90)\\d{7}",,,,,,, [9]], [,, "2[2-8]\\d{7}",,,, "222345678"], [,, "(?:6[125-9]|7[13-9])\\d{7}",,,, "621234567"], [,, "80[08]\\d{6}",,,, "800123456"], [,, "90\\d{7}",,,, "900123456"], [,, "8(?:40|6[01])\\d{6}",,,, "840123456"], [,,,,,,,,, [-1]], [,, "41\\d{7}",,,, "412345678"], "TZ", 255, "00[056]", "0",,, "0",,,, [[, "(\\d{3})(\\d{2})(\\d{4})", "$1 $2 $3", ["[89]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[24]"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["5"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[67]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,, "(?:8(?:[04]0|6[01])|90\\d)\\d{6}"], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          UA: [, [,, "[89]\\d{9}|[3-9]\\d{8}",,,,,,, [9, 10], [5, 6, 7]], [,, "(?:3[1-8]|4[13-8]|5[1-7]|6[12459])\\d{7}",,,, "311234567",,, [9], [5, 6, 7]], [,, "790\\d{6}|(?:39|50|6[36-8]|7[1-357]|9[1-9])\\d{7}",,,, "501234567",,, [9]], [,, "800[1-8]\\d{5,6}",,,, "800123456"], [,, "900[239]\\d{5,6}",,,, "900212345"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "89[1-579]\\d{6}",,,, "891234567",,, [9]], "UA", 380, "00", "0",,, "0",, "0~0",, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["6[12][29]|(?:3[1-8]|4[136-8]|5[12457]|6[49])2|(?:56|65)[24]", "6[12][29]|(?:35|4[1378]|5[12457]|6[49])2|(?:56|65)[24]|(?:3[1-46-8]|46)2[013-9]"], "0$1"], [, "(\\d{4})(\\d{5})", "$1 $2", ["3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6[0135689]|7[4-6])|6(?:[12][3-7]|[459])", "3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6(?:[015689]|3[02389])|7[4-6])|6(?:[12][3-7]|[459])"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[3-7]|89|9[1-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[89]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          UG: [, [,, "800\\d{6}|(?:[29]0|[347]\\d)\\d{7}",,,,,,, [9], [5, 6, 7]], [,, "20(?:(?:240|30[67])\\d|6(?:00[0-2]|30[0-4]))\\d{3}|(?:20(?:[017]\\d|2[5-9]|3[1-4]|5[0-4]|6[15-9])|[34]\\d{3})\\d{5}",,,, "312345678",,,, [5, 6, 7]], [,, "72[48]0\\d{5}|7(?:[015-8]\\d|2[067]|36|4[0-5]|9[89])\\d{6}",,,, "712345678"], [,, "800[1-3]\\d{5}",,,, "800123456"], [,, "90[1-3]\\d{6}",,,, "901123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "UG", 256, "00[057]", "0",,, "0",,,, [[, "(\\d{4})(\\d{5})", "$1 $2", ["202", "2024"], "0$1"], [, "(\\d{3})(\\d{6})", "$1 $2", ["[27-9]|4(?:6[45]|[7-9])"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["[34]"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          US: [, [,, "[2-9]\\d{9}|3\\d{6}",,,,,,, [10], [7]], [,, "(?:3052(?:0[0-8]|[1-9]\\d)|5056(?:[0-35-9]\\d|4[468])|7302[0-4]\\d)\\d{4}|(?:305[3-9]|472[24]|505[2-57-9]|7306|983[2-47-9])\\d{6}|(?:2(?:0[1-35-9]|1[02-9]|2[03-57-9]|3[1459]|4[08]|5[1-46]|6[0279]|7[0269]|8[13])|3(?:0[1-47-9]|1[02-9]|2[013569]|3[0-24679]|4[167]|5[0-2]|6[01349]|8[056])|4(?:0[124-9]|1[02-579]|2[3-5]|3[0245]|4[023578]|58|6[349]|7[0589]|8[04])|5(?:0[1-47-9]|1[0235-8]|20|3[0149]|4[01]|5[179]|6[1-47]|7[0-5]|8[0256])|6(?:0[1-35-9]|1[024-9]|2[03689]|3[016]|4[0156]|5[01679]|6[0-279]|78|8[0-29])|7(?:0[1-46-8]|1[2-9]|2[04-8]|3[1247]|4[037]|5[47]|6[02359]|7[0-59]|8[156])|8(?:0[1-68]|1[02-8]|2[068]|3[0-2589]|4[03578]|5[046-9]|6[02-5]|7[028])|9(?:0[1346-9]|1[02-9]|2[0589]|3[0146-8]|4[01357-9]|5[12469]|7[0-389]|8[04-69]))[2-9]\\d{6}",,,, "2015550123",,,, [7]], [,, "(?:3052(?:0[0-8]|[1-9]\\d)|5056(?:[0-35-9]\\d|4[468])|7302[0-4]\\d)\\d{4}|(?:305[3-9]|472[24]|505[2-57-9]|7306|983[2-47-9])\\d{6}|(?:2(?:0[1-35-9]|1[02-9]|2[03-57-9]|3[1459]|4[08]|5[1-46]|6[0279]|7[0269]|8[13])|3(?:0[1-47-9]|1[02-9]|2[013569]|3[0-24679]|4[167]|5[0-2]|6[01349]|8[056])|4(?:0[124-9]|1[02-579]|2[3-5]|3[0245]|4[023578]|58|6[349]|7[0589]|8[04])|5(?:0[1-47-9]|1[0235-8]|20|3[0149]|4[01]|5[179]|6[1-47]|7[0-5]|8[0256])|6(?:0[1-35-9]|1[024-9]|2[03689]|3[016]|4[0156]|5[01679]|6[0-279]|78|8[0-29])|7(?:0[1-46-8]|1[2-9]|2[04-8]|3[1247]|4[037]|5[47]|6[02359]|7[0-59]|8[156])|8(?:0[1-68]|1[02-8]|2[068]|3[0-2589]|4[03578]|5[046-9]|6[02-5]|7[028])|9(?:0[1346-9]|1[02-9]|2[0589]|3[0146-8]|4[01357-9]|5[12469]|7[0-389]|8[04-69]))[2-9]\\d{6}",,,, "2015550123",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,, "305209\\d{4}",,,, "3052090123",,,, [7]], "US", 1, "011", "1",,, "1",,, 1, [[, "(\\d{3})(\\d{4})", "$1-$2", ["310"],,, 1], [, "(\\d{3})(\\d{4})", "$1-$2", ["[24-9]|3(?:[02-9]|1[1-9])"]], [, "(\\d{3})(\\d{3})(\\d{4})", "($1) $2-$3", ["[2-9]"],,, 1]], [[, "(\\d{3})(\\d{4})", "$1-$2", ["310"],,, 1], [, "(\\d{3})(\\d{3})(\\d{4})", "$1-$2-$3", ["[2-9]"]]], [,,,,,,,,, [-1]], 1,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          UY: [, [,, "0004\\d{2,9}|[1249]\\d{7}|(?:[49]\\d|80)\\d{5}",,,,,,, [6, 7, 8, 9, 10, 11, 12, 13]], [,, "(?:1(?:770|9(?:20|[89]7))|(?:2\\d|4[2-7])\\d\\d)\\d{4}",,,, "21231234",,, [8], [7]], [,, "9[1-9]\\d{6}",,,, "94231234",,, [8]], [,, "0004\\d{2,9}|(?:405|80[05])\\d{4}",,,, "8001234"], [,, "90[0-8]\\d{4}",,,, "9001234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "UY", 598, "0(?:0|1[3-9]\\d)", "0", " int. ",, "0",, "00",, [[, "(\\d{3})(\\d{3,4})", "$1 $2", ["0"]], [, "(\\d{3})(\\d{4})", "$1 $2", ["[49]0|8"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["9"], "0$1"], [, "(\\d{4})(\\d{4})", "$1 $2", ["[124]"]], [, "(\\d{3})(\\d{3})(\\d{2,4})", "$1 $2 $3", ["0"]], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{2,4})", "$1 $2 $3 $4", ["0"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          UZ: [, [,, "(?:20|33|[5-79]\\d|88)\\d{7}",,,,,,, [9]], [,, "(?:55\\d\\d|6(?:1(?:22|3[124]|4[1-4]|5[1-3578]|64)|2(?:22|3[0-57-9]|41)|5(?:22|3[3-7]|5[024-8])|[69]\\d\\d|7(?:[23]\\d|7[69]))|7(?:0(?:5[4-9]|6[0146]|7[124-6]|9[135-8])|(?:1[12]|[68]\\d)\\d|2(?:22|3[13-57-9]|4[1-3579]|5[14])|3(?:2\\d|3[1578]|4[1-35-7]|5[1-57]|61)|4(?:2\\d|3[1-579]|7[1-79])|5(?:22|5[1-9]|6[1457])|9(?:22|5[1-9])))\\d{5}",,,, "669050123"], [,, "(?:(?:[25]0|33|88|9[0-57-9])\\d{3}|6(?:1(?:2(?:2[01]|98)|35[0-4]|50\\d|61[23]|7(?:[01][017]|4\\d|55|9[5-9]))|2(?:(?:11|7\\d)\\d|2(?:[12]1|9[01379])|5(?:[126]\\d|3[0-4]))|5(?:19[01]|2(?:27|9[26])|(?:30|59|7\\d)\\d)|6(?:2(?:1[5-9]|2[0367]|38|41|52|60)|(?:3[79]|9[0-3])\\d|4(?:56|83)|7(?:[07]\\d|1[017]|3[07]|4[047]|5[057]|67|8[0178]|9[79]))|7(?:2(?:24|3[237]|4[5-9]|7[15-8])|5(?:7[12]|8[0589])|7(?:0\\d|[39][07])|9(?:0\\d|7[079])))|7(?:[07]\\d{3}|1(?:13[01]|6(?:0[47]|1[67]|66)|71[3-69]|98\\d)|2(?:2(?:2[79]|95)|3(?:2[5-9]|6[0-6])|57\\d|7(?:0\\d|1[17]|2[27]|3[37]|44|5[057]|66|88))|3(?:2(?:1[0-6]|21|3[469]|7[159])|(?:33|9[4-6])\\d|5(?:0[0-4]|5[579]|9\\d)|7(?:[0-3579]\\d|4[0467]|6[67]|8[078]))|4(?:2(?:29|5[0257]|6[0-7]|7[1-57])|5(?:1[0-4]|8\\d|9[5-9])|7(?:0\\d|1[024589]|2[0-27]|3[0137]|[46][07]|5[01]|7[5-9]|9[079])|9(?:7[015-9]|[89]\\d))|5(?:112|2(?:0\\d|2[29]|[49]4)|3[1568]\\d|52[6-9]|7(?:0[01578]|1[017]|[23]7|4[047]|[5-7]\\d|8[78]|9[079]))|9(?:22[128]|3(?:2[0-4]|7\\d)|57[02569]|7(?:2[05-9]|3[37]|4\\d|60|7[2579]|87|9[07]))))\\d{4}",,,, "912345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "UZ", 998, "00",,,,,,,, [[, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["[235-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          VA: [, [,, "0\\d{5,10}|3[0-8]\\d{7,10}|55\\d{8}|8\\d{5}(?:\\d{2,4})?|(?:1\\d|39)\\d{7,8}",,,,,,, [6, 7, 8, 9, 10, 11, 12]], [,, "06698\\d{1,6}",,,, "0669812345",,, [6, 7, 8, 9, 10, 11]], [,, "3[1-9]\\d{8}|3[2-9]\\d{7}",,,, "3123456789",,, [9, 10]], [,, "80(?:0\\d{3}|3)\\d{3}",,,, "800123456",,, [6, 9]], [,, "(?:0878\\d{3}|89(?:2\\d|3[04]|4(?:[0-4]|[5-9]\\d\\d)|5[0-4]))\\d\\d|(?:1(?:44|6[346])|89(?:38|5[5-9]|9))\\d{6}",,,, "899123456",,, [6, 8, 9, 10]], [,, "84(?:[08]\\d{3}|[17])\\d{3}",,,, "848123456",,, [6, 9]], [,, "1(?:78\\d|99)\\d{6}",,,, "1781234567",,, [9, 10]], [,, "55\\d{8}",,,, "5512345678",,, [10]], "VA", 39, "00",,,,,,,,,, [,,,,,,,,, [-1]],, "06698", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,, "3[2-8]\\d{9,10}",,,, "33101234501",,, [11, 12]]],
          VC: [, [,, "(?:[58]\\d\\d|784|900)\\d{7}",,,,,,, [10], [7]], [,, "784(?:266|3(?:6[6-9]|7\\d|8[0-6])|4(?:38|5[0-36-8]|8[0-8])|5(?:55|7[0-2]|93)|638|784)\\d{4}",,,, "7842661234",,,, [7]], [,, "784(?:4(?:3[0-5]|5[45]|89|9[0-8])|5(?:2[6-9]|3[0-4])|720)\\d{4}",,,, "7844301234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,, "78451[0-2]\\d{4}",,,, "7845101234",,,, [7]], "VC", 1, "011", "1",,, "([2-7]\\d{6})$|1", "784$1",,,,, [,,,,,,,,, [-1]],, "784", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          VE: [, [,, "[68]00\\d{7}|(?:[24]\\d|[59]0)\\d{8}",,,,,,, [10], [7]], [,, "(?:2(?:12|3[457-9]|[467]\\d|[58][1-9]|9[1-6])|[4-6]00)\\d{7}",,,, "2121234567",,,, [7]], [,, "4(?:1[24-8]|2[46])\\d{7}",,,, "4121234567"], [,, "800\\d{7}",,,, "8001234567"], [,, "90[01]\\d{7}",,,, "9001234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "VE", 58, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{7})", "$1-$2", ["[24-689]"], "0$1", "$CC $1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "501\\d{7}",,,, "5010123456",,,, [7]],,, [,,,,,,,,, [-1]]],
          VG: [, [,, "(?:284|[58]\\d\\d|900)\\d{7}",,,,,,, [10], [7]], [,, "284(?:229|4(?:22|9[45])|774|8(?:52|6[459]))\\d{4}",,,, "2842291234",,,, [7]], [,, "284(?:245|3(?:0[0-3]|4[0-7]|68|9[34])|4(?:4[0-6]|68|9[69])|5(?:4[0-7]|68|9[69]))\\d{4}",,,, "2843001234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "VG", 1, "011", "1",,, "([2-578]\\d{6})$|1", "284$1",,,,, [,,,,,,,,, [-1]],, "284", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          VI: [, [,, "[58]\\d{9}|(?:34|90)0\\d{7}",,,,,,, [10], [7]], [,, "340(?:2(?:0\\d|10|2[06-8]|4[49]|77)|3(?:32|44)|4(?:2[23]|44|7[34]|89)|5(?:1[34]|55)|6(?:2[56]|4[23]|77|9[023])|7(?:1[2-57-9]|2[57]|7\\d)|884|998)\\d{4}",,,, "3406421234",,,, [7]], [,, "340(?:2(?:0\\d|10|2[06-8]|4[49]|77)|3(?:32|44)|4(?:2[23]|44|7[34]|89)|5(?:1[34]|55)|6(?:2[56]|4[23]|77|9[023])|7(?:1[2-57-9]|2[57]|7\\d)|884|998)\\d{4}",,,, "3406421234",,,, [7]], [,, "8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",,,, "8002345678"], [,, "900[2-9]\\d{6}",,,, "9002345678"], [,,,,,,,,, [-1]], [,, "52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}",,,, "5002345678"], [,,,,,,,,, [-1]], "VI", 1, "011", "1",,, "([2-9]\\d{6})$|1", "340$1",, 1,,, [,,,,,,,,, [-1]],, "340", [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          VN: [, [,, "[12]\\d{9}|[135-9]\\d{8}|[16]\\d{7}|[16-8]\\d{6}",,,,,,, [7, 8, 9, 10]], [,, "2(?:0[3-9]|1[0-689]|2[0-25-9]|[38][2-9]|4[2-8]|5[124-9]|6[0-39]|7[0-7]|9[0-4679])\\d{7}",,,, "2101234567",,, [10]], [,, "(?:5(?:2[238]|59)|89[6-9]|99[013-9])\\d{6}|(?:3\\d|5[1689]|7[06-9]|8[1-8]|9[0-8])\\d{7}",,,, "912345678",,, [9]], [,, "1800\\d{4,6}|12(?:0[13]|28)\\d{4}",,,, "1800123456",,, [8, 9, 10]], [,, "1900\\d{4,6}",,,, "1900123456",,, [8, 9, 10]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "672\\d{6}",,,, "672012345",,, [9]], "VN", 84, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[17]99"], "0$1",, 1], [, "(\\d{2})(\\d{5})", "$1 $2", ["80"], "0$1",, 1], [, "(\\d{3})(\\d{4,5})", "$1 $2", ["69"], "0$1",, 1], [, "(\\d{4})(\\d{4,6})", "$1 $2", ["1"],,, 1], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["6"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[357-9]"], "0$1",, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["2[48]"], "0$1",, 1], [, "(\\d{3})(\\d{4})(\\d{3})", "$1 $2 $3", ["2"], "0$1",, 1]], [[, "(\\d{2})(\\d{5})", "$1 $2", ["80"], "0$1",, 1], [, "(\\d{4})(\\d{4,6})", "$1 $2", ["1"],,, 1], [, "(\\d{2})(\\d{3})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["6"], "0$1",, 1], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[357-9]"], "0$1",, 1], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["2[48]"], "0$1",, 1], [, "(\\d{3})(\\d{4})(\\d{3})", "$1 $2 $3", ["2"], "0$1",, 1]], [,,,,,,,,, [-1]],,, [,, "[17]99\\d{4}|69\\d{5,6}",,,,,,, [7, 8]], [,, "(?:[17]99|80\\d)\\d{4}|69\\d{5,6}",,,, "1992000",,, [7, 8]],,, [,,,,,,,,, [-1]]],
          VU: [, [,, "[57-9]\\d{6}|(?:[238]\\d|48)\\d{3}",,,,,,, [5, 7]], [,, "(?:38[0-8]|48[4-9])\\d\\d|(?:2[02-9]|3[4-7]|88)\\d{3}",,,, "22123",,, [5]], [,, "(?:[58]\\d|7[013-7])\\d{5}",,,, "5912345",,, [7]], [,, "81[18]\\d\\d",,,, "81123",,, [5]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:0[1-9]|1[01])\\d{4}",,,, "9010123",,, [7]], "VU", 678, "00",,,,,,,, [[, "(\\d{3})(\\d{4})", "$1 $2", ["[57-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "(?:3[03]|900\\d)\\d{3}",,,, "30123"],,, [,,,,,,,,, [-1]]],
          WF: [, [,, "(?:40|72)\\d{4}|8\\d{5}(?:\\d{3})?",,,,,,, [6, 9]], [,, "72\\d{4}",,,, "721234",,, [6]], [,, "(?:72|8[23])\\d{4}",,,, "821234",,, [6]], [,, "80[0-5]\\d{6}",,,, "800012345",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "WF", 681, "00",,,,,,,, [[, "(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3", ["[478]"]], [, "(\\d{3})(\\d{2})(\\d{2})(\\d{2})", "$1 $2 $3 $4", ["8"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,, "[48]0\\d{4}",,,, "401234",,, [6]]],
          WS: [, [,, "(?:[2-6]|8\\d{5})\\d{4}|[78]\\d{6}|[68]\\d{5}",,,,,,, [5, 6, 7, 10]], [,, "6[1-9]\\d{3}|(?:[2-5]|60)\\d{4}",,,, "22123",,, [5, 6]], [,, "(?:7[1-35-7]|8(?:[3-7]|9\\d{3}))\\d{5}",,,, "7212345",,, [7, 10]], [,, "800\\d{3}",,,, "800123",,, [6]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "WS", 685, "0",,,,,,,, [[, "(\\d{5})", "$1", ["[2-5]|6[1-9]"]], [, "(\\d{3})(\\d{3,7})", "$1 $2", ["[68]"]], [, "(\\d{2})(\\d{5})", "$1 $2", ["7"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          XK: [, [,, "2\\d{7,8}|3\\d{7,11}|(?:4\\d\\d|[89]00)\\d{5}",,,,,,, [8, 9, 10, 11, 12]], [,, "38\\d{6,10}|(?:2[89]|39)(?:0\\d{5,6}|[1-9]\\d{5})",,,, "28012345"], [,, "4[3-9]\\d{6}",,,, "43201234",,, [8]], [,, "800\\d{5}",,,, "80001234",,, [8]], [,, "900\\d{5}",,,, "90001234",,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "XK", 383, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{5})", "$1 $2", ["[89]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3})", "$1 $2 $3", ["[2-4]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["2|39"], "0$1"], [, "(\\d{2})(\\d{7,10})", "$1 $2", ["3"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          YE: [, [,, "(?:1|7\\d)\\d{7}|[1-7]\\d{6}",,,,,,, [7, 8, 9], [6]], [,, "78[0-7]\\d{4}|17\\d{6}|(?:[12][2-68]|3[2358]|4[2-58]|5[2-6]|6[3-58]|7[24-6])\\d{5}",,,, "1234567",,, [7, 8], [6]], [,, "7[01378]\\d{7}",,,, "712345678",,, [9]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "YE", 967, "00", "0",,, "0",,,, [[, "(\\d)(\\d{3})(\\d{3,4})", "$1 $2 $3", ["[1-6]|7(?:[24-6]|8[0-7])"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["7"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          YT: [, [,, "(?:80|9\\d)\\d{7}|(?:26|63)9\\d{6}",,,,,,, [9]], [,, "269(?:0[0-467]|15|5[0-4]|6\\d|[78]0)\\d{4}",,,, "269601234"], [,, "639(?:0[0-79]|1[019]|[267]\\d|3[09]|40|5[05-9]|9[04-79])\\d{4}",,,, "639012345"], [,, "80\\d{7}",,,, "801234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "9(?:(?:39|47)8[01]|769\\d)\\d{4}",,,, "939801234"], "YT", 262, "00", "0",,, "0",,,,,, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ZA: [, [,, "[1-79]\\d{8}|8\\d{4,9}",,,,,,, [5, 6, 7, 8, 9, 10]], [,, "(?:2(?:0330|4302)|52087)0\\d{3}|(?:1[0-8]|2[1-378]|3[1-69]|4\\d|5[1346-8])\\d{7}",,,, "101234567",,, [9]], [,, "(?:1(?:3492[0-25]|4495[0235]|549(?:20|5[01]))|4[34]492[01])\\d{3}|8[1-4]\\d{3,7}|(?:2[27]|47|54)4950\\d{3}|(?:1(?:049[2-4]|9[12]\\d\\d)|(?:6\\d\\d|7(?:[0-46-9]\\d|5[0-4]))\\d\\d|8(?:5\\d{3}|7(?:08[67]|158|28[5-9]|310)))\\d{4}|(?:1[6-8]|28|3[2-69]|4[025689]|5[36-8])4920\\d{3}|(?:12|[2-5]1)492\\d{4}",,,, "711234567",,, [5, 6, 7, 8, 9]], [,, "80\\d{7}",,,, "801234567",,, [9]], [,, "(?:86[2-9]|9[0-2]\\d)\\d{6}",,,, "862345678",,, [9]], [,, "860\\d{6}",,,, "860123456",,, [9]], [,,,,,,,,, [-1]], [,, "87(?:08[0-589]|15[0-79]|28[0-4]|31[1-9])\\d{4}|87(?:[02][0-79]|1[0-46-9]|3[02-9]|[4-9]\\d)\\d{5}",,,, "871234567",,, [9]], "ZA", 27, "00", "0",,, "0",,,, [[, "(\\d{2})(\\d{3,4})", "$1 $2", ["8[1-4]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{2,3})", "$1 $2 $3", ["8[1-4]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["860"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["[1-9]"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["8"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "861\\d{6,7}",,,, "861123456",,, [9, 10]],,, [,,,,,,,,, [-1]]],
          ZM: [, [,, "800\\d{6}|(?:21|63|[79]\\d)\\d{7}",,,,,,, [9], [6]], [,, "21[1-8]\\d{6}",,,, "211234567",,,, [6]], [,, "(?:7[5-79]|9[5-8])\\d{7}",,,, "955123456"], [,, "800\\d{6}",,,, "800123456"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "63\\d{7}",,,, "630123456"], "ZM", 260, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3})", "$1 $2", ["[1-9]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[28]"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["[79]"], "0$1"]], [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[28]"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["[79]"], "0$1"]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          ZW: [, [,, "2(?:[0-57-9]\\d{6,8}|6[0-24-9]\\d{6,7})|[38]\\d{9}|[35-8]\\d{8}|[3-6]\\d{7}|[1-689]\\d{6}|[1-3569]\\d{5}|[1356]\\d{4}",,,,,,, [5, 6, 7, 8, 9, 10], [3, 4]], [,, "(?:1(?:(?:3\\d|9)\\d|[4-8])|2(?:(?:(?:0(?:2[014]|5)|(?:2[0157]|31|84|9)\\d\\d|[56](?:[14]\\d\\d|20)|7(?:[089]|2[03]|[35]\\d\\d))\\d|4(?:2\\d\\d|8))\\d|1(?:2|[39]\\d{4}))|3(?:(?:123|(?:29\\d|92)\\d)\\d\\d|7(?:[19]|[56]\\d))|5(?:0|1[2-478]|26|[37]2|4(?:2\\d{3}|83)|5(?:25\\d\\d|[78])|[689]\\d)|6(?:(?:[16-8]21|28|52[013])\\d\\d|[39])|8(?:[1349]28|523)\\d\\d)\\d{3}|(?:4\\d\\d|9[2-9])\\d{4,5}|(?:(?:2(?:(?:(?:0|8[146])\\d|7[1-7])\\d|2(?:[278]\\d|92)|58(?:2\\d|3))|3(?:[26]|9\\d{3})|5(?:4\\d|5)\\d\\d)\\d|6(?:(?:(?:[0-246]|[78]\\d)\\d|37)\\d|5[2-8]))\\d\\d|(?:2(?:[569]\\d|8[2-57-9])|3(?:[013-59]\\d|8[37])|6[89]8)\\d{3}",,,, "1312345",,,, [3, 4]], [,, "7(?:[1278]\\d|3[1-9])\\d{6}",,,, "712345678",,, [9]], [,, "80(?:[01]\\d|20|8[0-8])\\d{3}",,,, "8001234",,, [7]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "86(?:1[12]|22|30|44|55|77|8[368])\\d{6}",,,, "8686123456",,, [10]], "ZW", 263, "00", "0",,, "0",,,, [[, "(\\d{3})(\\d{3,5})", "$1 $2", ["2(?:0[45]|2[278]|[49]8)|3(?:[09]8|17)|6(?:[29]8|37|75)|[23][78]|(?:33|5[15]|6[68])[78]"], "0$1"], [, "(\\d)(\\d{3})(\\d{2,4})", "$1 $2 $3", ["[49]"], "0$1"], [, "(\\d{3})(\\d{4})", "$1 $2", ["80"], "0$1"], [, "(\\d{2})(\\d{7})", "$1 $2", ["24|8[13-59]|(?:2[05-79]|39|5[45]|6[15-8])2", "2(?:02[014]|4|[56]20|[79]2)|392|5(?:42|525)|6(?:[16-8]21|52[013])|8[13-59]"], "(0$1)"], [, "(\\d{2})(\\d{3})(\\d{4})", "$1 $2 $3", ["7"], "0$1"], [, "(\\d{3})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["2(?:1[39]|2[0157]|[378]|[56][14])|3(?:12|29)", "2(?:1[39]|2[0157]|[378]|[56][14])|3(?:123|29)"], "0$1"], [, "(\\d{4})(\\d{6})", "$1 $2", ["8"], "0$1"], [, "(\\d{2})(\\d{3,5})", "$1 $2", ["1|2(?:0[0-36-9]|12|29|[56])|3(?:1[0-689]|[24-6])|5(?:[0236-9]|1[2-4])|6(?:[013-59]|7[0-46-9])|(?:33|55|6[68])[0-69]|(?:29|3[09]|62)[0-79]"], "0$1"], [, "(\\d{2})(\\d{3})(\\d{3,4})", "$1 $2 $3", ["29[013-9]|39|54"], "0$1"], [, "(\\d{4})(\\d{3,5})", "$1 $2", ["(?:25|54)8", "258|5483"], "0$1"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          800: [, [,, "(?:00|[1-9]\\d)\\d{6}",,,,,,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:00|[1-9]\\d)\\d{6}",,,, "12345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 800,,,,,,,, 1, [[, "(\\d{4})(\\d{4})", "$1 $2", ["\\d"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          808: [, [,, "[1-9]\\d{7}",,,,,,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "[1-9]\\d{7}",,,, "12345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 808,,,,,,,, 1, [[, "(\\d{4})(\\d{4})", "$1 $2", ["[1-9]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          870: [, [,, "7\\d{11}|[35-7]\\d{8}",,,,,,, [9, 12]], [,,,,,,,,, [-1]], [,, "(?:[356]|774[45])\\d{8}|7[6-8]\\d{7}",,,, "301234567"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 870,,,,,,,,, [[, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["[35-7]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          878: [, [,, "10\\d{10}",,,,,,, [12]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "10\\d{10}",,,, "101234567890"], "001", 878,,,,,,,, 1, [[, "(\\d{2})(\\d{5})(\\d{5})", "$1 $2 $3", ["1"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          881: [, [,, "6\\d{9}|[0-36-9]\\d{8}",,,,,,, [9, 10]], [,,,,,,,,, [-1]], [,, "6\\d{9}|[0-36-9]\\d{8}",,,, "612345678"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 881,,,,,,,,, [[, "(\\d)(\\d{3})(\\d{5})", "$1 $2 $3", ["[0-37-9]"]], [, "(\\d)(\\d{3})(\\d{5,6})", "$1 $2 $3", ["6"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          882: [, [,, "[13]\\d{6}(?:\\d{2,5})?|[19]\\d{7}|(?:[25]\\d\\d|4)\\d{7}(?:\\d{2})?",,,,,,, [7, 8, 9, 10, 11, 12]], [,,,,,,,,, [-1]], [,, "342\\d{4}|(?:337|49)\\d{6}|(?:3(?:2|47|7\\d{3})|50\\d{3})\\d{7}",,,, "3421234",,, [7, 8, 9, 10, 12]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "1(?:3(?:0[0347]|[13][0139]|2[035]|4[013568]|6[0459]|7[06]|8[15-8]|9[0689])\\d{4}|6\\d{5,10})|(?:345\\d|9[89])\\d{6}|(?:10|2(?:3|85\\d)|3(?:[15]|[69]\\d\\d)|4[15-8]|51)\\d{8}",,,, "390123456789"], "001", 882,,,,,,,,, [[, "(\\d{2})(\\d{5})", "$1 $2", ["16|342"]], [, "(\\d{2})(\\d{6})", "$1 $2", ["49"]], [, "(\\d{2})(\\d{2})(\\d{4})", "$1 $2 $3", ["1[36]|9"]], [, "(\\d{2})(\\d{4})(\\d{3})", "$1 $2 $3", ["3[23]"]], [, "(\\d{2})(\\d{3,4})(\\d{4})", "$1 $2 $3", ["16"]], [, "(\\d{2})(\\d{4})(\\d{4})", "$1 $2 $3", ["10|23|3(?:[15]|4[57])|4|51"]], [, "(\\d{3})(\\d{4})(\\d{4})", "$1 $2 $3", ["34"]], [, "(\\d{2})(\\d{4,5})(\\d{5})", "$1 $2 $3", ["[1-35]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,, "348[57]\\d{7}",,,, "34851234567",,, [11]]],
          883: [, [,, "(?:[1-4]\\d|51)\\d{6,10}",,,,,,, [8, 9, 10, 11, 12]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "(?:2(?:00\\d\\d|10)|(?:370[1-9]|51\\d0)\\d)\\d{7}|51(?:00\\d{5}|[24-9]0\\d{4,7})|(?:1[0-79]|2[24-689]|3[02-689]|4[0-4])0\\d{5,9}",,,, "510012345"], "001", 883,,,,,,,, 1, [[, "(\\d{3})(\\d{3})(\\d{2,8})", "$1 $2 $3", ["[14]|2[24-689]|3[02-689]|51[24-9]"]], [, "(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3", ["510"]], [, "(\\d{3})(\\d{3})(\\d{4})", "$1 $2 $3", ["21"]], [, "(\\d{4})(\\d{4})(\\d{4})", "$1 $2 $3", ["51[13]"]], [, "(\\d{3})(\\d{3})(\\d{3})(\\d{3})", "$1 $2 $3 $4", ["[235]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]],
          888: [, [,, "\\d{11}",,,,,,, [11]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 888,,,,,,,, 1, [[, "(\\d{3})(\\d{3})(\\d{5})", "$1 $2 $3"]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,, "\\d{11}",,,, "12345678901"],,, [,,,,,,,,, [-1]]],
          979: [, [,, "[1359]\\d{8}",,,,,,, [9], [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,, "[1359]\\d{8}",,,, "123456789",,,, [8]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]], "001", 979,,,,,,,, 1, [[, "(\\d)(\\d{4})(\\d{4})", "$1 $2 $3", ["[1359]"]]],, [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,, [,,,,,,,,, [-1]]]
        }; /*
           Copyright (C) 2010 The Libphonenumber Authors.
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
           http://www.apache.org/licenses/LICENSE-2.0
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
           */
      function I() {
        this.g = {};
      }
      ba(I);
      var Ga = {
          0: "0",
          1: "1",
          2: "2",
          3: "3",
          4: "4",
          5: "5",
          6: "6",
          7: "7",
          8: "8",
          9: "9",
          "\uff10": "0",
          "\uff11": "1",
          "\uff12": "2",
          "\uff13": "3",
          "\uff14": "4",
          "\uff15": "5",
          "\uff16": "6",
          "\uff17": "7",
          "\uff18": "8",
          "\uff19": "9",
          "\u0660": "0",
          "\u0661": "1",
          "\u0662": "2",
          "\u0663": "3",
          "\u0664": "4",
          "\u0665": "5",
          "\u0666": "6",
          "\u0667": "7",
          "\u0668": "8",
          "\u0669": "9",
          "\u06f0": "0",
          "\u06f1": "1",
          "\u06f2": "2",
          "\u06f3": "3",
          "\u06f4": "4",
          "\u06f5": "5",
          "\u06f6": "6",
          "\u06f7": "7",
          "\u06f8": "8",
          "\u06f9": "9"
        },
        Ha = {
          0: "0",
          1: "1",
          2: "2",
          3: "3",
          4: "4",
          5: "5",
          6: "6",
          7: "7",
          8: "8",
          9: "9",
          "+": "+",
          "*": "*",
          "#": "#"
        },
        Ia = {
          0: "0",
          1: "1",
          2: "2",
          3: "3",
          4: "4",
          5: "5",
          6: "6",
          7: "7",
          8: "8",
          9: "9",
          "\uff10": "0",
          "\uff11": "1",
          "\uff12": "2",
          "\uff13": "3",
          "\uff14": "4",
          "\uff15": "5",
          "\uff16": "6",
          "\uff17": "7",
          "\uff18": "8",
          "\uff19": "9",
          "\u0660": "0",
          "\u0661": "1",
          "\u0662": "2",
          "\u0663": "3",
          "\u0664": "4",
          "\u0665": "5",
          "\u0666": "6",
          "\u0667": "7",
          "\u0668": "8",
          "\u0669": "9",
          "\u06f0": "0",
          "\u06f1": "1",
          "\u06f2": "2",
          "\u06f3": "3",
          "\u06f4": "4",
          "\u06f5": "5",
          "\u06f6": "6",
          "\u06f7": "7",
          "\u06f8": "8",
          "\u06f9": "9",
          A: "2",
          B: "2",
          C: "2",
          D: "3",
          E: "3",
          F: "3",
          G: "4",
          H: "4",
          I: "4",
          J: "5",
          K: "5",
          L: "5",
          M: "6",
          N: "6",
          O: "6",
          P: "7",
          Q: "7",
          R: "7",
          S: "7",
          T: "8",
          U: "8",
          V: "8",
          W: "9",
          X: "9",
          Y: "9",
          Z: "9"
        },
        Ja = /[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?/,
        Ka = RegExp("[+\uff0b]+"),
        J = RegExp("^[+\uff0b]+"),
        La = RegExp("([0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9])"),
        Ma = RegExp("[+\uff0b0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]"),
        Na = /[\\\/] *x/,
        Oa = RegExp("[^0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9A-Za-z#]+$"),
        Pa = /(?:.*?[A-Za-z]){3}.*/,
        Qa = RegExp("^\\+([0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]|[\\-\\.\\(\\)]?)*[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]([0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]|[\\-\\.\\(\\)]?)*$"),
        Ra = RegExp("^([A-Za-z0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]+((\\-)*[A-Za-z0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9])*\\.)*[A-Za-z]+((\\-)*[A-Za-z0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9])*\\.?$");
      function K(a) {
        return "([0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]{1," + a + "})";
      }
      function Sa() {
        return ";ext=" + K("20") + "|[ \u00a0\\t,]*(?:e?xt(?:ensi(?:o\u0301?|\u00f3))?n?|\uff45?\uff58\uff54\uff4e?|\u0434\u043e\u0431|anexo)[:\\.\uff0e]?[ \u00a0\\t,-]*" + (K("20") + "#?|[ \u00a0\\t,]*(?:[x\uff58#\uff03~\uff5e]|int|\uff49\uff4e\uff54)[:\\.\uff0e]?[ \u00a0\\t,-]*") + (K("9") + "#?|[- ]+") + (K("6") + "#|[ \u00a0\\t]*(?:,{2}|;)[:\\.\uff0e]?[ \u00a0\\t,-]*") + (K("15") + "#?|[ \u00a0\\t]*(?:,)+[:\\.\uff0e]?[ \u00a0\\t,-]*") + (K("9") + "#?");
      }
      var Ta = new RegExp("(?:" + Sa() + ")$", "i"),
        Ua = new RegExp("^[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]{2}$|^[+\uff0b]*(?:[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e*]*[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]){3,}[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e*A-Za-z0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]*(?:" + Sa() + ")?$", "i"),
        Va = /(\$\d)/,
        Wa = /^\(?\$1\)?$/;
      function Xa(a) {
        return 2 > a.length ? !1 : L(Ua, a);
      }
      function Ya(a) {
        return L(Pa, a) ? M(a, Ia) : M(a, Ga);
      }
      function Za(a) {
        var b = Ya(a.toString());
        A(a);
        a.g(b);
      }
      function $a() {
        return Object.keys(H).filter(function (a) {
          return isNaN(a);
        });
      }
      function ab() {
        return Object.keys(H).filter(function (a) {
          return !isNaN(a);
        }).map(function (a) {
          return parseInt(a, 10);
        });
      }
      function bb() {
        var a = Object.keys(F);
        return [...ab(), ...a.map(function (b) {
          return parseInt(b, 10);
        })];
      }
      function M(a, b) {
        for (var c = new z(), d, e = a.length, f = 0; f < e; ++f) d = a.charAt(f), d = b[d.toUpperCase()], null != d && c.g(d);
        return c.toString();
      }
      function db(a) {
        return 0 == a.length || Wa.test(a);
      }
      function N(a) {
        return null != a && isNaN(a) && a.toUpperCase() in H;
      }
      I.prototype.format = function (a, b) {
        if (0 == p(a, 2) && m(a, 5)) {
          var c = u(a, 5);
          if (0 < c.length) return c;
        }
        c = u(a, 1);
        var d = O(a);
        if (0 == b) return eb(c, 0, d, "");
        if (!(c in F)) return d;
        var e = P(this, c, Q(c));
        a = fb(a, e, b);
        d = gb(d, e, b);
        return eb(c, b, d, a);
      };
      function P(a, b, c) {
        return "001" == c ? R(a, "" + b) : R(a, c);
      }
      function hb(a, b) {
        var c = S;
        if (!N(b)) return c.format(a, 1);
        var d = u(a, 1),
          e = O(a);
        if (!(d in F)) return e;
        if (1 == d) {
          if (null != b && F[1].includes(b.toUpperCase())) return d + " " + c.format(a, 2);
        } else if (d == T(c, b)) return c.format(a, 2);
        var f = R(c, b),
          g = u(f, 11);
        b = "";
        m(f, 17) ? b = u(f, 17) : L(Ja, g) && (b = g);
        c = P(c, d, Q(d));
        e = gb(e, c, 1);
        a = fb(a, c, 1);
        return 0 < b.length ? b + " " + d + " " + e + a : eb(d, 1, e, a);
      }
      function O(a) {
        if (!m(a, 2)) return "";
        var b = "" + p(a, 2);
        return m(a, 4) && p(a, 4) && 0 < u(a, 8) ? Array(u(a, 8) + 1).join("0") + b : b;
      }
      function eb(a, b, c, d) {
        switch (b) {
          case 0:
            return "+" + a + c + d;
          case 1:
            return "+" + a + " " + c + d;
          case 3:
            return "tel:+" + a + "-" + c + d;
          default:
            return c + d;
        }
      }
      function gb(a, b, c) {
        b = 0 == r(b, 20).length || 2 == c ? r(b, 19) : r(b, 20);
        a: {
          for (var d, e = b.length, f = 0; f < e; ++f) {
            d = b[f];
            var g = v(d, 3);
            if (0 == g || 0 == a.search(p(d, 3, g - 1))) if (g = new RegExp(p(d, 1)), L(g, a)) {
              b = d;
              break a;
            }
          }
          b = null;
        }
        null == b ? c = a : (e = b, b = u(e, 2), d = new RegExp(p(e, 1)), u(e, 5), e = u(e, 4), a = 2 == c && null != e && 0 < e.length ? a.replace(d, b.replace(Va, e)) : a.replace(d, b), 3 == c && (a = a.replace(RegExp("^[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]+"), ""), a = a.replace(RegExp("[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]+", "g"), "-")), c = a);
        return c;
      }
      function ib(a, b) {
        var c = S;
        if (!N(a)) return null;
        b = jb(R(c, a), b);
        try {
          if (m(b, 6)) {
            var d = p(b, 6);
            return kb(c, d, a);
          }
        } catch (e) {}
        return null;
      }
      function fb(a, b, c) {
        return m(a, 3) && 0 != p(a, 3).length ? 3 == c ? ";ext=" + p(a, 3) : m(b, 13) ? p(b, 13) + u(a, 3) : " ext. " + u(a, 3) : "";
      }
      function jb(a, b) {
        switch (b) {
          case 4:
            return p(a, 5);
          case 3:
            return p(a, 4);
          case 1:
            return p(a, 3);
          case 0:
          case 2:
            return p(a, 2);
          case 5:
            return p(a, 6);
          case 6:
            return p(a, 8);
          case 7:
            return p(a, 7);
          case 8:
            return p(a, 21);
          case 9:
            return p(a, 25);
          case 10:
            return p(a, 28);
          default:
            return p(a, 1);
        }
      }
      function lb(a, b) {
        return U(a, p(b, 1)) ? U(a, p(b, 5)) ? 4 : U(a, p(b, 4)) ? 3 : U(a, p(b, 6)) ? 5 : U(a, p(b, 8)) ? 6 : U(a, p(b, 7)) ? 7 : U(a, p(b, 21)) ? 8 : U(a, p(b, 25)) ? 9 : U(a, p(b, 28)) ? 10 : U(a, p(b, 2)) ? p(b, 18) || U(a, p(b, 3)) ? 2 : 0 : !p(b, 18) && U(a, p(b, 3)) ? 1 : -1 : -1;
      }
      function R(a, b) {
        if (null == b) return null;
        b = b.toUpperCase();
        var c = a.g[b];
        if (null == c) {
          c = H[b];
          if (null == c) return null;
          c = new y().g(D.o(), c);
          a.g[b] = c;
        }
        return c;
      }
      function U(a, b) {
        var c = a.length;
        return 0 < v(b, 9) && -1 == r(b, 9).indexOf(c) ? !1 : L(u(b, 2), a);
      }
      function mb(a) {
        var b = S,
          c = nb(b, a);
        var d = u(a, 1);
        var e = P(b, d, c);
        null == e || "001" != c && d != T(b, c) ? e = !1 : (a = O(a), e = -1 != lb(a, e));
        return e;
      }
      function nb(a, b) {
        if (null == b) return null;
        var c = u(b, 1);
        c = F[c];
        if (null == c) a = null;else if (1 == c.length) a = c[0];else a: {
          b = O(b);
          for (var d, e = c.length, f = 0; f < e; f++) {
            d = c[f];
            var g = R(a, d);
            if (m(g, 23)) {
              if (0 == b.search(p(g, 23))) {
                a = d;
                break a;
              }
            } else if (-1 != lb(b, g)) {
              a = d;
              break a;
            }
          }
          a = null;
        }
        return a;
      }
      function Q(a) {
        a = F[a];
        return null == a ? "ZZ" : a[0];
      }
      function T(a, b) {
        a = R(a, b);
        if (null == a) throw Error("Invalid region code: " + b);
        return u(a, 10);
      }
      function ob(a) {
        a = pb(a);
        return 0 == a || 4 == a;
      }
      function qb(a, b, c, d) {
        var e = jb(c, d),
          f = 0 == v(e, 9) ? r(p(c, 1), 9) : r(e, 9);
        e = r(e, 10);
        if (-1 == f[0]) return 5;
        b = b.length;
        if (-1 < e.indexOf(b)) return 4;
        c = f[0];
        return c == b ? 0 : c > b ? 2 : f[f.length - 1] < b ? 3 : -1 < f.indexOf(b, 1) ? 0 : 5;
      }
      function pb(a) {
        var b = S,
          c = O(a);
        a = u(a, 1);
        if (!(a in F)) return 1;
        a = P(b, a, Q(a));
        return qb(b, c, a, -1);
      }
      function rb(a, b) {
        a = a.toString();
        if (0 == a.length || "0" == a.charAt(0)) return 0;
        for (var c, d = a.length, e = 1; 3 >= e && e <= d; ++e) if (c = parseInt(a.substring(0, e), 10), c in F) return b.g(a.substring(e)), c;
        return 0;
      }
      function sb(a, b, c, d, e) {
        if (0 == b.length) return 0;
        b = new z(b);
        var f;
        null != c && (f = p(c, 11));
        null == f && (f = "NonMatch");
        var g = b.toString();
        if (0 == g.length) f = 20;else if (J.test(g)) g = g.replace(J, ""), A(b), b.g(Ya(g)), f = 1;else {
          g = new RegExp(f);
          Za(b);
          f = b.toString();
          if (0 == f.search(g)) {
            g = f.match(g)[0].length;
            var l = f.substring(g).match(La);
            l && null != l[1] && 0 < l[1].length && "0" == M(l[1], Ga) ? f = !1 : (A(b), b.g(f.substring(g)), f = !0);
          } else f = !1;
          f = f ? 5 : 20;
        }
        if (20 != f) {
          if (2 >= b.h.length) throw Error("Phone number too short after IDD");
          a = rb(b, d);
          if (0 != a) return q(e, 1, a), a;
          throw Error("Invalid country calling code");
        }
        if (null != c && (f = u(c, 10), g = "" + f, l = b.toString(), 0 == l.lastIndexOf(g, 0) && (g = new z(l.substring(g.length)), l = p(c, 1), l = new RegExp(u(l, 2)), tb(g, c, null), g = g.toString(), !L(l, b.toString()) && L(l, g) || 3 == qb(a, b.toString(), c, -1)))) return d.g(g), q(e, 1, f), f;
        q(e, 1, 0);
        return 0;
      }
      function tb(a, b, c) {
        var d = a.toString(),
          e = d.length,
          f = p(b, 15);
        if (0 != e && null != f && 0 != f.length) {
          var g = new RegExp("^(?:" + f + ")");
          if (e = g.exec(d)) {
            f = new RegExp(u(p(b, 1), 2));
            var l = L(f, d),
              n = e.length - 1;
            b = p(b, 16);
            if (null == b || 0 == b.length || null == e[n] || 0 == e[n].length) {
              if (!l || L(f, d.substring(e[0].length))) null != c && 0 < n && null != e[n] && c.g(e[1]), a.set(d.substring(e[0].length));
            } else if (d = d.replace(g, b), !l || L(f, d)) null != c && 0 < n && c.g(e[1]), a.set(d);
          }
        }
      }
      function kb(a, b, c) {
        if (null == b) throw Error("The string supplied did not seem to be a phone number");
        if (250 < b.length) throw Error("The string supplied is too long to be a phone number");
        var d = new z();
        var e = b.indexOf(";phone-context=");
        if (-1 === e) e = null;else if (e += 15, e >= b.length) e = "";else {
          var f = b.indexOf(";", e);
          e = -1 !== f ? b.substring(e, f) : b.substring(e);
        }
        var g = e;
        null == g ? f = !0 : 0 === g.length ? f = !1 : (f = Qa.exec(g), g = Ra.exec(g), f = null !== f || null !== g);
        if (!f) throw Error("The string supplied did not seem to be a phone number");
        null != e ? ("+" === e.charAt(0) && d.g(e), e = b.indexOf("tel:"), d.g(b.substring(0 <= e ? e + 4 : 0, b.indexOf(";phone-context=")))) : (e = d.g, b = null != b ? b : "", f = b.search(Ma), 0 <= f ? (b = b.substring(f), b = b.replace(Oa, ""), f = b.search(Na), 0 <= f && (b = b.substring(0, f))) : b = "", e.call(d, b));
        b = d.toString();
        e = b.indexOf(";isub=");
        0 < e && (A(d), d.g(b.substring(0, e)));
        if (!Xa(d.toString())) throw Error("The string supplied did not seem to be a phone number");
        b = d.toString();
        if (!(N(c) || null != b && 0 < b.length && J.test(b))) throw Error("Invalid country calling code");
        b = new E();
        a: {
          e = d.toString();
          f = e.search(Ta);
          if (0 <= f && Xa(e.substring(0, f))) {
            g = e.match(Ta);
            for (var l = g.length, n = 1; n < l; ++n) if (null != g[n] && 0 < g[n].length) {
              A(d);
              d.g(e.substring(0, f));
              e = g[n];
              break a;
            }
          }
          e = "";
        }
        0 < e.length && q(b, 3, e);
        f = R(a, c);
        e = new z();
        g = 0;
        l = d.toString();
        try {
          g = sb(a, l, f, e, b);
        } catch (G) {
          if ("Invalid country calling code" == G.message && J.test(l)) {
            if (l = l.replace(J, ""), g = sb(a, l, f, e, b), 0 == g) throw G;
          } else throw G;
        }
        0 != g ? (d = Q(g), d != c && (f = P(a, g, d))) : (Za(d), e.g(d.toString()), null != c && (g = u(f, 10), q(b, 1, g)));
        if (2 > e.h.length) throw Error("The string supplied is too short to be a phone number");
        null != f && (c = new z(e.toString()), tb(c, f, new z()), a = qb(a, c.toString(), f, -1), 2 != a && 4 != a && 5 != a && (e = c));
        a = e.toString();
        c = a.length;
        if (2 > c) throw Error("The string supplied is too short to be a phone number");
        if (17 < c) throw Error("The string supplied is too long to be a phone number");
        if (1 < a.length && "0" == a.charAt(0)) {
          q(b, 4, !0);
          for (c = 1; c < a.length - 1 && "0" == a.charAt(c);) c++;
          1 != c && q(b, 8, c);
        }
        q(b, 2, parseInt(a, 10));
        return b;
      }
      I.prototype.ja = function (a) {
        var b = R(this, nb(this, a));
        if (null == b) return !0;
        a = O(a);
        return !U(a, p(b, 24));
      };
      function L(a, b) {
        return (a = "string" == typeof a ? b.match("^(?:" + a + ")$") : b.match(a)) && a[0].length == b.length ? !0 : !1;
      }
      function ub(a) {
        this.ka = RegExp("\u2008");
        this.la = "";
        this.$ = new z();
        this.da = "";
        this.u = new z();
        this.ba = new z();
        this.v = !0;
        this.ea = this.ca = this.oa = !1;
        this.qa = I.pa();
        this.aa = 0;
        this.h = new z();
        this.ha = !1;
        this.s = "";
        this.g = new z();
        this.j = [];
        this.ma = a;
        this.Aa = this.m = vb(this, this.ma);
      }
      var wb = new D();
      q(wb, 11, "NA");
      var xb = RegExp("^[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]*\\$1[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]*(\\$\\d[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]*)*$"),
        yb = /[- ]/;
      function vb(a, b) {
        b = N(b) ? T(a.qa, b) : 0;
        a = R(a.qa, Q(b));
        return null != a ? a : wb;
      }
      function zb(a) {
        for (var b = a.j.length, c = 0; c < b; ++c) {
          var d = a.j[c],
            e = u(d, 1);
          if (a.da == e) return !1;
          var f = a;
          var g = d,
            l = u(g, 1);
          A(f.$);
          var n = f;
          g = u(g, 2);
          var G = "999999999999999".match(l)[0];
          G.length < n.g.h.length ? n = "" : (n = G.replace(new RegExp(l, "g"), g), n = n.replace(RegExp("9", "g"), "\u2008"));
          0 < n.length ? (f.$.g(n), f = !0) : f = !1;
          if (f) return a.da = e, a.ha = yb.test(p(d, 4)), a.aa = 0, !0;
        }
        return a.v = !1;
      }
      function Ab(a, b) {
        for (var c = [], d = b.length - 3, e = a.j.length, f = 0; f < e; ++f) {
          var g = a.j[f];
          0 == v(g, 3) ? c.push(a.j[f]) : (g = p(g, 3, Math.min(d, v(g, 3) - 1)), 0 == b.search(g) && c.push(a.j[f]));
        }
        a.j = c;
      }
      function Bb(a, b) {
        a.u.g(b);
        var c = b;
        La.test(c) || 1 == a.u.h.length && Ka.test(c) ? ("+" == b ? (c = b, a.ba.g(b)) : (c = Ga[b], a.ba.g(c), a.g.g(c)), b = c) : (a.v = !1, a.oa = !0);
        if (!a.v) {
          if (!a.oa) if (Cb(a)) {
            if (Db(a)) return Eb(a);
          } else if (0 < a.s.length && (b = a.g.toString(), A(a.g), a.g.g(a.s), a.g.g(b), b = a.h.toString(), c = b.lastIndexOf(a.s), A(a.h), a.h.g(b.substring(0, c))), a.s != Fb(a)) return a.h.g(" "), Eb(a);
          return a.u.toString();
        }
        switch (a.ba.h.length) {
          case 0:
          case 1:
          case 2:
            return a.u.toString();
          case 3:
            if (Cb(a)) a.ea = !0;else return a.s = Fb(a), Gb(a);
          default:
            if (a.ea) return Db(a) && (a.ea = !1), a.h.toString() + a.g.toString();
            if (0 < a.j.length) {
              b = Hb(a, b);
              c = Ib(a);
              if (0 < c.length) return c;
              Ab(a, a.g.toString());
              return zb(a) ? Jb(a) : a.v ? Kb(a, b) : a.u.toString();
            }
            return Gb(a);
        }
      }
      function Eb(a) {
        a.v = !0;
        a.ea = !1;
        a.j = [];
        a.aa = 0;
        A(a.$);
        a.da = "";
        return Gb(a);
      }
      function Ib(a) {
        for (var b = a.g.toString(), c = a.j.length, d = 0; d < c; ++d) {
          var e = a.j[d],
            f = u(e, 1);
          if (new RegExp("^(?:" + f + ")$").test(b) && (a.ha = yb.test(p(e, 4)), e = b.replace(new RegExp(f, "g"), p(e, 2)), e = Kb(a, e), M(e, Ha) == a.ba)) return e;
        }
        return "";
      }
      function Kb(a, b) {
        var c = a.h.h.length;
        return a.ha && 0 < c && " " != a.h.toString().charAt(c - 1) ? a.h + " " + b : a.h + b;
      }
      function Gb(a) {
        var b = a.g.toString();
        if (3 <= b.length) {
          for (var c = a.ca && 0 == a.s.length && 0 < v(a.m, 20) ? r(a.m, 20) : r(a.m, 19), d = c.length, e = 0; e < d; ++e) {
            var f = c[e];
            0 < a.s.length && db(u(f, 4)) && !p(f, 6) && !m(f, 5) || (0 != a.s.length || a.ca || db(u(f, 4)) || p(f, 6)) && xb.test(u(f, 2)) && a.j.push(f);
          }
          Ab(a, b);
          b = Ib(a);
          return 0 < b.length ? b : zb(a) ? Jb(a) : a.u.toString();
        }
        return Kb(a, b);
      }
      function Jb(a) {
        var b = a.g.toString(),
          c = b.length;
        if (0 < c) {
          for (var d = "", e = 0; e < c; e++) d = Hb(a, b.charAt(e));
          return a.v ? Kb(a, d) : a.u.toString();
        }
        return a.h.toString();
      }
      function Fb(a) {
        var b = a.g.toString(),
          c = 0;
        if (1 != a.m.ia()) var d = !1;else d = a.g.toString(), d = "1" == d.charAt(0) && "0" != d.charAt(1) && "1" != d.charAt(1);
        d ? (c = 1, a.h.g("1").g(" "), a.ca = !0) : m(a.m, 15) && (d = new RegExp("^(?:" + p(a.m, 15) + ")"), d = b.match(d), null != d && null != d[0] && 0 < d[0].length && (a.ca = !0, c = d[0].length, a.h.g(b.substring(0, c))));
        A(a.g);
        a.g.g(b.substring(c));
        return b.substring(0, c);
      }
      function Cb(a) {
        var b = a.ba.toString(),
          c = new RegExp("^(?:\\+|" + p(a.m, 11) + ")");
        c = b.match(c);
        return null != c && null != c[0] && 0 < c[0].length ? (a.ca = !0, c = c[0].length, A(a.g), a.g.g(b.substring(c)), A(a.h), a.h.g(b.substring(0, c)), "+" != b.charAt(0) && a.h.g(" "), !0) : !1;
      }
      function Db(a) {
        if (0 == a.g.h.length) return !1;
        var b = new z(),
          c = rb(a.g, b);
        if (0 == c) return !1;
        A(a.g);
        a.g.g(b.toString());
        b = Q(c);
        "001" == b ? a.m = R(a.qa, "" + c) : b != a.ma && (a.m = vb(a, b));
        a.h.g("" + c).g(" ");
        a.s = "";
        return !0;
      }
      function Hb(a, b) {
        var c = a.$.toString();
        if (0 <= c.substring(a.aa).search(a.ka)) {
          var d = c.search(a.ka);
          b = c.replace(a.ka, b);
          A(a.$);
          a.$.g(b);
          a.aa = d;
          return b.substring(0, a.aa + 1);
        }
        1 == a.j.length && (a.v = !1);
        a.da = "";
        return a.u.toString();
      }
      var Lb = {
        AC: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "AC",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "9(?:11|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        AD: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[0268]",,,, "110"], [,,,,,,,,, [-1]],,,, "AD",,,,,,,,,,,,,,,,,, [,, "11[0268]",,,, "110"],, [,, "11[0268]",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        AE: [, [,, "[149]\\d{2,3}",,,,,,, [3, 4]],,, [,, "112|99[7-9]",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "AE",,,,,,,,,,,,,,,,,, [,, "112|99[7-9]",,,, "112",,, [3]],, [,, "112|445[16]|99[7-9]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "445\\d",,,, "4450",,, [4]]],
        AF: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "1(?:0[02]|19)",,,, "100",,, [3]], [,,,,,,,,, [-1]],,,, "AF",,,,,,,,,,,,,,,,,, [,, "1(?:0[02]|19)",,,, "100",,, [3]],, [,, "1(?:0[02]|19)|40404",,,, "100"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        AG: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "AG",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "176|9(?:11|88|99)",,,, "176"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        AI: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "AI",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "176|9(?:11|88)",,,, "176"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        AL: [, [,, "[15]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1(?:2|6[01]\\d\\d)|2[7-9]|3[15]|41)",,,, "112",,, [3, 6]], [,, "5\\d{4}",,,, "50000",,, [5]],,,, "AL",,,,,,,,,,,,,,,,,, [,, "1(?:12|2[7-9])",,,, "112",,, [3]],, [,, "1(?:1(?:6(?:000|1(?:06|11|23))|8\\d\\d)|65\\d|89[12])|5\\d{4}|1(?:[1349]\\d|2[2-9])",,,, "110"], [,,,,,,,,, [-1]], [,, "123",,,, "123",,, [3]],, [,, "131|5\\d{4}",,,, "131",,, [3, 5]]],
        AM: [, [,, "[148]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "10[1-3]",,,, "101",,, [3]], [,,,,,,,,, [-1]],,,, "AM",,,,,,,,,,,,,,,,,, [,, "10[1-3]",,,, "101",,, [3]],, [,, "(?:1|8[1-7])\\d\\d|40404",,,, "100"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        AO: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[235]",,,, "112"], [,,,,,,,,, [-1]],,,, "AO",,,,,,,,,,,,,,,,,, [,, "11[235]",,,, "112"],, [,, "11[235]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        AR: [, [,, "[01389]\\d{1,4}",,,,,,, [2, 3, 4, 5]],,, [,, "000|1(?:0[0-35-7]|1[0245]|2[015]|3[47]|4[478]|9)|911",,,, "19",,, [2, 3]], [,,,,,,,,, [-1]],,,, "AR",,,,,,,,,,,,,,,,,, [,, "10[017]|911",,,, "100",,, [3]],, [,, "000|1(?:0[0-35-7]|1[02-5]|2[015]|3[47]|4[478]|9)|3372|89338|911",,,, "19"], [,,,,,,,,, [-1]], [,, "893\\d\\d",,,, "89300",,, [5]],, [,, "(?:337|893\\d)\\d",,,, "3370",,, [4, 5]]],
        AS: [, [,, "[49]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "9(?:11|88)",,,, "911",,, [3]], [,,,,,,,,, [-1]],,,, "AS",,,,,,,,,,,,,,,,,, [,, "911",,,, "911",,, [3]],, [,, "40404|9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        AT: [, [,, "[1268]\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "1(?:12|2[0238]|3[03]|4[0-247])|1(?:16\\d\\d|4[58])\\d",,,, "112"], [,,,,,,,,, [-1]],,,, "AT",,,,,,,,,,,,,,,,,, [,, "1(?:[12]2|33|44)",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:00[06]|1(?:17|23)))|2[0238]|3[03]|4(?:[0-247]|5[05]|84))|(?:220|61|8108[1-3])0",,,, "112"], [,,,,,,,,, [-1]], [,, "(?:220|810\\d\\d)\\d|610",,,, "610"],, [,,,,,,,,, [-1]]],
        AU: [, [,, "[0-27]\\d{2,7}",,,,,,, [3, 4, 5, 6, 7, 8]],,, [,, "000|1(?:06|12|258885|55\\d)|733",,,, "000",,, [3, 4, 7]], [,, "1(?:2(?:34|456)|9\\d{4,6})",,,, "1234",,, [4, 5, 6, 7, 8]],,,, "AU",,,,,,,,,,,,,,,,,, [,, "000|1(?:06|12)",,,, "000",,, [3]],, [,, "000|1(?:06|1(?:00|2|9[46])|2(?:014[1-3]|[23]\\d|(?:4|5\\d)\\d{2,3}|68[689]|72(?:20|3\\d\\d)|8(?:[013-9]\\d|2))|555|9\\d{4,6})|225|7(?:33|67)",,,, "000"], [,, "1(?:1[09]\\d|24733)|225|767",,,, "225",,, [3, 4, 6]], [,, "1(?:258885|55\\d)",,,, "1550",,, [4, 7]],, [,, "19\\d{4,6}",,,, "190000",,, [6, 7, 8]]],
        AW: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "100|911",,,, "100"], [,,,,,,,,, [-1]],,,, "AW",,,,,,,,,,,,,,,,,, [,, "100|911",,,, "100"],, [,, "1(?:00|18|76)|91[13]",,,, "100"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        AX: [, [,, "[17]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "112",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "AX",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "112|75[12]\\d\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        AZ: [, [,, "[148]\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:0[1-3]|12)",,,, "101",,, [3]], [,,,,,,,,, [-1]],,,, "AZ",,,,,,,,,,,,,,,,,, [,, "1(?:0[1-3]|12)",,,, "101",,, [3]],, [,, "1(?:0[1-3]|12)|(?:404|880)0",,,, "101"], [,,,,,,,,, [-1]], [,, "(?:404|880)\\d",,,, "4040",,, [4]],, [,, "(?:404|880)\\d",,,, "4040",,, [4]]],
        BA: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:16\\d{3}|2[2-4])",,,, "122",,, [3, 6]], [,,,,,,,,, [-1]],,,, "BA",,,,,,,,,,,,,,,,,, [,, "12[2-4]",,,, "122",,, [3]],, [,, "1(?:16(?:00[06]|1(?:1[17]|23))|2(?:0[0-7]|[2-5]|6[0-26])|(?:[3-5]|7\\d)\\d\\d)|1(?:18|2[78])\\d\\d?",,,, "122"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BB: [, [,, "[2-689]\\d\\d",,,,,,, [3]],,, [,, "988|[2359]11",,,, "211"], [,,,,,,,,, [-1]],,,, "BB",,,,,,,,,,,,,,,,,, [,, "[2359]11",,,, "211"],, [,, "988|[2-689]11",,,, "211"], [,,,,,,,,, [-1]], [,, "[468]11",,,, "411"],, [,,,,,,,,, [-1]]],
        BD: [, [,, "[1579]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "10[0-26]|[19]99",,,, "100",,, [3]], [,,,,,,,,, [-1]],,,, "BD",,,,,,,,,,,,,,,,,, [,, "10[0-2]|[19]99",,,, "100",,, [3]],, [,, "1(?:0(?:[0-369]|5[1-4]|7[0-4]|8[0-29])|1[16-9]|2(?:[134]|2[0-5])|3(?:1\\d?|6[3-6])|5[2-9])|5012|786|9594|[19]99|1(?:0(?:50|6\\d)|33|4(?:0|1\\d))\\d",,,, "100"], [,,,,,,,,, [-1]], [,, "1(?:11|2[13])|(?:501|959)\\d|786",,,, "111",,, [3, 4]],, [,, "959\\d",,,, "9590",,, [4]]],
        BE: [, [,, "[1-9]\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "1(?:0[0-35-8]|1[0269]|7(?:12|77)|813)|(?:116|8)\\d{3}",,,, "100"], [,, "1(?:2[03]|40)4|(?:1(?:[24]1|3[01])|[2-79]\\d\\d)\\d",,,, "1204",,, [4]],,,, "BE",,,,,,,,,,,,,,,,,, [,, "1(?:0[01]|12)",,,, "100",,, [3]],, [,, "1(?:0[0-8]|16117|2(?:12|3[0-24])|313|414|5(?:1[05]|5[15]|66|95)|6(?:1[167]|36|6[16])|7(?:[07][017]|1[27-9]|22|33|65)|81[39])|[2-9]\\d{3}|11[02679]|1(?:1600|45)0|1(?:[2-4]9|78)9|1[2-4]0[47]",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "[2-9]\\d{3}",,,, "2000",,, [4]]],
        BF: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]],,,, "BF",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17"],, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BG: [, [,, "1\\d\\d(?:\\d{3})?",,,,,,, [3, 6]],,, [,, "1(?:1(?:2|6\\d{3})|50|6[06])",,,, "112"], [,,,,,,,,, [-1]],,,, "BG",,,,,,,,,,,,,,,,,, [,, "1(?:12|50|6[06])",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:000|111))|50|6[06])",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BH: [, [,, "[0189]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "(?:0[167]|81)\\d{3}|[19]99",,,, "199"], [,, "9[148]\\d{3}",,,, "91000",,, [5]],,,, "BH",,,,,,,,,,,,,,,,,, [,, "[19]99",,,, "199",,, [3]],, [,, "1(?:[02]\\d|12|4[01]|51|8[18]|9[169])|99[02489]|(?:0[167]|8[158]|9[148])\\d{3}",,,, "100"], [,,,,,,,,, [-1]], [,, "0[67]\\d{3}|88000|98555",,,, "06000",,, [5]],, [,, "88000|98555",,,, "88000",,, [5]]],
        BI: [, [,, "[16-9]\\d{2,3}",,,,,,, [3, 4]],,, [,, "11[237]|611",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "BI",,,,,,,,,,,,,,,,,, [,, "11[237]",,,, "112",,, [3]],, [,, "1(?:1\\d|5[2-9]|6[0-256])|611|7(?:10|77|979)|8[28]8|900",,,, "110"], [,,,,,,,,, [-1]], [,, "611|7(?:10|77)|888|900",,,, "611",,, [3]],, [,, "(?:71|90)0",,,, "710",,, [3]]],
        BJ: [, [,, "[17]\\d{2,3}",,,,,,, [3, 4]],,, [,, "11[78]|7[3-5]\\d\\d",,,, "117"], [,,,,,,,,, [-1]],,,, "BJ",,,,,,,,,,,,,,,,,, [,, "11[78]",,,, "117",,, [3]],, [,, "1(?:1[78]|2[02-5]|60)|7[0-5]\\d\\d",,,, "117"], [,,,,,,,,, [-1]], [,, "12[02-5]",,,, "120",,, [3]],, [,,,,,,,,, [-1]]],
        BL: [, [,, "1\\d",,,,,,, [2]],,, [,, "18",,,, "18"], [,,,,,,,,, [-1]],,,, "BL",,,,,,,,,,,,,,,,,, [,, "18",,,, "18"],, [,, "18",,,, "18"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BM: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "BM",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "176|9(?:11|88)",,,, "176"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        BN: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "99[135]",,,, "991"], [,,,,,,,,, [-1]],,,, "BN",,,,,,,,,,,,,,,,,, [,, "99[135]",,,, "991"],, [,, "99[135]",,,, "991"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BO: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "11[089]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "BO",,,,,,,,,,,,,,,,,, [,, "11[089]",,,, "110",,, [3]],, [,, "11[089]|40404",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        BQ: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "112|911",,,, "112"], [,,,,,,,,, [-1]],,,, "BQ",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112"],, [,, "1(?:12|76)|911",,,, "112"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        BR: [, [,, "[1-69]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:00|12|28|8[015]|9[0-47-9])|4(?:57|82\\d)|911",,,, "100",,, [3, 4]], [,,,,,,,,, [-1]],,,, "BR",,,,,,,,,,,,,,,,,, [,, "1(?:12|28|9[023])|911",,,, "112",,, [3]],, [,, "1(?:0(?:[02]|3(?:1[2-579]|2[13-9]|3[124-9]|4[1-3578]|5[1-468]|6[139]|8[149]|9[168])|5[0-35-9]|6(?:0|1[0-35-8]?|2[0145]|3[0137]?|4[37-9]?|5[0-35]|6[016]?|7[137]?|8[5-8]|9[1359]))|1[25-8]|2[357-9]|3[024-68]|4[12568]|5\\d|6[0-8]|8[015]|9[0-47-9])|2(?:7(?:330|878)|85959?)|(?:32|91)1|4(?:0404?|57|828)|55555|6(?:0\\d{4}|10000)|(?:133|411)[12]",,,, "100"], [,, "102|273\\d\\d|321",,,, "102",,, [3, 5]], [,, "151|(?:278|555)\\d\\d|4(?:04\\d\\d?|11\\d|57)",,,, "151",,, [3, 4, 5]],, [,, "285\\d{2,3}|321|40404|(?:27[38]\\d|482)\\d|6(?:0\\d|10)\\d{3}",,,, "321"]],
        BS: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:1[19]|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "BS",,,,,,,,,,,,,,,,,, [,, "91[19]",,,, "911"],, [,, "9(?:1[19]|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BT: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "11[023]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "BT",,,,,,,,,,,,,,,,,, [,, "11[023]",,,, "110",,, [3]],, [,, "11[0-6]|40404",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        BW: [, [,, "[19]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "9(?:11|9[7-9])",,,, "911",,, [3]], [,,,,,,,,, [-1]],,,, "BW",,,,,,,,,,,,,,,,,, [,, "9(?:11|9[7-9])",,,, "911",,, [3]],, [,, "1(?:1[26]|3123)|9(?:1[14]|9[1-57-9])",,,, "112"], [,,,,,,,,, [-1]], [,, "131\\d\\d",,,, "13100",,, [5]],, [,, "131\\d\\d",,,, "13100",,, [5]]],
        BY: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "1(?:0[1-3]|12)",,,, "101"], [,,,,,,,,, [-1]],,,, "BY",,,,,,,,,,,,,,,,,, [,, "1(?:0[1-3]|12)",,,, "101"],, [,, "1(?:0[1-79]|1[246]|35|5[1-35]|6[89]|7[5-7]|8[58]|9[1-7])",,,, "101"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        BZ: [, [,, "9\\d\\d?",,,,,,, [2, 3]],,, [,, "9(?:0|11|22|66|77|9[09])",,,, "90"], [,,,,,,,,, [-1]],,,, "BZ",,,,,,,,,,,,,,,,,, [,, "9(?:0|11|90)",,,, "90"],, [,, "9(?:0|11|22|66|77|9[09])",,,, "90"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CA: [, [,, "[1-9]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "112|988|[29]11",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "CA",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112",,, [3]],, [,, "[1-35-9]\\d{4,5}|112|[2-8]11|9(?:11|88)",,,, "112"], [,,,,,,,,, [-1]], [,, "[235-7]11",,,, "211",,, [3]],, [,, "[1-35-9]\\d{4,5}",,,, "10000",,, [5, 6]]],
        CC: [, [,, "[01]\\d\\d",,,,,,, [3]],,, [,, "000|112",,,, "000"], [,,,,,,,,, [-1]],,,, "CC",,,,,,,,,,,,,,,,,, [,, "000|112",,,, "000"],, [,, "000|112",,,, "000"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CD: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "1(?:1[348]|77|88)",,,, "113",,, [3]], [,,,,,,,,, [-1]],,,, "CD",,,,,,,,,,,,,,,,,, [,, "1(?:1[348]|77|88)",,,, "113",,, [3]],, [,, "1(?:1[348]|23|77|88)|40404",,,, "113"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        CF: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[78]|22\\d)",,,, "117"], [,,,,,,,,, [-1]],,,, "CF",,,,,,,,,,,,,,,,,, [,, "1(?:1[78]|220)",,,, "117"],, [,, "1(?:1[478]|220)",,,, "114"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CG: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[178]",,,, "111"], [,,,,,,,,, [-1]],,,, "CG",,,,,,,,,,,,,,,,,, [,, "11[78]",,,, "117"],, [,, "11[126-8]",,,, "111"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CH: [, [,, "[1-9]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1(?:[278]|6\\d{3})|4[47])|5200",,,, "112",,, [3, 4, 6]], [,, "1(?:14|8[0-2589])\\d|543|83111",,,, "543",,, [3, 4, 5]],,,, "CH",,,,,,,,,,,,,,,,,, [,, "1(?:1[278]|44)",,,, "112",,, [3]],, [,, "1(?:0[78]\\d\\d|1(?:[278]|45|6(?:000|111))|4(?:[03-57]|1[0145])|6(?:00|[1-46])|8(?:02|1[189]|[25]0|7|8[08]|99))|[2-9]\\d{2,4}",,,, "112"], [,, "1(?:4[035]|6[1-46])|1(?:41|60)\\d",,,, "140",,, [3, 4]], [,, "5(?:200|35)",,,, "535",,, [3, 4]],, [,, "[2-9]\\d{2,4}",,,, "200",,, [3, 4, 5]]],
        CI: [, [,, "[14]\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[01]|[78]0)",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "CI",,,,,,,,,,,,,,,,,, [,, "1(?:1[01]|[78]0)",,,, "110",,, [3]],, [,, "1(?:1[01]|[78]0)|4443",,,, "110"], [,,,,,,,,, [-1]], [,, "444\\d",,,, "4440",,, [4]],, [,, "444\\d",,,, "4440",,, [4]]],
        CK: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "99[689]",,,, "996"], [,,,,,,,,, [-1]],,,, "CK",,,,,,,,,,,,,,,,,, [,, "99[689]",,,, "996"],, [,, "99[689]",,,, "996"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CL: [, [,, "[1-9]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:213|3[1-3])|434\\d|911",,,, "131",,, [3, 4]], [,, "1(?:211|3(?:13|[348]0|5[01]))|(?:1(?:[05]6|[48]1|9[18])|2(?:01\\d|[23]2|77|88)|3(?:0[59]|13|3[279]|66)|4(?:[12]4|36\\d|4[017]|55)|5(?:00|41\\d|5[67]|99)|6(?:07\\d|13|22|3[06]|50|69)|787|8(?:[01]1|[48]8)|9(?:01|[12]0|33))\\d",,,, "1060",,, [4, 5]],,,, "CL",,,,,,,,,,,,,,,,,, [,, "13[1-3]|911",,,, "131",,, [3]],, [,, "1(?:00|21[13]|3(?:13|[348]0|5[01])|4(?:0[02-6]|17|[379])|818|919)|2(?:0(?:01|122)|22[47]|323|777|882)|3(?:0(?:51|99)|132|3(?:29|[37]7)|665)|43656|5(?:(?:00|415)4|5(?:66|77)|995)|6(?:131|222|366|699)|7878|8(?:011|11[28]|482|889)|9(?:01|1)1|13\\d|4(?:[13]42|243|4(?:02|15|77)|554)|(?:1(?:[05]6|98)|339|6(?:07|[35])0|9(?:[12]0|33))0",,,, "100"], [,, "(?:200|333)\\d",,,, "2000",,, [4]], [,,,,,,,,, [-1]],, [,, "13(?:13|[348]0|5[01])|(?:1(?:[05]6|[28]1|4[01]|9[18])|2(?:0(?:0|1\\d)|[23]2|77|88)|3(?:0[59]|13|3[2379]|66)|436\\d|5(?:00|41\\d|5[67]|99)|6(?:07\\d|13|22|3[06]|50|69)|787|8(?:[01]1|[48]8)|9(?:01|[12]0|33))\\d|4(?:[1-3]4|4[017]|55)\\d",,,, "1060",,, [4, 5]]],
        CM: [, [,, "[18]\\d{1,3}",,,,,,, [2, 3, 4]],,, [,, "1(?:1[37]|[37])",,,, "13",,, [2, 3]], [,,,,,,,,, [-1]],,,, "CM",,,,,,,,,,,,,,,,,, [,, "1(?:1[37]|[37])",,,, "13",,, [2, 3]],, [,, "1(?:1[37]|[37])|8711",,,, "13"], [,,,,,,,,, [-1]], [,, "871\\d",,,, "8710",,, [4]],, [,, "871\\d",,,, "8710",,, [4]]],
        CN: [, [,, "[19]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1[09]|2(?:[02]|1\\d\\d|395))",,,, "110",,, [3, 5]], [,,,,,,,,, [-1]],,,, "CN",,,,,,,,,,,,,,,,,, [,, "1(?:1[09]|20)",,,, "110",,, [3]],, [,, "1(?:00|1[0249]|2395|6[08])|9[56]\\d{3,4}|12[023]|1(?:0(?:[0-26]\\d|8)|21\\d)\\d",,,, "100"], [,, "1(?:0(?:[0-26]\\d|8)\\d|1[24]|23|6[08])|9[56]\\d{3,4}|100",,,, "100"], [,,,,,,,,, [-1]],, [,, "12110",,,, "12110",,, [5]]],
        CO: [, [,, "[1-589]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "1(?:1[29]|23|32|56)",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "CO",,,,,,,,,,,,,,,,,, [,, "1(?:1[29]|23|32|56)",,,, "112",,, [3]],, [,, "1(?:06|1[2-9]|2[35-7]|3[27]|4[467]|5[36]|6[4-7]|95)|(?:29002|39003)9|40404|5930\\d\\d|85432|(?:[2359][57]|8(?:7|9\\d))\\d{3}",,,, "106"], [,,,,,,,,, [-1]], [,, "(?:40|85)4\\d\\d",,,, "40400",,, [5]],, [,, "(?:40|85)4\\d\\d",,,, "40400",,, [5]]],
        CR: [, [,, "[1359]\\d{2,3}",,,,,,, [3, 4]],,, [,, "112|911",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "CR",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112",,, [3]],, [,, "1(?:0(?:00|15|2[2-4679])|1(?:1[0-35-9]|2|37|[46]6|7[57]|8[79]|9[0-379])|2(?:00|[12]2|34|55)|3(?:21|33)|4(?:0[06]|1[4-6])|5(?:15|5[15])|693|7(?:00|1[7-9]|2[02]|[67]7)|975)|3855|5(?:0(?:30|49)|510)|911",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "(?:385|5(?:0[34]|51))\\d",,,, "3850",,, [4]]],
        CU: [, [,, "[12]\\d\\d(?:\\d{3,4})?",,,,,,, [3, 6, 7]],,, [,, "10[4-7]|(?:116|204\\d)\\d{3}",,,, "104"], [,,,,,,,,, [-1]],,,, "CU",,,,,,,,,,,,,,,,,, [,, "10[4-6]",,,, "104",,, [3]],, [,, "1(?:0[4-7]|1(?:6111|8)|40)|2045252",,,, "104"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CV: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "13[0-2]",,,, "130"], [,,,,,,,,, [-1]],,,, "CV",,,,,,,,,,,,,,,,,, [,, "13[0-2]",,,, "130"],, [,, "13[0-2]",,,, "130"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CW: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "112|911",,,, "112"], [,,,,,,,,, [-1]],,,, "CW",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112"],, [,, "1(?:12|76)|911",,,, "112"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        CX: [, [,, "[01]\\d\\d",,,,,,, [3]],,, [,, "000|112",,,, "000"], [,,,,,,,,, [-1]],,,, "CX",,,,,,,,,,,,,,,,,, [,, "000|112",,,, "000"],, [,, "000|112",,,, "000"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CY: [, [,, "1\\d\\d(?:\\d{3})?",,,,,,, [3, 6]],,, [,, "1(?:1(?:2|6\\d{3})|99)",,,, "112"], [,,,,,,,,, [-1]],,,, "CY",,,,,,,,,,,,,,,,,, [,, "1(?:12|99)",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:000|111))|99)",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        CZ: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1(?:2|6(?:00[06]|1(?:11|23)))|5\\d)",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "CZ",,,,,,,,,,,,,,,,,, [,, "1(?:12|5\\d)",,,, "112",,, [3]],, [,, "1(?:1(?:2|8\\d)|(?:2|3\\d)\\d{2,3}|5\\d|99)|1(?:16|4)\\d{3}",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        DE: [, [,, "[13]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:[02]|6\\d{3})",,,, "110",,, [3, 6]], [,,,,,,,,, [-1]],,,, "DE",,,,,,,,,,,,,,,,,, [,, "11[02]",,,, "110",,, [3]],, [,, "11(?:[025]|6(?:00[06]|1(?:1[167]|23))|800\\d)|3311|118\\d\\d",,,, "110"], [,,,,,,,,, [-1]], [,, "331\\d",,,, "3310",,, [4]],, [,,,,,,,,, [-1]]],
        DJ: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]],,,, "DJ",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17"],, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        DK: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:[24]|6\\d{3})",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "DK",,,,,,,,,,,,,,,,,, [,, "11[24]",,,, "112",,, [3]],, [,, "1(?:1(?:[2-48]|6(?:00[06]|111))|619[0-2]|8(?:01|1[0238]|28|30|5[13]|8[18]))",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        DM: [, [,, "[39]\\d\\d",,,,,,, [3]],,, [,, "333|9(?:11|88|99)",,,, "333"], [,,,,,,,,, [-1]],,,, "DM",,,,,,,,,,,,,,,,,, [,, "333|9(?:11|99)",,,, "333"],, [,, "333|9(?:11|88|99)",,,, "333"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        DO: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "112|9(?:11|88)",,,, "112"], [,,,,,,,,, [-1]],,,, "DO",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112"],, [,, "112|9(?:11|88)",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        DZ: [, [,, "[17]\\d{1,3}",,,,,,, [2, 3, 4]],,, [,, "1(?:12|[47]|54\\d)",,,, "14"], [,,,,,,,,, [-1]],,,, "DZ",,,,,,,,,,,,,,,,,, [,, "1(?:12|[47])",,,, "14",,, [2, 3]],, [,, "1(?:055|12|[47]|548)|730",,,, "14"], [,,,,,,,,, [-1]], [,, "730",,,, "730",,, [3]],, [,, "730",,,, "730",,, [3]]],
        EC: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "1(?:0[12]|12)|911",,,, "101"], [,,,,,,,,, [-1]],,,, "EC",,,,,,,,,,,,,,,,,, [,, "1(?:0[12]|12)|911",,,, "101"],, [,, "1(?:0[12]|12)|911",,,, "101"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        EE: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1(?:[02]|6\\d{3})|2(?:05|28)|3(?:014|3(?:21|5\\d?)|660)|492|5(?:1[03]|410|501)|6(?:112|333|644)|7(?:012|127|89)|8(?:10|8[57])|9(?:0[134]|14))",,,, "110"], [,, "1(?:18(?:00|[12458]\\d?)|2(?:0(?:[02-46-8]\\d?|1[0-36])|1(?:[0-4]\\d?|6[06])|2(?:[0-4]\\d?|5[25])|[367]|4(?:0[04]|[12]\\d?|4[24]|54)|55[12457])|3(?:0(?:[02]\\d?|1[13578]|3[356])|1[1347]|2[02-5]|3(?:[01347]\\d?|2[023]|88)|4(?:[35]\\d?|4[34])|5(?:3[134]|5[035])|666)|4(?:2(?:00|4\\d?)|4(?:0[01358]|1[024]|50|7\\d?)|900)|5(?:0[0-35]|1(?:[1267]\\d?|5[0-7]|82)|2(?:[014-6]\\d?|22)|330|4(?:[35]\\d?|44)|5(?:00|[1-69]\\d?)|9(?:[159]\\d?|[38]0|77))|6(?:1(?:00|1[19]|[35-9]\\d?)|2(?:2[26]|[68]\\d?)|3(?:22|36|6[36])|5|6(?:[0-359]\\d?|6[0-26])|7(?:00|55|7\\d?|8[89])|9(?:00|1\\d?|69))|7(?:0(?:[023]\\d?|1[0578])|1(?:00|2[034]|[4-9]\\d?)|2(?:[07]\\d?|20|44)|7(?:[0-57]\\d?|9[79])|8(?:0[08]|2\\d?|8[0178])|9(?:00|97))|8(?:1[127]|8[1268]|9[269])|9(?:0(?:[02]\\d?|69|9[0269])|1[1-3689]|21))",,,, "123",,, [3, 4, 5]],,,, "EE",,,,,,,,,,,,,,,,,, [,, "11[02]",,,, "110",,, [3]],, [,, "1(?:1(?:[02-579]|6(?:000|111)|8(?:[09]\\d|[1-8]))|2[36-9]|3[7-9]|4[05-7]|5[6-8]|6[05]|7[3-6]|8[02-7]|9[3-9])|1(?:2[0-245]|3[0-6]|4[1-489]|5[0-59]|6[1-46-9]|7[0-27-9]|8[189]|9[0-2])\\d\\d?",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "1(?:18[1258]|2(?:0(?:1[036]|[46]\\d?)|166|21|4(?:0[04]|1\\d?|5[47])|[67])|3(?:0(?:1[13-578]|2\\d?|3[56])|1[15]|2[045]|3(?:[13]\\d?|2[13])|43|5(?:00|3[34]|53))|44(?:0[0135]|14|50|7\\d?)|5(?:05|1(?:[12]\\d?|5[1246]|8[12])|2(?:[01]\\d?|22)|3(?:00|3[03])|4(?:15|5\\d?)|500|9(?:5\\d?|77|80))|6(?:1[35-8]|226|3(?:22|3[36]|66)|644|7(?:00|7\\d?|89)|9(?:00|69))|7(?:01[258]|1(?:00|[15]\\d?)|2(?:44|7\\d?)|8(?:00|87|9\\d?))|8(?:1[128]|8[56]|9(?:[26]\\d?|77))|90(?:2\\d?|69|92))",,,, "126",,, [3, 4, 5]]],
        EG: [, [,, "[13]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "1(?:2[23]|80)",,,, "122",,, [3]], [,,,,,,,,, [-1]],,,, "EG",,,,,,,,,,,,,,,,,, [,, "1(?:2[23]|80)",,,, "122",,, [3]],, [,, "1(?:2[23]|[679]\\d{3}|80)|34400",,,, "122"], [,,,,,,,,, [-1]], [,, "344\\d\\d",,,, "34400",,, [5]],, [,, "344\\d\\d",,,, "34400",,, [5]]],
        EH: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:[59]|77)",,,, "15"], [,,,,,,,,, [-1]],,,, "EH",,,,,,,,,,,,,,,,,, [,, "1(?:[59]|77)",,,, "15"],, [,, "1(?:[59]|77)",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ER: [, [,, "[12]\\d\\d(?:\\d{3})?",,,,,,, [3, 6]],,, [,, "11[2-46]|(?:12[47]|20[12])\\d{3}",,,, "112"], [,,,,,,,,, [-1]],,,, "ER",,,,,,,,,,,,,,,,,, [,, "1(?:1[2-46]|24422)|20(?:1(?:606|917)|2914)|(?:1277|2020)99",,,, "112"],, [,, "1(?:1[2-6]|24422)|20(?:1(?:606|917)|2914)|(?:1277|2020)99",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ES: [, [,, "[0-379]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "0(?:16|6[57]|8[58])|1(?:006|12|[3-7]\\d\\d)|(?:116|20\\d)\\d{3}",,,, "016",,, [3, 4, 6]], [,, "[12]2\\d{1,4}|90(?:5\\d|7)|(?:118|2(?:[357]\\d|80)|3[357]\\d)\\d\\d|[79]9[57]\\d{3}",,,, "120"],,,, "ES",,,,,,,,,,,,,,,,,, [,, "08[58]|112",,,, "085",,, [3]],, [,, "0(?:1[0-26]|6[0-257]|8[058]|9[12])|1(?:0[03-57]\\d{1,3}|1(?:2|6(?:000|111)|8\\d\\d)|2\\d{1,4}|[3-9]\\d\\d)|2(?:2\\d{1,4}|80\\d\\d)|90(?:5[124578]|7)|1(?:3[34]|77)|(?:2[01]\\d|[79]9[57])\\d{3}|[23][357]\\d{3}",,,, "010"], [,, "0(?:[16][0-2]|80|9[12])|21\\d{4}",,,, "010",,, [3, 6]], [,, "1(?:3[34]|77)|[12]2\\d{1,4}",,,, "120"],, [,, "(?:2[0-2]\\d|3[357]|[79]9[57])\\d{3}|2(?:[2357]\\d|80)\\d\\d",,,, "22000",,, [5, 6]]],
        ET: [, [,, "9\\d\\d?",,,,,,, [2, 3]],,, [,, "9(?:07|11?|2|39?|9[17])",,,, "91"], [,,,,,,,,, [-1]],,,, "ET",,,,,,,,,,,,,,,,,, [,, "9(?:11?|2|39?|9[17])",,,, "91"],, [,, "9(?:07|11?|2|39?|45|9[17])",,,, "91"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        FI: [, [,, "[17]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "11(?:2|6\\d{3})",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "FI",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "11(?:2|6(?:00[06]|1(?:1[17]|23)))|(?:1[235-8]\\d|75[12])\\d\\d",,,, "112"], [,, "1[235-8]\\d{3}",,,, "12000",,, [5]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        FJ: [, [,, "[0-579]\\d(?:\\d(?:\\d{2})?)?",,,,,,, [2, 3, 5]],,, [,, "91[17]",,,, "911",,, [3]], [,,,,,,,,, [-1]],,,, "FJ",,,,,,,,,,,,,,,,,, [,, "91[17]",,,, "911",,, [3]],, [,, "0(?:1[34]|8[1-4])|1(?:0[1-3]|[25]9)|2[289]|30|40404|91[137]|[45]4|75",,,, "22"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        FK: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "FK",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "1\\d\\d|999",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        FM: [, [,, "[39]\\d\\d(?:\\d{3})?",,,,,,, [3, 6]],,, [,, "320\\d{3}|911",,,, "911"], [,,,,,,,,, [-1]],,,, "FM",,,,,,,,,,,,,,,,,, [,, "(?:32022|91)1",,,, "911"],, [,, "(?:32022|91)1",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        FO: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[24]|81\\d)",,,, "112"], [,,,,,,,,, [-1]],,,, "FO",,,,,,,,,,,,,,,,,, [,, "11[24]",,,, "112",,, [3]],, [,, "1(?:1[248]|819)|1(?:4[124]|71|8[7-9])\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        FR: [, [,, "[1-8]\\d{1,5}",,,,,,, [2, 3, 4, 5, 6]],,, [,, "1(?:1[02459]|[578]|9[167])|224|(?:3370|74)0|(?:116\\d|3[01])\\d\\d",,,, "15"], [,, "(?:1(?:0|18\\d)|366|[4-8]\\d\\d)\\d\\d|3[2-9]\\d\\d",,,, "1000",,, [4, 5, 6]],,,, "FR",,,,,,,,,,,,,,,,,, [,, "1(?:12|[578])",,,, "15",,, [2, 3]],, [,, "1(?:0\\d\\d|1(?:[02459]|6(?:000|111)|8\\d{3})|[578]|9[167])|2(?:0(?:00|2)0|24)|[3-8]\\d{4}|3\\d{3}|6(?:1[14]|34)|7(?:0[06]|22|40)",,,, "15"], [,, "202\\d|6(?:1[14]|34)|70[06]",,,, "611",,, [3, 4]], [,, "118777|224|6(?:1[14]|34)|7(?:0[06]|22|40)|20(?:0\\d|2)\\d",,,, "224",,, [3, 4, 5, 6]],, [,, "114|[3-8]\\d{4}",,,, "114",,, [3, 5]]],
        GA: [, [,, "1\\d(?:\\d{2})?",,,,,,, [2, 4]],,, [,, "18|1(?:3\\d|73)\\d",,,, "18"], [,,,,,,,,, [-1]],,,, "GA",,,,,,,,,,,,,,,,,, [,, "1(?:3\\d\\d|730|8)",,,, "18"],, [,, "1(?:3\\d\\d|730|8)",,,, "18"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GB: [, [,, "[1-46-9]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:05|1(?:[29]|6\\d{3})|7[56]\\d|8000)|2(?:20\\d|48)|4444|999",,,, "105"], [,,,,,,,,, [-1]],,,, "GB",,,,,,,,,,,,,,,,,, [,, "112|999",,,, "112",,, [3]],, [,, "1(?:0[015]|1(?:[129]|6(?:000|1(?:11|23))|8\\d{3})|2(?:[1-3]|50)|33|4(?:1|7\\d)|571|7(?:0\\d|[56]0)|800\\d|9[15])|2(?:0202|1300|2(?:02|11)|3(?:02|336|45)|4(?:25|8))|3[13]3|4(?:0[02]|35[01]|44[45]|5\\d)|(?:[68]\\d|7[089])\\d{3}|15\\d|2[02]2|650|789|9(?:01|99)",,,, "100"], [,,,,,,,,, [-1]], [,, "1(?:(?:25|7[56])\\d|571)|2(?:02(?:\\d{2})?|[13]3\\d\\d|48)|4444|901",,,, "202",,, [3, 4, 5]],, [,, "(?:125|2(?:020|13\\d)|(?:7[089]|8[01])\\d\\d)\\d",,,, "1250",,, [4, 5]]],
        GD: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "GD",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "176|9(?:11|88)",,,, "176"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        GE: [, [,, "[014]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "0(?:11|33)|11[1-3]|[01]22",,,, "011",,, [3]], [,,,,,,,,, [-1]],,,, "GE",,,,,,,,,,,,,,,,,, [,, "0(?:11|33)|11[1-3]|[01]22",,,, "011",,, [3]],, [,, "0(?:11|33)|11[1-3]|40404|[01]22",,,, "011"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        GF: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]],,,, "GF",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15"],, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GG: [, [,, "[19]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "112|999",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "GG",,,,,,,,,,,,,,,,,, [,, "112|999",,,, "112",,, [3]],, [,, "1(?:0[01]|1[12]|23|41|55|9[05])|999|1(?:1[68]\\d\\d|47|800)\\d",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GH: [, [,, "[14589]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "19[1-3]|999",,,, "191",,, [3]], [,,,,,,,,, [-1]],,,, "GH",,,,,,,,,,,,,,,,,, [,, "19[1-3]|999",,,, "191",,, [3]],, [,, "19[1-3]|40404|(?:54|83)00|999",,,, "191"], [,,,,,,,,, [-1]], [,, "404\\d\\d|(?:54|83)0\\d",,,, "5400",,, [4, 5]],, [,, "404\\d\\d|(?:54|83)0\\d",,,, "5400",,, [4, 5]]],
        GI: [, [,, "[158]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:00|1[25]|23|4(?:1|7\\d)|5[15]|9[02-49])|555|(?:116\\d|80)\\d\\d",,,, "100",,, [3, 4, 6]], [,, "8[1-69]\\d\\d",,,, "8100",,, [4]],,,, "GI",,,,,,,,,,,,,,,,,, [,, "1(?:12|9[09])",,,, "112",,, [3]],, [,, "1(?:00|1(?:[25]|6(?:00[06]|1(?:1[17]|23))|8\\d\\d)|23|4(?:1|7[014])|5[015]|9[02-49])|555|8[0-79]\\d\\d|8(?:00|4[0-2]|8[0-589])",,,, "100"], [,, "150|87\\d\\d",,,, "150",,, [3, 4]], [,, "1(?:00|1(?:5|8\\d\\d)|23|51|9[2-4])|555|8(?:00|4[0-2]|8[0-589])",,,, "100",,, [3, 5]],, [,,,,,,,,, [-1]]],
        GL: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "112",,,, "112"], [,,,,,,,,, [-1]],,,, "GL",,,,,,,,,,,,,,,,,, [,, "112",,,, "112"],, [,, "1[1-8]\\d",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GM: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:1[6-8]|[6-8])",,,, "16"], [,,,,,,,,, [-1]],,,, "GM",,,,,,,,,,,,,,,,,, [,, "1(?:1[6-8]|[6-8])",,,, "16"],, [,, "1(?:1[6-8]|[6-8])",,,, "16"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GN: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],,,, "GN",,,,,,,,,,,,,,,,,, [,,,,,,,,, [-1]],, [,, "12\\d|40404",,,, "120"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        GP: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]],,,, "GP",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15"],, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GR: [, [,, "1\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "1(?:0[089]|1(?:2|6\\d{3})|66|99)",,,, "100",,, [3, 6]], [,,,,,,,,, [-1]],,,, "GR",,,,,,,,,,,,,,,,,, [,, "1(?:00|12|66|99)",,,, "100",,, [3]],, [,, "1(?:0[089]|1(?:2|320|6(?:000|1(?:1[17]|23)))|(?:389|9)9|66)",,,, "100"], [,, "113\\d\\d",,,, "11300",,, [5]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GT: [, [,, "[14]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:10|2[03])",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "GT",,,,,,,,,,,,,,,,,, [,, "1(?:10|2[03])",,,, "110",,, [3]],, [,, "110|40404|1(?:2|[57]\\d)\\d",,,, "110"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        GU: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "GU",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GW: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[378]",,,, "113"], [,,,,,,,,, [-1]],,,, "GW",,,,,,,,,,,,,,,,,, [,, "11[378]",,,, "113"],, [,, "11[378]",,,, "113"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        GY: [, [,, "[019]\\d{2,3}",,,,,,, [3, 4]],,, [,, "91[1-3]",,,, "911",,, [3]], [,,,,,,,,, [-1]],,,, "GY",,,,,,,,,,,,,,,,,, [,, "91[1-3]",,,, "911",,, [3]],, [,, "0(?:02|(?:17|80)1|444|7(?:[67]7|9)|9(?:0[78]|[2-47]))|1(?:443|5[568])|91[1-3]",,,, "002"], [,,,,,,,,, [-1]], [,, "144\\d",,,, "1440",,, [4]],, [,, "144\\d",,,, "1440",,, [4]]],
        HK: [, [,, "[19]\\d{2,6}",,,,,,, [3, 4, 5, 6, 7]],,, [,, "112|99[29]",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "HK",,,,,,,,,,,,,,,,,, [,, "112|99[29]",,,, "112",,, [3]],, [,, "1(?:0(?:(?:[0136]\\d|2[14])\\d{0,3}|8[138])|12|2(?:[0-3]\\d{0,4}|(?:58|8[13])\\d{0,3})|7(?:[135-9]\\d{0,4}|219\\d{0,2})|8(?:0(?:(?:[13]|60\\d)\\d|8)|1(?:0\\d|[2-8])|2(?:0[5-9]|(?:18|2)2|3|8[128])|(?:(?:3[0-689]\\d|7(?:2[1-389]|8[0235-9]|93))\\d|8)\\d|50[138]|6(?:1(?:11|86)|8)))|99[29]|10[0139]",,,, "100"], [,,,,,,,,, [-1]], [,, "109|1(?:08|85\\d)\\d",,,, "109",,, [3, 4, 5]],, [,, "992",,,, "992",,, [3]]],
        HN: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "199",,,, "199",,, [3]], [,,,,,,,,, [-1]],,,, "HN",,,,,,,,,,,,,,,,,, [,, "199",,,, "199",,, [3]],, [,, "199|40404",,,, "199"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        HR: [, [,, "[19]\\d{1,5}",,,,,,, [2, 3, 4, 5, 6]],,, [,, "1(?:12|9[2-4])|9[34]|1(?:16\\d|39)\\d\\d",,,, "93",,, [2, 3, 5, 6]], [,, "118\\d\\d",,,, "11800",,, [5]],,,, "HR",,,,,,,,,,,,,,,,,, [,, "1(?:12|9[2-4])|9[34]",,,, "93",,, [2, 3]],, [,, "1(?:1(?:2|6(?:00[06]|1(?:1[17]|23))|8\\d\\d)|3977|9(?:[2-5]|87))|9[34]",,,, "93"], [,,,,,,,,, [-1]], [,, "139\\d\\d",,,, "13900",,, [5]],, [,, "139\\d\\d",,,, "13900",,, [5]]],
        HT: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "11[48]",,,, "114",,, [3]], [,,,,,,,,, [-1]],,,, "HT",,,,,,,,,,,,,,,,,, [,, "11[48]",,,, "114",,, [3]],, [,, "11[48]|40404",,,, "114"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        HU: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:0[457]|12|4[0-4]\\d)|1(?:16\\d|37|45)\\d\\d",,,, "104"], [,,,,,,,,, [-1]],,,, "HU",,,,,,,,,,,,,,,,,, [,, "1(?:0[457]|12)",,,, "104",,, [3]],, [,, "1(?:0[457]|1(?:2|6(?:000|1(?:11|23))|800)|2(?:0[0-4]|1[013489]|2[0-5]|3[0-46]|4[0-24-68]|5[0-2568]|6[06]|7[0-25-7]|8[028]|9[08])|37(?:00|37|7[07])|4(?:0[0-5]|1[013-8]|2[034]|3[23]|4[02-9]|5(?:00|41|67))|777|8(?:1[27-9]|2[04]|40|[589]))",,,, "104"], [,,,,,,,,, [-1]], [,, "1(?:4[0-4]|77)\\d|1(?:18|2|45)\\d\\d",,,, "1200",,, [4, 5]],, [,, "184\\d",,,, "1840",,, [4]]],
        ID: [, [,, "[178]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "11[02389]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "ID",,,,,,,,,,,,,,,,,, [,, "11[02389]",,,, "110",,, [3]],, [,, "1(?:1[02389]|40\\d\\d|50264)|71400|89887",,,, "110"], [,,,,,,,,, [-1]], [,, "(?:714|898)\\d\\d",,,, "71400",,, [5]],, [,, "714\\d\\d",,,, "71400",,, [5]]],
        IE: [, [,, "[159]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:2|6\\d{3})|999",,,, "112",,, [3, 6]], [,, "5[37]\\d{3}",,,, "53000",,, [5]],,,, "IE",,,,,,,,,,,,,,,,,, [,, "112|999",,,, "112",,, [3]],, [,, "11(?:2|6(?:00[06]|1(?:1[17]|23)))|999|(?:1(?:18|9)|5[0137]\\d)\\d\\d",,,, "112"], [,, "51\\d{3}",,,, "51000",,, [5]], [,, "51210",,,, "51210",,, [5]],, [,, "51210|(?:118|5[037]\\d)\\d\\d",,,, "11800",,, [5]]],
        IL: [, [,, "[12]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:0[0-2]|12)",,,, "100",,, [3]], [,,,,,,,,, [-1]],,,, "IL",,,,,,,,,,,,,,,,,, [,, "1(?:0[0-2]|12)",,,, "100",,, [3]],, [,, "1(?:0[0-2]|1(?:[013-9]\\d|2)|[2-9]\\d\\d)|2407|(?:104|27)00",,,, "100"], [,,,,,,,,, [-1]], [,, "104\\d\\d",,,, "10400",,, [5]],, [,, "104\\d\\d",,,, "10400",,, [5]]],
        IM: [, [,, "[189]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "999",,,, "999",,, [3]], [,,,,,,,,, [-1]],,,, "IM",,,,,,,,,,,,,,,,,, [,, "999",,,, "999",,, [3]],, [,, "1\\d\\d(?:\\d{3})?|8(?:6444|9887)|999",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "8(?:64|98)\\d\\d",,,, "86400",,, [5]]],
        IN: [, [,, "[12578]\\d{2,8}",,,,,,, [3, 4, 5, 6, 7, 8, 9]],,, [,, "1(?:0[0-248]|1[289]|21|[39][89]|4[01]|6(?:1|6\\d?)|8[12])|777|800|1[05]5\\d|1(?:07|51|94)\\d\\d?|(?:1(?:[05]5\\d|70)\\d|261)\\d|1(?:0[369]|10|29|3[126]|9[0-256])\\d",,,, "100",,, [3, 4, 5, 6]], [,, "11[67]\\d{4}|56161561",,,, "1160000",,, [7, 8]],,,, "IN",,,,,,,,,,,,,,,,,, [,, "1(?:0[0-28]|12|298)|2611",,,, "100",,, [3, 4]],, [,, "1(?:0(?:[0-248]|3[39]|5(?:010|6)|6[3468]|7(?:[01357]|[28]0?|4[01])|9[0135-9])|1(?:00|[289])|2(?:1|98)|3(?:11|2[0-2]|63|[89])|4[01]|5(?:1(?:0[0-36]|[127])|54)|6(?:1|6[01]?)|7000|8[12]|9(?:0[013-59]|12|25|4[4-9]\\d?|50|6[1347]|[89]))|2611|5(?:0(?:0(?:0\\d|1|20?)|325|5[2-79]\\d{3,5})|1(?:234|555|717|818|96[49])|2(?:0(?:0[01]|[14]0)|151|555|666|888|9(?:06|99\\d?))|3(?:0[01]0|131|553|(?:66|77)6)|(?:464|55[05])\\d{1,3}|6(?:070|3[68]|43)|717\\d)|777|800|5(?:05(?:0|1\\d)|221|3(?:03|3[23]))\\d{1,4}|5(?:(?:04|88)0|2(?:2[0267]|3[16])|4(?:1[04]|20|3[02])|5(?:3[16]|67)|6(?:06|[67]\\d)|787|9(?:64|90))\\d\\d?|(?:1(?:05[79]|(?:1[67][0-2]|802)\\d|55[23])\\d|5(?:(?:00(?:0\\d|1)|(?:304|616)\\d\\d)\\d|1(?:0[12]|4[2-4])|2(?:2[3589]|3(?:1\\d{3}|2)|4[04]|7[78])|4(?:[02]4|32\\d{4}|4[04]|99)|5(?:1[25]|[36]5|4[45]|93)|7(?:(?:17\\d|57)\\d\\d|[27]7|88)|8(?:3[4-69]|4[01]|5[58]|88(?:8\\d\\d|9)|99)|9(?:0(?:0|2\\d{3})|55|6[67]|77|88)))\\d",,,, "100"], [,, "5(?:14(?:2[5-9]|[34]\\d)|757555)",,,, "51425",,, [5, 7]], [,, "1(?:(?:1[67]\\d\\d|70)\\d\\d|55330|909)|5(?:300\\d|6161(?:17[89]|561))|1(?:[19][89]|21|4[01])",,,, "118",,, [3, 4, 5, 6, 7, 8]],, [,, "1(?:39|90[019])|5(?:14(?:2[5-9]|[34]\\d)|6161(?:17[89]|561)|757555)",,,, "139",,, [3, 4, 5, 7, 8]]],
        IQ: [, [,, "[1479]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:0[04]|15|22)",,,, "100",,, [3]], [,,,,,,,,, [-1]],,,, "IQ",,,,,,,,,,,,,,,,,, [,, "1(?:0[04]|15|22)",,,, "100",,, [3]],, [,, "1(?:0[04]|15|22)|4432|71117|9988",,,, "100"], [,,,,,,,,, [-1]], [,, "(?:443|711\\d|998)\\d",,,, "4430",,, [4, 5]],, [,, "(?:443|711\\d|998)\\d",,,, "4430",,, [4, 5]]],
        IR: [, [,, "[129]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1[0-68]|2[0-59]|9[0-579])|911",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "IR",,,,,,,,,,,,,,,,,, [,, "1(?:1[025]|25)|911",,,, "110",,, [3]],, [,, "1(?:1[0-68]|2[0-59]|3[346-8]|4(?:[0147]|[289]0)|5(?:0[14]|1[02479]|2[0-3]|39|[49]0|65)|6(?:[16]6|[27]|90)|8(?:03|1[18]|22|3[37]|4[28]|88|99)|9[0-579])|20(?:[09]0|1(?:[038]|1[079]|26|9[69])|2[01])|9(?:11|9(?:0009|90))",,,, "110"], [,, "1(?:5[0-469]|8[0-489])\\d",,,, "1500",,, [4]], [,, "(?:1(?:5[0-469]|8[0-489])|99(?:0\\d\\d|9))\\d",,,, "1500",,, [4, 6]],, [,, "990\\d{3}",,,, "990000",,, [6]]],
        IS: [, [,, "1\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "1(?:12|71\\d)",,,, "112",,, [3, 4]], [,,,,,,,,, [-1]],,,, "IS",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "1(?:1(?:[28]|61(?:16|23))|4(?:00|1[145]|4[0146])|55|7(?:00|17|7[07-9])|8(?:[02]0|1[16-9]|88)|900)",,,, "112"], [,,,,,,,,, [-1]], [,, "14(?:0\\d|41)",,,, "1400",,, [4]],, [,, "1(?:415|90\\d)",,,, "1415",,, [4]]],
        IT: [, [,, "[14]\\d{2,6}",,,,,,, [3, 4, 5, 6, 7]],,, [,, "1(?:1(?:[2358]|6\\d{3})|87)",,,, "112",,, [3, 6]], [,, "(?:12|4(?:[478](?:[0-4]|[5-9]\\d\\d)|55))\\d\\d",,,, "1200",,, [4, 5, 7]],,,, "IT",,,,,,,,,,,,,,,,,, [,, "11[2358]",,,, "112",,, [3]],, [,, "1(?:0\\d{2,3}|1(?:[2-57-9]|6(?:000|111))|3[39]|4(?:82|9\\d{1,3})|5(?:00|1[58]|2[25]|3[03]|44|[59])|60|8[67]|9(?:[01]|2[2-9]|4\\d|696))|4(?:2323|5045)|(?:1(?:2|92[01])|4(?:3(?:[01]|[45]\\d\\d)|[478](?:[0-4]|[5-9]\\d\\d)|55))\\d\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "4(?:3(?:[01]|[45]\\d\\d)|[478](?:[0-4]|[5-9]\\d\\d)|5[05])\\d\\d",,,, "43000",,, [5, 7]]],
        JE: [, [,, "[129]\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "112|999",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "JE",,,,,,,,,,,,,,,,,, [,, "112|999",,,, "112",,, [3]],, [,, "1(?:00|1(?:2|8\\d{3})|23|4(?:[14]|28|7\\d)|5\\d|7(?:0[12]|[128]|35?)|808|9[0135])|23[2-4]|999",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        JM: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "11[029]|9(?:11|88)",,,, "110"], [,,,,,,,,, [-1]],,,, "JM",,,,,,,,,,,,,,,,,, [,, "11[029]|911",,,, "110"],, [,, "1(?:1[029]|76)|9(?:11|88)",,,, "110"], [,,,,,,,,, [-1]], [,, "176",,,, "176"],, [,, "176",,,, "176"]],
        JO: [, [,, "[19]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "1(?:0[235]|1[2-6]|9[127])|911",,,, "102",,, [3]], [,, "9[0-4689]\\d{3}",,,, "90000",,, [5]],,,, "JO",,,,,,,,,,,,,,,,,, [,, "1(?:12|9[127])|911",,,, "112",,, [3]],, [,, "1(?:0[2359]|1[0-68]|9[0-24-79])|9[0-4689]\\d{3}|911",,,, "102"], [,,,,,,,,, [-1]], [,, "9[0-4689]\\d{3}",,,, "90000",,, [5]],, [,, "9[0-4689]\\d{3}",,,, "90000",,, [5]]],
        JP: [, [,, "[01]\\d\\d(?:\\d{7})?",,,,,,, [3, 10]],,, [,, "11[089]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "JP",,,,,,,,,,,,,,,,,, [,, "11[09]",,,, "110",,, [3]],, [,, "000[259]\\d{6}|1(?:0[24]|1[089]|44|89)",,,, "102"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "000[259]\\d{6}",,,, "0002000000",,, [10]]],
        KE: [, [,, "[1-9]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:1(?:[246]|9\\d)|5(?:01|2[127]|6[26]\\d))|999",,,, "112"], [,, "909\\d\\d",,,, "90900",,, [5]],,,, "KE",,,,,,,,,,,,,,,,,, [,, "11[24]|999",,,, "112",,, [3]],, [,, "1(?:0(?:[07-9]|1[0-25]|400)|1(?:[024-6]|9[0-579])|2[1-3]|3[01]|4[14]|5(?:[01][01]|2[0-24-79]|33|4[05]|5[59]|6(?:00|29|6[67]))|(?:6[035]\\d|[78])\\d|9(?:[02-9]\\d\\d|19))|(?:(?:2[0-79]|[37][0-29]|4[0-4]|6[2357]|8\\d)\\d|5(?:[0-7]\\d|99))\\d\\d|9(?:09\\d\\d|99)|8988",,,, "100"], [,,,,,,,,, [-1]], [,, "1(?:(?:04|6[35])\\d\\d|3[01]|4[14]|5(?:1\\d|2[25]))|(?:(?:2[0-79]|[37][0-29]|4[0-4]|6[2357]|8\\d)\\d|5(?:[0-7]\\d|99)|909)\\d\\d|898\\d",,,, "130"],, [,, "1(?:(?:04|6[035])\\d\\d|4[14]|5(?:01|55|6[26]\\d))|40404|8988|909\\d\\d",,,, "141"]],
        KG: [, [,, "[14]\\d{2,3}",,,,,,, [3, 4]],,, [,, "10[1-3]",,,, "101",,, [3]], [,,,,,,,,, [-1]],,,, "KG",,,,,,,,,,,,,,,,,, [,, "10[1-3]",,,, "101",,, [3]],, [,, "10[1-3]|4040",,,, "101"], [,,,,,,,,, [-1]], [,, "404\\d",,,, "4040",,, [4]],, [,, "404\\d",,,, "4040",,, [4]]],
        KH: [, [,, "[146]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "11[7-9]|666",,,, "117",,, [3]], [,,,,,,,,, [-1]],,,, "KH",,,,,,,,,,,,,,,,,, [,, "11[7-9]|666",,,, "117",,, [3]],, [,, "11[7-9]|40404|666",,,, "117"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        KI: [, [,, "[179]\\d{2,3}",,,,,,, [3, 4]],,, [,, "19[2-5]|99[2-4]",,,, "192",,, [3]], [,,,,,,,,, [-1]],,,, "KI",,,,,,,,,,,,,,,,,, [,, "19[2-5]|99[2-4]",,,, "192",,, [3]],, [,, "1(?:05[0-259]|88|9[2-5])|777|99[2-4]|10[0-8]",,,, "100"], [,, "103",,,, "103",,, [3]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        KM: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]],,,, "KM",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17"],, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        KN: [, [,, "[39]\\d\\d",,,,,,, [3]],,, [,, "333|9(?:11|88|99)",,,, "333"], [,,,,,,,,, [-1]],,,, "KN",,,,,,,,,,,,,,,,,, [,, "333|9(?:11|99)",,,, "333"],, [,, "333|9(?:11|88|99)",,,, "333"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        KP: [, [,, "[18]\\d\\d",,,,,,, [3]],,, [,, "11[29]|819",,,, "112"], [,,,,,,,,, [-1]],,,, "KP",,,,,,,,,,,,,,,,,, [,, "11[29]|819",,,, "112"],, [,, "11[29]|819",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        KR: [, [,, "1\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:1[27-9]|28|330|82)",,,, "112",,, [3, 4]], [,,,,,,,,, [-1]],,,, "KR",,,,,,,,,,,,,,,,,, [,, "11[29]",,,, "112",,, [3]],, [,, "1(?:[016-9]114|3(?:0[01]|2|3[0-35-9]|45?|5[057]|6[569]|7[79]|8[2589]|9[0189]))|1(?:0[015]|1\\d|2[01357-9]|41|8[28])",,,, "100"], [,,,,,,,,, [-1]], [,, "1(?:0[01]|1[4-6]|41)|1(?:[06-9]1\\d|111)\\d",,,, "100",,, [3, 5]],, [,,,,,,,,, [-1]]],
        KW: [, [,, "[18]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "112",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "KW",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "1[0-7]\\d|89887",,,, "100"], [,,,,,,,,, [-1]], [,, "898\\d\\d",,,, "89800",,, [5]],, [,,,,,,,,, [-1]]],
        KY: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "KY",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        KZ: [, [,, "[1-4]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:0[1-3]|12)|212\\d",,,, "101",,, [3, 4]], [,,,,,,,,, [-1]],,,, "KZ",,,,,,,,,,,,,,,,,, [,, "1(?:0[1-3]|12)",,,, "101",,, [3]],, [,, "1(?:0[1-4]|12)|2121|(?:3040|404)0",,,, "101"], [,,,,,,,,, [-1]], [,, "(?:304\\d|404)\\d",,,, "4040",,, [4, 5]],, [,, "(?:304\\d|404)\\d",,,, "4040",,, [4, 5]]],
        LA: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "19[015]",,,, "190"], [,,,,,,,,, [-1]],,,, "LA",,,,,,,,,,,,,,,,,, [,, "19[015]",,,, "190"],, [,, "19[015]",,,, "190"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LB: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "1(?:12|40|75)|999",,,, "112"], [,,,,,,,,, [-1]],,,, "LB",,,,,,,,,,,,,,,,,, [,, "1(?:12|40|75)|999",,,, "112"],, [,, "1(?:12|40|75)|999",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LC: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "LC",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LI: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[278]|44)",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "LI",,,,,,,,,,,,,,,,,, [,, "1(?:1[278]|44)",,,, "112",,, [3]],, [,, "1(?:1(?:[278]|45)|4[3-57]|50|75|81[18])",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LK: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "11[02689]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "LK",,,,,,,,,,,,,,,,,, [,, "11[02689]",,,, "110",,, [3]],, [,, "1(?:1[024-9]|3(?:00|1[2-49]|2[23]|3[1-3]|44|5[07]|[67]9|88|9[039])|9(?:0[0-2589]|1[0-357-9]|2[0-25689]|3[0389]|4[0489]|5[014-69]|6[0-2689]|7[03579]|8[02457-9]|9[0-2569]))",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LR: [, [,, "[3489]\\d{2,3}",,,,,,, [3, 4]],,, [,, "355|911",,,, "355",,, [3]], [,,,,,,,,, [-1]],,,, "LR",,,,,,,,,,,,,,,,,, [,, "355|911",,,, "355",,, [3]],, [,, "355|4040|8(?:400|933)|911",,,, "355"], [,,,,,,,,, [-1]], [,, "(?:404|8(?:40|93))\\d",,,, "4040",,, [4]],, [,, "(?:404|8(?:40|93))\\d",,,, "4040",,, [4]]],
        LS: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[257]",,,, "112"], [,,,,,,,,, [-1]],,,, "LS",,,,,,,,,,,,,,,,,, [,, "11[257]",,,, "112"],, [,, "11[257]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LT: [, [,, "[01]\\d(?:\\d(?:\\d{3})?)?",,,,,,, [2, 3, 6]],,, [,, "0(?:11?|22?|33?)|1(?:0[1-3]|1(?:2|6111))|116(?:0\\d|12)\\d",,,, "01"], [,,,,,,,,, [-1]],,,, "LT",,,,,,,,,,,,,,,,,, [,, "0(?:11?|22?|33?)|1(?:0[1-3]|12)",,,, "01",,, [2, 3]],, [,, "0(?:11?|22?|33?)|1(?:0[1-3]|1(?:[27-9]|6(?:000|1(?:1[17]|23))))",,,, "01"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LU: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:[23]|6\\d{3})",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "LU",,,,,,,,,,,,,,,,,, [,, "11[23]",,,, "112",,, [3]],, [,, "11(?:[23]|6(?:000|111))|1(?:18|[25]\\d|3)\\d\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        LV: [, [,, "[018]\\d{1,5}",,,,,,, [2, 3, 4, 5, 6]],,, [,, "0[1-3]|11(?:[023]|6\\d{3})",,,, "01",,, [2, 3, 6]], [,, "1180|821\\d\\d",,,, "1180",,, [4, 5]],,,, "LV",,,,,,,,,,,,,,,,,, [,, "0[1-3]|11[023]",,,, "01",,, [2, 3]],, [,, "0[1-4]|1(?:1(?:[02-4]|6(?:000|111)|8[0189])|(?:5|65)5|77)|821[57]4",,,, "01"], [,, "1181",,,, "1181",,, [4]], [,, "165\\d",,,, "1650",,, [4]],, [,,,,,,,,, [-1]]],
        LY: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "19[013]",,,, "190"], [,,,,,,,,, [-1]],,,, "LY",,,,,,,,,,,,,,,,,, [,, "19[013]",,,, "190"],, [,, "19[013]",,,, "190"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MA: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:[59]|77)",,,, "15"], [,,,,,,,,, [-1]],,,, "MA",,,,,,,,,,,,,,,,,, [,, "1(?:[59]|77)",,,, "15"],, [,, "1(?:[59]|77)",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MC: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:12|[578])",,,, "15"], [,,,,,,,,, [-1]],,,, "MC",,,,,,,,,,,,,,,,,, [,, "1(?:12|[578])",,,, "15"],, [,, "1(?:12|41|[578])",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MD: [, [,, "[19]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:2|6(?:000|1(?:11|2\\d)))|90[1-3]",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "MD",,,,,,,,,,,,,,,,,, [,, "112|90[1-3]",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:00[06]|1(?:1[17]|23))|8\\d\\d?|99)|90[04-9])|90[1-3]|1(?:4\\d\\d|6[0-389]|9[1-4])\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ME: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:12|2[2-4])",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "ME",,,,,,,,,,,,,,,,,, [,, "1(?:12|2[2-4])",,,, "112",,, [3]],, [,, "1(?:1(?:(?:[013-57-9]|6\\d\\d)\\d|2)|[249]\\d{3}|5999|8(?:0[089]|1[0-8]|888))|1(?:[02-5]\\d\\d|60[06]|700)|12\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MF: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]],,,, "MF",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15"],, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MG: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:1[78]|[78])",,,, "17"], [,,,,,,,,, [-1]],,,, "MG",,,,,,,,,,,,,,,,,, [,, "1(?:1[78]|[78])",,,, "17"],, [,, "1(?:1[78]|[78])",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MH: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "911",,,, "911"], [,,,,,,,,, [-1]],,,, "MH",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "911",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MK: [, [,, "1\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "1(?:1(?:2|6\\d{3})|9[2-4])",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "MK",,,,,,,,,,,,,,,,,, [,, "1(?:12|9[2-4])",,,, "112",,, [3]],, [,, "1(?:1(?:2|8\\d)|3\\d|9[2-4])|1(?:16|2\\d)\\d{3}",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ML: [, [,, "[136-8]\\d{1,4}",,,,,,, [2, 3, 4, 5]],,, [,, "1[578]|(?:352|67)00|7402|(?:677|744|8000)\\d",,,, "15",,, [2, 4, 5]], [,, "(?:12|800)2\\d|3(?:52(?:11|2[02]|3[04-6]|99)|7574)",,,, "1220",,, [4, 5]],,,, "ML",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15",,, [2]],, [,, "1(?:1(?:[013-9]\\d|2)|2(?:1[02-469]|2[13])|[578])|350(?:35|57)|67(?:0[09]|[59]9|77|8[89])|74(?:0[02]|44|55)|800[0-2][12]|3(?:52|[67]\\d)\\d\\d",,,, "15"], [,, "37(?:433|575)|7400|8001\\d",,,, "7400",,, [4, 5]], [,, "3503\\d|(?:3[67]\\d|800)\\d\\d",,,, "35030",,, [5]],, [,, "374(?:0[24-9]|[1-9]\\d)|7400|3(?:6\\d|75)\\d\\d",,,, "7400",,, [4, 5]]],
        MM: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "199",,,, "199"], [,,,,,,,,, [-1]],,,, "MM",,,,,,,,,,,,,,,,,, [,, "199",,,, "199"],, [,, "199",,,, "199"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MN: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "10[0-35]",,,, "100"], [,,,,,,,,, [-1]],,,, "MN",,,,,,,,,,,,,,,,,, [,, "10[0-35]",,,, "100"],, [,, "10[0-35]",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MO: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "MO",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "999",,,, "999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MP: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "MP",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MQ: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:12|[578])",,,, "15"], [,,,,,,,,, [-1]],,,, "MQ",,,,,,,,,,,,,,,,,, [,, "1(?:12|[578])",,,, "15"],, [,, "1(?:12|[578])",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MR: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]],,,, "MR",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17"],, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MS: [, [,, "[29]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "MS",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "211|9(?:11|88|99)",,,, "211"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MT: [, [,, "1\\d\\d(?:\\d{3})?",,,,,,, [3, 6]],,, [,, "11(?:2|6\\d{3})",,,, "112"], [,,,,,,,,, [-1]],,,, "MT",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "11(?:2|6(?:000|1(?:11|23)))",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MU: [, [,, "[189]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "11[45]|99[59]",,,, "114",,, [3]], [,,,,,,,,, [-1]],,,, "MU",,,,,,,,,,,,,,,,,, [,, "11[45]|99[59]",,,, "114",,, [3]],, [,, "1\\d{2,4}|(?:8\\d\\d|99)\\d",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        MV: [, [,, "[14]\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:02|1[89])",,,, "102",,, [3]], [,,,,,,,,, [-1]],,,, "MV",,,,,,,,,,,,,,,,,, [,, "1(?:02|1[89])",,,, "102",,, [3]],, [,, "1(?:[0-37-9]|[4-6]\\d)\\d|4040|1[45]1",,,, "100"], [,,,,,,,,, [-1]], [,, "1[45]1",,,, "141",,, [3]],, [,,,,,,,,, [-1]]],
        MW: [, [,, "[189]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "199|99[7-9]",,,, "199",,, [3]], [,,,,,,,,, [-1]],,,, "MW",,,,,,,,,,,,,,,,,, [,, "199|99[7-9]",,,, "199",,, [3]],, [,, "199|80400|99[7-9]",,,, "199"], [,,,,,,,,, [-1]], [,, "804\\d\\d",,,, "80400",,, [5]],, [,, "804\\d\\d",,,, "80400",,, [5]]],
        MX: [, [,, "[0579]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "0(?:6[0568]|80)|911",,,, "060",,, [3]], [,, "(?:530\\d|776)\\d",,,, "7760",,, [4, 5]],,,, "MX",,,,,,,,,,,,,,,,,, [,, "0(?:6[0568]|80)|911",,,, "060",,, [3]],, [,, "0[1-9]\\d|53053|7766|911",,,, "010"], [,,,,,,,,, [-1]], [,, "0(?:[249]0|[35][01])",,,, "020",,, [3]],, [,,,,,,,,, [-1]]],
        MY: [, [,, "[1369]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "112|999",,,, "112",,, [3]], [,,,,,,,,, [-1]],,,, "MY",,,,,,,,,,,,,,,,,, [,, "112|999",,,, "112",,, [3]],, [,, "1(?:0[01348]|1(?:[02]|1[128]|311)|2(?:0[125]|[13-6]|2\\d{0,2})|(?:3[1-35-79]|7[45])\\d\\d?|5(?:454|5\\d\\d?|77|888|999?)|8(?:18?|2|8[18])|9(?:[124]\\d?|68|71|9[0679]))|66628|99[1-469]|13[5-7]|(?:1(?:0[569]|309|5[12]|7[136-9]|9[03])|3[23679]\\d\\d)\\d",,,, "100"], [,, "666\\d\\d",,,, "66600",,, [5]], [,,,,,,,,, [-1]],, [,, "(?:3[23679]\\d|666)\\d\\d",,,, "32000",,, [5]]],
        MZ: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[79]|9[78])",,,, "117",,, [3]], [,,,,,,,,, [-1]],,,, "MZ",,,,,,,,,,,,,,,,,, [,, "1(?:1[79]|9[78])",,,, "117",,, [3]],, [,, "1(?:[02-5]\\d\\d|1[79]|9[78])",,,, "117"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NA: [, [,, "[19]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "10111",,,, "10111",,, [5]], [,,,,,,,,, [-1]],,,, "NA",,,,,,,,,,,,,,,,,, [,, "10111",,,, "10111",,, [5]],, [,, "(?:10|93)111|(?:1\\d|9)\\d\\d",,,, "900"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NC: [, [,, "[135]\\d{1,3}",,,,,,, [2, 3, 4]],,, [,, "1(?:0(?:00|1[23]|3[0-2]|8\\d)|[5-8])|363\\d|577",,,, "15"], [,,,,,,,,, [-1]],,,, "NC",,,,,,,,,,,,,,,,,, [,, "1[5-8]",,,, "15",,, [2]],, [,, "1(?:0(?:0[06]|1[02-46]|20|3[0-25]|42|5[058]|77|88)|[5-8])|3631|5[6-8]\\d",,,, "15"], [,, "5(?:67|88)",,,, "567",,, [3]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NE: [, [,, "[1-3578]\\d(?:\\d(?:\\d{3})?)?",,,,,,, [2, 3, 6]],,, [,, "1(?:18|[578])|723\\d{3}",,,, "15"], [,,,,,,,,, [-1]],,,, "NE",,,,,,,,,,,,,,,,,, [,, "1(?:18|[578])|723141",,,, "15"],, [,, "1(?:0[01]|1[128]|2[034]|3[013]|[46]0|55?|[78])|222|333|555|723141|888",,,, "15"], [,,,,,,,,, [-1]], [,, "1(?:0[01]|1[12]|2[034]|3[013]|[46]0|55)|222|333|555|888",,,, "100",,, [3]],, [,,,,,,,,, [-1]]],
        NF: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|55|77)",,,, "911"], [,,,,,,,,, [-1]],,,, "NF",,,,,,,,,,,,,,,,,, [,, "9(?:11|55|77)",,,, "911"],, [,, "9(?:11|55|77)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NG: [, [,, "[14]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "199",,,, "199",,, [3]], [,,,,,,,,, [-1]],,,, "NG",,,,,,,,,,,,,,,,,, [,, "199",,,, "199",,, [3]],, [,, "199|40700",,,, "199"], [,,,,,,,,, [-1]], [,, "407\\d\\d",,,, "40700",,, [5]],, [,, "407\\d\\d",,,, "40700",,, [5]]],
        NI: [, [,, "[12467]\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[58]|2[08])|737\\d",,,, "115"], [,,,,,,,,, [-1]],,,, "NI",,,,,,,,,,,,,,,,,, [,, "1(?:1[58]|2[08])",,,, "115",,, [3]],, [,, "1(?:1[58]|200)|4878|7(?:010|373)|12[0158]|(?:19|[267]1)00",,,, "115"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NL: [, [,, "[1349]\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "11(?:2|6\\d{3})|911",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "NL",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:00[06]|1(?:11|23)))|2(?:0[0-4]|3[34]|44)|3[03-9]\\d|400|8(?:[02-9]\\d|1[0-79]))|[34]000|911",,,, "112"], [,,,,,,,,, [-1]], [,, "120\\d",,,, "1200",,, [4]],, [,, "[34]00\\d",,,, "3000",,, [4]]],
        NO: [, [,, "[01]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:[023]|6\\d{3})",,,, "110",,, [3, 6]], [,,,,,,,,, [-1]],,,, "NO",,,,,,,,,,,,,,,,,, [,, "11[023]",,,, "110",,, [3]],, [,, "04\\d{3}|1(?:1(?:[0239]|61(?:1[17]|23))|2[048]|4(?:12|[59])|7[57]|8[5-9]\\d|90)",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "04\\d{3}",,,, "04000",,, [5]]],
        NP: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:0[0-36]|12)|1(?:09|11)\\d",,,, "100"], [,,,,,,,,, [-1]],,,, "NP",,,,,,,,,,,,,,,,,, [,, "1(?:0[0-3]|12)",,,, "100",,, [3]],, [,, "1(?:0(?:[0-36]|98)|1(?:1[1-4]|2))",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NR: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[0-2]",,,, "110"], [,,,,,,,,, [-1]],,,, "NR",,,,,,,,,,,,,,,,,, [,, "11[0-2]",,,, "110"],, [,, "1(?:1[0-2]|23|92)",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        NU: [, [,, "[019]\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "NU",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "01[05]|101|999",,,, "010"], [,,,,,,,,, [-1]], [,, "010",,,, "010"],, [,,,,,,,,, [-1]]],
        NZ: [, [,, "\\d{3,4}",,,,,,, [3, 4]],,, [,, "111",,,, "111",,, [3]], [,, "018",,,, "018",,, [3]],,,, "NZ",,,,,,,,,,,,,,,,,, [,, "111",,,, "111",,, [3]],, [,, "018|1(?:(?:1|37)1|(?:23|94)4|7[03]7)|[2-57-9]\\d{2,3}|6(?:161|26[0-3]|742)",,,, "018"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "018|(?:1(?:23|37|7[03]|94)|6(?:[12]6|74))\\d|[2-57-9]\\d{2,3}",,,, "018"]],
        OM: [, [,, "[19]\\d{3}",,,,,,, [4]],,, [,, "1444|999\\d",,,, "1444"], [,,,,,,,,, [-1]],,,, "OM",,,,,,,,,,,,,,,,,, [,, "1444|9999",,,, "1444"],, [,, "1(?:111|222|4(?:4[0-5]|50|66|7[7-9])|51[0-8])|9999|1(?:2[3-5]|3[0-2]|50)\\d",,,, "1111"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PA: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "911",,,, "911"], [,,,,,,,,, [-1]],,,, "PA",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "10[2-4]|911",,,, "102"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PE: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "1(?:05|1[67])",,,, "105"], [,,,,,,,,, [-1]],,,, "PE",,,,,,,,,,,,,,,,,, [,, "1(?:05|1[67])",,,, "105"],, [,, "1(?:05|1[67])",,,, "105"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PF: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]],,,, "PF",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15"],, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PG: [, [,, "[01]\\d{2,6}",,,,,,, [3, 4, 5, 6, 7]],,, [,, "000|11[01]",,,, "000",,, [3]], [,,,,,,,,, [-1]],,,, "PG",,,,,,,,,,,,,,,,,, [,, "000|11[01]",,,, "000",,, [3]],, [,, "000|1(?:1[01]|5\\d\\d|6\\d{2,5})",,,, "000"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "16\\d{2,5}",,,, "1600",,, [4, 5, 6, 7]]],
        PH: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "11[27]|911",,,, "112"], [,,,,,,,,, [-1]],,,, "PH",,,,,,,,,,,,,,,,,, [,, "11[27]|911",,,, "112"],, [,, "11[27]|911",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PK: [, [,, "1\\d{1,3}",,,,,,, [2, 3, 4]],,, [,, "1(?:1(?:2\\d?|5)|[56])",,,, "15"], [,,,,,,,,, [-1]],,,, "PK",,,,,,,,,,,,,,,,,, [,, "1(?:1(?:22?|5)|[56])",,,, "15"],, [,, "1(?:122|3[014]|[56])|11[2457-9]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PL: [, [,, "[19]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "11(?:2|6\\d{3})|99[7-9]",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "PL",,,,,,,,,,,,,,,,,, [,, "112|99[7-9]",,,, "112",,, [3]],, [,, "1(?:1(?:2|61(?:11|23)|891[23])|9\\d{3})|9(?:8[4-7]|9[1-9])|11[68]000",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PM: [, [,, "[13]\\d(?:\\d{2})?",,,,,,, [2, 4]],,, [,, "1[578]",,,, "15",,, [2]], [,,,,,,,,, [-1]],,,, "PM",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15",,, [2]],, [,, "1[578]|3103",,,, "15"], [,,,,,,,,, [-1]], [,, "310\\d",,,, "3100",,, [4]],, [,,,,,,,,, [-1]]],
        PR: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "PR",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PS: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:0[0-2]|66)",,,, "100",,, [3]], [,,,,,,,,, [-1]],,,, "PS",,,,,,,,,,,,,,,,,, [,, "10[0-2]",,,, "100",,, [3]],, [,, "1(?:0[0-2]|122|44|66|99)",,,, "100"], [,,,,,,,,, [-1]], [,, "112\\d",,,, "1120",,, [4]],, [,,,,,,,,, [-1]]],
        PT: [, [,, "1\\d\\d(?:\\d(?:\\d{2})?)?",,,,,,, [3, 4, 6]],,, [,, "11[257]|1(?:16\\d\\d|5[1589]|8[279])\\d",,,, "112"], [,,,,,,,,, [-1]],,,, "PT",,,,,,,,,,,,,,,,,, [,, "11[25]",,,, "112",,, [3]],, [,, "1(?:0(?:45|5[01])|1(?:[2578]|600[06])|4(?:1[45]|4)|583|6(?:1[0236]|3[02]|9[169]))|1(?:1611|59)1|1[068]78|1[08]9[16]|1(?:0[1-38]|40|5[15]|6[258]|82)0",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PW: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "911",,,, "911"], [,,,,,,,,, [-1]],,,, "PW",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "911",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        PY: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "128|911",,,, "128"], [,,,,,,,,, [-1]],,,, "PY",,,,,,,,,,,,,,,,,, [,, "128|911",,,, "128"],, [,, "1[1-9]\\d|911",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        QA: [, [,, "[129]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "99\\d",,,, "990",,, [3]], [,, "900",,,, "900",,, [3]],,,, "QA",,,,,,,,,,,,,,,,,, [,, "999",,,, "999",,, [3]],, [,, "9(?:00|[19]\\d)|(?:1|20|9[27]\\d)\\d\\d",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        RE: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:12|[578])",,,, "15"], [,,,,,,,,, [-1]],,,, "RE",,,,,,,,,,,,,,,,,, [,, "1(?:12|[578])",,,, "15"],, [,, "1(?:12|[578])",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        RO: [, [,, "[18]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:2|6\\d{3})",,,, "112",,, [3, 6]], [,, "(?:1(?:18[39]|[24])|8[48])\\d\\d",,,, "1200",,, [4, 6]],,,, "RO",,,,,,,,,,,,,,,,,, [,, "112",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:000|1(?:11|23))|8(?:(?:01|8[18])1|119|[23]00|932))|[24]\\d\\d|9(?:0(?:00|19)|1[19]|21|3[02]|5[178]))|8[48]\\d\\d",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "(?:1[24]|8[48])\\d\\d",,,, "1200",,, [4]]],
        RS: [, [,, "[19]\\d{1,5}",,,,,,, [2, 3, 4, 5, 6]],,, [,, "112|9[2-4]",,,, "92",,, [2, 3]], [,,,,,,,,, [-1]],,,, "RS",,,,,,,,,,,,,,,,,, [,, "112|9[2-4]",,,, "92",,, [2, 3]],, [,, "1[189]\\d{1,4}|9[2-4]",,,, "92"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        RU: [, [,, "[01]\\d\\d?",,,,,,, [2, 3]],,, [,, "112|(?:0|10)[1-3]",,,, "01"], [,,,,,,,,, [-1]],,,, "RU",,,,,,,,,,,,,,,,,, [,, "112|(?:0|10)[1-3]",,,, "01"],, [,, "112|(?:0|10)[1-4]",,,, "01"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        RW: [, [,, "[14]\\d\\d",,,,,,, [3]],,, [,, "11[1245]",,,, "111"], [,,,,,,,,, [-1]],,,, "RW",,,,,,,,,,,,,,,,,, [,, "11[12]",,,, "111"],, [,, "1(?:0[0-2]|1[0-24-6]|2[13]|70|99)|456",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SA: [, [,, "[19]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:2|6\\d{3})|9(?:11|37|9[7-9])",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "SA",,,,,,,,,,,,,,,,,, [,, "112|9(?:11|9[79])",,,, "112",,, [3]],, [,, "1(?:1(?:00|2|6111)|410|9(?:00|1[89]|9(?:099|22|9[0-3])))|9(?:0[24-79]|11|3[379]|40|66|8[5-9]|9[02-9])",,,, "112"], [,, "141\\d",,,, "1410",,, [4]], [,, "1(?:10|41)\\d|90[24679]",,,, "902",,, [3, 4]],, [,,,,,,,,, [-1]]],
        SB: [, [,, "[127-9]\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "SB",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "1(?:[02]\\d|1[12]|[35][01]|[49][1-9]|6[2-9]|7[7-9]|8[0-8])|269|777|835|9(?:[01]1|22|33|55|77|88|99)",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SC: [, [,, "[19]\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[1468]|60)|999",,,, "111",,, [3]], [,,,,,,,,, [-1]],,,, "SC",,,,,,,,,,,,,,,,,, [,, "999",,,, "999",,, [3]],, [,, "1(?:[06]\\d|1[0-246-8]|2[0-8]|3[13]|4[0-2]|5[15]|7[124-6]|8[158]|9[015])|9(?:6\\d\\d|99)",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SD: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "SD",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "999",,,, "999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SE: [, [,, "[1-37-9]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:2|(?:3|6\\d)\\d\\d|414|77)|900\\d\\d",,,, "112"], [,, "11811[89]|72\\d{3}",,,, "72000",,, [5, 6]],,,, "SE",,,,,,,,,,,,,,,,,, [,, "112|90000",,,, "112",,, [3, 5]],, [,, "11(?:[25]|313|6(?:00[06]|1(?:1[17]|23))|7[0-8])|2(?:2[02358]|33|4[01]|50|6[1-4])|32[13]|8(?:22|88)|9(?:0(?:00|51)0|12)|(?:11(?:4|8[02-46-9])|7\\d\\d|90[2-4])\\d\\d|(?:118|90)1(?:[02-9]\\d|1[013-9])",,,, "112"], [,,,,,,,,, [-1]], [,, "2(?:2[02358]|33|4[01]|50|6[1-4])|32[13]|8(?:22|88)|912",,,, "220",,, [3]],, [,, "7\\d{4}",,,, "70000",,, [5]]],
        SG: [, [,, "[179]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "99[359]",,,, "993",,, [3]], [,,,,,,,,, [-1]],,,, "SG",,,,,,,,,,,,,,,,,, [,, "99[359]",,,, "993",,, [3]],, [,, "1(?:(?:[01368]\\d|44)\\d|[57]\\d{2,3}|9(?:0[1-9]|[1-9]\\d))|77222|99[02-9]|100",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "772\\d\\d",,,, "77200",,, [5]]],
        SH: [, [,, "[129]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "9(?:11|99)",,,, "911",,, [3]], [,,,,,,,,, [-1]],,,, "SH",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911",,, [3]],, [,, "1\\d{2,3}|26[01]\\d\\d|9(?:11|99)",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SI: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "11(?:(?:0|6\\d)\\d\\d|[23]|8\\d\\d?)",,,, "112"], [,,,,,,,,, [-1]],,,, "SI",,,,,,,,,,,,,,,,,, [,, "11[23]",,,, "112",,, [3]],, [,, "1(?:1(?:00[146]|[23]|6(?:000|1(?:11|23))|8(?:[08]|99))|9(?:059|1(?:0[12]|16)|5|70|87|9(?:00|[149])))|19(?:08|81)[09]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SJ: [, [,, "[01]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "11[023]",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "SJ",,,,,,,,,,,,,,,,,, [,, "11[023]",,,, "110",,, [3]],, [,, "04\\d{3}|11[023]",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,, "04\\d{3}",,,, "04000",,, [5]]],
        SK: [, [,, "1\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:1(?:2|6\\d{3})|5[058])",,,, "112",,, [3, 6]], [,,,,,,,,, [-1]],,,, "SK",,,,,,,,,,,,,,,,,, [,, "1(?:12|5[058])",,,, "112",,, [3]],, [,, "1(?:1(?:2|6(?:000|111)|8[0-8])|[248]\\d{3}|5[0589])",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SL: [, [,, "[069]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "(?:01|99)9",,,, "019",,, [3]], [,,,,,,,,, [-1]],,,, "SL",,,,,,,,,,,,,,,,,, [,, "(?:01|99)9",,,, "019",,, [3]],, [,, "(?:01|99)9|60400",,,, "019"], [,,,,,,,,, [-1]], [,, "604\\d\\d",,,, "60400",,, [5]],, [,, "604\\d\\d",,,, "60400",,, [5]]],
        SM: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[358]",,,, "113"], [,,,,,,,,, [-1]],,,, "SM",,,,,,,,,,,,,,,,,, [,, "11[358]",,,, "113"],, [,, "11[358]",,,, "113"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SN: [, [,, "[12]\\d{1,5}",,,,,,, [2, 3, 4, 5, 6]],,, [,, "1(?:515|[78])|2(?:00|1)\\d{3}",,,, "17",,, [2, 4, 5, 6]], [,, "2(?:0[246]|[468])\\d{3}",,,, "24000",,, [5, 6]],,,, "SN",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17",,, [2]],, [,, "1(?:1[69]|(?:[246]\\d|51)\\d)|2(?:0[0-246]|[12468])\\d{3}|1[278]",,,, "12"], [,, "2(?:01|2)\\d{3}",,,, "22000",,, [5, 6]], [,, "1[46]\\d\\d",,,, "1400",,, [4]],, [,, "2[468]\\d{3}",,,, "24000",,, [5]]],
        SO: [, [,, "[57-9]\\d\\d",,,,,,, [3]],,, [,, "555|888|999",,,, "555"], [,,,,,,,,, [-1]],,,, "SO",,,,,,,,,,,,,,,,,, [,, "555|888|999",,,, "555"],, [,, "555|777|888|999",,,, "555"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SR: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "115",,,, "115",,, [3]], [,,,,,,,,, [-1]],,,, "SR",,,,,,,,,,,,,,,,,, [,, "115",,,, "115",,, [3]],, [,, "1\\d{2,3}",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SS: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "SS",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "999",,,, "999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ST: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "112",,,, "112"], [,,,,,,,,, [-1]],,,, "ST",,,,,,,,,,,,,,,,,, [,, "112",,,, "112"],, [,, "112",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SV: [, [,, "[149]\\d\\d(?:\\d{2,3})?",,,,,,, [3, 5, 6]],,, [,, "116\\d{3}|911",,,, "911",,, [3, 6]], [,,,,,,,,, [-1]],,,, "SV",,,,,,,,,,,,,,,,,, [,, "91[13]",,,, "911",,, [3]],, [,, "1(?:1(?:2|6111)|2[136-8]|3[0-6]|9[05])|40404|9(?:1\\d|29)",,,, "112"], [,,,,,,,,, [-1]], [,, "404\\d\\d",,,, "40400",,, [5]],, [,, "404\\d\\d",,,, "40400",,, [5]]],
        SX: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:19|88)",,,, "919"], [,,,,,,,,, [-1]],,,, "SX",,,,,,,,,,,,,,,,,, [,, "919",,,, "919"],, [,, "9(?:19|88)",,,, "919"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SY: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[023]",,,, "110"], [,,,,,,,,, [-1]],,,, "SY",,,,,,,,,,,,,,,,,, [,, "11[023]",,,, "110"],, [,, "11[023]",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        SZ: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "SZ",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "999",,,, "999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TC: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "TC",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TD: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]],,,, "TD",,,,,,,,,,,,,,,,,, [,, "1[78]",,,, "17"],, [,, "1[78]",,,, "17"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TG: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1[78]|7[127])",,,, "117",,, [3]], [,,,,,,,,, [-1]],,,, "TG",,,,,,,,,,,,,,,,,, [,, "1(?:1[78]|7[127])",,,, "117",,, [3]],, [,, "1(?:011|1[078]|7[127])",,,, "110"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TH: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "1(?:1(?:00|2[03]|3[3479]|7[67]|9[0246])|578|6(?:44|6[79]|88|9[16])|88\\d|9[19])|1[15]55",,,, "191"], [,, "1(?:113|2[23]\\d|5(?:09|56))",,,, "1113",,, [4]],,,, "TH",,,,,,,,,,,,,,,,,, [,, "1(?:669|9[19])",,,, "191"],, [,, "1(?:0[0-2]|1(?:0[03]|1[1-35]|2[0358]|3[03-79]|4[02-489]|5[04-9]|6[04-79]|7[03-9]|8[027-9]|9[02-9])|2(?:22|3[89]|66)|3(?:18|2[23]|3[013]|5[56]|6[45]|73)|477|5(?:0\\d|4[0-37-9]|5[1-8]|6[01679]|7[12568]|8[0-24589]|9[013589])|6(?:0[0-29]|2[03]|4[3-6]|6[1-9]|7[0257-9]|8[0158]|9[014-9])|7(?:[14]9|7[27]|90)|888|9[19])",,,, "100"], [,, "1(?:1(?:03|1[15]|2[58]|3[056]|4[02-49]|5[046-9]|7[03-589]|9[57-9])|5(?:0[0-8]|4[0-378]|5[1-478]|7[156])|6(?:20|4[356]|6[1-68]|7[057-9]|8[015]|9[0457-9]))|1(?:1[68]|26|3[1-35]|5[689]|60|7[17])\\d",,,, "1103",,, [4]], [,, "114[89]",,,, "1148",,, [4]],, [,,,,,,,,, [-1]]],
        TJ: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "1(?:0[1-3]|12)",,,, "101"], [,,,,,,,,, [-1]],,,, "TJ",,,,,,,,,,,,,,,,,, [,, "1(?:0[1-3]|12)",,,, "101"],, [,, "1(?:0[1-3]|12)",,,, "101"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TL: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[25]",,,, "112"], [,,,,,,,,, [-1]],,,, "TL",,,,,,,,,,,,,,,,,, [,, "11[25]",,,, "112"],, [,, "1(?:0[02]|1[25]|2[0138]|72|9[07])",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TM: [, [,, "0\\d",,,,,,, [2]],,, [,, "0[1-49]",,,, "01"], [,,,,,,,,, [-1]],,,, "TM",,,,,,,,,,,,,,,,,, [,, "0[1-3]",,,, "01"],, [,, "0[1-49]",,,, "01"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TN: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "19[078]",,,, "190"], [,,,,,,,,, [-1]],,,, "TN",,,,,,,,,,,,,,,,,, [,, "19[078]",,,, "190"],, [,, "19[078]",,,, "190"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TO: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|22|33|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "TO",,,,,,,,,,,,,,,,,, [,, "9(?:11|22|33|99)",,,, "911"],, [,, "9(?:11|22|33|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TR: [, [,, "[1-9]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:1[02]|22|3[126]|4[04]|5[15-9]|6[18]|77|83)",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "TR",,,,,,,,,,,,,,,,,, [,, "1(?:1[02]|55)",,,, "110",,, [3]],, [,, "1(?:1(?:[02-79]|8(?:1[018]|2[0245]|3[2-4]|42|5[058]|6[06]|7[07]|8[01389]|9[089]))|3(?:37|[58]6|65)|471|5(?:07|78)|6(?:[02]6|99)|8(?:63|95))|2(?:077|268|4(?:17|23)|5(?:7[26]|82)|6[14]4|8\\d\\d|9(?:30|89))|3(?:0(?:05|72)|353|4(?:06|30|64)|502|674|747|851|9(?:1[29]|60))|4(?:0(?:25|3[12]|[47]2)|3(?:3[13]|[89]1)|439|5(?:43|55)|717|832)|5(?:145|290|[4-6]\\d\\d|772|833|9(?:[06]1|92))|6(?:236|6(?:12|39|8[59])|769)|7890|8(?:688|7(?:28|65)|85[06])|9(?:159|290)|1[2-9]\\d",,,, "110"], [,, "(?:285|542)0",,,, "2850",,, [4]], [,,,,,,,,, [-1]],, [,, "1(?:3(?:37|[58]6|65)|4(?:4|71)|5(?:07|78)|6(?:[02]6|99)|8(?:3|63|95))|(?:2(?:07|26|4[12]|5[78]|6[14]|8\\d|9[38])|3(?:0[07]|[38]5|4[036]|50|67|74|9[16])|4(?:0[2-47]|3[389]|[48]3|5[45]|71)|5(?:14|29|[4-6]\\d|77|83|9[069])|6(?:23|6[138]|76)|789|8(?:68|7[26]|85)|9(?:15|29))\\d",,,, "144",,, [3, 4]]],
        TT: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:88|9[09])",,,, "988"], [,,,,,,,,, [-1]],,,, "TT",,,,,,,,,,,,,,,,,, [,, "99[09]",,,, "990"],, [,, "9(?:88|9[09])",,,, "988"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TV: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "911",,,, "911"], [,,,,,,,,, [-1]],,,, "TV",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "1\\d\\d|911",,,, "100"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TW: [, [,, "1\\d{2,3}",,,,,,, [3, 4]],,, [,, "11[0289]|1(?:81|92)\\d",,,, "110"], [,, "10[56]",,,, "105",,, [3]],,,, "TW",,,,,,,,,,,,,,,,,, [,, "11[029]",,,, "110",,, [3]],, [,, "1(?:0[04-6]|1[0237-9]|3[389]|6[05-8]|7[07]|8(?:0|11)|9(?:19|22|5[057]|68|8[05]|9[15689]))",,,, "100"], [,, "1(?:65|9(?:1\\d|50|85|98))",,,, "165"], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        TZ: [, [,, "[149]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "1(?:1[0-79]|9[09])|999",,,, "110",,, [3]], [,,,,,,,,, [-1]],,,, "TZ",,,,,,,,,,,,,,,,,, [,, "11[0-245]|999",,,, "110",,, [3]],, [,, "1(?:1\\d|9[09])|46400|999",,,, "110"], [,,,,,,,,, [-1]], [,, "464\\d\\d",,,, "46400",,, [5]],, [,, "464\\d\\d",,,, "46400",,, [5]]],
        UA: [, [,, "[189]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "1(?:0[1-3]|1(?:2|6\\d{3}))",,,, "101",,, [3, 6]], [,,,,,,,,, [-1]],,,, "UA",,,,,,,,,,,,,,,,,, [,, "1(?:0[1-3]|12)",,,, "101",,, [3]],, [,, "1(?:0[1-49]|1(?:2|6(?:000|1(?:11|23))|8\\d\\d?)|(?:[278]|5\\d)\\d)|[89]00\\d\\d?|151|1(?:06|4\\d|6)\\d\\d",,,, "101"], [,,,,,,,,, [-1]], [,, "(?:118|[89]00)\\d\\d?",,,, "1180",,, [4, 5]],, [,,,,,,,,, [-1]]],
        UG: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "999",,,, "999"], [,,,,,,,,, [-1]],,,, "UG",,,,,,,,,,,,,,,,,, [,, "999",,,, "999"],, [,, "999",,,, "999"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        US: [, [,, "[1-9]\\d{2,5}",,,,,,, [3, 4, 5, 6]],,, [,, "112|611|9(?:11|33|88)",,,, "112",,, [3]], [,, "24280|(?:381|968)35|4(?:3355|7553|8221)|5(?:(?:489|934)2|5928)|72078|(?:323|960)40|(?:276|414)63|(?:2(?:520|744)|7390|9968)9|(?:693|732|976)88|(?:3(?:556|825)|5294|8623|9729)4|(?:3378|4136|7642|8961|9979)6|(?:4(?:6(?:15|32)|827)|(?:591|720)8|9529)7",,,, "24280",,, [5]],,,, "US",,,,,,,,,,,,,,,,,, [,, "112|911",,,, "112",,, [3]],, [,, "11(?:2|5[1-47]|[68]\\d|7[0-57]|98)|[2-9]\\d{3,5}|[2-8]11|9(?:11|33|88)",,,, "112"], [,, "2(?:3333|(?:4224|7562|900)2|56447|6688)|3(?:1010|2665|7404)|40404|560560|6(?:0060|22639|5246|7622)|7(?:0701|3822|4666)|8(?:(?:3825|7226)5|4816)|99099",,,, "23333",,, [5, 6]], [,, "336\\d\\d|[2-9]\\d{3}|[2356]11",,,, "211",,, [3, 4, 5]],, [,, "[2-9]\\d{4,5}",,,, "20000",,, [5, 6]]],
        UY: [, [,, "[129]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "128|911",,,, "128",,, [3]], [,,,,,,,,, [-1]],,,, "UY",,,,,,,,,,,,,,,,,, [,, "128|911",,,, "128",,, [3]],, [,, "1(?:0[4-9]|1[2368]|2[0-3568]|787|997\\d?)|21997|911",,,, "104"], [,, "178\\d",,,, "1780",,, [4]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        UZ: [, [,, "[04]\\d(?:\\d(?:\\d{2})?)?",,,,,,, [2, 3, 5]],,, [,, "0(?:0[1-3]|[1-3]|50)",,,, "01",,, [2, 3]], [,,,,,,,,, [-1]],,,, "UZ",,,,,,,,,,,,,,,,,, [,, "0(?:0[1-3]|[1-3]|50)",,,, "01",,, [2, 3]],, [,, "0(?:0[1-3]|[1-3]|50)|45400",,,, "01"], [,,,,,,,,, [-1]], [,, "454\\d\\d",,,, "45400",,, [5]],, [,, "454\\d\\d",,,, "45400",,, [5]]],
        VA: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[2358]",,,, "112"], [,,,,,,,,, [-1]],,,, "VA",,,,,,,,,,,,,,,,,, [,, "11[2358]",,,, "112"],, [,, "11[2358]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VC: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "VC",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VE: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "1(?:12|71)|911",,,, "112"], [,,,,,,,,, [-1]],,,, "VE",,,,,,,,,,,,,,,,,, [,, "1(?:12|71)|911",,,, "112"],, [,, "1(?:12|71)|911",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VG: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]],,,, "VG",,,,,,,,,,,,,,,,,, [,, "9(?:11|99)",,,, "911"],, [,, "9(?:11|88|99)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VI: [, [,, "9\\d\\d",,,,,,, [3]],,, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]],,,, "VI",,,,,,,,,,,,,,,,,, [,, "911",,,, "911"],, [,, "9(?:11|88)",,,, "911"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VN: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "11[3-5]",,,, "113"], [,,,,,,,,, [-1]],,,, "VN",,,,,,,,,,,,,,,,,, [,, "11[3-5]",,,, "113"],, [,, "11[3-5]",,,, "113"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        VU: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "112",,,, "112"], [,,,,,,,,, [-1]],,,, "VU",,,,,,,,,,,,,,,,,, [,, "112",,,, "112"],, [,, "112",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        WF: [, [,, "1\\d",,,,,,, [2]],,, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]],,,, "WF",,,,,,,,,,,,,,,,,, [,, "1[578]",,,, "15"],, [,, "1[578]",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        WS: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "9(?:11|9[4-69])",,,, "911"], [,,,,,,,,, [-1]],,,, "WS",,,,,,,,,,,,,,,,,, [,, "9(?:11|9[4-69])",,,, "911"],, [,, "1(?:1[12]|2[0-6]|[39]0)|9(?:11|9[4-79])",,,, "111"], [,,,,,,,,, [-1]], [,, "12[0-6]",,,, "120"],, [,,,,,,,,, [-1]]],
        XK: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "1(?:12|9[2-4])",,,, "112"], [,,,,,,,,, [-1]],,,, "XK",,,,,,,,,,,,,,,,,, [,, "1(?:12|9[2-4])",,,, "112"],, [,, "1(?:12|9[2-4])",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        YE: [, [,, "1\\d\\d",,,,,,, [3]],,, [,, "19[1459]",,,, "191"], [,,,,,,,,, [-1]],,,, "YE",,,,,,,,,,,,,,,,,, [,, "19[1459]",,,, "191"],, [,, "19[1459]",,,, "191"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        YT: [, [,, "1\\d\\d?",,,,,,, [2, 3]],,, [,, "1(?:12|5)",,,, "15"], [,,,,,,,,, [-1]],,,, "YT",,,,,,,,,,,,,,,,,, [,, "1(?:12|5)",,,, "15"],, [,, "1(?:12|5)",,,, "15"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ZA: [, [,, "[134]\\d{2,4}",,,,,,, [3, 4, 5]],,, [,, "1(?:01\\d\\d|12)",,,, "112",,, [3, 5]], [,, "41(?:348|851)",,,, "41348",,, [5]],,,, "ZA",,,,,,,,,,,,,,,,,, [,, "1(?:01(?:11|77)|12)",,,, "112",,, [3, 5]],, [,, "1(?:0(?:1(?:11|77)|20|7)|1[12]|77(?:3[237]|[45]7|6[279]|9[26]))|[34]\\d{4}",,,, "107"], [,, "3(?:078[23]|7(?:064|567)|8126)|4(?:394[16]|7751|8837)|4[23]699",,,, "30782",,, [5]], [,, "111",,,, "111",,, [3]],, [,, "[34]\\d{4}",,,, "30000",,, [5]]],
        ZM: [, [,, "[19]\\d\\d",,,,,,, [3]],,, [,, "112|99[139]",,,, "112"], [,,,,,,,,, [-1]],,,, "ZM",,,,,,,,,,,,,,,,,, [,, "112|99[139]",,,, "112"],, [,, "112|99[139]",,,, "112"], [,,,,,,,,, [-1]], [,,,,,,,,, [-1]],, [,,,,,,,,, [-1]]],
        ZW: [, [,, "[139]\\d\\d(?:\\d{2})?",,,,,,, [3, 5]],,, [,, "112|9(?:5[023]|61|9[3-59])",,,, "112",,, [3]], [,, "3[013-57-9]\\d{3}",,,, "30000",,, [5]],,,, "ZW",,,,,,,,,,,,,,,,,, [,, "112|99[3-59]",,,, "112",,, [3]],, [,, "11[2469]|3[013-57-9]\\d{3}|9(?:5[023]|6[0-25]|9[3-59])",,,, "112"], [,,,,,,,,, [-1]], [,, "114|9(?:5[023]|6[0-25])",,,, "114",,, [3]],, [,,,,,,,,, [-1]]]
      }; /*
         Copyright (C) 2018 The Libphonenumber Authors.
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
         You may obtain a copy of the License at
         http://www.apache.org/licenses/LICENSE-2.0
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         See the License for the specific language governing permissions and
         limitations under the License.
         */
      function Mb() {
        this.g = {};
      }
      ba(Mb);
      function Nb(a) {
        return (a = F[a]) ? a : [];
      }
      function Ob(a) {
        var b = Pb;
        if (!a) return null;
        a = a.toUpperCase();
        var c = b.g[a];
        if (null == c) {
          c = Lb[a];
          if (null == c) return null;
          c = new y().g(D.o(), c);
          b.g[a] = c;
        }
        return c;
      }
      function Qb(a) {
        if (!m(a, 2)) return "";
        var b = "" + p(a, 2);
        return m(a, 4) && p(a, 4) && 0 < u(a, 8) ? Array(u(a, 8) + 1).join("0") + b : b;
      }
      function Rb(a, b) {
        return 0 < r(b, 9).length && !r(b, 9).includes(a.length) ? !1 : L(u(b, 2), a.toString());
      }
      var S = I.pa(),
        Pb = Mb.pa();
      function Sb(a) {
        var b = S,
          c = nb(b, a);
        b = P(b, u(a, 1), c);
        null == b ? a = -1 : (a = O(a), a = lb(a, b));
        switch (a) {
          case 0:
            return "fixed-line";
          case 2:
            return "fixed-line-or-mobile";
          case 1:
            return "mobile";
          case 8:
            return "pager";
          case 7:
            return "personal-number";
          case 4:
            return "premium-rate";
          case 5:
            return "shared-cost";
          case 3:
            return "toll-free";
          case 9:
            return "uan";
          case 6:
            return "voip";
          default:
          case -1:
            return "unknown";
        }
      }
      function Tb(a) {
        switch (a) {
          case "fixed-line":
            return 0;
          case "fixed-line-or-mobile":
            return 2;
          case "mobile":
            return 1;
          case "pager":
            return 8;
          case "personal-number":
            return 7;
          case "premium-rate":
            return 4;
          case "shared-cost":
            return 5;
          case "toll-free":
            return 3;
          case "uan":
            return 9;
          case "voip":
            return 6;
          default:
          case "unknown":
            return -1;
        }
      }
      function Ub(a) {
        try {
          switch (pb(a)) {
            case 0:
              return "is-possible";
            case 1:
              return "invalid-country-code";
            case 3:
              return "too-long";
            case 2:
              return "too-short";
          }
          if (ob(a)) return "is-possible";
        } catch (b) {}
        return "unknown";
      }
      function Vb(a, b) {
        if ("+" !== a.charAt(0) && "00" !== a.slice(0, 2)) return {
          parsed: c,
          fa: d
        };
        try {
          var c = kb(S, a, b);
        } catch (e) {}
        if (c) {
          var d = nb(S, c);
          if (null != d && "ZZ" !== d) return {
            parsed: c,
            fa: d
          };
        }
        for (b = 1; 4 > b; ++b) {
          d = void 0;
          if (a.length < b + 1) return {
            parsed: c,
            fa: d
          };
          d = Q(a.substring(1, b + 1));
          if ("ZZ" !== d) return {
            fa: d
          };
        }
        return {
          parsed: c,
          fa: void 0
        };
      }
      var Wb;
      a: {
        try {
          Wb = new WeakMap();
          break a;
        } catch (a) {}
        Wb = void 0;
      }
      var Xb = Wb;
      function V(a, b) {
        if (!(this instanceof V)) return new V(a, b);
        var c = null == b ? void 0 : b.regionCode;
        if ("string" === typeof a) var d = !1;else try {
          mb(a), d = !0;
        } catch (n) {
          d = !1;
        }
        if (!d && "string" !== typeof a) throw Error("Invalid phone number, expected a string");
        if (!d && "object" !== typeof b && "undefined" !== typeof b) throw Error(`Invalid options, expected object, got ${typeof b}. ` + "This may be because of not yet upgraded code.");
        if (!d && null != c && "string" !== typeof c) throw Error("Invalid region code, expected a string, got " + `${typeof c} ${c}`);
        d || (a = a.trim(), c && "+" === a.charAt(0) && (c = null), c && "+" !== a.charAt(0) && "00" !== a.slice(0, 2) || ({
          fa: c = null,
          parsed: e
        } = Vb(a, c)));
        this.g = {
          number: {},
          regionCode: c,
          valid: !1,
          possible: !1,
          shortPossible: !1,
          shortValid: !1
        };
        Xb && Xb.set(this.g, this);
        if (d) this.l = a;else {
          this.l = null;
          this.g.number.input = a;
          if (!c) {
            this.g.possibility = "invalid-country-code";
            return;
          }
          if (0 === Yb(c)) {
            this.g.possibility = "invalid-country-code";
            return;
          }
          try {
            this.l = e ? e : kb(S, a, c);
          } catch (n) {
            this.g.possibility = Ub(a);
            return;
          }
        }
        this.g.number.international = S.format(this.l, 1);
        this.g.number.national = S.format(this.l, 2);
        this.g.number.e164 = S.format(this.l, 0);
        this.g.number.rfc3966 = S.format(this.l, 3);
        this.g.number.significant = O(this.l);
        this.g.canBeInternationallyDialled = S.ja(this.l);
        this.g.valid = mb(this.l);
        this.g.possible = ob(this.l);
        this.g.possibility = Ub(this.l);
        a = this.g;
        b = this.l;
        var e = Nb(u(b, 1));
        a: if (0 === e.length) d = null;else if (1 === e.length) d = e[0];else {
          d = Qb(b);
          for (var f = 0; f < e.length; f++) {
            var g = e[f],
              l = Ob(g);
            if (l && Rb(d, p(l, 29))) {
              d = g;
              break a;
            }
          }
          d = null;
        }
        1 < e.length && null != d ? b = !0 : (e = d, d = Nb(u(b, 1)), null != e && d.includes(e) ? (e = Ob(e)) ? (b = Qb(b), d = p(e, 1), Rb(b, d) ? (e = p(e, 29), b = Rb(b, e)) : b = !1) : b = !1 : b = !1);
        a.shortValid = b;
        a = this.g;
        a: {
          e = this.l;
          b = Nb(u(e, 1));
          e = Qb(e).length;
          for (d = 0; d < b.length; d++) if ((f = Ob(b[d])) && r(p(f, 1), 9).includes(e)) {
            b = !0;
            break a;
          }
          b = !1;
        }
        a.shortPossible = b;
        this.g.type = Sb(this.l);
        this.g.typeIsMobile = this.ua();
        this.g.typeIsFixedLine = this.ta();
        this.g.countryCode = N(c) ? T(S, c) : 0;
      }
      var W = ["PhoneNumber$$module$src$index"],
        X = aa;
      W[0] in X || "undefined" == typeof X.execScript || X.execScript("var " + W[0]);
      for (var Y; W.length && (Y = W.shift());) W.length || void 0 === V ? X[Y] && X[Y] !== Object.prototype[Y] ? X = X[Y] : X = X[Y] = {} : X[Y] = V;
      function Yb(a) {
        return N(a) ? T(S, a) : 0;
      }
      V.getCountryCodeForRegionCode = Yb;
      V.getRegionCodeForCountryCode = function (a) {
        return Q(a);
      };
      V.findNumbers = function (a, b) {
        var c = null == b ? void 0 : b.defaultRegionCode;
        var d;
        var e = null != (d = null == b ? void 0 : b.leniency) ? d : "valid";
        var f;
        b = null != (f = null == b ? void 0 : b.maxTries) ? f : Number.MAX_SAFE_INTEGER;
        f = /([0-9]+(?: [0-9]+)*)/g;
        d = [];
        for (let l = 0; l < b; ++l) {
          var g = f.exec(a);
          if (!g) break;
          let n = g.index;
          g = g.index + g[1].length;
          0 < n && "+" === a.charAt(n - 1) && --n;
          var G = a.slice(n, g),
            ua = new V(G, {
              regionCode: c
            });
          (ua.wa() || "possible" === e && ua.va()) && d.push({
            text: G,
            phoneNumber: ua.toJSON(),
            start: n,
            end: g
          });
        }
        return d;
      };
      function Zb(a) {
        var b = {};
        return a.filter(c => {
          if (b.hasOwnProperty(c)) return !1;
          b[c] = 1;
          return !0;
        });
      }
      V.getSupportedRegionCodes = function () {
        return Zb($a());
      };
      V.getSupportedCallingCodes = function () {
        return Zb(bb());
      };
      V.getExample = function (a, b) {
        var c;
        b ? c = ib(a, Tb(b)) : c = ib(a, 0);
        return new V(c, a).toJSON();
      };
      V.getAsYouType = function (a) {
        return new Z(a);
      };
      V.getNumberFrom = function (a, b) {
        try {
          a: {
            if (Xb) {
              var e = Xb.get(a);
              if (e) {
                var c = e;
                break a;
              }
            }
            let d;
            c = new V(null == a ? void 0 : null == (d = a.number) ? void 0 : d.e164, {});
          }
          return {
            valid: !0,
            number: hb(c.l, b)
          };
        } catch (d) {
          return {
            valid: !1,
            error: d
          };
        }
      };
      V.prototype.toJSON = function () {
        return this.g;
      };
      V.prototype.toJSON = V.prototype.toJSON;
      V.prototype.ja = function () {
        return this.g.canBeInternationallyDialled;
      };
      V.prototype.canBeInternationallyDialled = V.prototype.ja;
      V.prototype.wa = function () {
        return this.g.valid;
      };
      V.prototype.isValid = V.prototype.wa;
      V.prototype.va = function () {
        return this.g.possible;
      };
      V.prototype.isPossible = V.prototype.va;
      V.prototype.getType = function () {
        return this.g.type;
      };
      V.prototype.getType = V.prototype.getType;
      V.prototype.ua = function () {
        return "mobile" === this.g.type || "fixed-line-or-mobile" === this.g.type;
      };
      V.prototype.isMobile = V.prototype.ua;
      V.prototype.ta = function () {
        return "fixed-line" === this.g.type || "fixed-line-or-mobile" === this.g.type;
      };
      V.prototype.isFixedLine = V.prototype.ta;
      V.prototype.xa = function (a) {
        return this.g.number[null == a ? "e164" : a];
      };
      V.prototype.getNumber = V.prototype.xa;
      V.prototype.za = function () {
        return this.g.regionCode;
      };
      V.prototype.getRegionCode = V.prototype.za;
      V.prototype.ia = function () {
        return Yb(this.g.regionCode);
      };
      V.prototype.getCountryCode = V.prototype.ia;
      function Z(a) {
        this.j = a;
        this.h = new ub(a);
        this.l = this.g = "";
      }
      Z.prototype.sa = function (a) {
        this.g += a;
        var b = this.h;
        b.la = Bb(b, a);
        return this.l = b.la;
      };
      Z.prototype.addChar = Z.prototype.sa;
      Z.prototype.Ba = function () {
        return this.l;
      };
      Z.prototype.number = Z.prototype.Ba;
      Z.prototype.Ca = function () {
        return "" === this.g ? this.l : this.reset(this.g.slice(0, this.g.length - 1));
      };
      Z.prototype.removeChar = Z.prototype.Ca;
      Z.prototype.reset = function (a) {
        var b = this.h;
        b.la = "";
        A(b.u);
        A(b.ba);
        A(b.$);
        b.aa = 0;
        b.da = "";
        A(b.h);
        b.s = "";
        A(b.g);
        b.v = !0;
        b.oa = !1;
        b.ca = !1;
        b.ea = !1;
        b.j = [];
        b.ha = !1;
        b.m != b.Aa && (b.m = vb(b, b.ma));
        this.l = this.g = "";
        if (a) {
          b = 0;
          for (var c = a.length; b < c; ++b) this.sa(a.charAt(b));
        }
        return this.l;
      };
      Z.prototype.reset = Z.prototype.reset;
      Z.prototype.ya = function () {
        return new V(this.l, {
          regionCode: this.j
        }).toJSON();
      };
      Z.prototype.getPhoneNumber = Z.prototype.ya;
    }).call(module.exports || typeof globalThis !== 'undefined' && globalThis || typeof commonjsGlobal !== 'undefined' && commonjsGlobal || typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || lib);
  })(lib$1);
  return lib$1.exports;
}
var awesomePhonenumber = awesomePhonenumber$1.exports;
var hasRequiredAwesomePhonenumber;
function requireAwesomePhonenumber() {
  if (hasRequiredAwesomePhonenumber) return awesomePhonenumber$1.exports;
  hasRequiredAwesomePhonenumber = 1;
  (function (module) {
    const exportedName = 'PhoneNumber$$module$src$index';
    module.exports = requireLib()[exportedName] || (typeof globalThis !== 'undefined' && globalThis || typeof commonjsGlobal !== 'undefined' && commonjsGlobal || typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || awesomePhonenumber)[exportedName];
    Object.defineProperty(module.exports, "__esModule", {
      value: true
    });
    module.exports.parsePhoneNumber = (...args) => {
      try {
        const ret = module.exports(...args).toJSON();
        if (!ret.valid && !ret.possible) {
          ret.possible = false;
          if (!ret.possibility) ret.possibility = 'invalid';
        }
        return ret;
      } catch (error) {
        return {
          valid: false,
          possible: false,
          possibility: 'invalid',
          error
        };
      }
    };
    module.exports.getCountryCodeForRegionCode = module.exports.getCountryCodeForRegionCode;
    module.exports.getRegionCodeForCountryCode = module.exports.getRegionCodeForCountryCode;
    module.exports.getSupportedCallingCodes = module.exports.getSupportedCallingCodes;
    module.exports.getSupportedRegionCodes = module.exports.getSupportedRegionCodes;
    module.exports.getExample = module.exports.getExample;
    module.exports.getAsYouType = module.exports.getAsYouType;
    module.exports.getNumberFrom = module.exports.getNumberFrom;
    module.exports.findNumbers = module.exports.findNumbers;
  })(awesomePhonenumber$1);
  return awesomePhonenumber$1.exports;
}
var awesomePhonenumberExports = requireAwesomePhonenumber();
var index = /*@__PURE__*/getDefaultExportFromCjs(awesomePhonenumberExports);

const {
  PhoneNumber,
  AsYouType,
  getCountryCodeForRegionCode,
  getRegionCodeForCountryCode,
  getSupportedCallingCodes,
  getSupportedRegionCodes,
  findNumbers,
  getExample,
  getAsYouType,
  getNumberFrom
} = index;
const parsePhoneNumber = (...args) => {
  try {
    const ret = index(...args).toJSON();
    if (!ret.valid && !ret.possible) {
      ret.possible = false;
      if (!ret.possibility) ret.possibility = 'invalid';
    }
    return ret;
  } catch (error) {
    return {
      valid: false,
      possible: false,
      possibility: 'invalid',
      error
    };
  }
};


/***/ }),

/***/ 4003:
/*!****************************************************************************************!*\
  !*** ./node_modules/.pnpm/jwt-decode@4.0.0/node_modules/jwt-decode/build/esm/index.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   InvalidTokenError: () => (/* binding */ InvalidTokenError),
/* harmony export */   jwtDecode: () => (/* binding */ jwtDecode)
/* harmony export */ });
class InvalidTokenError extends Error {}
InvalidTokenError.prototype.name = "InvalidTokenError";
function b64DecodeUnicode(str) {
  return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {
    let code = p.charCodeAt(0).toString(16).toUpperCase();
    if (code.length < 2) {
      code = "0" + code;
    }
    return "%" + code;
  }));
}
function base64UrlDecode(str) {
  let output = str.replace(/-/g, "+").replace(/_/g, "/");
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += "==";
      break;
    case 3:
      output += "=";
      break;
    default:
      throw new Error("base64 string is not of the correct length");
  }
  try {
    return b64DecodeUnicode(output);
  } catch (err) {
    return atob(output);
  }
}
function jwtDecode(token, options) {
  if (typeof token !== "string") {
    throw new InvalidTokenError("Invalid token specified: must be a string");
  }
  options || (options = {});
  const pos = options.header === true ? 0 : 1;
  const part = token.split(".")[pos];
  if (typeof part !== "string") {
    throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);
  }
  let decoded;
  try {
    decoded = base64UrlDecode(part);
  } catch (e) {
    throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);
  }
  try {
    return JSON.parse(decoded);
  } catch (e) {
    throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);
  }
}

/***/ }),

/***/ 4626:
/*!**************************************************************************************************************!*\
  !*** ./node_modules/.pnpm/@babel+runtime@7.26.0/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js ***!
  \**************************************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ _asyncToGenerator)
/* harmony export */ });
function asyncGeneratorStep(n, t, e, r, o, a, c) {
  try {
    var i = n[a](c),
      u = i.value;
  } catch (n) {
    return void e(n);
  }
  i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
  return function () {
    var t = this,
      e = arguments;
    return new Promise(function (r, o) {
      var a = n.apply(t, e);
      function _next(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
      }
      function _throw(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
      }
      _next(void 0);
    });
  };
}


/***/ }),

/***/ 3215:
/*!*************************************************************************!*\
  !*** ./node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs ***!
  \*************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   __addDisposableResource: () => (/* binding */ __addDisposableResource),
/* harmony export */   __assign: () => (/* binding */ __assign),
/* harmony export */   __asyncDelegator: () => (/* binding */ __asyncDelegator),
/* harmony export */   __asyncGenerator: () => (/* binding */ __asyncGenerator),
/* harmony export */   __asyncValues: () => (/* binding */ __asyncValues),
/* harmony export */   __await: () => (/* binding */ __await),
/* harmony export */   __awaiter: () => (/* binding */ __awaiter),
/* harmony export */   __classPrivateFieldGet: () => (/* binding */ __classPrivateFieldGet),
/* harmony export */   __classPrivateFieldIn: () => (/* binding */ __classPrivateFieldIn),
/* harmony export */   __classPrivateFieldSet: () => (/* binding */ __classPrivateFieldSet),
/* harmony export */   __createBinding: () => (/* binding */ __createBinding),
/* harmony export */   __decorate: () => (/* binding */ __decorate),
/* harmony export */   __disposeResources: () => (/* binding */ __disposeResources),
/* harmony export */   __esDecorate: () => (/* binding */ __esDecorate),
/* harmony export */   __exportStar: () => (/* binding */ __exportStar),
/* harmony export */   __extends: () => (/* binding */ __extends),
/* harmony export */   __generator: () => (/* binding */ __generator),
/* harmony export */   __importDefault: () => (/* binding */ __importDefault),
/* harmony export */   __importStar: () => (/* binding */ __importStar),
/* harmony export */   __makeTemplateObject: () => (/* binding */ __makeTemplateObject),
/* harmony export */   __metadata: () => (/* binding */ __metadata),
/* harmony export */   __param: () => (/* binding */ __param),
/* harmony export */   __propKey: () => (/* binding */ __propKey),
/* harmony export */   __read: () => (/* binding */ __read),
/* harmony export */   __rest: () => (/* binding */ __rest),
/* harmony export */   __rewriteRelativeImportExtension: () => (/* binding */ __rewriteRelativeImportExtension),
/* harmony export */   __runInitializers: () => (/* binding */ __runInitializers),
/* harmony export */   __setFunctionName: () => (/* binding */ __setFunctionName),
/* harmony export */   __spread: () => (/* binding */ __spread),
/* harmony export */   __spreadArray: () => (/* binding */ __spreadArray),
/* harmony export */   __spreadArrays: () => (/* binding */ __spreadArrays),
/* harmony export */   __values: () => (/* binding */ __values),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */

var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  return extendStatics(d, b);
};

function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() { this.constructor = d; }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
  __assign = Object.assign || function __assign(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
      return t;
  }
  return __assign.apply(this, arguments);
}

function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
              t[p[i]] = s[p[i]];
      }
  return t;
}

function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
  return function (target, key) { decorator(target, key, paramIndex); }
}

function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
      var context = {};
      for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
      for (var p in contextIn.access) context.access[p] = contextIn.access[p];
      context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
      var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
      if (kind === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
      }
      else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
      }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
};

function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
};

function __propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
};

function __setFunctionName(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  return new (P || (P = Promise))(function (resolve, reject) {
      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
      function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}

function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  function verb(n) { return function (v) { return step([n, v]); }; }
  function step(op) {
      if (f) throw new TypeError("Generator is already executing.");
      while (g && (g = 0, op[0] && (_ = 0)), _) try {
          if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
          if (y = 0, t) op = [op[0] & 2, t.value];
          switch (op[0]) {
              case 0: case 1: t = op; break;
              case 4: _.label++; return { value: op[1], done: false };
              case 5: _.label++; y = op[1]; op = [0]; continue;
              case 7: op = _.ops.pop(); _.trys.pop(); continue;
              default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                  if (t[2]) _.ops.pop();
                  _.trys.pop(); continue;
          }
          op = body.call(thisArg, _);
      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  }
}

var __createBinding = Object.create ? (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
  }
  Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});

function __exportStar(m, o) {
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
      next: function () {
          if (o && i >= o.length) o = void 0;
          return { value: o && o[i++], done: !o };
      }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  }
  catch (error) { e = { error: error }; }
  finally {
      try {
          if (r && !r.done && (m = i["return"])) m.call(i);
      }
      finally { if (e) throw e.error; }
  }
  return ar;
}

/** @deprecated */
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
      ar = ar.concat(__read(arguments[i]));
  return ar;
}

/** @deprecated */
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
          r[k] = a[j];
  return r;
}

function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
      }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}

function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
  function fulfill(value) { resume("next", value); }
  function reject(value) { resume("throw", value); }
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
  return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
  Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
  o["default"] = v;
};

var ownKeys = function(o) {
  ownKeys = Object.getOwnPropertyNames || function (o) {
    var ar = [];
    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
    return ar;
  };
  return ownKeys(o);
};

function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  __setModuleDefault(result, mod);
  return result;
}

function __importDefault(mod) {
  return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}

function __addDisposableResource(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
    env.stack.push({ value: value, dispose: dispose, async: async });
  }
  else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}

var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

function __disposeResources(env) {
  function fail(e) {
    env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
    env.hasError = true;
  }
  var r, s = 0;
  function next() {
    while (r = env.stack.pop()) {
      try {
        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
        if (r.dispose) {
          var result = r.dispose.call(r.value);
          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
        }
        else s |= 1;
      }
      catch (e) {
        fail(e);
      }
    }
    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError) throw env.error;
  }
  return next();
}

function __rewriteRelativeImportExtension(path, preserveJsx) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
      return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
          return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
      });
  }
  return path;
}

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  __extends,
  __assign,
  __rest,
  __decorate,
  __param,
  __esDecorate,
  __runInitializers,
  __propKey,
  __setFunctionName,
  __metadata,
  __awaiter,
  __generator,
  __createBinding,
  __exportStar,
  __values,
  __read,
  __spread,
  __spreadArrays,
  __spreadArray,
  __await,
  __asyncGenerator,
  __asyncDelegator,
  __asyncValues,
  __makeTemplateObject,
  __importStar,
  __importDefault,
  __classPrivateFieldGet,
  __classPrivateFieldSet,
  __classPrivateFieldIn,
  __addDisposableResource,
  __disposeResources,
  __rewriteRelativeImportExtension,
});


/***/ })

},
/******/ __webpack_require__ => { // webpackRuntimeModules
/******/ var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
/******/ var __webpack_exports__ = (__webpack_exec__(4675));
/******/ }
]);
//# sourceMappingURL=main.js.map