{"version":3,"sources":["node_modules/dayjs/dayjs.min.js","node_modules/@servicestack/client/dist/index.js","node_modules/@angular/core/fesm2022/primitives/signals.mjs","node_modules/rxjs/_esm2015/internal/util/isFunction.js","node_modules/rxjs/_esm2015/internal/config.js","node_modules/rxjs/_esm2015/internal/util/hostReportError.js","node_modules/rxjs/_esm2015/internal/Observer.js","node_modules/rxjs/_esm2015/internal/util/isArray.js","node_modules/rxjs/_esm2015/internal/util/isObject.js","node_modules/rxjs/_esm2015/internal/util/UnsubscriptionError.js","node_modules/rxjs/_esm2015/internal/Subscription.js","node_modules/rxjs/_esm2015/internal/symbol/rxSubscriber.js","node_modules/rxjs/_esm2015/internal/Subscriber.js","node_modules/rxjs/_esm2015/internal/util/canReportError.js","node_modules/rxjs/_esm2015/internal/util/toSubscriber.js","node_modules/rxjs/_esm2015/internal/symbol/observable.js","node_modules/rxjs/_esm2015/internal/util/identity.js","node_modules/rxjs/_esm2015/internal/util/pipe.js","node_modules/rxjs/_esm2015/internal/Observable.js","node_modules/rxjs/_esm2015/internal/util/ObjectUnsubscribedError.js","node_modules/rxjs/_esm2015/internal/SubjectSubscription.js","node_modules/rxjs/_esm2015/internal/Subject.js","node_modules/rxjs/_esm2015/internal/operators/refCount.js","node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js","node_modules/rxjs/_esm2015/internal/BehaviorSubject.js","node_modules/rxjs/_esm2015/internal/scheduler/Action.js","node_modules/rxjs/_esm2015/internal/scheduler/AsyncAction.js","node_modules/rxjs/_esm2015/internal/scheduler/QueueAction.js","node_modules/rxjs/_esm2015/internal/Scheduler.js","node_modules/rxjs/_esm2015/internal/scheduler/AsyncScheduler.js","node_modules/rxjs/_esm2015/internal/scheduler/QueueScheduler.js","node_modules/rxjs/_esm2015/internal/scheduler/queue.js","node_modules/rxjs/_esm2015/internal/observable/empty.js","node_modules/rxjs/_esm2015/internal/util/isScheduler.js","node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js","node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js","node_modules/rxjs/_esm2015/internal/observable/fromArray.js","node_modules/rxjs/_esm2015/internal/observable/of.js","node_modules/rxjs/_esm2015/internal/observable/throwError.js","node_modules/rxjs/_esm2015/internal/Notification.js","node_modules/rxjs/_esm2015/internal/operators/observeOn.js","node_modules/rxjs/_esm2015/internal/ReplaySubject.js","node_modules/rxjs/_esm2015/internal/scheduler/async.js","node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameAction.js","node_modules/rxjs/_esm2015/internal/scheduler/AnimationFrameScheduler.js","node_modules/rxjs/_esm2015/internal/scheduler/animationFrame.js","node_modules/rxjs/_esm2015/internal/util/noop.js","node_modules/rxjs/_esm2015/internal/util/isObservable.js","node_modules/rxjs/_esm2015/internal/util/ArgumentOutOfRangeError.js","node_modules/rxjs/_esm2015/internal/util/EmptyError.js","node_modules/rxjs/_esm2015/internal/operators/map.js","node_modules/rxjs/_esm2015/internal/OuterSubscriber.js","node_modules/rxjs/_esm2015/internal/InnerSubscriber.js","node_modules/rxjs/_esm2015/internal/util/subscribeToPromise.js","node_modules/rxjs/_esm2015/internal/symbol/iterator.js","node_modules/rxjs/_esm2015/internal/util/subscribeToIterable.js","node_modules/rxjs/_esm2015/internal/util/subscribeToObservable.js","node_modules/rxjs/_esm2015/internal/util/isArrayLike.js","node_modules/rxjs/_esm2015/internal/util/isPromise.js","node_modules/rxjs/_esm2015/internal/util/subscribeTo.js","node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js","node_modules/rxjs/_esm2015/internal/observable/combineLatest.js","node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js","node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js","node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js","node_modules/rxjs/_esm2015/internal/util/isInteropObservable.js","node_modules/rxjs/_esm2015/internal/util/isIterable.js","node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js","node_modules/rxjs/_esm2015/internal/observable/from.js","node_modules/rxjs/_esm2015/internal/operators/mergeMap.js","node_modules/rxjs/_esm2015/internal/operators/mergeAll.js","node_modules/rxjs/_esm2015/internal/operators/concatAll.js","node_modules/rxjs/_esm2015/internal/observable/concat.js","node_modules/rxjs/_esm2015/internal/observable/defer.js","node_modules/rxjs/_esm2015/internal/observable/forkJoin.js","node_modules/rxjs/_esm2015/internal/observable/fromEvent.js","node_modules/rxjs/_esm2015/internal/observable/iif.js","node_modules/rxjs/_esm2015/internal/util/isNumeric.js","node_modules/rxjs/_esm2015/internal/observable/merge.js","node_modules/rxjs/_esm2015/internal/observable/never.js","node_modules/rxjs/_esm2015/internal/operators/filter.js","node_modules/rxjs/_esm2015/internal/observable/race.js","node_modules/rxjs/_esm2015/internal/observable/timer.js","node_modules/rxjs/_esm2015/internal/observable/zip.js","node_modules/rxjs/_esm2015/internal/operators/catchError.js","node_modules/rxjs/_esm2015/internal/operators/concatMap.js","node_modules/rxjs/_esm2015/internal/operators/defaultIfEmpty.js","node_modules/rxjs/_esm2015/internal/util/isDate.js","node_modules/rxjs/_esm2015/internal/operators/delay.js","node_modules/rxjs/_esm2015/internal/operators/distinctUntilChanged.js","node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js","node_modules/rxjs/_esm2015/internal/operators/take.js","node_modules/rxjs/_esm2015/internal/operators/endWith.js","node_modules/rxjs/_esm2015/internal/operators/finalize.js","node_modules/rxjs/_esm2015/internal/operators/first.js","node_modules/rxjs/_esm2015/internal/operators/takeLast.js","node_modules/rxjs/_esm2015/internal/operators/last.js","node_modules/rxjs/_esm2015/internal/operators/mapTo.js","node_modules/rxjs/_esm2015/internal/operators/scan.js","node_modules/rxjs/_esm2015/internal/operators/pluck.js","node_modules/rxjs/_esm2015/internal/operators/shareReplay.js","node_modules/rxjs/_esm2015/internal/operators/skip.js","node_modules/rxjs/_esm2015/internal/operators/startWith.js","node_modules/rxjs/_esm2015/internal/operators/switchMap.js","node_modules/rxjs/_esm2015/internal/operators/takeUntil.js","node_modules/rxjs/_esm2015/internal/operators/tap.js","node_modules/rxjs/_esm2015/internal/operators/withLatestFrom.js","node_modules/@angular/core/fesm2022/primitives/event-dispatch.mjs","node_modules/@angular/core/fesm2022/core.mjs","node_modules/@angular/common/fesm2022/common.mjs","node_modules/@angular/common/fesm2022/http.mjs","node_modules/@angular/platform-browser/fesm2022/platform-browser.mjs","node_modules/@angular/forms/fesm2022/forms.mjs","node_modules/ngp-image-picker/fesm2020/ngp-image-picker.mjs","node_modules/@kolkov/angular-editor/fesm2020/kolkov-angular-editor.mjs","src/app/bekerwedstrijden/bekerwedstrijden.component.ts","src/app/bekerwedstrijden/bekerwedstrijden.component.html","node_modules/@angular/router/fesm2022/router.mjs","src/app/nhsb/nhsb.component.ts","src/app/nhsb/nhsb.component.html","src/app/services/competitie.service.ts","node_modules/@angular/core/fesm2022/rxjs-interop.mjs","node_modules/@popperjs/core/lib/enums.js","node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","node_modules/@popperjs/core/lib/dom-utils/getWindow.js","node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","node_modules/@popperjs/core/lib/modifiers/applyStyles.js","node_modules/@popperjs/core/lib/utils/getBasePlacement.js","node_modules/@popperjs/core/lib/utils/math.js","node_modules/@popperjs/core/lib/utils/userAgent.js","node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","node_modules/@popperjs/core/lib/dom-utils/contains.js","node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","node_modules/@popperjs/core/lib/utils/within.js","node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","node_modules/@popperjs/core/lib/utils/expandToHashMap.js","node_modules/@popperjs/core/lib/modifiers/arrow.js","node_modules/@popperjs/core/lib/utils/getVariation.js","node_modules/@popperjs/core/lib/modifiers/computeStyles.js","node_modules/@popperjs/core/lib/modifiers/eventListeners.js","node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","node_modules/@popperjs/core/lib/utils/rectToClientRect.js","node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","node_modules/@popperjs/core/lib/utils/computeOffsets.js","node_modules/@popperjs/core/lib/utils/detectOverflow.js","node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","node_modules/@popperjs/core/lib/modifiers/flip.js","node_modules/@popperjs/core/lib/modifiers/offset.js","node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","node_modules/@popperjs/core/lib/utils/getAltAxis.js","node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","node_modules/@popperjs/core/lib/utils/orderModifiers.js","node_modules/@popperjs/core/lib/utils/debounce.js","node_modules/@popperjs/core/lib/utils/mergeByName.js","node_modules/@popperjs/core/lib/createPopper.js","node_modules/@popperjs/core/lib/popper-lite.js","node_modules/@ng-bootstrap/ng-bootstrap/fesm2022/ng-bootstrap.mjs","src/app/yearselector/yearselector.component.ts","src/app/yearselector/yearselector.component.html","src/app/wedstrijdentabel/wedstrijdentabel.component.ts","src/app/wedstrijdentabel/wedstrijdentabel.component.html","src/app/pipes/order-by-pipe.ts","src/app/competitie-speeldag/competitie-speeldag.component.ts","src/app/competitie-speeldag/competitie-speeldag.component.html","src/app/competitie-stand/competitie-stand.component.ts","src/app/competitie-stand/competitie-stand.component.html","src/app/privacystatement/privacystatement.component.ts","src/app/privacystatement/privacystatement.component.html","src/app/home/home.component.ts","src/app/home/home.component.html","enpassantapi.dtos.ts","src/app/agenda/agenda.component.ts","src/app/agenda/agenda.component.html","src/app/services/api.client.provider.service.ts","node_modules/@auth0/angular-jwt/fesm2020/auth0-angular-jwt.mjs","node_modules/@auth0/auth0-spa-js/dist/auth0-spa-js.production.esm.js","node_modules/@auth0/auth0-angular/fesm2020/auth0-auth0-angular.mjs","src/app/services/authservice.service.ts","src/app/services/form-builder-typed.ts","node_modules/ngx-bootstrap/chronos/fesm2022/ngx-bootstrap-chronos.mjs","node_modules/ngx-bootstrap/utils/fesm2022/ngx-bootstrap-utils.mjs","node_modules/ngx-bootstrap/positioning/fesm2022/ngx-bootstrap-positioning.mjs","node_modules/ngx-bootstrap/mini-ngrx/fesm2022/ngx-bootstrap-mini-ngrx.mjs","node_modules/ngx-bootstrap/timepicker/fesm2022/ngx-bootstrap-timepicker.mjs","node_modules/@angular/animations/fesm2022/animations.mjs","node_modules/tslib/tslib.es6.mjs","node_modules/ngx-bootstrap/component-loader/fesm2022/ngx-bootstrap-component-loader.mjs","node_modules/ngx-bootstrap/tooltip/fesm2022/ngx-bootstrap-tooltip.mjs","node_modules/ngx-bootstrap/datepicker/fesm2022/ngx-bootstrap-datepicker.mjs","src/app/artikelen/artikelen.component.ts","src/app/artikelen/artikelen.component.html","src/app/pipes/sanitize-html.pipe.ts","src/app/competitie-speler/competitie-speler.component.ts","src/app/competitie-speler/competitie-speler.component.html","src/app/app-routing.module.ts","src/app/app.component.ts","src/app/app.component.html","node_modules/@angular/common/locales/nl.mjs","node_modules/@angular/common/locales/extra/nl.mjs","node_modules/@angular/animations/fesm2022/browser.mjs","node_modules/@angular/platform-browser/fesm2022/animations.mjs","src/app/app.module.ts","src/environments/environment.ts","src/main.ts"],"sourcesContent":["!function (t, e) {\n \"object\" == typeof exports && \"undefined\" != typeof module ? module.exports = e() : \"function\" == typeof define && define.amd ? define(e) : (t = \"undefined\" != typeof globalThis ? globalThis : t || self).dayjs = e();\n}(this, function () {\n \"use strict\";\n\n var t = 1e3,\n e = 6e4,\n n = 36e5,\n r = \"millisecond\",\n i = \"second\",\n s = \"minute\",\n u = \"hour\",\n a = \"day\",\n o = \"week\",\n c = \"month\",\n f = \"quarter\",\n h = \"year\",\n d = \"date\",\n l = \"Invalid Date\",\n $ = /^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,\n y = /\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,\n M = {\n name: \"en\",\n weekdays: \"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),\n months: \"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),\n ordinal: function (t) {\n var e = [\"th\", \"st\", \"nd\", \"rd\"],\n n = t % 100;\n return \"[\" + t + (e[(n - 20) % 10] || e[n] || e[0]) + \"]\";\n }\n },\n m = function (t, e, n) {\n var r = String(t);\n return !r || r.length >= e ? t : \"\" + Array(e + 1 - r.length).join(n) + t;\n },\n v = {\n s: m,\n z: function (t) {\n var e = -t.utcOffset(),\n n = Math.abs(e),\n r = Math.floor(n / 60),\n i = n % 60;\n return (e <= 0 ? \"+\" : \"-\") + m(r, 2, \"0\") + \":\" + m(i, 2, \"0\");\n },\n m: function t(e, n) {\n if (e.date() < n.date()) return -t(n, e);\n var r = 12 * (n.year() - e.year()) + (n.month() - e.month()),\n i = e.clone().add(r, c),\n s = n - i < 0,\n u = e.clone().add(r + (s ? -1 : 1), c);\n return +(-(r + (n - i) / (s ? i - u : u - i)) || 0);\n },\n a: function (t) {\n return t < 0 ? Math.ceil(t) || 0 : Math.floor(t);\n },\n p: function (t) {\n return {\n M: c,\n y: h,\n w: o,\n d: a,\n D: d,\n h: u,\n m: s,\n s: i,\n ms: r,\n Q: f\n }[t] || String(t || \"\").toLowerCase().replace(/s$/, \"\");\n },\n u: function (t) {\n return void 0 === t;\n }\n },\n g = \"en\",\n D = {};\n D[g] = M;\n var p = \"$isDayjsObject\",\n S = function (t) {\n return t instanceof _ || !(!t || !t[p]);\n },\n w = function t(e, n, r) {\n var i;\n if (!e) return g;\n if (\"string\" == typeof e) {\n var s = e.toLowerCase();\n D[s] && (i = s), n && (D[s] = n, i = s);\n var u = e.split(\"-\");\n if (!i && u.length > 1) return t(u[0]);\n } else {\n var a = e.name;\n D[a] = e, i = a;\n }\n return !r && i && (g = i), i || !r && g;\n },\n O = function (t, e) {\n if (S(t)) return t.clone();\n var n = \"object\" == typeof e ? e : {};\n return n.date = t, n.args = arguments, new _(n);\n },\n b = v;\n b.l = w, b.i = S, b.w = function (t, e) {\n return O(t, {\n locale: e.$L,\n utc: e.$u,\n x: e.$x,\n $offset: e.$offset\n });\n };\n var _ = function () {\n function M(t) {\n this.$L = w(t.locale, null, !0), this.parse(t), this.$x = this.$x || t.x || {}, this[p] = !0;\n }\n var m = M.prototype;\n return m.parse = function (t) {\n this.$d = function (t) {\n var e = t.date,\n n = t.utc;\n if (null === e) return new Date(NaN);\n if (b.u(e)) return new Date();\n if (e instanceof Date) return new Date(e);\n if (\"string\" == typeof e && !/Z$/i.test(e)) {\n var r = e.match($);\n if (r) {\n var i = r[2] - 1 || 0,\n s = (r[7] || \"0\").substring(0, 3);\n return n ? new Date(Date.UTC(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s)) : new Date(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s);\n }\n }\n return new Date(e);\n }(t), this.init();\n }, m.init = function () {\n var t = this.$d;\n this.$y = t.getFullYear(), this.$M = t.getMonth(), this.$D = t.getDate(), this.$W = t.getDay(), this.$H = t.getHours(), this.$m = t.getMinutes(), this.$s = t.getSeconds(), this.$ms = t.getMilliseconds();\n }, m.$utils = function () {\n return b;\n }, m.isValid = function () {\n return !(this.$d.toString() === l);\n }, m.isSame = function (t, e) {\n var n = O(t);\n return this.startOf(e) <= n && n <= this.endOf(e);\n }, m.isAfter = function (t, e) {\n return O(t) < this.startOf(e);\n }, m.isBefore = function (t, e) {\n return this.endOf(e) < O(t);\n }, m.$g = function (t, e, n) {\n return b.u(t) ? this[e] : this.set(n, t);\n }, m.unix = function () {\n return Math.floor(this.valueOf() / 1e3);\n }, m.valueOf = function () {\n return this.$d.getTime();\n }, m.startOf = function (t, e) {\n var n = this,\n r = !!b.u(e) || e,\n f = b.p(t),\n l = function (t, e) {\n var i = b.w(n.$u ? Date.UTC(n.$y, e, t) : new Date(n.$y, e, t), n);\n return r ? i : i.endOf(a);\n },\n $ = function (t, e) {\n return b.w(n.toDate()[t].apply(n.toDate(\"s\"), (r ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e)), n);\n },\n y = this.$W,\n M = this.$M,\n m = this.$D,\n v = \"set\" + (this.$u ? \"UTC\" : \"\");\n switch (f) {\n case h:\n return r ? l(1, 0) : l(31, 11);\n case c:\n return r ? l(1, M) : l(0, M + 1);\n case o:\n var g = this.$locale().weekStart || 0,\n D = (y < g ? y + 7 : y) - g;\n return l(r ? m - D : m + (6 - D), M);\n case a:\n case d:\n return $(v + \"Hours\", 0);\n case u:\n return $(v + \"Minutes\", 1);\n case s:\n return $(v + \"Seconds\", 2);\n case i:\n return $(v + \"Milliseconds\", 3);\n default:\n return this.clone();\n }\n }, m.endOf = function (t) {\n return this.startOf(t, !1);\n }, m.$set = function (t, e) {\n var n,\n o = b.p(t),\n f = \"set\" + (this.$u ? \"UTC\" : \"\"),\n l = (n = {}, n[a] = f + \"Date\", n[d] = f + \"Date\", n[c] = f + \"Month\", n[h] = f + \"FullYear\", n[u] = f + \"Hours\", n[s] = f + \"Minutes\", n[i] = f + \"Seconds\", n[r] = f + \"Milliseconds\", n)[o],\n $ = o === a ? this.$D + (e - this.$W) : e;\n if (o === c || o === h) {\n var y = this.clone().set(d, 1);\n y.$d[l]($), y.init(), this.$d = y.set(d, Math.min(this.$D, y.daysInMonth())).$d;\n } else l && this.$d[l]($);\n return this.init(), this;\n }, m.set = function (t, e) {\n return this.clone().$set(t, e);\n }, m.get = function (t) {\n return this[b.p(t)]();\n }, m.add = function (r, f) {\n var d,\n l = this;\n r = Number(r);\n var $ = b.p(f),\n y = function (t) {\n var e = O(l);\n return b.w(e.date(e.date() + Math.round(t * r)), l);\n };\n if ($ === c) return this.set(c, this.$M + r);\n if ($ === h) return this.set(h, this.$y + r);\n if ($ === a) return y(1);\n if ($ === o) return y(7);\n var M = (d = {}, d[s] = e, d[u] = n, d[i] = t, d)[$] || 1,\n m = this.$d.getTime() + r * M;\n return b.w(m, this);\n }, m.subtract = function (t, e) {\n return this.add(-1 * t, e);\n }, m.format = function (t) {\n var e = this,\n n = this.$locale();\n if (!this.isValid()) return n.invalidDate || l;\n var r = t || \"YYYY-MM-DDTHH:mm:ssZ\",\n i = b.z(this),\n s = this.$H,\n u = this.$m,\n a = this.$M,\n o = n.weekdays,\n c = n.months,\n f = n.meridiem,\n h = function (t, n, i, s) {\n return t && (t[n] || t(e, r)) || i[n].slice(0, s);\n },\n d = function (t) {\n return b.s(s % 12 || 12, t, \"0\");\n },\n $ = f || function (t, e, n) {\n var r = t < 12 ? \"AM\" : \"PM\";\n return n ? r.toLowerCase() : r;\n };\n return r.replace(y, function (t, r) {\n return r || function (t) {\n switch (t) {\n case \"YY\":\n return String(e.$y).slice(-2);\n case \"YYYY\":\n return b.s(e.$y, 4, \"0\");\n case \"M\":\n return a + 1;\n case \"MM\":\n return b.s(a + 1, 2, \"0\");\n case \"MMM\":\n return h(n.monthsShort, a, c, 3);\n case \"MMMM\":\n return h(c, a);\n case \"D\":\n return e.$D;\n case \"DD\":\n return b.s(e.$D, 2, \"0\");\n case \"d\":\n return String(e.$W);\n case \"dd\":\n return h(n.weekdaysMin, e.$W, o, 2);\n case \"ddd\":\n return h(n.weekdaysShort, e.$W, o, 3);\n case \"dddd\":\n return o[e.$W];\n case \"H\":\n return String(s);\n case \"HH\":\n return b.s(s, 2, \"0\");\n case \"h\":\n return d(1);\n case \"hh\":\n return d(2);\n case \"a\":\n return $(s, u, !0);\n case \"A\":\n return $(s, u, !1);\n case \"m\":\n return String(u);\n case \"mm\":\n return b.s(u, 2, \"0\");\n case \"s\":\n return String(e.$s);\n case \"ss\":\n return b.s(e.$s, 2, \"0\");\n case \"SSS\":\n return b.s(e.$ms, 3, \"0\");\n case \"Z\":\n return i;\n }\n return null;\n }(t) || i.replace(\":\", \"\");\n });\n }, m.utcOffset = function () {\n return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);\n }, m.diff = function (r, d, l) {\n var $,\n y = this,\n M = b.p(d),\n m = O(r),\n v = (m.utcOffset() - this.utcOffset()) * e,\n g = this - m,\n D = function () {\n return b.m(y, m);\n };\n switch (M) {\n case h:\n $ = D() / 12;\n break;\n case c:\n $ = D();\n break;\n case f:\n $ = D() / 3;\n break;\n case o:\n $ = (g - v) / 6048e5;\n break;\n case a:\n $ = (g - v) / 864e5;\n break;\n case u:\n $ = g / n;\n break;\n case s:\n $ = g / e;\n break;\n case i:\n $ = g / t;\n break;\n default:\n $ = g;\n }\n return l ? $ : b.a($);\n }, m.daysInMonth = function () {\n return this.endOf(c).$D;\n }, m.$locale = function () {\n return D[this.$L];\n }, m.locale = function (t, e) {\n if (!t) return this.$L;\n var n = this.clone(),\n r = w(t, e, !0);\n return r && (n.$L = r), n;\n }, m.clone = function () {\n return b.w(this.$d, this);\n }, m.toDate = function () {\n return new Date(this.valueOf());\n }, m.toJSON = function () {\n return this.isValid() ? this.toISOString() : null;\n }, m.toISOString = function () {\n return this.$d.toISOString();\n }, m.toString = function () {\n return this.$d.toUTCString();\n }, M;\n }(),\n k = _.prototype;\n return O.prototype = k, [[\"$ms\", r], [\"$s\", i], [\"$m\", s], [\"$H\", u], [\"$W\", a], [\"$M\", c], [\"$y\", h], [\"$D\", d]].forEach(function (t) {\n k[t[1]] = function (e) {\n return this.$g(e, t[0], t[1]);\n };\n }), O.extend = function (t, e) {\n return t.$i || (t(e, _, O), t.$i = !0), O;\n }, O.locale = w, O.isDayjs = S, O.unix = function (t) {\n return O(1e3 * t);\n }, O.en = D[g], O.Ls = D, O.p = {}, O;\n});","\"use strict\";\n\nvar __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {\n function adopt(value) {\n return value instanceof P ? value : new P(function (resolve) {\n resolve(value);\n });\n }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) {\n try {\n step(generator.next(value));\n } catch (e) {\n reject(e);\n }\n }\n function rejected(value) {\n try {\n step(generator[\"throw\"](value));\n } catch (e) {\n reject(e);\n }\n }\n function step(result) {\n result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);\n }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.chop = exports.lastRightPart = exports.lastLeftPart = exports.rightPart = exports.leftPart = exports.splitOnLast = exports.splitOnFirst = exports.css = exports.nameOf = exports.sanitize = exports.map = exports.toKebabCase = exports.toPascalCase = exports.toCamelCase = exports.createError = exports.isFormData = exports.createFieldError = exports.createErrorStatus = exports.ApiResult = exports.getResponseStatus = exports.getMethod = exports.JsonServiceClient = exports.GetAccessTokenResponse = exports.HttpMethods = exports.ServerEventUser = exports.GetEventSubscribers = exports.UpdateEventSubscriberResponse = exports.UpdateEventSubscriber = exports.ServerEventReceiver = exports.ServerEventsClient = exports.ReadyState = exports.SingletonInstanceResolver = exports.NewInstanceResolver = exports.MetadataType = exports.MetadataPropertyType = exports.MetadataAttribute = exports.MetadataDataMember = exports.MetadataDataContract = exports.MetadataTypeName = exports.MetadataTypes = exports.MetadataOperationType = exports.MetadataRoute = exports.MetadataTypesConfig = exports.GetNavItemsResponse = exports.GetNavItems = exports.NavItem = exports.EmptyResponse = exports.ErrorResponse = exports.ResponseError = exports.ResponseStatus = void 0;\nexports.sanitizeFormData = exports.serializeToFormData = exports.serializeToUrlEncoded = exports.serializeToObject = exports.serializeForm = exports.ajaxSubmit = exports.formSubmit = exports.toVarNames = exports.bootstrapForm = exports.bindHandlers = exports.bootstrap = exports.delaySet = exports.on = exports.$$ = exports.$1 = exports.createElement = exports.toLocalISOString = exports.timeFmt12 = exports.dateFmtHM = exports.dateFmt = exports.padInt = exports.toDateFmt = exports.toDate = exports.isDate = exports.errorResponse = exports.errorResponseExcept = exports.errorResponseSummary = exports.toObject = exports.toFormData = exports.parseResponseStatus = exports.getField = exports.normalize = exports.normalizeKey = exports.parseCookie = exports.tryDecode = exports.stripQuotes = exports.bytesToBase64 = exports.appendQueryString = exports.createUrl = exports.createPath = exports.combinePaths = exports.queryString = exports.humanify = exports.splitTitleCase = exports.isDigit = exports.isLower = exports.isUpper = exports.ucFirst = exports.humanize = exports.onlyProps = void 0;\nexports.alignCenter = exports.alignLeft = exports.uniqueKeys = exports.JSV = exports.StringBuffer = exports.toBase64String = exports.toByteArray = exports.fromByteArray = exports.toGuid = exports.fromGuid = exports.toTimeSpan = exports.fromTimeSpan = exports.toDateTime = exports.fromDateTime = exports.isNullOrEmpty = exports.indexOfAny = exports.htmlAttrs = exports.enc = exports.uniq = exports.flatMap = exports.toTimeSpanFmt = exports.toXsdDuration = exports.fromXsdDuration = exports.classNames = exports.NavOptions = exports.UserAttributes = exports.LinkButtonDefaults = exports.NavButtonGroupDefaults = exports.NavbarDefaults = exports.NavLinkDefaults = exports.NavDefaults = exports.btnClasses = exports.btnSizeClass = exports.BootstrapSizes = exports.btnColorClass = exports.BootstrapColors = exports.activeClass = exports.activeClassNav = exports.apiValueFmt = exports.apiValue = exports.mapGet = exports.resolve = exports.each = exports.apply = exports.omit = exports.pick = exports.safeVarName = exports.trimEnd = exports.populateForm = exports.triggerEvent = void 0;\nexports.Inspect = exports.createBus = exports.EventBus = exports.alignAuto = exports.alignRight = void 0;\nfunction nodeRequire() {\n //node require(), using dynamic access to fix web ng aot build\n try {\n let isNode = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined';\n if (isNode) return eval('require');\n return null;\n } catch (e) {\n return null;\n }\n}\nlet R = nodeRequire();\nif (R) R('cross-fetch/polyfill'); //fetch polyfill only required for node.js\nclass ResponseStatus {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.ResponseStatus = ResponseStatus;\nclass ResponseError {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.ResponseError = ResponseError;\nclass ErrorResponse {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.ErrorResponse = ErrorResponse;\nclass EmptyResponse {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.EmptyResponse = EmptyResponse;\nclass NavItem {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.NavItem = NavItem;\nclass GetNavItems {\n constructor(init) {\n Object.assign(this, init);\n }\n createResponse() {\n return new GetNavItemsResponse();\n }\n getTypeName() {\n return 'GetNavItems';\n }\n getMethod() {\n return 'GET';\n }\n}\nexports.GetNavItems = GetNavItems;\nclass GetNavItemsResponse {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.GetNavItemsResponse = GetNavItemsResponse;\nclass MetadataTypesConfig {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataTypesConfig = MetadataTypesConfig;\nclass MetadataRoute {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataRoute = MetadataRoute;\nclass MetadataOperationType {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataOperationType = MetadataOperationType;\nclass MetadataTypes {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataTypes = MetadataTypes;\nclass MetadataTypeName {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataTypeName = MetadataTypeName;\nclass MetadataDataContract {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataDataContract = MetadataDataContract;\nclass MetadataDataMember {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataDataMember = MetadataDataMember;\nclass MetadataAttribute {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataAttribute = MetadataAttribute;\nclass MetadataPropertyType {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataPropertyType = MetadataPropertyType;\nclass MetadataType {\n constructor(init) {\n Object.assign(this, init);\n }\n}\nexports.MetadataType = MetadataType;\nclass NewInstanceResolver {\n tryResolve(ctor) {\n return new ctor();\n }\n}\nexports.NewInstanceResolver = NewInstanceResolver;\nclass SingletonInstanceResolver {\n tryResolve(ctor) {\n return ctor.instance || (ctor.instance = new ctor());\n }\n}\nexports.SingletonInstanceResolver = SingletonInstanceResolver;\nfunction eventMessageType(evt) {\n switch (evt) {\n case 'onConnect':\n return 'ServerEventConnect';\n case 'onHeartbeat':\n return 'ServerEventHeartbeat';\n case 'onJoin':\n return 'ServerEventJoin';\n case 'onLeave':\n return 'ServerEventLeave';\n case 'onUpdate':\n return 'ServerEventUpdate';\n }\n return null;\n}\n/**\r\n * EventSource\r\n */\nvar ReadyState;\n(function (ReadyState) {\n ReadyState[ReadyState[\"CONNECTING\"] = 0] = \"CONNECTING\";\n ReadyState[ReadyState[\"OPEN\"] = 1] = \"OPEN\";\n ReadyState[ReadyState[\"CLOSED\"] = 2] = \"CLOSED\";\n})(ReadyState = exports.ReadyState || (exports.ReadyState = {}));\nclass ServerEventsClient {\n constructor(baseUrl, channels, options = {}, eventSource = null) {\n this.channels = channels;\n this.options = options;\n this.eventSource = eventSource;\n this.onMessage = e => {\n if (typeof document == \"undefined\") {\n //node\n //latest node-fetch + eventsource doesn't split SSE messages properly\n let requireSplitPos = e.data ? e.data.indexOf('\\n') : -1;\n if (requireSplitPos >= 0) {\n let data = e.data;\n let lastEventId = e.lastEventId;\n let e1 = Object.assign({}, {\n lastEventId,\n data: data.substring(0, requireSplitPos)\n }),\n e2 = Object.assign({}, {\n lastEventId,\n data: data.substring(requireSplitPos + 1)\n });\n this._onMessage(e1);\n this._onMessage(e2);\n return;\n }\n }\n this._onMessage(e);\n };\n this._onMessage = e => {\n if (this.stopped) return;\n let opt = this.options;\n if (typeof document == \"undefined\") {\n var document = {\n querySelectorAll: sel => []\n };\n }\n let $ = document.querySelectorAll.bind(document);\n let parts = splitOnFirst(e.data, \" \");\n let channel = null;\n let selector = parts[0];\n let selParts = splitOnFirst(selector, \"@\");\n if (selParts.length > 1) {\n channel = selParts[0];\n selector = selParts[1];\n }\n const json = parts[1];\n let body = null;\n try {\n body = json ? JSON.parse(json) : null;\n } catch (ignore) {}\n parts = splitOnFirst(selector, \".\");\n if (parts.length <= 1) throw \"invalid selector format: \" + selector;\n let op = parts[0],\n target = parts[1].replace(new RegExp(\"%20\", \"g\"), \" \");\n const tokens = splitOnFirst(target, \"$\");\n const [cmd, cssSelector] = tokens;\n const els = cssSelector && $(cssSelector);\n const el = els && els[0];\n const eventId = parseInt(e.lastEventId);\n const data = e.data;\n const type = eventMessageType(cmd) || \"ServerEventMessage\";\n const request = {\n eventId,\n data,\n type,\n channel,\n selector,\n json,\n body,\n op,\n target: tokens[0],\n cssSelector,\n meta: {}\n };\n const mergedBody = typeof body == \"object\" ? Object.assign({}, request, body) : request;\n if (opt.validate && opt.validate(request) === false) return;\n let headers = new Headers();\n headers.set(\"Content-Type\", \"text/plain\");\n if (op === \"cmd\") {\n if (cmd === \"onConnect\") {\n this.connectionInfo = mergedBody;\n if (typeof body.heartbeatIntervalMs == \"string\") this.connectionInfo.heartbeatIntervalMs = parseInt(body.heartbeatIntervalMs);\n if (typeof body.idleTimeoutMs == \"string\") this.connectionInfo.idleTimeoutMs = parseInt(body.idleTimeoutMs);\n Object.assign(opt, body);\n let fn = opt.handlers[\"onConnect\"];\n if (fn) {\n fn.call(el || document.body, this.connectionInfo, request);\n if (this.stopped) return;\n }\n if (opt.heartbeatUrl) {\n if (opt.heartbeat) {\n clearInterval(opt.heartbeat);\n }\n opt.heartbeat = setInterval(() => {\n if (this.eventSource.readyState === EventSource.CLOSED) {\n clearInterval(opt.heartbeat);\n const stopFn = opt.handlers[\"onStop\"];\n if (stopFn != null) stopFn.apply(this.eventSource);\n this.reconnectServerEvents({\n error: new Error(\"EventSource is CLOSED\")\n });\n return;\n }\n fetch(new Request(opt.heartbeatUrl, {\n method: \"POST\",\n mode: \"cors\",\n headers: headers,\n credentials: this.serviceClient.credentials\n })).then(res => {\n if (!res.ok) throw new Error(`${res.status} - ${res.statusText}`);\n }).catch(error => this.reconnectServerEvents({\n error\n }));\n }, this.connectionInfo && this.connectionInfo.heartbeatIntervalMs || opt.heartbeatIntervalMs || 10000);\n }\n if (opt.unRegisterUrl) {\n if (typeof window != \"undefined\") {\n window.onunload = () => {\n if (navigator.sendBeacon) {\n // Chrome https://developers.google.com/web/updates/2019/12/chrome-80-deps-rems\n this.stopped = true;\n if (this.eventSource) this.eventSource.close();\n navigator.sendBeacon(opt.unRegisterUrl);\n } else {\n this.stop();\n }\n };\n }\n }\n this.updateSubscriberUrl = opt.updateSubscriberUrl;\n this.updateChannels((opt.channels || \"\").split(\",\"));\n } else {\n let isCmdMsg = cmd == \"onJoin\" || cmd == \"onLeave\" || cmd == \"onUpdate\";\n let fn = opt.handlers[cmd];\n if (fn) {\n if (isCmdMsg) {\n fn.call(el || document.body, mergedBody);\n } else {\n fn.call(el || document.body, body, request);\n }\n } else {\n if (!isCmdMsg) {\n //global receiver\n let r = opt.receivers && opt.receivers[\"cmd\"];\n this.invokeReceiver(r, cmd, el, request, \"cmd\");\n }\n }\n if (isCmdMsg) {\n fn = opt.handlers[\"onCommand\"];\n if (fn) {\n fn.call(el || document.body, mergedBody);\n }\n }\n }\n } else if (op === \"trigger\") {\n this.raiseEvent(target, request);\n } else if (op === \"css\") {\n css(els || $(\"body\"), cmd, body);\n }\n //Named Receiver\n let r = opt.receivers && opt.receivers[op];\n this.invokeReceiver(r, cmd, el, request, op);\n if (!eventMessageType(cmd)) {\n let fn = opt.handlers[\"onMessage\"];\n if (fn) {\n fn.call(el || document.body, mergedBody);\n }\n }\n if (opt.onTick) opt.onTick();\n };\n this.onError = error => {\n if (this.stopped) return;\n if (!error) error = event;\n let fn = this.options.onException;\n if (fn != null) fn.call(this.eventSource, error);\n if (this.options.onTick) this.options.onTick();\n };\n if (this.channels.length === 0) throw \"at least 1 channel is required\";\n this.resolver = this.options.resolver || new NewInstanceResolver();\n this.eventStreamUri = combinePaths(baseUrl, \"event-stream\") + \"?\";\n this.updateChannels(channels);\n this.serviceClient = new JsonServiceClient(baseUrl);\n this.listeners = {};\n this.withCredentials = true;\n if (!this.options.handlers) this.options.handlers = {};\n }\n getEventSourceOptions() {\n return {\n withCredentials: this.withCredentials\n };\n }\n reconnectServerEvents(opt = {}) {\n if (this.stopped) return;\n if (opt.error) this.onError(opt.error);\n const hold = this.eventSource;\n let url = opt.url || this.eventStreamUri || hold.url;\n if (this.options.resolveStreamUrl != null) {\n url = this.options.resolveStreamUrl(url);\n }\n const es = this.EventSource ? new this.EventSource(url, this.getEventSourceOptions()) : new EventSource(url, this.getEventSourceOptions());\n es.addEventListener('error', e => (opt.onerror || hold.onerror || this.onError)(e));\n es.addEventListener('message', opt.onmessage || hold.onmessage || this.onMessage);\n let fn = this.options.onReconnect;\n if (fn != null) fn.call(es, opt.error);\n if (hold.removeEventListener) {\n hold.removeEventListener('error', this.onError);\n hold.removeEventListener('message', this.onMessage);\n }\n hold.close();\n return this.eventSource = es;\n }\n start() {\n this.stopped = false;\n if (this.eventSource == null || this.eventSource.readyState === EventSource.CLOSED) {\n let url = this.eventStreamUri;\n if (this.options.resolveStreamUrl != null) {\n url = this.options.resolveStreamUrl(url);\n }\n this.eventSource = this.EventSource ? new this.EventSource(url, this.getEventSourceOptions()) : new EventSource(url, this.getEventSourceOptions());\n this.eventSource.addEventListener('error', this.onError);\n this.eventSource.addEventListener('message', e => this.onMessage(e));\n }\n return this;\n }\n stop() {\n this.stopped = true;\n if (this.eventSource) {\n this.eventSource.close();\n }\n let opt = this.options;\n if (opt && opt.heartbeat) {\n clearInterval(opt.heartbeat);\n }\n let hold = this.connectionInfo;\n if (hold == null || hold.unRegisterUrl == null) return new Promise((resolve, reject) => resolve());\n this.connectionInfo = null;\n return fetch(new Request(hold.unRegisterUrl, {\n method: \"POST\",\n mode: \"cors\",\n credentials: this.serviceClient.credentials\n })).then(res => {\n if (!res.ok) throw new Error(`${res.status} - ${res.statusText}`);\n }).catch(this.onError);\n }\n invokeReceiver(r, cmd, el, request, name) {\n if (r) {\n if (typeof r == \"function\") {\n r = this.resolver.tryResolve(r);\n }\n cmd = cmd.replace(\"-\", \"\");\n r.client = this;\n r.request = request;\n if (typeof r[cmd] == \"function\") {\n r[cmd].call(el || r, request.body, request);\n } else if (cmd in r) {\n r[cmd] = request.body;\n } else {\n let metaProp = Object.getOwnPropertyDescriptor(r, cmd);\n if (metaProp != null) {\n if (metaProp.set) {\n metaProp.set(request.body);\n } else if (metaProp.writable) {\n r[cmd] = request.body;\n }\n return;\n }\n let cmdLower = cmd.toLowerCase();\n for (let k in r) {\n if (k.toLowerCase() == cmdLower) {\n if (typeof r[k] == \"function\") {\n r[k].call(el || r, request.body, request);\n } else {\n r[k] = request.body;\n }\n return;\n }\n }\n let noSuchMethod = r[\"noSuchMethod\"];\n if (typeof noSuchMethod == \"function\") {\n noSuchMethod.call(el || r, request.target, request);\n }\n }\n }\n }\n hasConnected() {\n return this.connectionInfo != null;\n }\n registerHandler(name, fn) {\n if (!this.options.handlers) this.options.handlers = {};\n this.options.handlers[name] = fn;\n return this;\n }\n setResolver(resolver) {\n this.options.resolver = resolver;\n return this;\n }\n registerReceiver(receiver) {\n return this.registerNamedReceiver(\"cmd\", receiver);\n }\n registerNamedReceiver(name, receiver) {\n if (!this.options.receivers) this.options.receivers = {};\n this.options.receivers[name] = receiver;\n return this;\n }\n unregisterReceiver(name = \"cmd\") {\n if (this.options.receivers) {\n delete this.options.receivers[name];\n }\n return this;\n }\n updateChannels(channels) {\n this.channels = channels;\n const url = this.eventSource != null ? this.eventSource.url : this.eventStreamUri;\n this.eventStreamUri = url.substring(0, Math.min(url.indexOf(\"?\"), url.length)) + \"?channels=\" + channels.join(\",\") + \"&t=\" + new Date().getTime();\n }\n update(subscribe, unsubscribe) {\n let sub = typeof subscribe == \"string\" ? subscribe.split(',') : subscribe;\n let unsub = typeof unsubscribe == \"string\" ? unsubscribe.split(',') : unsubscribe;\n let channels = [];\n for (let i in this.channels) {\n let c = this.channels[i];\n if (unsub == null || unsub.indexOf(c) === -1) {\n channels.push(c);\n }\n }\n if (sub) {\n for (let i in sub) {\n let c = sub[i];\n if (channels.indexOf(c) === -1) {\n channels.push(c);\n }\n }\n }\n this.updateChannels(channels);\n }\n addListener(eventName, handler) {\n let handlers = this.listeners[eventName] || (this.listeners[eventName] = []);\n handlers.push(handler);\n return this;\n }\n removeListener(eventName, handler) {\n let handlers = this.listeners[eventName];\n if (handlers) {\n let pos = handlers.indexOf(handler);\n if (pos >= 0) {\n handlers.splice(pos, 1);\n }\n }\n return this;\n }\n raiseEvent(eventName, msg) {\n let handlers = this.listeners[eventName];\n if (handlers) {\n handlers.forEach(x => {\n try {\n x(msg);\n } catch (e) {\n this.onError(e);\n }\n });\n }\n }\n getConnectionInfo() {\n if (this.connectionInfo == null) throw \"Not Connected\";\n return this.connectionInfo;\n }\n getSubscriptionId() {\n return this.getConnectionInfo().id;\n }\n updateSubscriber(request) {\n if (request.id == null) request.id = this.getSubscriptionId();\n return this.serviceClient.post(request).then(x => {\n this.update(request.subscribeChannels, request.unsubscribeChannels);\n }).catch(this.onError);\n }\n subscribeToChannels(...channels) {\n let request = new UpdateEventSubscriber();\n request.id = this.getSubscriptionId();\n request.subscribeChannels = channels;\n return this.serviceClient.post(request).then(x => {\n this.update(channels, null);\n }).catch(this.onError);\n }\n unsubscribeFromChannels(...channels) {\n let request = new UpdateEventSubscriber();\n request.id = this.getSubscriptionId();\n request.unsubscribeChannels = channels;\n return this.serviceClient.post(request).then(x => {\n this.update(null, channels);\n }).catch(this.onError);\n }\n getChannelSubscribers() {\n let request = new GetEventSubscribers();\n request.channels = this.channels;\n return this.serviceClient.get(request).then(r => r.map(x => this.toServerEventUser(x))).catch(e => {\n this.onError(e);\n return [];\n });\n }\n toServerEventUser(map) {\n let channels = map[\"channels\"];\n let to = new ServerEventUser();\n to.userId = map[\"userId\"];\n to.displayName = map[\"displayName\"];\n to.profileUrl = map[\"profileUrl\"];\n to.channels = channels ? channels.split(',') : null;\n for (let k in map) {\n if (k == \"userId\" || k == \"displayName\" || k == \"profileUrl\" || k == \"channels\") continue;\n if (to.meta == null) to.meta = {};\n to.meta[k] = map[k];\n }\n return to;\n }\n}\nexports.ServerEventsClient = ServerEventsClient;\nServerEventsClient.UnknownChannel = \"*\";\nclass ServerEventReceiver {\n noSuchMethod(selector, message) {}\n}\nexports.ServerEventReceiver = ServerEventReceiver;\nclass UpdateEventSubscriber {\n createResponse() {\n return new UpdateEventSubscriberResponse();\n }\n getTypeName() {\n return \"UpdateEventSubscriber\";\n }\n}\nexports.UpdateEventSubscriber = UpdateEventSubscriber;\nclass UpdateEventSubscriberResponse {}\nexports.UpdateEventSubscriberResponse = UpdateEventSubscriberResponse;\nclass GetEventSubscribers {\n createResponse() {\n return [];\n }\n getTypeName() {\n return \"GetEventSubscribers\";\n }\n}\nexports.GetEventSubscribers = GetEventSubscribers;\nclass ServerEventUser {}\nexports.ServerEventUser = ServerEventUser;\nclass HttpMethods {}\nexports.HttpMethods = HttpMethods;\nHttpMethods.Get = \"GET\";\nHttpMethods.Post = \"POST\";\nHttpMethods.Put = \"PUT\";\nHttpMethods.Delete = \"DELETE\";\nHttpMethods.Patch = \"PATCH\";\nHttpMethods.Head = \"HEAD\";\nHttpMethods.Options = \"OPTIONS\";\nHttpMethods.hasRequestBody = method => !(method === \"GET\" || method === \"DELETE\" || method === \"HEAD\" || method === \"OPTIONS\");\nclass GetAccessToken {\n constructor(init) {\n Object.assign(this, init);\n }\n createResponse() {\n return new GetAccessTokenResponse();\n }\n getTypeName() {\n return 'GetAccessToken';\n }\n getMethod() {\n return 'POST';\n }\n}\nclass GetAccessTokenResponse {}\nexports.GetAccessTokenResponse = GetAccessTokenResponse;\nclass JsonServiceClient {\n constructor(baseUrl = \"/\") {\n this.baseUrl = baseUrl;\n this.replyBaseUrl = combinePaths(baseUrl, \"json\", \"reply\") + \"/\";\n this.oneWayBaseUrl = combinePaths(baseUrl, \"json\", \"oneway\") + \"/\";\n this.mode = \"cors\";\n this.credentials = \"include\";\n this.headers = new Headers();\n this.headers.set(\"Content-Type\", \"application/json\");\n this.manageCookies = typeof document == \"undefined\"; //because node-fetch doesn't\n this.cookies = {};\n this.enableAutoRefreshToken = true;\n }\n setCredentials(userName, password) {\n this.userName = userName;\n this.password = password;\n }\n useBasePath(path) {\n this.basePath = path;\n return this;\n }\n set basePath(path) {\n if (!path) {\n this.replyBaseUrl = combinePaths(this.baseUrl, \"json\", \"reply\") + \"/\";\n this.oneWayBaseUrl = combinePaths(this.baseUrl, \"json\", \"oneway\") + \"/\";\n } else {\n if (path[0] != '/') {\n path = '/' + path;\n }\n this.replyBaseUrl = combinePaths(this.baseUrl, path) + \"/\";\n this.oneWayBaseUrl = combinePaths(this.baseUrl, path) + \"/\";\n }\n }\n apply(f) {\n f(this);\n return this;\n }\n get(request, args) {\n return typeof request != \"string\" ? this.fetch(HttpMethods.Get, request, args) : this.fetch(HttpMethods.Get, null, args, this.toAbsoluteUrl(request));\n }\n delete(request, args) {\n return typeof request != \"string\" ? this.fetch(HttpMethods.Delete, request, args) : this.fetch(HttpMethods.Delete, null, args, this.toAbsoluteUrl(request));\n }\n post(request, args) {\n return this.fetch(HttpMethods.Post, request, args);\n }\n postToUrl(url, request, args) {\n return this.fetch(HttpMethods.Post, request, args, this.toAbsoluteUrl(url));\n }\n postBody(request, body, args) {\n return this.fetchBody(HttpMethods.Post, request, body, args);\n }\n put(request, args) {\n return this.fetch(HttpMethods.Put, request, args);\n }\n putToUrl(url, request, args) {\n return this.fetch(HttpMethods.Put, request, args, this.toAbsoluteUrl(url));\n }\n putBody(request, body, args) {\n return this.fetchBody(HttpMethods.Put, request, body, args);\n }\n patch(request, args) {\n return this.fetch(HttpMethods.Patch, request, args);\n }\n patchToUrl(url, request, args) {\n return this.fetch(HttpMethods.Patch, request, args, this.toAbsoluteUrl(url));\n }\n patchBody(request, body, args) {\n return this.fetchBody(HttpMethods.Patch, request, body, args);\n }\n publish(request, args) {\n return this.sendOneWay(request, args);\n }\n sendOneWay(request, args) {\n const url = combinePaths(this.oneWayBaseUrl, nameOf(request));\n return this.fetch(HttpMethods.Post, request, null, url);\n }\n sendAll(requests) {\n if (requests.length == 0) return Promise.resolve([]);\n const url = combinePaths(this.replyBaseUrl, nameOf(requests[0]) + \"[]\");\n return this.fetch(HttpMethods.Post, requests, null, url);\n }\n sendAllOneWay(requests) {\n if (requests.length == 0) return Promise.resolve(void 0);\n const url = combinePaths(this.oneWayBaseUrl, nameOf(requests[0]) + \"[]\");\n return this.fetch(HttpMethods.Post, requests, null, url).then(r => void 0);\n }\n createUrlFromDto(method, request) {\n let url = combinePaths(this.replyBaseUrl, nameOf(request));\n const hasRequestBody = HttpMethods.hasRequestBody(method);\n if (!hasRequestBody) url = appendQueryString(url, request);\n return url;\n }\n toAbsoluteUrl(relativeOrAbsoluteUrl) {\n return relativeOrAbsoluteUrl.startsWith(\"http://\") || relativeOrAbsoluteUrl.startsWith(\"https://\") ? relativeOrAbsoluteUrl : combinePaths(this.baseUrl, relativeOrAbsoluteUrl);\n }\n deleteCookie(name) {\n if (this.manageCookies) {\n delete this.cookies[name];\n } else {\n if (document) {\n document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';\n }\n }\n }\n createRequest({\n method,\n request,\n url,\n args,\n body\n }) {\n if (!url) url = this.createUrlFromDto(method, request);\n if (args) url = appendQueryString(url, args);\n if (this.bearerToken != null) {\n this.headers.set(\"Authorization\", \"Bearer \" + this.bearerToken);\n } else if (this.userName != null) {\n this.headers.set('Authorization', 'Basic ' + JsonServiceClient.toBase64(`${this.userName}:${this.password}`));\n }\n if (this.manageCookies) {\n let cookies = Object.keys(this.cookies).map(x => {\n let c = this.cookies[x];\n return c.expires && c.expires < new Date() ? null : `${c.name}=${encodeURIComponent(c.value)}`;\n }).filter(x => !!x);\n if (cookies.length > 0) this.headers.set(\"Cookie\", cookies.join(\"; \"));else this.headers.delete(\"Cookie\");\n }\n let headers = new Headers(this.headers);\n let hasRequestBody = HttpMethods.hasRequestBody(method);\n let reqInit = {\n url,\n method: method,\n mode: this.mode,\n credentials: this.credentials,\n headers,\n compress: false // https://github.com/bitinn/node-fetch/issues/93#issuecomment-200791658\n };\n if (hasRequestBody) {\n reqInit.body = body || JSON.stringify(request);\n if (isFormData(body)) {\n reqInit.body = sanitizeFormData(body);\n headers.delete('Content-Type'); //set by FormData\n }\n }\n if (this.requestFilter != null) this.requestFilter(reqInit);\n if (JsonServiceClient.globalRequestFilter != null) JsonServiceClient.globalRequestFilter(reqInit);\n return reqInit;\n }\n json(res) {\n if (this.parseJson) return this.parseJson(res);\n return res.json();\n }\n applyResponseFilters(res) {\n if (this.responseFilter != null) this.responseFilter(res);\n if (JsonServiceClient.globalResponseFilter != null) JsonServiceClient.globalResponseFilter(res);\n }\n createResponse(res, request) {\n if (!res.ok) {\n this.applyResponseFilters(res);\n throw res;\n }\n if (this.manageCookies) {\n let setCookies = [];\n res.headers.forEach((v, k) => {\n switch (k.toLowerCase()) {\n case \"set-cookie\":\n let cookies = v.split(',');\n cookies.forEach(c => setCookies.push(c));\n break;\n }\n });\n setCookies.forEach(x => {\n let cookie = parseCookie(x);\n if (cookie) this.cookies[cookie.name] = cookie;\n });\n }\n res.headers.forEach((v, k) => {\n switch (k.toLowerCase()) {\n case \"x-cookies\":\n if (v.split(',').indexOf('ss-reftok') >= 0) this.useTokenCookie = true;\n break;\n }\n });\n this.applyResponseFilters(res);\n let x = request && typeof request != \"string\" && typeof request.createResponse == 'function' ? request.createResponse() : null;\n if (typeof x === 'string') return res.text().then(o => o);\n let contentType = res.headers.get(\"content-type\");\n let isJson = contentType && contentType.indexOf(\"application/json\") !== -1;\n if (isJson) {\n return this.json(res).then(o => o);\n }\n if (typeof Uint8Array != \"undefined\" && x instanceof Uint8Array) {\n if (typeof res.arrayBuffer != 'function') throw new Error(\"This fetch polyfill does not implement 'arrayBuffer'\");\n return res.arrayBuffer().then(o => new Uint8Array(o));\n } else if (typeof Blob == \"function\" && x instanceof Blob) {\n if (typeof res.blob != 'function') throw new Error(\"This fetch polyfill does not implement 'blob'\");\n return res.blob().then(o => o);\n }\n let contentLength = res.headers.get(\"content-length\");\n if (contentLength === \"0\" || contentLength == null && !isJson) {\n return x;\n }\n return this.json(res).then(o => o); //fallback\n }\n handleError(holdRes, res, type = null) {\n if (res instanceof Error) throw this.raiseError(holdRes, res);\n // res.json can only be called once.\n if (res.bodyUsed) throw this.raiseError(res, createErrorResponse(res.status, res.statusText, type));\n let isErrorResponse = typeof res.json == \"undefined\" && res.responseStatus;\n if (isErrorResponse) {\n return new Promise((resolve, reject) => reject(this.raiseError(null, res)));\n }\n return this.json(res).then(o => {\n let errorDto = sanitize(o);\n if (!errorDto.responseStatus) throw createErrorResponse(res.status, res.statusText, type);\n if (type != null) errorDto.type = type;\n throw errorDto;\n }).catch(error => {\n // No responseStatus body, set from `res` Body object\n if (error instanceof Error || typeof window != \"undefined\" && error instanceof window.DOMException /*MS Edge*/) {\n throw this.raiseError(res, createErrorResponse(res.status, res.statusText, type));\n }\n throw this.raiseError(res, error);\n });\n }\n fetch(method, request, args, url) {\n return this.sendRequest({\n method,\n request,\n args,\n url\n });\n }\n fetchBody(method, request, body, args) {\n let url = combinePaths(this.replyBaseUrl, nameOf(request));\n return this.sendRequest({\n method,\n request: body,\n body: typeof body == \"string\" ? body : isFormData(body) ? body : JSON.stringify(body),\n url: appendQueryString(url, request),\n args,\n returns: request\n });\n }\n sendRequest(info) {\n const req = this.createRequest(info);\n const returns = info.returns || info.request;\n let holdRes = null;\n const resendRequest = () => {\n const req = this.createRequest(info);\n if (this.urlFilter) this.urlFilter(req.url);\n return fetch(req.url, req).then(res => this.createResponse(res, returns)).catch(res => this.handleError(holdRes, res));\n };\n if (this.urlFilter) this.urlFilter(req.url);\n return fetch(req.url, req).then(res => {\n holdRes = res;\n const response = this.createResponse(res, returns);\n return response;\n }).catch(res => {\n if (res.status === 401) {\n if (this.enableAutoRefreshToken && (this.refreshToken || this.useTokenCookie || this.cookies['ss-reftok'] != null)) {\n const jwtReq = new GetAccessToken({\n refreshToken: this.refreshToken,\n useTokenCookie: !!this.useTokenCookie\n });\n let url = this.refreshTokenUri || this.createUrlFromDto(HttpMethods.Post, jwtReq);\n if (this.useTokenCookie) {\n this.bearerToken = null;\n this.headers.delete(\"Authorization\");\n }\n let jwtRequest = this.createRequest({\n method: HttpMethods.Post,\n request: jwtReq,\n args: null,\n url\n });\n return fetch(url, jwtRequest).then(r => this.createResponse(r, jwtReq).then(jwtResponse => {\n this.bearerToken = jwtResponse.accessToken || null;\n return resendRequest();\n })).catch(res => {\n if (this.onAuthenticationRequired) {\n return this.onAuthenticationRequired().then(resendRequest).catch(resHandler => {\n return this.handleError(holdRes, resHandler, \"RefreshTokenException\");\n });\n } else {\n return this.handleError(holdRes, res, \"RefreshTokenException\");\n }\n });\n } else {\n if (this.onAuthenticationRequired) {\n return this.onAuthenticationRequired().then(resendRequest);\n }\n }\n }\n return this.handleError(holdRes, res);\n });\n }\n raiseError(res, error) {\n if (this.exceptionFilter != null) {\n this.exceptionFilter(res, error);\n }\n return error;\n }\n // Generic send that uses APIs preferred HTTP Method (requires v5.13+ DTOs)\n send(request, args, url) {\n return this.sendRequest({\n method: getMethod(request),\n request,\n args,\n url\n });\n }\n // Generic send IReturnVoid that uses APIs preferred HTTP Method (requires v5.13+ DTOs)\n sendVoid(request, args, url) {\n return this.sendRequest({\n method: getMethod(request),\n request,\n args,\n url\n });\n }\n api(request, args, method) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = yield this.fetch(getMethod(request, method), request, args);\n return new ApiResult({\n response: result\n });\n } catch (e) {\n return new ApiResult({\n error: getResponseStatus(e)\n });\n }\n });\n }\n apiVoid(request, args, method) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = yield this.fetch(getMethod(request, method), request, args);\n return new ApiResult({\n response: result !== null && result !== void 0 ? result : new EmptyResponse()\n });\n } catch (e) {\n return new ApiResult({\n error: getResponseStatus(e)\n });\n }\n });\n }\n apiForm(request, body, args, method) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = yield this.fetchBody(getMethod(request, method), request, body, args);\n return new ApiResult({\n response: result\n });\n } catch (e) {\n return new ApiResult({\n error: getResponseStatus(e)\n });\n }\n });\n }\n apiFormVoid(request, body, args, method) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const result = yield this.fetchBody(getMethod(request, method), request, body, args);\n return new ApiResult({\n response: result !== null && result !== void 0 ? result : new EmptyResponse()\n });\n } catch (e) {\n return new ApiResult({\n error: getResponseStatus(e)\n });\n }\n });\n }\n}\nexports.JsonServiceClient = JsonServiceClient;\nfunction getMethod(request, method) {\n return (method !== null && method !== void 0 ? method : typeof request.getMethod == \"function\") ? request.getMethod() : HttpMethods.Post;\n}\nexports.getMethod = getMethod;\nfunction getResponseStatus(e) {\n var _a, _b;\n return (_b = (_a = e.responseStatus) !== null && _a !== void 0 ? _a : e.ResponseStatus) !== null && _b !== void 0 ? _b : e.errorCode ? e : e.message ? createErrorStatus(e.message, e.errorCode) : null;\n}\nexports.getResponseStatus = getResponseStatus;\nclass ApiResult {\n constructor(init) {\n Object.assign(this, init);\n }\n get completed() {\n return this.response != null || this.error != null;\n }\n get failed() {\n var _a, _b;\n return ((_a = this.error) === null || _a === void 0 ? void 0 : _a.errorCode) != null || ((_b = this.error) === null || _b === void 0 ? void 0 : _b.message) != null;\n }\n get succeeded() {\n return !this.failed && this.response != null;\n }\n get errorMessage() {\n var _a;\n return (_a = this.error) === null || _a === void 0 ? void 0 : _a.message;\n }\n get errorCode() {\n var _a;\n return (_a = this.error) === null || _a === void 0 ? void 0 : _a.errorCode;\n }\n get errors() {\n var _a, _b;\n return (_b = (_a = this.error) === null || _a === void 0 ? void 0 : _a.errors) !== null && _b !== void 0 ? _b : [];\n }\n get errorSummary() {\n return this.error != null && this.errors.length == 0 ? this.errorMessage : null;\n }\n fieldError(fieldName) {\n var _a;\n let matchField = fieldName.toLowerCase();\n return (_a = this.errors) === null || _a === void 0 ? void 0 : _a.find(x => x.fieldName.toLowerCase() == matchField);\n }\n fieldErrorMessage(fieldName) {\n var _a;\n return (_a = this.fieldError(fieldName)) === null || _a === void 0 ? void 0 : _a.message;\n }\n hasFieldError(fieldName) {\n return this.fieldError(fieldName) != null;\n }\n showSummary(exceptFields = []) {\n if (!this.failed) return false;\n return exceptFields.every(x => !this.hasFieldError(x));\n }\n summaryMessage(exceptFields = []) {\n if (this.showSummary(exceptFields)) {\n // Return first field error that's not visible\n let fieldSet = exceptFields.map(x => x.toLowerCase());\n let fieldError = fieldSet.find(x => fieldSet.indexOf(x.toLowerCase()) == -1);\n return fieldError !== null && fieldError !== void 0 ? fieldError : this.errorMessage;\n }\n }\n addFieldError(fieldName, message, errorCode = 'Exception') {\n if (!this.error) this.error = new ResponseStatus();\n const fieldError = this.fieldError(fieldName);\n if (fieldError != null) {\n fieldError.errorCode = errorCode;\n fieldError.message = message;\n } else {\n this.error.errors.push(new ResponseError({\n fieldName,\n errorCode,\n message\n }));\n }\n }\n}\nexports.ApiResult = ApiResult;\nfunction createErrorStatus(message, errorCode = 'Exception') {\n return new ResponseStatus({\n errorCode,\n message\n });\n}\nexports.createErrorStatus = createErrorStatus;\nfunction createFieldError(fieldName, message, errorCode = 'Exception') {\n return new ResponseStatus({\n errors: [new ResponseError({\n fieldName,\n errorCode,\n message\n })]\n });\n}\nexports.createFieldError = createFieldError;\nfunction isFormData(body) {\n return typeof window != \"undefined\" && body instanceof FormData;\n}\nexports.isFormData = isFormData;\nfunction createErrorResponse(errorCode, message, type = null) {\n const error = apply(new ErrorResponse(), e => {\n if (type != null) e.type = type;\n e.responseStatus = apply(new ResponseStatus(), status => {\n status.errorCode = errorCode && errorCode.toString();\n status.message = message;\n });\n });\n return error;\n}\nfunction createError(errorCode, message, fieldName) {\n return new ErrorResponse({\n responseStatus: new ResponseStatus({\n errorCode,\n message,\n errors: fieldName ? [new ResponseError({\n errorCode,\n message,\n fieldName\n })] : undefined\n })\n });\n}\nexports.createError = createError;\nfunction toCamelCase(s) {\n return !s ? s : s.charAt(0).toLowerCase() + s.substring(1);\n}\nexports.toCamelCase = toCamelCase;\nfunction toPascalCase(s) {\n return !s ? s : s.charAt(0).toUpperCase() + s.substring(1);\n}\nexports.toPascalCase = toPascalCase;\nfunction toKebabCase(s) {\n return (s || '').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\nexports.toKebabCase = toKebabCase;\nfunction map(o, f) {\n return o == null ? null : f(o);\n}\nexports.map = map;\nfunction sanitize(status) {\n if (status.responseStatus) return status;\n if (status.errors) return status;\n let to = {};\n for (let k in status) {\n if (status.hasOwnProperty(k)) {\n if (status[k] instanceof Object) to[toCamelCase(k)] = sanitize(status[k]);else to[toCamelCase(k)] = status[k];\n }\n }\n to.errors = [];\n if (status.Errors != null) {\n for (let i = 0, len = status.Errors.length; i < len; i++) {\n let o = status.Errors[i];\n let err = {};\n for (let k in o) err[toCamelCase(k)] = o[k];\n to.errors.push(err);\n }\n }\n return to;\n}\nexports.sanitize = sanitize;\nfunction nameOf(o) {\n if (!o) return \"null\";\n if (typeof o.getTypeName == \"function\") return o.getTypeName();\n let ctor = o && o.constructor;\n if (ctor == null) throw `${o} doesn't have constructor`;\n if (ctor.name) return ctor.name;\n let str = ctor.toString();\n return str.substring(9, str.indexOf(\"(\")); //\"function \".length == 9\n}\nexports.nameOf = nameOf;\n/* utils */\nfunction log(o, prefix = \"LOG\") {\n console.log(prefix, o);\n return o;\n}\nfunction css(selector, name, value) {\n const els = typeof selector == \"string\" ? document.querySelectorAll(selector) : selector;\n for (let i = 0; i < els.length; i++) {\n const el = els[i];\n if (el != null && el.style != null) {\n el.style[name] = value;\n }\n }\n}\nexports.css = css;\nfunction splitOnFirst(s, c) {\n if (!s) return [s];\n let pos = s.indexOf(c);\n return pos >= 0 ? [s.substring(0, pos), s.substring(pos + 1)] : [s];\n}\nexports.splitOnFirst = splitOnFirst;\nfunction splitOnLast(s, c) {\n if (!s) return [s];\n let pos = s.lastIndexOf(c);\n return pos >= 0 ? [s.substring(0, pos), s.substring(pos + 1)] : [s];\n}\nexports.splitOnLast = splitOnLast;\nfunction leftPart(s, needle) {\n if (s == null) return null;\n let pos = s.indexOf(needle);\n return pos == -1 ? s : s.substring(0, pos);\n}\nexports.leftPart = leftPart;\nfunction rightPart(s, needle) {\n if (s == null) return null;\n let pos = s.indexOf(needle);\n return pos == -1 ? s : s.substring(pos + needle.length);\n}\nexports.rightPart = rightPart;\nfunction lastLeftPart(s, needle) {\n if (s == null) return null;\n let pos = s.lastIndexOf(needle);\n return pos == -1 ? s : s.substring(0, pos);\n}\nexports.lastLeftPart = lastLeftPart;\nfunction lastRightPart(s, needle) {\n if (s == null) return null;\n let pos = s.lastIndexOf(needle);\n return pos == -1 ? s : s.substring(pos + needle.length);\n}\nexports.lastRightPart = lastRightPart;\nfunction chop(str, len = 1) {\n len = Math.abs(len);\n return str ? len < str.length ? str.substring(0, str.length - len) : '' : str;\n}\nexports.chop = chop;\nfunction onlyProps(obj, keys) {\n let to = {};\n keys.forEach(key => to[key] = obj[key]);\n return to;\n}\nexports.onlyProps = onlyProps;\nfunction splitCase(t) {\n return typeof t != 'string' ? t : t.replace(/([A-Z]|[0-9]+)/g, ' $1').replace(/_/g, ' ').trim();\n}\nfunction humanize(s) {\n return !s || s.indexOf(' ') >= 0 ? s : splitCase(toPascalCase(s));\n}\nexports.humanize = humanize;\nconst ucFirst = s => s.charAt(0).toUpperCase() + s.substring(1);\nexports.ucFirst = ucFirst;\nconst isUpper = c => c >= 'A' && c <= 'Z';\nexports.isUpper = isUpper;\nconst isLower = c => c >= 'a' && c <= 'z';\nexports.isLower = isLower;\nconst isDigit = c => c >= '0' && c <= '9';\nexports.isDigit = isDigit;\nconst upperOrDigit = c => (0, exports.isUpper)(c) || (0, exports.isDigit)(c);\nfunction splitTitleCase(s) {\n let to = [];\n if (typeof s != 'string') return to;\n let lastSplit = 0;\n for (let i = 0; i < s.length; i++) {\n let c = s[i];\n let prev = i > 0 ? s[i - 1] : null;\n let next = i + 1 < s.length ? s[i + 1] : null;\n if (upperOrDigit(c) && (!upperOrDigit(prev) || !upperOrDigit(next))) {\n to.push(s.substring(lastSplit, i));\n lastSplit = i;\n }\n }\n to.push(s.substring(lastSplit, s.length));\n return to.filter(x => !!x);\n}\nexports.splitTitleCase = splitTitleCase;\nconst humanify = s => !s || s.indexOf(' ') >= 0 ? s : (0, exports.ucFirst)(splitTitleCase(s).join(' '));\nexports.humanify = humanify;\nfunction queryString(url) {\n if (!url || url.indexOf('?') === -1) return {};\n let pairs = splitOnFirst(url, '?')[1].split('&');\n let map = {};\n for (let i = 0; i < pairs.length; ++i) {\n let p = pairs[i].split('=');\n map[p[0]] = p.length > 1 ? decodeURIComponent(p[1].replace(/\\+/g, ' ')) : null;\n }\n return map;\n}\nexports.queryString = queryString;\nfunction combinePaths(...paths) {\n let parts = [],\n i,\n l;\n for (i = 0, l = paths.length; i < l; i++) {\n let arg = paths[i];\n parts = arg.indexOf(\"://\") === -1 ? parts.concat(arg.split(\"/\")) : parts.concat(arg.lastIndexOf(\"/\") === arg.length - 1 ? arg.substring(0, arg.length - 1) : arg);\n }\n let combinedPaths = [];\n for (i = 0, l = parts.length; i < l; i++) {\n let part = parts[i];\n if (!part || part === \".\") continue;\n if (part === \"..\") combinedPaths.pop();else combinedPaths.push(part);\n }\n if (parts[0] === \"\") combinedPaths.unshift(\"\");\n return combinedPaths.join(\"/\") || (combinedPaths.length ? \"/\" : \".\");\n}\nexports.combinePaths = combinePaths;\nfunction createPath(route, args) {\n let argKeys = {};\n for (let k in args) {\n argKeys[k.toLowerCase()] = k;\n }\n let parts = route.split(\"/\");\n let url = \"\";\n for (let i = 0; i < parts.length; i++) {\n let p = parts[i];\n if (p == null) p = \"\";\n if (p[0] === \"{\" && p[p.length - 1] === \"}\") {\n const key = argKeys[p.substring(1, p.length - 1).toLowerCase()];\n if (key) {\n p = args[key];\n delete args[key];\n }\n }\n if (url.length > 0) url += \"/\";\n url += p;\n }\n return url;\n}\nexports.createPath = createPath;\nfunction createUrl(route, args) {\n let url = createPath(route, args);\n return appendQueryString(url, args);\n}\nexports.createUrl = createUrl;\nfunction appendQueryString(url, args) {\n for (let k in args) {\n if (args.hasOwnProperty(k)) {\n let val = args[k];\n if (typeof val == 'undefined') continue;\n url += url.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n url += k + \"=\" + qsValue(val);\n }\n }\n return url;\n}\nexports.appendQueryString = appendQueryString;\nfunction qsValue(arg) {\n if (arg == null) return \"\";\n if (typeof Uint8Array != \"undefined\" && arg instanceof Uint8Array) return bytesToBase64(arg);\n return encodeURIComponent(arg) || \"\";\n}\n//from: https://github.com/madmurphy/stringview.js/blob/master/stringview.js\nfunction bytesToBase64(aBytes) {\n let eqLen = (3 - aBytes.length % 3) % 3,\n sB64Enc = \"\";\n for (let nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {\n nMod3 = nIdx % 3;\n nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);\n if (nMod3 === 2 || aBytes.length - nIdx === 1) {\n sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));\n nUint24 = 0;\n }\n }\n return eqLen === 0 ? sB64Enc : sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? \"=\" : \"==\");\n}\nexports.bytesToBase64 = bytesToBase64;\nfunction uint6ToB64(nUint6) {\n return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65;\n}\nfunction _btoa(base64) {\n return typeof btoa == 'function' ? btoa(base64) : Buffer.from(base64).toString('base64');\n}\nfunction _atob(base64) {\n return typeof atob == 'function' ? atob(base64) : Buffer.from(base64, 'base64').toString();\n}\n//from: http://stackoverflow.com/a/30106551/85785\nJsonServiceClient.toBase64 = str => _btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode(new Number('0x' + p1).valueOf())));\nfunction stripQuotes(s) {\n return s && s[0] == '\"' && s[s.length] == '\"' ? s.slice(1, -1) : s;\n}\nexports.stripQuotes = stripQuotes;\nfunction tryDecode(s) {\n try {\n return decodeURIComponent(s);\n } catch (e) {\n return s;\n }\n}\nexports.tryDecode = tryDecode;\nfunction parseCookie(setCookie) {\n if (!setCookie) return null;\n let to = null;\n let pairs = setCookie.split(/; */);\n for (let i = 0; i < pairs.length; i++) {\n let pair = pairs[i];\n let parts = splitOnFirst(pair, '=');\n let name = parts[0].trim();\n let value = parts.length > 1 ? tryDecode(stripQuotes(parts[1].trim())) : null;\n if (i == 0) {\n to = {\n name,\n value,\n path: \"/\"\n };\n } else {\n let lower = name.toLowerCase();\n if (lower == \"httponly\") {\n to.httpOnly = true;\n } else if (lower == \"secure\") {\n to.secure = true;\n } else if (lower == \"expires\") {\n to.expires = new Date(value);\n // MS Edge returns Invalid Date when using '-' in \"12-Mar-2037\"\n if (to.expires.toString() === \"Invalid Date\") {\n to.expires = new Date(value.replace(/-/g, \" \"));\n }\n } else {\n to[name] = value;\n }\n }\n }\n return to;\n}\nexports.parseCookie = parseCookie;\nfunction normalizeKey(key) {\n return key.toLowerCase().replace(/_/g, '');\n}\nexports.normalizeKey = normalizeKey;\nfunction isArray(o) {\n return Object.prototype.toString.call(o) === '[object Array]';\n}\nfunction normalize(dto, deep) {\n if (isArray(dto)) {\n if (!deep) return dto;\n const to = [];\n for (let i = 0; i < dto.length; i++) {\n to[i] = normalize(dto[i], deep);\n }\n return to;\n }\n if (typeof dto != \"object\") return dto;\n let o = {};\n for (let k in dto) {\n o[normalizeKey(k)] = deep ? normalize(dto[k], deep) : dto[k];\n }\n return o;\n}\nexports.normalize = normalize;\nfunction getField(o, name) {\n return o == null || name == null ? null : o[name] || o[Object.keys(o).filter(k => normalizeKey(k) === normalizeKey(name))[0] || ''];\n}\nexports.getField = getField;\nfunction parseResponseStatus(json, defaultMsg = null) {\n try {\n let err = JSON.parse(json);\n return sanitize(err.ResponseStatus || err.responseStatus);\n } catch (e) {\n return {\n message: defaultMsg || e.message || e,\n __error: {\n error: e,\n json: json\n }\n };\n }\n}\nexports.parseResponseStatus = parseResponseStatus;\nfunction toFormData(o) {\n if (typeof window == \"undefined\") return;\n let formData = new FormData();\n for (let name in o) {\n formData.append(name, o[name]);\n }\n return formData;\n}\nexports.toFormData = toFormData;\nfunction toObject(keys) {\n const to = {};\n if (!keys) return to;\n if (typeof keys != \"object\") throw new Error(\"keys must be an Array of object keys\");\n const arr = Array.prototype.slice.call(keys);\n arr.forEach(key => {\n if (this[key]) {\n to[key] = this[key];\n }\n });\n return to;\n}\nexports.toObject = toObject;\nfunction errorResponseSummary() {\n const responseStatus = this.responseStatus || this.ResponseStatus;\n if (responseStatus == null) return undefined;\n const status = responseStatus.ErrorCode ? sanitize(responseStatus) : responseStatus;\n return !status.errors || status.errors.length == 0 ? status.message || status.errorCode : undefined;\n}\nexports.errorResponseSummary = errorResponseSummary;\nfunction errorResponseExcept(fieldNames) {\n const responseStatus = this.responseStatus || this.ResponseStatus;\n if (responseStatus == null) return undefined;\n const status = responseStatus.ErrorCode ? sanitize(responseStatus) : responseStatus;\n const names = toVarNames(fieldNames);\n if (names && !(status.errors == null || status.errors.length == 0)) {\n const lowerFieldsNames = names.map(x => (x || '').toLowerCase());\n for (let field of status.errors) {\n if (lowerFieldsNames.indexOf((field.fieldName || '').toLowerCase()) !== -1) {\n return undefined;\n }\n }\n for (let field of status.errors) {\n if (lowerFieldsNames.indexOf((field.fieldName || '').toLowerCase()) === -1) {\n return field.message || field.errorCode;\n }\n }\n }\n return status.message || status.errorCode || undefined;\n}\nexports.errorResponseExcept = errorResponseExcept;\nfunction errorResponse(fieldName) {\n if (fieldName == null) return errorResponseSummary.call(this);\n const responseStatus = this.responseStatus || this.ResponseStatus;\n if (responseStatus == null) return undefined;\n const status = responseStatus.ErrorCode ? sanitize(responseStatus) : responseStatus;\n if (status.errors == null || status.errors.length == 0) return undefined;\n const field = status.errors.find(x => (x.fieldName || '').toLowerCase() == fieldName.toLowerCase());\n return field ? field.message || field.errorCode : undefined;\n}\nexports.errorResponse = errorResponse;\nfunction isDate(d) {\n return d && Object.prototype.toString.call(d) === \"[object Date]\" && !isNaN(d);\n}\nexports.isDate = isDate;\nfunction toDate(s) {\n return !s ? null : isDate(s) ? s : s[0] == '/' ? new Date(parseFloat(/Date\\(([^)]+)\\)/.exec(s)[1])) : new Date(s);\n}\nexports.toDate = toDate;\nfunction toDateFmt(s) {\n return dateFmt(toDate(s));\n}\nexports.toDateFmt = toDateFmt;\nfunction padInt(n) {\n return n < 10 ? '0' + n : n;\n}\nexports.padInt = padInt;\nfunction dateFmt(d = new Date()) {\n return d.getFullYear() + '/' + padInt(d.getMonth() + 1) + '/' + padInt(d.getDate());\n}\nexports.dateFmt = dateFmt;\nfunction dateFmtHM(d = new Date()) {\n return d.getFullYear() + '/' + padInt(d.getMonth() + 1) + '/' + padInt(d.getDate()) + ' ' + padInt(d.getHours()) + \":\" + padInt(d.getMinutes());\n}\nexports.dateFmtHM = dateFmtHM;\nfunction timeFmt12(d = new Date()) {\n return padInt((d.getHours() + 24) % 12 || 12) + \":\" + padInt(d.getMinutes()) + \":\" + padInt(d.getSeconds()) + \" \" + (d.getHours() > 12 ? \"PM\" : \"AM\");\n}\nexports.timeFmt12 = timeFmt12;\nfunction toLocalISOString(d = new Date()) {\n return `${d.getFullYear()}-${padInt(d.getMonth() + 1)}-${padInt(d.getDate())}T${padInt(d.getHours())}:${padInt(d.getMinutes())}:${padInt(d.getSeconds())}`;\n}\nexports.toLocalISOString = toLocalISOString;\nfunction bsAlert(msg) {\n return '
' + msg + '
';\n}\nfunction attr(e, name) {\n return e.getAttribute(name);\n}\nfunction sattr(e, name, value) {\n return e.setAttribute(name, value);\n}\nfunction rattr(e, name) {\n return e.removeAttribute(name);\n}\nfunction createElement(tagName, options, attrs) {\n const keyAliases = {\n className: 'class',\n htmlFor: 'for'\n };\n const el = document.createElement(tagName);\n if (attrs) {\n for (const key in attrs) {\n sattr(el, keyAliases[key] || key, attrs[key]);\n }\n }\n if (options && options.insertAfter) {\n options.insertAfter.parentNode.insertBefore(el, options.insertAfter.nextSibling);\n }\n return el;\n}\nexports.createElement = createElement;\nfunction showInvalidInputs() {\n let errorMsg = attr(this, 'data-invalid');\n if (errorMsg) {\n //[data-invalid] can either be on input control or .form-check container containing group of radio/checkbox\n const isCheck = this.type === \"checkbox\" || this.type === \"radio\" || hasClass(this, 'form-check');\n const elFormCheck = isCheck ? parent(this, 'form-check') : null;\n if (!isCheck) addClass(this, 'is-invalid');else addClass(elFormCheck || this.parentElement, 'is-invalid form-control');\n const elNext = this.nextElementSibling;\n const elLast = elNext && (attr(elNext, 'for') === this.id || elNext.tagName === \"SMALL\") ? isCheck ? elFormCheck || elNext.parentElement : elNext : this;\n const elError = elLast != null && elLast.nextElementSibling && hasClass(elLast.nextElementSibling, 'invalid-feedback') ? elLast.nextElementSibling : createElement(\"div\", {\n insertAfter: elLast\n }, {\n className: 'invalid-feedback'\n });\n elError.innerHTML = errorMsg;\n }\n}\nfunction parent(el, cls) {\n while (el != null && !hasClass(el, cls)) el = el.parentElement;\n return el;\n}\nfunction hasClass(el, cls) {\n return !el ? false : el.classList ? el.classList.contains(cls) : (\" \" + el.className + \" \").replace(/[\\n\\t\\r]/g, \" \").indexOf(\" \" + cls + \" \") > -1;\n}\nfunction addClass(el, cls) {\n return !el ? null : el.classList ? el.classList.add(...cls.split(' ')) : !hasClass(el, cls) ? el.className = (el.className + \" \" + cls).trim() : null;\n}\nfunction remClass(el, cls) {\n return !el ? null : el.classList ? el.classList.remove(cls) : hasClass(el, cls) ? el.className = el.className.replace(/(\\s|^)someclass(\\s|$)/, ' ') : null;\n}\nfunction $1(sel, el) {\n return typeof sel === \"string\" ? (el || document).querySelector(sel) : sel || null;\n}\nexports.$1 = $1;\nfunction $$(sel, el) {\n return typeof sel === \"string\" ? Array.prototype.slice.call((el || document).querySelectorAll(sel)) : Array.isArray(sel) ? sel : [sel];\n}\nexports.$$ = $$;\nfunction on(sel, handlers) {\n $$(sel).forEach(e => {\n Object.keys(handlers).forEach(function (evt) {\n let fn = handlers[evt];\n if (typeof evt === 'string' && typeof fn === 'function') {\n e.addEventListener(evt, fn.bind(e));\n }\n });\n });\n}\nexports.on = on;\nfunction delaySet(f, opt) {\n let duration = opt && opt.duration || 300;\n let timeout = setTimeout(() => f(true), duration);\n return () => {\n clearTimeout(timeout);\n f(false);\n };\n}\nexports.delaySet = delaySet;\n// init generic behavior to bootstrap elements\nfunction bootstrap(el) {\n const els = (el || document).querySelectorAll('[data-invalid]');\n for (let i = 0; i < els.length; i++) {\n showInvalidInputs.call(els[i]);\n }\n}\nexports.bootstrap = bootstrap;\nif (typeof window != \"undefined\" && window.Element !== undefined) {\n // polyfill IE9+\n if (!Element.prototype.matches) {\n Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;\n }\n if (!Element.prototype.closest) {\n Element.prototype.closest = function (s) {\n let el = this;\n do {\n if (el.matches(s)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n return null;\n };\n }\n}\nfunction handleEvent(handlers, el = document, type) {\n el.addEventListener(type, function (evt) {\n const evtData = `data-${type}`;\n let el = evt.target;\n let x = attr(el, evtData);\n if (!x) {\n let elParent = el.closest(`[${evtData}]`);\n if (elParent) {\n x = attr(elParent, evtData);\n el = elParent;\n }\n }\n if (!x) return;\n let pos = x.indexOf(':');\n if (pos >= 0) {\n const cmd = x.substring(0, pos);\n const data = x.substring(pos + 1);\n const fn = handlers[cmd];\n if (fn) {\n fn.apply(el, data.split(','));\n }\n } else {\n const fn = handlers[x];\n if (fn) {\n fn.apply(el, [].slice.call(arguments));\n }\n }\n });\n}\nfunction bindHandlers(handlers, el = document, opt = null) {\n if (opt && opt.events) {\n opt.events.forEach(evt => handleEvent(handlers, el, evt));\n } else {\n ['click', 'dblclick', 'change', 'focus', 'blur', 'focusin', 'focusout', 'select', 'keydown', 'keypress', 'keyup', 'hover', 'toggle', 'input'].forEach(evt => {\n if (el.querySelector(`[data-${evt}]`)) {\n handleEvent(handlers, el, evt);\n }\n });\n }\n}\nexports.bindHandlers = bindHandlers;\nfunction bootstrapForm(form, options) {\n if (!form) return;\n if (options.model) populateForm(form, options.model);\n form.onsubmit = function (evt) {\n evt.preventDefault();\n options.type = \"bootstrap-v4\";\n return ajaxSubmit(form, options);\n };\n}\nexports.bootstrapForm = bootstrapForm;\nfunction applyErrors(f, status, opt) {\n const validation = {\n overrideMessages: false,\n messages: {\n NotEmpty: \"Required\",\n NotNull: \"Required\",\n Email: \"Invalid email\",\n AlreadyExists: \"Already exists\"\n },\n errorFilter: function (errorMsg, errorCode, type) {\n return this.overrideMessages ? this.messages[errorCode] || errorMsg || splitCase(errorCode) : errorMsg || splitCase(errorCode);\n }\n };\n clearErrors(f);\n if (!status) return;\n status = sanitize(status);\n addClass(f, \"has-errors\");\n const bs4 = opt && opt.type === \"bootstrap-v4\";\n const v = Object.assign(Object.assign({}, validation), opt);\n if (opt.messages) {\n v.overrideMessages = true;\n }\n const filter = v.errorFilter.bind(v);\n const errors = status.errors;\n let $ = f.querySelectorAll.bind(f);\n if (errors && errors.length) {\n let fieldMap = {},\n fieldLabelMap = {};\n $(\"input,textarea,select,button\").forEach(x => {\n const el = x;\n const prev = el.previousElementSibling;\n const next = el.nextElementSibling;\n const isCheck = el.type === \"radio\" || el.type === \"checkbox\";\n const fieldId = (!isCheck ? el.id : null) || attr(el, \"name\");\n if (!fieldId) return;\n const key = fieldId.toLowerCase();\n fieldMap[key] = el;\n if (!bs4) {\n if (hasClass(prev, \"help-inline\") || hasClass(prev, \"help-block\")) {\n fieldLabelMap[key] = prev;\n } else if (hasClass(next, \"help-inline\") || hasClass(next, \"help-block\")) {\n fieldLabelMap[key] = next;\n }\n }\n });\n $(\".help-inline[data-for],.help-block[data-for]\").forEach(el => {\n const key = attr(el, \"data-for\").toLowerCase();\n fieldLabelMap[key] = el;\n });\n for (let error of errors) {\n const key = (error.fieldName || \"\").toLowerCase();\n const field = fieldMap[key];\n if (field) {\n if (!bs4) {\n addClass(field, \"error\");\n addClass(field.parentElement, \"has-error\");\n } else {\n const type = attr(field, 'type'),\n isCheck = type === \"radio\" || type === \"checkbox\";\n if (!isCheck) addClass(field, \"is-invalid\");\n sattr(field, \"data-invalid\", filter(error.message, error.errorCode, \"field\"));\n }\n }\n const lblErr = fieldLabelMap[key];\n if (!lblErr) continue;\n addClass(lblErr, \"error\");\n lblErr.innerHTML = filter(error.message, error.errorCode, \"field\");\n lblErr.style.display = 'block';\n }\n $(\"[data-validation-summary]\").forEach(el => {\n const fields = attr(el, 'data-validation-summary').split(',');\n const summaryMsg = errorResponseExcept.call(status, fields);\n if (summaryMsg) el.innerHTML = bsAlert(summaryMsg);\n });\n } else {\n const htmlSummary = filter(status.message || splitCase(status.errorCode), status.errorCode, \"summary\");\n if (!bs4) {\n $(\".error-summary\").forEach(el => {\n el.innerHTML = htmlSummary(el).style.display = 'block';\n });\n } else {\n $('[data-validation-summary]').forEach(el => el.innerHTML = htmlSummary[0] === \"<\" ? htmlSummary : bsAlert(htmlSummary));\n }\n }\n return f;\n}\nfunction clearErrors(f) {\n remClass(f, 'has-errors');\n let $ = f.querySelectorAll.bind(f);\n $('.error-summary').forEach(el => {\n el.innerHTML = \"\";\n el.style.display = \"none\";\n });\n $('[data-validation-summary]').forEach(el => {\n el.innerHTML = \"\";\n });\n $('.error').forEach(el => remClass(el, 'error'));\n $('.form-check.is-invalid [data-invalid]').forEach(el => {\n rattr(el, 'data-invalid');\n });\n $('.form-check.is-invalid').forEach(el => remClass(el, 'form-control'));\n $('.is-invalid').forEach(el => {\n remClass(el, 'is-invalid');\n rattr(el, 'data-invalid');\n });\n $('.is-valid').forEach(el => remClass(el, 'is-valid'));\n}\nvar Types;\n(function (Types) {\n Types[\"MultiPart\"] = \"multipart/form-data\";\n Types[\"UrlEncoded\"] = \"application/x-www-form-urlencoded\";\n Types[\"Json\"] = \"application/json\";\n})(Types || (Types = {}));\nfunction toVarNames(names) {\n return !names ? [] : isArray(names) ? names : names.split(',').map(s => s.trim());\n}\nexports.toVarNames = toVarNames;\nfunction formSubmit(options = {}) {\n const f = this;\n const contentType = attr(f, 'enctype') || Types.UrlEncoded;\n if (contentType == Types.MultiPart && window.FormData === undefined) throw new Error(`FormData Type is needed to send '${Types.MultiPart}' Content Types`);\n let body;\n try {\n body = serializeForm(f, contentType);\n } catch (e) {\n throw new Error(`${e.message || e}`);\n }\n const headers = new Headers();\n headers.set(\"Accept\", Types.Json);\n headers.set(\"Content-Type\", contentType);\n const req = {\n method: attr(f, 'method') || 'POST',\n credentials: 'include',\n mode: 'cors',\n headers,\n body\n };\n if (options.requestFilter) options.requestFilter(req);\n return fetch(new Request(options.url || attr(f, 'action'), req)).catch(e => {\n throw new Error(`Network is unreachable (${e.message || e})`);\n }).then(r => {\n if (options.responseFilter) options.responseFilter(r);\n if (!r.ok) {\n return r.json().catch(e => {\n throw new Error(\"The request failed with \" + (r.statusText || r.status));\n }).then(o => {\n throw Object.assign(new ErrorResponse(), sanitize(o));\n });\n }\n handleHeaderBehaviors(f, r);\n return fromResponse(r);\n });\n}\nexports.formSubmit = formSubmit;\nfunction handleHeaderBehaviors(f, r) {\n const loc = r.headers.get('X-Location');\n if (loc) {\n location.href = loc;\n }\n const evt = r.headers.get('X-Trigger');\n if (evt) {\n const pos = evt.indexOf(':');\n const cmd = pos >= 0 ? evt.substring(0, pos) : evt;\n const data = pos >= 0 ? evt.substring(pos + 1) : null;\n triggerEvent(f, cmd, data ? [data] : []);\n }\n}\nfunction ajaxSubmit(f, options = {}) {\n const type = options.type;\n const bs4 = type === \"bootstrap-v4\";\n clearErrors(f);\n try {\n if (options.validate && options.validate.call(f) === false) return false;\n } catch (e) {\n return false;\n }\n let $ = f.querySelectorAll.bind(f);\n addClass(f, 'loading');\n const disableSel = options.onSubmitDisable == null ? \"[type=submit]\" : options.onSubmitDisable;\n const disable = disableSel != null && disableSel != \"\";\n if (disable) {\n $(disableSel).forEach(el => {\n sattr(el, 'disabled', 'disabled');\n });\n }\n function handleError(errMsg, err = null) {\n if (err) {\n applyErrors(f, err.ResponseStatus || err.responseStatus, Object.assign({}, options));\n } else if (errMsg) {\n addClass(f, \"has-errors\");\n const errorSummary = $(\".error-summary\")[0];\n if (errorSummary) {\n errorSummary.innerHTML = errMsg;\n }\n if (bs4) {\n const elSummary = $('[data-validation-summary]')[0];\n if (elSummary) {\n elSummary.innerHTML = bsAlert(errMsg);\n }\n }\n }\n if (options.error) {\n options.error.call(f, err);\n }\n if (bs4) {\n $('[data-invalid]').forEach(el => showInvalidInputs.call(el));\n }\n }\n const submitFn = options.submit || formSubmit;\n return submitFn.call(f, options).then(obj => {\n if (options.success) options.success.call(f, obj);\n return false;\n }).catch(e => {\n if (e.responseStatus) handleError(null, e);else handleError(`${e.message || e}`, null);\n }).finally(() => {\n remClass(f, 'loading');\n if (disable) {\n $(disableSel).forEach(el => {\n rattr(el, 'disabled');\n });\n }\n if (options.complete) {\n options.complete.call(f);\n }\n });\n}\nexports.ajaxSubmit = ajaxSubmit;\nfunction fromResponse(r) {\n const contentType = r.headers.get(\"content-type\");\n const isJson = contentType && contentType.indexOf(Types.Json) !== -1;\n if (isJson) return r.json();\n let len = r.headers.get(\"content-length\");\n if (len === \"0\" || len == null && !isJson) return null;\n return r.json();\n}\nfunction serializeForm(form, contentType = null) {\n return contentType === Types.MultiPart ? new FormData(form) : contentType == Types.Json ? JSON.stringify(serializeToObject(form)) : serializeToUrlEncoded(form);\n}\nexports.serializeForm = serializeForm;\nfunction formEntries(form, state, fn) {\n let field,\n f = form;\n let len = f.elements.length;\n for (let i = 0; i < len; i++) {\n field = f.elements[i];\n if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {\n if (field.type == 'select-multiple') {\n for (let j = f.elements[i].options.length - 1; j >= 0; j--) {\n if (field.options[j].selected) fn(state, field.name, field.options[j].value);\n }\n } else if (field.type != 'checkbox' && field.type != 'radio' || field.checked) {\n fn(state, field.name, field.value);\n }\n }\n }\n return state;\n}\nfunction serializeToObject(form) {\n return formEntries(form, {}, (to, name, value) => to[name] = value);\n}\nexports.serializeToObject = serializeToObject;\nfunction serializeToUrlEncoded(form) {\n const to = formEntries(form, [], (s, name, value) => typeof value == 'string' ? s.push(encodeURIComponent(name) + \"=\" + encodeURIComponent(value)) : null);\n return to.join('&').replace(/%20/g, '+');\n}\nexports.serializeToUrlEncoded = serializeToUrlEncoded;\nfunction serializeToFormData(form) {\n return formEntries(form, new FormData(), (to, name, value) => to.append(name, value));\n}\nexports.serializeToFormData = serializeToFormData;\nfunction sanitizeFormData(formData) {\n // @ts-ignore\n for (let [key, value] of formData) {\n // Remove 0 length files\n if (typeof value == 'object' && value.size === 0) {\n formData.delete(key);\n }\n }\n return formData;\n}\nexports.sanitizeFormData = sanitizeFormData;\nfunction triggerEvent(el, name, data = null) {\n if (document.createEvent) {\n let evt = document.createEvent(name == 'click' || name.startsWith('mouse') ? 'MouseEvents' : 'HTMLEvents');\n evt.initEvent(name, true, true);\n evt.data = data;\n el.dispatchEvent(evt);\n } else {\n let evt = document.createEventObject();\n el.fireEvent(\"on\" + name, evt);\n }\n}\nexports.triggerEvent = triggerEvent;\nfunction populateForm(form, model) {\n if (!model) return;\n const toggleCase = s => !s ? s : s[0] === s[0].toUpperCase() ? toCamelCase(s) : s[0] === s[0].toLowerCase() ? toPascalCase(s) : s;\n for (let key in model) {\n let val = model[key];\n if (typeof val == 'undefined' || val === null) val = '';\n const el = form.elements.namedItem(key) || form.elements.namedItem(toggleCase(key));\n const input = el;\n if (!el) continue;\n const type = input.type || el[0].type;\n switch (type) {\n case 'radio':\n case 'checkbox':\n const len = el.length;\n for (let i = 0; i < len; i++) {\n el[i].checked = val.indexOf(el[i].value) > -1;\n }\n break;\n case 'select-multiple':\n const values = isArray(val) ? val : [val];\n const select = el;\n for (let i = 0; i < select.options.length; i++) {\n select.options[i].selected = values.indexOf(select.options[i].value) > -1;\n }\n break;\n case 'select':\n case 'select-one':\n input.value = val.toString() || val;\n break;\n case 'date':\n const d = toDate(val);\n if (d) input.value = d.toISOString().split('T')[0];\n break;\n default:\n input.value = val;\n break;\n }\n }\n}\nexports.populateForm = populateForm;\nfunction trimEnd(s, c) {\n let end = s.length;\n while (end > 0 && s[end - 1] === c) {\n --end;\n }\n return end < s.length ? s.substring(0, end) : s;\n}\nexports.trimEnd = trimEnd;\nfunction safeVarName(s) {\n return s.replace(/[\\W]+/g, '');\n}\nexports.safeVarName = safeVarName;\nfunction pick(o, keys) {\n const to = {};\n for (const k in o) {\n if (o.hasOwnProperty(k) && keys.indexOf(k) >= 0) {\n to[k] = o[k];\n }\n }\n return to;\n}\nexports.pick = pick;\nfunction omit(o, keys) {\n const to = {};\n for (const k in o) {\n if (o.hasOwnProperty(k) && keys.indexOf(k) < 0) {\n to[k] = o[k];\n }\n }\n return to;\n}\nexports.omit = omit;\nfunction apply(x, fn) {\n fn(x);\n return x;\n}\nexports.apply = apply;\nfunction each(xs, f, o) {\n return xs.reduce((acc, x) => {\n f(acc, x);\n return acc;\n }, o || {});\n}\nexports.each = each;\nfunction resolve(o, f) {\n let ret = typeof o == 'function' ? o() : o;\n return typeof f == 'function' ? f(ret) : ret;\n}\nexports.resolve = resolve;\nfunction mapGet(o, name) {\n if (!o || !name) return null;\n let ret = o[name];\n if (ret) return ret;\n if (typeof o == 'object') {\n let nameLower = name.toLowerCase();\n let match = Object.keys(o).find(k => k.toLowerCase() === nameLower);\n return match ? o[match] : null;\n }\n return null;\n}\nexports.mapGet = mapGet;\nfunction apiValue(o) {\n if (o == null) return '';\n if (typeof o == 'string') return o.substring(0, 6) === '/Date(' ? toDate(o) : o.trim();\n return o;\n}\nexports.apiValue = apiValue;\nfunction apiValueFmt(o) {\n let ret = apiValue(o);\n return (ret != null ? isDate(ret) ? dateFmt(ret) : ret : null) || '';\n}\nexports.apiValueFmt = apiValueFmt;\n/* NAV */\nfunction activeClassNav(x, activePath) {\n return x.href != null && (x.exact || activePath.length <= 1 ? trimEnd(activePath, '/').toLowerCase() === trimEnd(x.href, '/').toLowerCase() : trimEnd(activePath, '/').toLowerCase().startsWith(trimEnd(x.href, '/').toLowerCase())) ? 'active' : null;\n}\nexports.activeClassNav = activeClassNav;\nfunction activeClass(href, activePath, exact) {\n return href != null && (exact || activePath.length <= 1 ? trimEnd(activePath, '/').toLowerCase() === trimEnd(href, '/').toLowerCase() : trimEnd(activePath, '/').toLowerCase().startsWith(trimEnd(href, '/').toLowerCase())) ? 'active' : null;\n}\nexports.activeClass = activeClass;\nfunction bootstrapColors() {\n return ['primary', 'secondary', 'success', 'info', 'warning', 'danger', 'light', 'dark'];\n}\nexports.BootstrapColors = bootstrapColors();\nfunction btnColorClass(props) {\n for (const color of bootstrapColors()) {\n if (props[color]) {\n return 'btn-' + color;\n }\n if (props['outline-' + color]) {\n return 'btn-outline-' + color;\n }\n }\n return null;\n}\nexports.btnColorClass = btnColorClass;\nfunction bootstrapSizes() {\n return ['xs', 'sm', 'md', 'lg'];\n}\nexports.BootstrapSizes = bootstrapSizes();\nfunction btnSizeClass(props) {\n for (const size of bootstrapSizes()) {\n if (props[size]) {\n return 'btn-' + size;\n }\n }\n return null;\n}\nexports.btnSizeClass = btnSizeClass;\nfunction btnClasses(props) {\n const to = [];\n const color = btnColorClass(props);\n if (color) {\n to.push(color);\n }\n const size = btnSizeClass(props);\n if (size) {\n to.push(size);\n }\n if (props.block) {\n to.push('btn-block');\n }\n return to;\n}\nexports.btnClasses = btnClasses;\nclass NavDefaults {\n static create() {\n return new NavOptions();\n }\n static forNav(options) {\n return options || NavDefaults.create();\n }\n static overrideDefaults(targets, source) {\n if (targets == null) {\n return source;\n }\n targets = Object.assign({}, targets); // clone\n if (targets.navClass === NavDefaults.navClass && source.navClass != null) {\n targets.navClass = source.navClass;\n }\n if (targets.navItemClass === NavDefaults.navItemClass && source.navItemClass != null) {\n targets.navItemClass = source.navItemClass;\n }\n if (targets.navLinkClass === NavDefaults.navLinkClass && source.navLinkClass != null) {\n targets.navLinkClass = source.navLinkClass;\n }\n if (targets.childNavItemClass === NavDefaults.childNavItemClass && source.childNavItemClass != null) {\n targets.childNavItemClass = source.childNavItemClass;\n }\n if (targets.childNavLinkClass === NavDefaults.childNavLinkClass && source.childNavLinkClass != null) {\n targets.childNavLinkClass = source.childNavLinkClass;\n }\n if (targets.childNavMenuClass === NavDefaults.childNavMenuClass && source.childNavMenuClass != null) {\n targets.childNavMenuClass = source.childNavMenuClass;\n }\n if (targets.childNavMenuItemClass === NavDefaults.childNavMenuItemClass && source.childNavMenuItemClass != null) {\n targets.childNavMenuItemClass = source.childNavMenuItemClass;\n }\n return targets;\n }\n static showNav(navItem, attributes) {\n if (attributes == null || attributes.length === 0) {\n return navItem.show == null;\n }\n if (navItem.show != null && attributes.indexOf(navItem.show) < 0) {\n return false;\n }\n if (navItem.hide != null && attributes.indexOf(navItem.hide) >= 0) {\n return false;\n }\n return true;\n }\n}\nexports.NavDefaults = NavDefaults;\nNavDefaults.navClass = 'nav';\nNavDefaults.navItemClass = 'nav-item';\nNavDefaults.navLinkClass = 'nav-link';\nNavDefaults.childNavItemClass = 'nav-item dropdown';\nNavDefaults.childNavLinkClass = 'nav-link dropdown-toggle';\nNavDefaults.childNavMenuClass = 'dropdown-menu';\nNavDefaults.childNavMenuItemClass = 'dropdown-item';\nclass NavLinkDefaults {\n static forNavLink(options) {\n return options || NavDefaults.create();\n }\n}\nexports.NavLinkDefaults = NavLinkDefaults;\nclass NavbarDefaults {\n static create() {\n return new NavOptions({\n navClass: NavbarDefaults.navClass\n });\n }\n static forNavbar(options) {\n return NavDefaults.overrideDefaults(options, NavbarDefaults.create());\n }\n}\nexports.NavbarDefaults = NavbarDefaults;\nNavbarDefaults.navClass = 'navbar-nav';\nclass NavButtonGroupDefaults {\n static create() {\n return new NavOptions({\n navClass: NavButtonGroupDefaults.navClass,\n navItemClass: NavButtonGroupDefaults.navItemClass\n });\n }\n static forNavButtonGroup(options) {\n return NavDefaults.overrideDefaults(options, NavButtonGroupDefaults.create());\n }\n}\nexports.NavButtonGroupDefaults = NavButtonGroupDefaults;\nNavButtonGroupDefaults.navClass = 'btn-group';\nNavButtonGroupDefaults.navItemClass = 'btn btn-primary';\nclass LinkButtonDefaults {\n static create() {\n return new NavOptions({\n navItemClass: LinkButtonDefaults.navItemClass\n });\n }\n static forLinkButton(options) {\n return NavDefaults.overrideDefaults(options || null, LinkButtonDefaults.create());\n }\n}\nexports.LinkButtonDefaults = LinkButtonDefaults;\nLinkButtonDefaults.navItemClass = 'btn';\nclass UserAttributes {\n static fromSession(session) {\n const to = [];\n if (session != null) {\n to.push('auth');\n if (session.roles) {\n to.push(...session.roles.map(x => 'role:' + x));\n }\n if (session.permissions) {\n to.push(...session.permissions.map(x => 'perm:' + x));\n }\n }\n return to;\n }\n}\nexports.UserAttributes = UserAttributes;\nclass NavOptions {\n static fromSession(session, to) {\n to = to || new NavOptions();\n to.attributes = UserAttributes.fromSession(session);\n return to;\n }\n constructor(init) {\n this.attributes = [];\n this.navClass = NavDefaults.navClass;\n this.navItemClass = NavDefaults.navItemClass;\n this.navLinkClass = NavDefaults.navLinkClass;\n this.childNavItemClass = NavDefaults.childNavItemClass;\n this.childNavLinkClass = NavDefaults.childNavLinkClass;\n this.childNavMenuClass = NavDefaults.childNavMenuClass;\n this.childNavMenuItemClass = NavDefaults.childNavMenuItemClass;\n Object.assign(this, init);\n }\n}\nexports.NavOptions = NavOptions;\nfunction classNames(...args) {\n const classes = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!arg) continue;\n const argType = typeof arg;\n if (argType === 'string' || argType === 'number') {\n classes.push(arg);\n } else if (Array.isArray(arg) && arg.length) {\n const inner = classNames.apply(null, arg);\n if (inner) {\n classes.push(inner);\n }\n } else if (argType === 'object') {\n for (let key of Object.keys(arg)) {\n if (arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n return classes.join(' ');\n}\nexports.classNames = classNames;\nfunction fromXsdDuration(xsd) {\n let days = 0;\n let hours = 0;\n let minutes = 0;\n let seconds = 0;\n let ms = 0.0;\n let t = splitOnFirst(xsd.substring(1), 'T');\n let hasTime = t.length == 2;\n let d = splitOnFirst(t[0], 'D');\n if (d.length == 2) {\n days = parseInt(d[0], 10) || 0;\n }\n if (hasTime) {\n let h = splitOnFirst(t[1], 'H');\n if (h.length == 2) {\n hours = parseInt(h[0], 10) || 0;\n }\n let m = splitOnFirst(h[h.length - 1], 'M');\n if (m.length == 2) {\n minutes = parseInt(m[0], 10) || 0;\n }\n let s = splitOnFirst(m[m.length - 1], 'S');\n if (s.length == 2) {\n ms = parseFloat(s[0]);\n }\n seconds = ms | 0;\n ms -= seconds;\n }\n let totalSecs = days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds;\n return totalSecs + ms;\n}\nexports.fromXsdDuration = fromXsdDuration;\nfunction timeFmt(time, asXsd) {\n let totalSeconds = time;\n let wholeSeconds = time | 0;\n let seconds = wholeSeconds;\n let sec = seconds >= 60 ? seconds % 60 : seconds;\n seconds = seconds / 60;\n let min = seconds >= 60 ? seconds % 60 : seconds;\n seconds = seconds / 60;\n let hours = seconds >= 24 ? seconds % 24 : seconds;\n let days = seconds / 24;\n let remainingSecs = sec + (totalSeconds - wholeSeconds);\n let sb = asXsd ? 'P' : '';\n if (asXsd) {\n if ((days | 0) > 0) {\n sb += `${days | 0}D`;\n }\n if (days == 0 || hours + min + sec + remainingSecs > 0) {\n sb += \"T\";\n if ((hours | 0) > 0) {\n sb += `${hours | 0}H`;\n }\n if ((min | 0) > 0) {\n sb += `${min | 0}M`;\n }\n if (remainingSecs > 0) {\n let secFmt = remainingSecs.toFixed(7);\n secFmt = trimEnd(trimEnd(secFmt, '0'), '.');\n sb += `${secFmt}S`;\n } else if (sb.length == 2) {\n sb += '0S';\n }\n }\n } else {\n if ((days | 0) > 0) {\n sb += `${days | 0}:`;\n }\n sb += `${padInt(hours | 0)}:${padInt(min | 0)}:`;\n if (remainingSecs > 0) {\n let secFmt = remainingSecs.toFixed(7);\n secFmt = trimEnd(trimEnd(secFmt, '0'), '.');\n sb += remainingSecs >= 10 ? `${secFmt}` : `0${secFmt}`;\n } else {\n sb += '00';\n }\n }\n return sb;\n}\nfunction toXsdDuration(time) {\n return timeFmt(time, true);\n}\nexports.toXsdDuration = toXsdDuration;\nfunction toTimeSpanFmt(time) {\n return timeFmt(time, false);\n}\nexports.toTimeSpanFmt = toTimeSpanFmt;\nfunction flatMap(f, xs) {\n return xs.reduce((r, x) => r.concat(f(x)), []);\n}\nexports.flatMap = flatMap;\nfunction uniq(xs) {\n return Array.from(new Set(xs)).sort((x, y) => x > y ? 1 : -1);\n}\nexports.uniq = uniq;\nfunction enc(o) {\n return o == null ? null : typeof o == 'string' ? o.replace(/&/g, '&').replace(//g, '>').replace(/'/g, ''').replace(/\"/g, '"') : `${o}`;\n}\nexports.enc = enc;\nfunction htmlAttrs(o) {\n let sb = [];\n Object.keys(o).forEach(k => {\n if (sb.length > 0) sb.push(' ');\n sb.push(k);\n sb.push('=\"');\n sb.push(enc(o[k]));\n sb.push('\"');\n });\n return sb.join('');\n}\nexports.htmlAttrs = htmlAttrs;\nfunction indexOfAny(str, needles) {\n for (let i = 0, len = needles.length; i < len; i++) {\n let pos = str.indexOf(needles[i]);\n if (pos >= 0) return pos;\n }\n return -1;\n}\nexports.indexOfAny = indexOfAny;\nfunction isNullOrEmpty(o) {\n return o === null || o === undefined || o === \"\";\n}\nexports.isNullOrEmpty = isNullOrEmpty;\n// From .NET DateTime (WCF JSON or ISO Date) to JS Date\nfunction fromDateTime(dateTime) {\n return toDate(dateTime);\n}\nexports.fromDateTime = fromDateTime;\n// From JS Date to .NET DateTime (WCF JSON Date)\nfunction toDateTime(date) {\n return `\\/Date(${date.getTime()})\\/`;\n}\nexports.toDateTime = toDateTime;\n// From .NET TimeSpan (XSD Duration) to JS String\nfunction fromTimeSpan(xsdDuration) {\n return xsdDuration;\n}\nexports.fromTimeSpan = fromTimeSpan;\n// From JS String to .NET TimeSpan (XSD Duration)\nfunction toTimeSpan(xsdDuration) {\n return xsdDuration;\n}\nexports.toTimeSpan = toTimeSpan;\n// From .NET Guid to JS String\nfunction fromGuid(xsdDuration) {\n return xsdDuration;\n}\nexports.fromGuid = fromGuid;\n// From JS String to .NET Guid\nfunction toGuid(xsdDuration) {\n return xsdDuration;\n}\nexports.toGuid = toGuid;\n// From .NET byte[] (Base64 String) to JVM signed byte[]\nfunction fromByteArray(base64) {\n let binaryStr = _atob(base64);\n let len = binaryStr.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryStr.charCodeAt(i);\n }\n return bytes;\n}\nexports.fromByteArray = fromByteArray;\n// From JS Uint8Array to .NET byte[] (Base64 String)\nfunction toByteArray(bytes) {\n let str = String.fromCharCode.apply(null, bytes);\n return _btoa(str);\n}\nexports.toByteArray = toByteArray;\n// From JS String to Base64 String\nfunction toBase64String(source) {\n return JsonServiceClient.toBase64(source);\n}\nexports.toBase64String = toBase64String;\nclass StringBuffer {\n constructor(opt_a1, ...var_args) {\n this.buffer_ = '';\n if (opt_a1 != null) this.append.apply(this, arguments);\n }\n set(s) {\n this.buffer_ = '' + s;\n }\n append(a1, opt_a2, ...var_args) {\n this.buffer_ += String(a1);\n if (opt_a2 != null) {\n for (let i = 1; i < arguments.length; i++) {\n this.buffer_ += arguments[i];\n }\n }\n return this;\n }\n clear() {\n this.buffer_ = '';\n }\n getLength() {\n return this.buffer_.length;\n }\n toString() {\n return this.buffer_;\n }\n}\nexports.StringBuffer = StringBuffer;\nclass JSV {\n static encodeString(str) {\n if (str == null) return null;\n if (str === '') return '\"\"';\n if (str.indexOf('\"')) str = str.replace(/\"/g, '\"\"');\n return indexOfAny(str, JSV.ESCAPE_CHARS) >= 0 ? '\"' + str + '\"' : str;\n }\n static encodeArray(array) {\n let value,\n sb = new StringBuffer();\n for (let i = 0, len = array.length; i < len; i++) {\n value = array[i];\n if (isNullOrEmpty(value) || typeof value === 'function') continue;\n if (sb.getLength() > 0) sb.append(',');\n sb.append(JSV.stringify(value));\n }\n return `[${sb.toString()}]`;\n }\n static encodeObject(obj) {\n let value,\n sb = new StringBuffer();\n for (let key in obj) {\n value = obj[key];\n if (!obj.hasOwnProperty(key) || isNullOrEmpty(value) || typeof value === 'function') continue;\n if (sb.getLength() > 0) sb.append(',');\n sb.append(JSV.encodeString(key));\n sb.append(':');\n sb.append(JSV.stringify(value));\n }\n return `{${sb.toString()}}`;\n }\n static stringify(obj) {\n if (obj === null || obj === undefined) return null;\n let typeOf = typeof obj;\n if (typeOf === 'function' || typeOf === 'symbol') return null;\n if (typeOf === 'object') {\n let ctorStr = obj.constructor.toString().toLowerCase();\n if (ctorStr.indexOf('string') >= 0) return JSV.encodeString(obj);\n if (ctorStr.indexOf('boolean') >= 0) return obj ? 'true' : 'false';\n if (ctorStr.indexOf('number') >= 0) return obj;\n if (ctorStr.indexOf('date') >= 0) return JSV.encodeString(toLocalISOString(obj));\n if (ctorStr.indexOf('array') >= 0) return JSV.encodeArray(obj);\n return JSV.encodeObject(obj);\n }\n switch (typeOf) {\n case 'string':\n return JSV.encodeString(obj);\n case 'boolean':\n return obj ? 'true' : 'false';\n case 'number':\n default:\n return obj;\n }\n }\n}\nexports.JSV = JSV;\nJSV.ESCAPE_CHARS = ['\"', ':', ',', '{', '}', '[', ']', '\\r', '\\n'];\nfunction uniqueKeys(rows) {\n let to = [];\n rows.forEach(o => Object.keys(o).forEach(k => {\n if (to.indexOf(k) === -1) {\n to.push(k);\n }\n }));\n return to;\n}\nexports.uniqueKeys = uniqueKeys;\nfunction alignLeft(str, len, pad = ' ') {\n if (len < 0) return '';\n let aLen = len + 1 - str.length;\n if (aLen <= 0) return str;\n return pad + str + pad.repeat(len + 1 - str.length);\n}\nexports.alignLeft = alignLeft;\nfunction alignCenter(str, len, pad = ' ') {\n if (len < 0) return '';\n if (!str) str = '';\n let nLen = str.length;\n let half = Math.floor(len / 2 - nLen / 2);\n let odds = Math.abs(nLen % 2 - len % 2);\n return pad.repeat(half + 1) + str + pad.repeat(half + 1 + odds);\n}\nexports.alignCenter = alignCenter;\nfunction alignRight(str, len, pad = ' ') {\n if (len < 0) return '';\n let aLen = len + 1 - str.length;\n if (aLen <= 0) return str;\n return pad.repeat(len + 1 - str.length) + str + pad;\n}\nexports.alignRight = alignRight;\nfunction alignAuto(obj, len, pad = ' ') {\n let str = `${obj}`;\n if (str.length <= len) {\n return typeof obj === \"number\" ? alignRight(str, len, pad) : alignLeft(str, len, pad);\n }\n return str;\n}\nexports.alignAuto = alignAuto;\nfunction EventBus() {\n let {\n subscribe,\n publish\n } = createBus();\n this.subscribe = subscribe;\n this.publish = publish;\n}\nexports.EventBus = EventBus;\nfunction createBus() {\n let subscriptions = {};\n function subscribe(type, callback) {\n let id = Symbol('id');\n if (!subscriptions[type]) subscriptions[type] = {};\n subscriptions[type][id] = callback;\n return {\n unsubscribe: function () {\n delete subscriptions[type][id];\n if (Object.getOwnPropertySymbols(subscriptions[type]).length === 0) {\n delete subscriptions[type];\n }\n }\n };\n }\n function publish(eventType, arg) {\n if (!subscriptions[eventType]) return;\n Object.getOwnPropertySymbols(subscriptions[eventType]).forEach(key => subscriptions[eventType][key](arg));\n }\n return {\n subscribe,\n publish\n };\n}\nexports.createBus = createBus;\nclass Inspect {\n static vars(obj) {\n let R = nodeRequire();\n if (typeof R !== 'function') return;\n let inspectVarsPath = process.env.INSPECT_VARS;\n if (!inspectVarsPath || !obj) return;\n let fs = R('fs');\n let varsPath = inspectVarsPath.replace(/\\\\/g, '/');\n if (varsPath.indexOf('/') >= 0) {\n let dir = R('path').dirname(varsPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir);\n }\n }\n fs.writeFileSync(varsPath, JSON.stringify(obj));\n }\n static dump(obj) {\n let to = JSON.stringify(obj, null, 4);\n return to.replace(/\"/g, '');\n }\n static printDump(obj) {\n console.log(Inspect.dump(obj));\n }\n static dumpTable(rows) {\n let mapRows = rows;\n let keys = uniqueKeys(mapRows);\n let colSizes = {};\n keys.forEach(k => {\n let max = k.length;\n mapRows.forEach(row => {\n let col = row[k];\n if (col != null) {\n let valSize = `${col}`.length;\n if (valSize > max) {\n max = valSize;\n }\n }\n });\n colSizes[k] = max;\n });\n // sum + ' padding ' + |\n let colSizesLength = Object.keys(colSizes).length;\n let rowWidth = Object.keys(colSizes).map(k => colSizes[k]).reduce((p, c) => p + c, 0) + colSizesLength * 2 + (colSizesLength + 1);\n let sb = [];\n sb.push(`+${'-'.repeat(rowWidth - 2)}+`);\n let head = '|';\n keys.forEach(k => head += alignCenter(k, colSizes[k]) + '|');\n sb.push(head);\n sb.push(`|${'-'.repeat(rowWidth - 2)}|`);\n mapRows.forEach(row => {\n let to = '|';\n keys.forEach(k => to += '' + alignAuto(row[k], colSizes[k]) + '|');\n sb.push(to);\n });\n sb.push(`+${'-'.repeat(rowWidth - 2)}+`);\n return sb.join('\\n');\n }\n static printDumpTable(rows) {\n console.log(Inspect.dumpTable(rows));\n }\n}\nexports.Inspect = Inspect;","/**\n * @license Angular v18.2.4\n * (c) 2010-2024 Google LLC. https://angular.io/\n * License: MIT\n */\n\n/**\n * The default equality function used for `signal` and `computed`, which uses referential equality.\n */\nfunction defaultEquals(a, b) {\n return Object.is(a, b);\n}\n\n/**\n * The currently active consumer `ReactiveNode`, if running code in a reactive context.\n *\n * Change this via `setActiveConsumer`.\n */\nlet activeConsumer = null;\nlet inNotificationPhase = false;\n/**\n * Global epoch counter. Incremented whenever a source signal is set.\n */\nlet epoch = 1;\n/**\n * Symbol used to tell `Signal`s apart from other functions.\n *\n * This can be used to auto-unwrap signals in various cases, or to auto-wrap non-signal values.\n */\nconst SIGNAL = /* @__PURE__ */Symbol('SIGNAL');\nfunction setActiveConsumer(consumer) {\n const prev = activeConsumer;\n activeConsumer = consumer;\n return prev;\n}\nfunction getActiveConsumer() {\n return activeConsumer;\n}\nfunction isInNotificationPhase() {\n return inNotificationPhase;\n}\nfunction isReactive(value) {\n return value[SIGNAL] !== undefined;\n}\nconst REACTIVE_NODE = {\n version: 0,\n lastCleanEpoch: 0,\n dirty: false,\n producerNode: undefined,\n producerLastReadVersion: undefined,\n producerIndexOfThis: undefined,\n nextProducerIndex: 0,\n liveConsumerNode: undefined,\n liveConsumerIndexOfThis: undefined,\n consumerAllowSignalWrites: false,\n consumerIsAlwaysLive: false,\n producerMustRecompute: () => false,\n producerRecomputeValue: () => {},\n consumerMarkedDirty: () => {},\n consumerOnSignalRead: () => {}\n};\n/**\n * Called by implementations when a producer's signal is read.\n */\nfunction producerAccessed(node) {\n if (inNotificationPhase) {\n throw new Error(typeof ngDevMode !== 'undefined' && ngDevMode ? `Assertion error: signal read during notification phase` : '');\n }\n if (activeConsumer === null) {\n // Accessed outside of a reactive context, so nothing to record.\n return;\n }\n activeConsumer.consumerOnSignalRead(node);\n // This producer is the `idx`th dependency of `activeConsumer`.\n const idx = activeConsumer.nextProducerIndex++;\n assertConsumerNode(activeConsumer);\n if (idx < activeConsumer.producerNode.length && activeConsumer.producerNode[idx] !== node) {\n // There's been a change in producers since the last execution of `activeConsumer`.\n // `activeConsumer.producerNode[idx]` holds a stale dependency which will be be removed and\n // replaced with `this`.\n //\n // If `activeConsumer` isn't live, then this is a no-op, since we can replace the producer in\n // `activeConsumer.producerNode` directly. However, if `activeConsumer` is live, then we need\n // to remove it from the stale producer's `liveConsumer`s.\n if (consumerIsLive(activeConsumer)) {\n const staleProducer = activeConsumer.producerNode[idx];\n producerRemoveLiveConsumerAtIndex(staleProducer, activeConsumer.producerIndexOfThis[idx]);\n // At this point, the only record of `staleProducer` is the reference at\n // `activeConsumer.producerNode[idx]` which will be overwritten below.\n }\n }\n if (activeConsumer.producerNode[idx] !== node) {\n // We're a new dependency of the consumer (at `idx`).\n activeConsumer.producerNode[idx] = node;\n // If the active consumer is live, then add it as a live consumer. If not, then use 0 as a\n // placeholder value.\n activeConsumer.producerIndexOfThis[idx] = consumerIsLive(activeConsumer) ? producerAddLiveConsumer(node, activeConsumer, idx) : 0;\n }\n activeConsumer.producerLastReadVersion[idx] = node.version;\n}\n/**\n * Increment the global epoch counter.\n *\n * Called by source producers (that is, not computeds) whenever their values change.\n */\nfunction producerIncrementEpoch() {\n epoch++;\n}\n/**\n * Ensure this producer's `version` is up-to-date.\n */\nfunction producerUpdateValueVersion(node) {\n if (consumerIsLive(node) && !node.dirty) {\n // A live consumer will be marked dirty by producers, so a clean state means that its version\n // is guaranteed to be up-to-date.\n return;\n }\n if (!node.dirty && node.lastCleanEpoch === epoch) {\n // Even non-live consumers can skip polling if they previously found themselves to be clean at\n // the current epoch, since their dependencies could not possibly have changed (such a change\n // would've increased the epoch).\n return;\n }\n if (!node.producerMustRecompute(node) && !consumerPollProducersForChange(node)) {\n // None of our producers report a change since the last time they were read, so no\n // recomputation of our value is necessary, and we can consider ourselves clean.\n node.dirty = false;\n node.lastCleanEpoch = epoch;\n return;\n }\n node.producerRecomputeValue(node);\n // After recomputing the value, we're no longer dirty.\n node.dirty = false;\n node.lastCleanEpoch = epoch;\n}\n/**\n * Propagate a dirty notification to live consumers of this producer.\n */\nfunction producerNotifyConsumers(node) {\n if (node.liveConsumerNode === undefined) {\n return;\n }\n // Prevent signal reads when we're updating the graph\n const prev = inNotificationPhase;\n inNotificationPhase = true;\n try {\n for (const consumer of node.liveConsumerNode) {\n if (!consumer.dirty) {\n consumerMarkDirty(consumer);\n }\n }\n } finally {\n inNotificationPhase = prev;\n }\n}\n/**\n * Whether this `ReactiveNode` in its producer capacity is currently allowed to initiate updates,\n * based on the current consumer context.\n */\nfunction producerUpdatesAllowed() {\n return activeConsumer?.consumerAllowSignalWrites !== false;\n}\nfunction consumerMarkDirty(node) {\n node.dirty = true;\n producerNotifyConsumers(node);\n node.consumerMarkedDirty?.(node);\n}\n/**\n * Prepare this consumer to run a computation in its reactive context.\n *\n * Must be called by subclasses which represent reactive computations, before those computations\n * begin.\n */\nfunction consumerBeforeComputation(node) {\n node && (node.nextProducerIndex = 0);\n return setActiveConsumer(node);\n}\n/**\n * Finalize this consumer's state after a reactive computation has run.\n *\n * Must be called by subclasses which represent reactive computations, after those computations\n * have finished.\n */\nfunction consumerAfterComputation(node, prevConsumer) {\n setActiveConsumer(prevConsumer);\n if (!node || node.producerNode === undefined || node.producerIndexOfThis === undefined || node.producerLastReadVersion === undefined) {\n return;\n }\n if (consumerIsLive(node)) {\n // For live consumers, we need to remove the producer -> consumer edge for any stale producers\n // which weren't dependencies after the recomputation.\n for (let i = node.nextProducerIndex; i < node.producerNode.length; i++) {\n producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);\n }\n }\n // Truncate the producer tracking arrays.\n // Perf note: this is essentially truncating the length to `node.nextProducerIndex`, but\n // benchmarking has shown that individual pop operations are faster.\n while (node.producerNode.length > node.nextProducerIndex) {\n node.producerNode.pop();\n node.producerLastReadVersion.pop();\n node.producerIndexOfThis.pop();\n }\n}\n/**\n * Determine whether this consumer has any dependencies which have changed since the last time\n * they were read.\n */\nfunction consumerPollProducersForChange(node) {\n assertConsumerNode(node);\n // Poll producers for change.\n for (let i = 0; i < node.producerNode.length; i++) {\n const producer = node.producerNode[i];\n const seenVersion = node.producerLastReadVersion[i];\n // First check the versions. A mismatch means that the producer's value is known to have\n // changed since the last time we read it.\n if (seenVersion !== producer.version) {\n return true;\n }\n // The producer's version is the same as the last time we read it, but it might itself be\n // stale. Force the producer to recompute its version (calculating a new value if necessary).\n producerUpdateValueVersion(producer);\n // Now when we do this check, `producer.version` is guaranteed to be up to date, so if the\n // versions still match then it has not changed since the last time we read it.\n if (seenVersion !== producer.version) {\n return true;\n }\n }\n return false;\n}\n/**\n * Disconnect this consumer from the graph.\n */\nfunction consumerDestroy(node) {\n assertConsumerNode(node);\n if (consumerIsLive(node)) {\n // Drop all connections from the graph to this node.\n for (let i = 0; i < node.producerNode.length; i++) {\n producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);\n }\n }\n // Truncate all the arrays to drop all connection from this node to the graph.\n node.producerNode.length = node.producerLastReadVersion.length = node.producerIndexOfThis.length = 0;\n if (node.liveConsumerNode) {\n node.liveConsumerNode.length = node.liveConsumerIndexOfThis.length = 0;\n }\n}\n/**\n * Add `consumer` as a live consumer of this node.\n *\n * Note that this operation is potentially transitive. If this node becomes live, then it becomes\n * a live consumer of all of its current producers.\n */\nfunction producerAddLiveConsumer(node, consumer, indexOfThis) {\n assertProducerNode(node);\n if (node.liveConsumerNode.length === 0 && isConsumerNode(node)) {\n // When going from 0 to 1 live consumers, we become a live consumer to our producers.\n for (let i = 0; i < node.producerNode.length; i++) {\n node.producerIndexOfThis[i] = producerAddLiveConsumer(node.producerNode[i], node, i);\n }\n }\n node.liveConsumerIndexOfThis.push(indexOfThis);\n return node.liveConsumerNode.push(consumer) - 1;\n}\n/**\n * Remove the live consumer at `idx`.\n */\nfunction producerRemoveLiveConsumerAtIndex(node, idx) {\n assertProducerNode(node);\n if (typeof ngDevMode !== 'undefined' && ngDevMode && idx >= node.liveConsumerNode.length) {\n throw new Error(`Assertion error: active consumer index ${idx} is out of bounds of ${node.liveConsumerNode.length} consumers)`);\n }\n if (node.liveConsumerNode.length === 1 && isConsumerNode(node)) {\n // When removing the last live consumer, we will no longer be live. We need to remove\n // ourselves from our producers' tracking (which may cause consumer-producers to lose\n // liveness as well).\n for (let i = 0; i < node.producerNode.length; i++) {\n producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);\n }\n }\n // Move the last value of `liveConsumers` into `idx`. Note that if there's only a single\n // live consumer, this is a no-op.\n const lastIdx = node.liveConsumerNode.length - 1;\n node.liveConsumerNode[idx] = node.liveConsumerNode[lastIdx];\n node.liveConsumerIndexOfThis[idx] = node.liveConsumerIndexOfThis[lastIdx];\n // Truncate the array.\n node.liveConsumerNode.length--;\n node.liveConsumerIndexOfThis.length--;\n // If the index is still valid, then we need to fix the index pointer from the producer to this\n // consumer, and update it from `lastIdx` to `idx` (accounting for the move above).\n if (idx < node.liveConsumerNode.length) {\n const idxProducer = node.liveConsumerIndexOfThis[idx];\n const consumer = node.liveConsumerNode[idx];\n assertConsumerNode(consumer);\n consumer.producerIndexOfThis[idxProducer] = idx;\n }\n}\nfunction consumerIsLive(node) {\n return node.consumerIsAlwaysLive || (node?.liveConsumerNode?.length ?? 0) > 0;\n}\nfunction assertConsumerNode(node) {\n node.producerNode ??= [];\n node.producerIndexOfThis ??= [];\n node.producerLastReadVersion ??= [];\n}\nfunction assertProducerNode(node) {\n node.liveConsumerNode ??= [];\n node.liveConsumerIndexOfThis ??= [];\n}\nfunction isConsumerNode(node) {\n return node.producerNode !== undefined;\n}\n\n/**\n * Create a computed signal which derives a reactive value from an expression.\n */\nfunction createComputed(computation) {\n const node = Object.create(COMPUTED_NODE);\n node.computation = computation;\n const computed = () => {\n // Check if the value needs updating before returning it.\n producerUpdateValueVersion(node);\n // Record that someone looked at this signal.\n producerAccessed(node);\n if (node.value === ERRORED) {\n throw node.error;\n }\n return node.value;\n };\n computed[SIGNAL] = node;\n return computed;\n}\n/**\n * A dedicated symbol used before a computed value has been calculated for the first time.\n * Explicitly typed as `any` so we can use it as signal's value.\n */\nconst UNSET = /* @__PURE__ */Symbol('UNSET');\n/**\n * A dedicated symbol used in place of a computed signal value to indicate that a given computation\n * is in progress. Used to detect cycles in computation chains.\n * Explicitly typed as `any` so we can use it as signal's value.\n */\nconst COMPUTING = /* @__PURE__ */Symbol('COMPUTING');\n/**\n * A dedicated symbol used in place of a computed signal value to indicate that a given computation\n * failed. The thrown error is cached until the computation gets dirty again.\n * Explicitly typed as `any` so we can use it as signal's value.\n */\nconst ERRORED = /* @__PURE__ */Symbol('ERRORED');\n// Note: Using an IIFE here to ensure that the spread assignment is not considered\n// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.\n// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.\nconst COMPUTED_NODE = /* @__PURE__ */(() => {\n return {\n ...REACTIVE_NODE,\n value: UNSET,\n dirty: true,\n error: null,\n equal: defaultEquals,\n producerMustRecompute(node) {\n // Force a recomputation if there's no current value, or if the current value is in the\n // process of being calculated (which should throw an error).\n return node.value === UNSET || node.value === COMPUTING;\n },\n producerRecomputeValue(node) {\n if (node.value === COMPUTING) {\n // Our computation somehow led to a cyclic read of itself.\n throw new Error('Detected cycle in computations.');\n }\n const oldValue = node.value;\n node.value = COMPUTING;\n const prevConsumer = consumerBeforeComputation(node);\n let newValue;\n try {\n newValue = node.computation();\n } catch (err) {\n newValue = ERRORED;\n node.error = err;\n } finally {\n consumerAfterComputation(node, prevConsumer);\n }\n if (oldValue !== UNSET && oldValue !== ERRORED && newValue !== ERRORED && node.equal(oldValue, newValue)) {\n // No change to `valueVersion` - old and new values are\n // semantically equivalent.\n node.value = oldValue;\n return;\n }\n node.value = newValue;\n node.version++;\n }\n };\n})();\nfunction defaultThrowError() {\n throw new Error();\n}\nlet throwInvalidWriteToSignalErrorFn = defaultThrowError;\nfunction throwInvalidWriteToSignalError() {\n throwInvalidWriteToSignalErrorFn();\n}\nfunction setThrowInvalidWriteToSignalError(fn) {\n throwInvalidWriteToSignalErrorFn = fn;\n}\n\n/**\n * If set, called after `WritableSignal`s are updated.\n *\n * This hook can be used to achieve various effects, such as running effects synchronously as part\n * of setting a signal.\n */\nlet postSignalSetFn = null;\n/**\n * Create a `Signal` that can be set or updated directly.\n */\nfunction createSignal(initialValue) {\n const node = Object.create(SIGNAL_NODE);\n node.value = initialValue;\n const getter = () => {\n producerAccessed(node);\n return node.value;\n };\n getter[SIGNAL] = node;\n return getter;\n}\nfunction setPostSignalSetFn(fn) {\n const prev = postSignalSetFn;\n postSignalSetFn = fn;\n return prev;\n}\nfunction signalGetFn() {\n producerAccessed(this);\n return this.value;\n}\nfunction signalSetFn(node, newValue) {\n if (!producerUpdatesAllowed()) {\n throwInvalidWriteToSignalError();\n }\n if (!node.equal(node.value, newValue)) {\n node.value = newValue;\n signalValueChanged(node);\n }\n}\nfunction signalUpdateFn(node, updater) {\n if (!producerUpdatesAllowed()) {\n throwInvalidWriteToSignalError();\n }\n signalSetFn(node, updater(node.value));\n}\nfunction runPostSignalSetFn() {\n postSignalSetFn?.();\n}\n// Note: Using an IIFE here to ensure that the spread assignment is not considered\n// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.\n// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.\nconst SIGNAL_NODE = /* @__PURE__ */(() => {\n return {\n ...REACTIVE_NODE,\n equal: defaultEquals,\n value: undefined\n };\n})();\nfunction signalValueChanged(node) {\n node.version++;\n producerIncrementEpoch();\n producerNotifyConsumers(node);\n postSignalSetFn?.();\n}\nfunction createWatch(fn, schedule, allowSignalWrites) {\n const node = Object.create(WATCH_NODE);\n if (allowSignalWrites) {\n node.consumerAllowSignalWrites = true;\n }\n node.fn = fn;\n node.schedule = schedule;\n const registerOnCleanup = cleanupFn => {\n node.cleanupFn = cleanupFn;\n };\n function isWatchNodeDestroyed(node) {\n return node.fn === null && node.schedule === null;\n }\n function destroyWatchNode(node) {\n if (!isWatchNodeDestroyed(node)) {\n consumerDestroy(node); // disconnect watcher from the reactive graph\n node.cleanupFn();\n // nullify references to the integration functions to mark node as destroyed\n node.fn = null;\n node.schedule = null;\n node.cleanupFn = NOOP_CLEANUP_FN;\n }\n }\n const run = () => {\n if (node.fn === null) {\n // trying to run a destroyed watch is noop\n return;\n }\n if (isInNotificationPhase()) {\n throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);\n }\n node.dirty = false;\n if (node.hasRun && !consumerPollProducersForChange(node)) {\n return;\n }\n node.hasRun = true;\n const prevConsumer = consumerBeforeComputation(node);\n try {\n node.cleanupFn();\n node.cleanupFn = NOOP_CLEANUP_FN;\n node.fn(registerOnCleanup);\n } finally {\n consumerAfterComputation(node, prevConsumer);\n }\n };\n node.ref = {\n notify: () => consumerMarkDirty(node),\n run,\n cleanup: () => node.cleanupFn(),\n destroy: () => destroyWatchNode(node),\n [SIGNAL]: node\n };\n return node.ref;\n}\nconst NOOP_CLEANUP_FN = () => {};\n// Note: Using an IIFE here to ensure that the spread assignment is not considered\n// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.\n// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.\nconst WATCH_NODE = /* @__PURE__ */(() => {\n return {\n ...REACTIVE_NODE,\n consumerIsAlwaysLive: true,\n consumerAllowSignalWrites: false,\n consumerMarkedDirty: node => {\n if (node.schedule !== null) {\n node.schedule(node.ref);\n }\n },\n hasRun: false,\n cleanupFn: NOOP_CLEANUP_FN\n };\n})();\nfunction setAlternateWeakRefImpl(impl) {\n // TODO: remove this function\n}\nexport { REACTIVE_NODE, SIGNAL, SIGNAL_NODE, consumerAfterComputation, consumerBeforeComputation, consumerDestroy, consumerMarkDirty, consumerPollProducersForChange, createComputed, createSignal, createWatch, defaultEquals, getActiveConsumer, isInNotificationPhase, isReactive, producerAccessed, producerIncrementEpoch, producerNotifyConsumers, producerUpdateValueVersion, producerUpdatesAllowed, runPostSignalSetFn, setActiveConsumer, setAlternateWeakRefImpl, setPostSignalSetFn, setThrowInvalidWriteToSignalError, signalSetFn, signalUpdateFn };\n","export function isFunction(x) {\n return typeof x === 'function';\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\nexport const config = {\n Promise: undefined,\n set useDeprecatedSynchronousErrorHandling(value) {\n if (value) {\n const error = new Error();\n console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n }\n};\n","export function hostReportError(err) {\n setTimeout(() => {\n throw err;\n }, 0);\n}\n","import { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nexport const empty = {\n closed: true,\n next(value) {},\n error(err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n },\n complete() {}\n};\n","export const isArray = (() => Array.isArray || (x => x && typeof x.length === 'number'))();\n","export function isObject(x) {\n return x !== null && typeof x === 'object';\n}\n","const UnsubscriptionErrorImpl = (() => {\n function UnsubscriptionErrorImpl(errors) {\n Error.call(this);\n this.message = errors ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}` : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n return UnsubscriptionErrorImpl;\n})();\nexport const UnsubscriptionError = UnsubscriptionErrorImpl;\n","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nexport class Subscription {\n constructor(unsubscribe) {\n this.closed = false;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (unsubscribe) {\n this._unsubscribe = unsubscribe;\n }\n }\n unsubscribe() {\n let errors;\n if (this.closed) {\n return;\n }\n let {\n _parentOrParents,\n _unsubscribe,\n _subscriptions\n } = this;\n this.closed = true;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n } else if (_parentOrParents !== null) {\n for (let index = 0; index < _parentOrParents.length; ++index) {\n const parent = _parentOrParents[index];\n parent.remove(this);\n }\n }\n if (isFunction(_unsubscribe)) {\n try {\n _unsubscribe.call(this);\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n if (isArray(_subscriptions)) {\n let index = -1;\n let len = _subscriptions.length;\n while (++index < len) {\n const sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n } catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n } else {\n errors.push(e);\n }\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n add(teardown) {\n let subscription = teardown;\n if (!teardown) {\n return Subscription.EMPTY;\n }\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n return subscription;\n } else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n } else if (!(subscription instanceof Subscription)) {\n const tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default:\n {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n let {\n _parentOrParents\n } = subscription;\n if (_parentOrParents === null) {\n subscription._parentOrParents = this;\n } else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n return subscription;\n }\n subscription._parentOrParents = [_parentOrParents, this];\n } else if (_parentOrParents.indexOf(this) === -1) {\n _parentOrParents.push(this);\n } else {\n return subscription;\n }\n const subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n } else {\n subscriptions.push(subscription);\n }\n return subscription;\n }\n remove(subscription) {\n const subscriptions = this._subscriptions;\n if (subscriptions) {\n const subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n }\n}\nSubscription.EMPTY = function (empty) {\n empty.closed = true;\n return empty;\n}(new Subscription());\nfunction flattenUnsubscriptionErrors(errors) {\n return errors.reduce((errs, err) => errs.concat(err instanceof UnsubscriptionError ? err.errors : err), []);\n}\n","export const rxSubscriber = (() => typeof Symbol === 'function' ? Symbol('rxSubscriber') : '@@rxSubscriber_' + Math.random())();\nexport const $$rxSubscriber = rxSubscriber;\n","import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nexport class Subscriber extends Subscription {\n constructor(destinationOrNext, error, complete) {\n super();\n this.syncErrorValue = null;\n this.syncErrorThrown = false;\n this.syncErrorThrowable = false;\n this.isStopped = false;\n switch (arguments.length) {\n case 0:\n this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n this.destination = destinationOrNext;\n destinationOrNext.add(this);\n } else {\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber(this, destinationOrNext);\n }\n break;\n }\n default:\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);\n break;\n }\n }\n [rxSubscriberSymbol]() {\n return this;\n }\n static create(next, error, complete) {\n const subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n }\n next(value) {\n if (!this.isStopped) {\n this._next(value);\n }\n }\n error(err) {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n }\n complete() {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n }\n unsubscribe() {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n super.unsubscribe();\n }\n _next(value) {\n this.destination.next(value);\n }\n _error(err) {\n this.destination.error(err);\n this.unsubscribe();\n }\n _complete() {\n this.destination.complete();\n this.unsubscribe();\n }\n _unsubscribeAndRecycle() {\n const {\n _parentOrParents\n } = this;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n }\n}\nexport class SafeSubscriber extends Subscriber {\n constructor(_parentSubscriber, observerOrNext, error, complete) {\n super();\n this._parentSubscriber = _parentSubscriber;\n let next;\n let context = this;\n if (isFunction(observerOrNext)) {\n next = observerOrNext;\n } else if (observerOrNext) {\n next = observerOrNext.next;\n error = observerOrNext.error;\n complete = observerOrNext.complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n this.add(context.unsubscribe.bind(context));\n }\n context.unsubscribe = this.unsubscribe.bind(this);\n }\n }\n this._context = context;\n this._next = next;\n this._error = error;\n this._complete = complete;\n }\n next(value) {\n if (!this.isStopped && this._next) {\n const {\n _parentSubscriber\n } = this;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n }\n error(err) {\n if (!this.isStopped) {\n const {\n _parentSubscriber\n } = this;\n const {\n useDeprecatedSynchronousErrorHandling\n } = config;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n } else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n } else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n } else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n }\n complete() {\n if (!this.isStopped) {\n const {\n _parentSubscriber\n } = this;\n if (this._complete) {\n const wrappedComplete = () => this._complete.call(this._context);\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n } else {\n this.unsubscribe();\n }\n }\n }\n __tryOrUnsub(fn, value) {\n try {\n fn.call(this._context, value);\n } catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n }\n }\n __tryOrSetError(parent, fn, value) {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n } else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n }\n _unsubscribe() {\n const {\n _parentSubscriber\n } = this;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nexport function canReportError(observer) {\n while (observer) {\n const {\n closed,\n destination,\n isStopped\n } = observer;\n if (closed || isStopped) {\n return false;\n } else if (destination && destination instanceof Subscriber) {\n observer = destination;\n } else {\n observer = null;\n }\n }\n return true;\n}\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nexport function toSubscriber(nextOrObserver, error, complete) {\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return nextOrObserver;\n }\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n return new Subscriber(nextOrObserver, error, complete);\n}\n","export const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n","export function identity(x) {\n return x;\n}\n","import { identity } from './identity';\nexport function pipe(...fns) {\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce((prev, fn) => fn(prev), input);\n };\n}\n","import { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nexport class Observable {\n constructor(subscribe) {\n this._isScalar = false;\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n lift(operator) {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n subscribe(observerOrNext, error, complete) {\n const {\n operator\n } = this;\n const sink = toSubscriber(observerOrNext, error, complete);\n if (operator) {\n sink.add(operator.call(sink, this.source));\n } else {\n sink.add(this.source || config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable ? this._subscribe(sink) : this._trySubscribe(sink));\n }\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n return sink;\n }\n _trySubscribe(sink) {\n try {\n return this._subscribe(sink);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n forEach(next, promiseCtor) {\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor((resolve, reject) => {\n let subscription;\n subscription = this.subscribe(value => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n });\n }\n _subscribe(subscriber) {\n const {\n source\n } = this;\n return source && source.subscribe(subscriber);\n }\n [Symbol_observable]() {\n return this;\n }\n pipe(...operations) {\n if (operations.length === 0) {\n return this;\n }\n return pipeFromArray(operations)(this);\n }\n toPromise(promiseCtor) {\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor((resolve, reject) => {\n let value;\n this.subscribe(x => value = x, err => reject(err), () => resolve(value));\n });\n }\n}\nObservable.create = subscribe => {\n return new Observable(subscribe);\n};\nfunction getPromiseCtor(promiseCtor) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n return promiseCtor;\n}\n","const ObjectUnsubscribedErrorImpl = (() => {\n function ObjectUnsubscribedErrorImpl() {\n Error.call(this);\n this.message = 'object unsubscribed';\n this.name = 'ObjectUnsubscribedError';\n return this;\n }\n ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);\n return ObjectUnsubscribedErrorImpl;\n})();\nexport const ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;\n","import { Subscription } from './Subscription';\nexport class SubjectSubscription extends Subscription {\n constructor(subject, subscriber) {\n super();\n this.subject = subject;\n this.subscriber = subscriber;\n this.closed = false;\n }\n unsubscribe() {\n if (this.closed) {\n return;\n }\n this.closed = true;\n const subject = this.subject;\n const observers = subject.observers;\n this.subject = null;\n if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n return;\n }\n const subscriberIndex = observers.indexOf(this.subscriber);\n if (subscriberIndex !== -1) {\n observers.splice(subscriberIndex, 1);\n }\n }\n}\n","import { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nexport class SubjectSubscriber extends Subscriber {\n constructor(destination) {\n super(destination);\n this.destination = destination;\n }\n}\nexport class Subject extends Observable {\n constructor() {\n super();\n this.observers = [];\n this.closed = false;\n this.isStopped = false;\n this.hasError = false;\n this.thrownError = null;\n }\n [rxSubscriberSymbol]() {\n return new SubjectSubscriber(this);\n }\n lift(operator) {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator;\n return subject;\n }\n next(value) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n if (!this.isStopped) {\n const {\n observers\n } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].next(value);\n }\n }\n }\n error(err) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.hasError = true;\n this.thrownError = err;\n this.isStopped = true;\n const {\n observers\n } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].error(err);\n }\n this.observers.length = 0;\n }\n complete() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.isStopped = true;\n const {\n observers\n } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].complete();\n }\n this.observers.length = 0;\n }\n unsubscribe() {\n this.isStopped = true;\n this.closed = true;\n this.observers = null;\n }\n _trySubscribe(subscriber) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else {\n return super._trySubscribe(subscriber);\n }\n }\n _subscribe(subscriber) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else if (this.hasError) {\n subscriber.error(this.thrownError);\n return Subscription.EMPTY;\n } else if (this.isStopped) {\n subscriber.complete();\n return Subscription.EMPTY;\n } else {\n this.observers.push(subscriber);\n return new SubjectSubscription(this, subscriber);\n }\n }\n asObservable() {\n const observable = new Observable();\n observable.source = this;\n return observable;\n }\n}\nSubject.create = (destination, source) => {\n return new AnonymousSubject(destination, source);\n};\nexport class AnonymousSubject extends Subject {\n constructor(destination, source) {\n super();\n this.destination = destination;\n this.source = source;\n }\n next(value) {\n const {\n destination\n } = this;\n if (destination && destination.next) {\n destination.next(value);\n }\n }\n error(err) {\n const {\n destination\n } = this;\n if (destination && destination.error) {\n this.destination.error(err);\n }\n }\n complete() {\n const {\n destination\n } = this;\n if (destination && destination.complete) {\n this.destination.complete();\n }\n }\n _subscribe(subscriber) {\n const {\n source\n } = this;\n if (source) {\n return this.source.subscribe(subscriber);\n } else {\n return Subscription.EMPTY;\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\nexport function refCount() {\n return function refCountOperatorFunction(source) {\n return source.lift(new RefCountOperator(source));\n };\n}\nclass RefCountOperator {\n constructor(connectable) {\n this.connectable = connectable;\n }\n call(subscriber, source) {\n const {\n connectable\n } = this;\n connectable._refCount++;\n const refCounter = new RefCountSubscriber(subscriber, connectable);\n const subscription = source.subscribe(refCounter);\n if (!refCounter.closed) {\n refCounter.connection = connectable.connect();\n }\n return subscription;\n }\n}\nclass RefCountSubscriber extends Subscriber {\n constructor(destination, connectable) {\n super(destination);\n this.connectable = connectable;\n }\n _unsubscribe() {\n const {\n connectable\n } = this;\n if (!connectable) {\n this.connection = null;\n return;\n }\n this.connectable = null;\n const refCount = connectable._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n connectable._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n const {\n connection\n } = this;\n const sharedConnection = connectable._connection;\n this.connection = null;\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n }\n}\n","import { SubjectSubscriber } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nexport class ConnectableObservable extends Observable {\n constructor(source, subjectFactory) {\n super();\n this.source = source;\n this.subjectFactory = subjectFactory;\n this._refCount = 0;\n this._isComplete = false;\n }\n _subscribe(subscriber) {\n return this.getSubject().subscribe(subscriber);\n }\n getSubject() {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject;\n }\n connect() {\n let connection = this._connection;\n if (!connection) {\n this._isComplete = false;\n connection = this._connection = new Subscription();\n connection.add(this.source.subscribe(new ConnectableSubscriber(this.getSubject(), this)));\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n refCount() {\n return higherOrderRefCount()(this);\n }\n}\nexport const connectableObservableDescriptor = (() => {\n const connectableProto = ConnectableObservable.prototype;\n return {\n operator: {\n value: null\n },\n _refCount: {\n value: 0,\n writable: true\n },\n _subject: {\n value: null,\n writable: true\n },\n _connection: {\n value: null,\n writable: true\n },\n _subscribe: {\n value: connectableProto._subscribe\n },\n _isComplete: {\n value: connectableProto._isComplete,\n writable: true\n },\n getSubject: {\n value: connectableProto.getSubject\n },\n connect: {\n value: connectableProto.connect\n },\n refCount: {\n value: connectableProto.refCount\n }\n };\n})();\nclass ConnectableSubscriber extends SubjectSubscriber {\n constructor(destination, connectable) {\n super(destination);\n this.connectable = connectable;\n }\n _error(err) {\n this._unsubscribe();\n super._error(err);\n }\n _complete() {\n this.connectable._isComplete = true;\n this._unsubscribe();\n super._complete();\n }\n _unsubscribe() {\n const connectable = this.connectable;\n if (connectable) {\n this.connectable = null;\n const connection = connectable._connection;\n connectable._refCount = 0;\n connectable._subject = null;\n connectable._connection = null;\n if (connection) {\n connection.unsubscribe();\n }\n }\n }\n}\nclass RefCountOperator {\n constructor(connectable) {\n this.connectable = connectable;\n }\n call(subscriber, source) {\n const {\n connectable\n } = this;\n connectable._refCount++;\n const refCounter = new RefCountSubscriber(subscriber, connectable);\n const subscription = source.subscribe(refCounter);\n if (!refCounter.closed) {\n refCounter.connection = connectable.connect();\n }\n return subscription;\n }\n}\nclass RefCountSubscriber extends Subscriber {\n constructor(destination, connectable) {\n super(destination);\n this.connectable = connectable;\n }\n _unsubscribe() {\n const {\n connectable\n } = this;\n if (!connectable) {\n this.connection = null;\n return;\n }\n this.connectable = null;\n const refCount = connectable._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n connectable._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n const {\n connection\n } = this;\n const sharedConnection = connectable._connection;\n this.connection = null;\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n }\n}\n","import { Subject } from './Subject';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nexport class BehaviorSubject extends Subject {\n constructor(_value) {\n super();\n this._value = _value;\n }\n get value() {\n return this.getValue();\n }\n _subscribe(subscriber) {\n const subscription = super._subscribe(subscriber);\n if (subscription && !subscription.closed) {\n subscriber.next(this._value);\n }\n return subscription;\n }\n getValue() {\n if (this.hasError) {\n throw this.thrownError;\n } else if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else {\n return this._value;\n }\n }\n next(value) {\n super.next(this._value = value);\n }\n}\n","import { Subscription } from '../Subscription';\nexport class Action extends Subscription {\n constructor(scheduler, work) {\n super();\n }\n schedule(state, delay = 0) {\n return this;\n }\n}\n","import { Action } from './Action';\nexport class AsyncAction extends Action {\n constructor(scheduler, work) {\n super(scheduler, work);\n this.scheduler = scheduler;\n this.work = work;\n this.pending = false;\n }\n schedule(state, delay = 0) {\n if (this.closed) {\n return this;\n }\n this.state = state;\n const id = this.id;\n const scheduler = this.scheduler;\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n this.pending = true;\n this.delay = delay;\n this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n return this;\n }\n requestAsyncId(scheduler, id, delay = 0) {\n return setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n recycleAsyncId(scheduler, id, delay = 0) {\n if (delay !== null && this.delay === delay && this.pending === false) {\n return id;\n }\n clearInterval(id);\n return undefined;\n }\n execute(state, delay) {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n _execute(state, delay) {\n let errored = false;\n let errorValue = undefined;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n errorValue = !!e && e || new Error(e);\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n _unsubscribe() {\n const id = this.id;\n const scheduler = this.scheduler;\n const actions = scheduler.actions;\n const index = actions.indexOf(this);\n this.work = null;\n this.state = null;\n this.pending = false;\n this.scheduler = null;\n if (index !== -1) {\n actions.splice(index, 1);\n }\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n this.delay = null;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nexport class QueueAction extends AsyncAction {\n constructor(scheduler, work) {\n super(scheduler, work);\n this.scheduler = scheduler;\n this.work = work;\n }\n schedule(state, delay = 0) {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n execute(state, delay) {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n requestAsyncId(scheduler, id, delay = 0) {\n if (delay !== null && delay > 0 || delay === null && this.delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n return scheduler.flush(this);\n }\n}\n","export class Scheduler {\n constructor(SchedulerAction, now = Scheduler.now) {\n this.SchedulerAction = SchedulerAction;\n this.now = now;\n }\n schedule(work, delay = 0, state) {\n return new this.SchedulerAction(this, work).schedule(state, delay);\n }\n}\nScheduler.now = () => Date.now();\n","import { Scheduler } from '../Scheduler';\nexport class AsyncScheduler extends Scheduler {\n constructor(SchedulerAction, now = Scheduler.now) {\n super(SchedulerAction, () => {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.now();\n } else {\n return now();\n }\n });\n this.actions = [];\n this.active = false;\n this.scheduled = undefined;\n }\n schedule(work, delay = 0, state) {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.schedule(work, delay, state);\n } else {\n return super.schedule(work, delay, state);\n }\n }\n flush(action) {\n const {\n actions\n } = this;\n if (this.active) {\n actions.push(action);\n return;\n }\n let error;\n this.active = true;\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (action = actions.shift());\n this.active = false;\n if (error) {\n while (action = actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\nexport class QueueScheduler extends AsyncScheduler {}\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\nexport const queue = new QueueScheduler(QueueAction);\n","import { Observable } from '../Observable';\nexport const EMPTY = new Observable(subscriber => subscriber.complete());\nexport function empty(scheduler) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\nfunction emptyScheduled(scheduler) {\n return new Observable(subscriber => scheduler.schedule(() => subscriber.complete()));\n}\n","export function isScheduler(value) {\n return value && typeof value.schedule === 'function';\n}\n","export const subscribeToArray = array => subscriber => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nexport function scheduleArray(input, scheduler) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\nexport function fromArray(input, scheduler) {\n if (!scheduler) {\n return new Observable(subscribeToArray(input));\n } else {\n return scheduleArray(input, scheduler);\n }\n}\n","import { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\nexport function of(...args) {\n let scheduler = args[args.length - 1];\n if (isScheduler(scheduler)) {\n args.pop();\n return scheduleArray(args, scheduler);\n } else {\n return fromArray(args);\n }\n}\n","import { Observable } from '../Observable';\nexport function throwError(error, scheduler) {\n if (!scheduler) {\n return new Observable(subscriber => subscriber.error(error));\n } else {\n return new Observable(subscriber => scheduler.schedule(dispatch, 0, {\n error,\n subscriber\n }));\n }\n}\nfunction dispatch({\n error,\n subscriber\n}) {\n subscriber.error(error);\n}\n","import { empty } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nexport var NotificationKind;\n(function (NotificationKind) {\n NotificationKind[\"NEXT\"] = \"N\";\n NotificationKind[\"ERROR\"] = \"E\";\n NotificationKind[\"COMPLETE\"] = \"C\";\n})(NotificationKind || (NotificationKind = {}));\nexport class Notification {\n constructor(kind, value, error) {\n this.kind = kind;\n this.value = value;\n this.error = error;\n this.hasValue = kind === 'N';\n }\n observe(observer) {\n switch (this.kind) {\n case 'N':\n return observer.next && observer.next(this.value);\n case 'E':\n return observer.error && observer.error(this.error);\n case 'C':\n return observer.complete && observer.complete();\n }\n }\n do(next, error, complete) {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return next && next(this.value);\n case 'E':\n return error && error(this.error);\n case 'C':\n return complete && complete();\n }\n }\n accept(nextOrObserver, error, complete) {\n if (nextOrObserver && typeof nextOrObserver.next === 'function') {\n return this.observe(nextOrObserver);\n } else {\n return this.do(nextOrObserver, error, complete);\n }\n }\n toObservable() {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return of(this.value);\n case 'E':\n return throwError(this.error);\n case 'C':\n return empty();\n }\n throw new Error('unexpected notification kind value');\n }\n static createNext(value) {\n if (typeof value !== 'undefined') {\n return new Notification('N', value);\n }\n return Notification.undefinedValueNotification;\n }\n static createError(err) {\n return new Notification('E', undefined, err);\n }\n static createComplete() {\n return Notification.completeNotification;\n }\n}\nNotification.completeNotification = new Notification('C');\nNotification.undefinedValueNotification = new Notification('N', undefined);\n","import { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nexport function observeOn(scheduler, delay = 0) {\n return function observeOnOperatorFunction(source) {\n return source.lift(new ObserveOnOperator(scheduler, delay));\n };\n}\nexport class ObserveOnOperator {\n constructor(scheduler, delay = 0) {\n this.scheduler = scheduler;\n this.delay = delay;\n }\n call(subscriber, source) {\n return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));\n }\n}\nexport class ObserveOnSubscriber extends Subscriber {\n constructor(destination, scheduler, delay = 0) {\n super(destination);\n this.scheduler = scheduler;\n this.delay = delay;\n }\n static dispatch(arg) {\n const {\n notification,\n destination\n } = arg;\n notification.observe(destination);\n this.unsubscribe();\n }\n scheduleMessage(notification) {\n const destination = this.destination;\n destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));\n }\n _next(value) {\n this.scheduleMessage(Notification.createNext(value));\n }\n _error(err) {\n this.scheduleMessage(Notification.createError(err));\n this.unsubscribe();\n }\n _complete() {\n this.scheduleMessage(Notification.createComplete());\n this.unsubscribe();\n }\n}\nexport class ObserveOnMessage {\n constructor(notification, destination) {\n this.notification = notification;\n this.destination = destination;\n }\n}\n","import { Subject } from './Subject';\nimport { queue } from './scheduler/queue';\nimport { Subscription } from './Subscription';\nimport { ObserveOnSubscriber } from './operators/observeOn';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nexport class ReplaySubject extends Subject {\n constructor(bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, scheduler) {\n super();\n this.scheduler = scheduler;\n this._events = [];\n this._infiniteTimeWindow = false;\n this._bufferSize = bufferSize < 1 ? 1 : bufferSize;\n this._windowTime = windowTime < 1 ? 1 : windowTime;\n if (windowTime === Number.POSITIVE_INFINITY) {\n this._infiniteTimeWindow = true;\n this.next = this.nextInfiniteTimeWindow;\n } else {\n this.next = this.nextTimeWindow;\n }\n }\n nextInfiniteTimeWindow(value) {\n const _events = this._events;\n _events.push(value);\n if (_events.length > this._bufferSize) {\n _events.shift();\n }\n super.next(value);\n }\n nextTimeWindow(value) {\n this._events.push(new ReplayEvent(this._getNow(), value));\n this._trimBufferThenGetEvents();\n super.next(value);\n }\n _subscribe(subscriber) {\n const _infiniteTimeWindow = this._infiniteTimeWindow;\n const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();\n const scheduler = this.scheduler;\n const len = _events.length;\n let subscription;\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else if (this.isStopped || this.hasError) {\n subscription = Subscription.EMPTY;\n } else {\n this.observers.push(subscriber);\n subscription = new SubjectSubscription(this, subscriber);\n }\n if (scheduler) {\n subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));\n }\n if (_infiniteTimeWindow) {\n for (let i = 0; i < len && !subscriber.closed; i++) {\n subscriber.next(_events[i]);\n }\n } else {\n for (let i = 0; i < len && !subscriber.closed; i++) {\n subscriber.next(_events[i].value);\n }\n }\n if (this.hasError) {\n subscriber.error(this.thrownError);\n } else if (this.isStopped) {\n subscriber.complete();\n }\n return subscription;\n }\n _getNow() {\n return (this.scheduler || queue).now();\n }\n _trimBufferThenGetEvents() {\n const now = this._getNow();\n const _bufferSize = this._bufferSize;\n const _windowTime = this._windowTime;\n const _events = this._events;\n const eventsCount = _events.length;\n let spliceCount = 0;\n while (spliceCount < eventsCount) {\n if (now - _events[spliceCount].time < _windowTime) {\n break;\n }\n spliceCount++;\n }\n if (eventsCount > _bufferSize) {\n spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);\n }\n if (spliceCount > 0) {\n _events.splice(0, spliceCount);\n }\n return _events;\n }\n}\nclass ReplayEvent {\n constructor(time, value) {\n this.time = time;\n this.value = value;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\nexport const async = new AsyncScheduler(AsyncAction);\n","import { AsyncAction } from './AsyncAction';\nexport class AnimationFrameAction extends AsyncAction {\n constructor(scheduler, work) {\n super(scheduler, work);\n this.scheduler = scheduler;\n this.work = work;\n }\n requestAsyncId(scheduler, id, delay = 0) {\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n scheduler.actions.push(this);\n return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(() => scheduler.flush(null)));\n }\n recycleAsyncId(scheduler, id, delay = 0) {\n if (delay !== null && delay > 0 || delay === null && this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n if (scheduler.actions.length === 0) {\n cancelAnimationFrame(id);\n scheduler.scheduled = undefined;\n }\n return undefined;\n }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\nexport class AnimationFrameScheduler extends AsyncScheduler {\n flush(action) {\n this.active = true;\n this.scheduled = undefined;\n const {\n actions\n } = this;\n let error;\n let index = -1;\n let count = actions.length;\n action = action || actions.shift();\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (++index < count && (action = actions.shift()));\n this.active = false;\n if (error) {\n while (++index < count && (action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nexport const animationFrame = new AnimationFrameScheduler(AnimationFrameAction);\n","export function noop() {}\n","import { Observable } from '../Observable';\nexport function isObservable(obj) {\n return !!obj && (obj instanceof Observable || typeof obj.lift === 'function' && typeof obj.subscribe === 'function');\n}\n","const ArgumentOutOfRangeErrorImpl = (() => {\n function ArgumentOutOfRangeErrorImpl() {\n Error.call(this);\n this.message = 'argument out of range';\n this.name = 'ArgumentOutOfRangeError';\n return this;\n }\n ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);\n return ArgumentOutOfRangeErrorImpl;\n})();\nexport const ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;\n","const EmptyErrorImpl = (() => {\n function EmptyErrorImpl() {\n Error.call(this);\n this.message = 'no elements in sequence';\n this.name = 'EmptyError';\n return this;\n }\n EmptyErrorImpl.prototype = Object.create(Error.prototype);\n return EmptyErrorImpl;\n})();\nexport const EmptyError = EmptyErrorImpl;\n","import { Subscriber } from '../Subscriber';\nexport function map(project, thisArg) {\n return function mapOperation(source) {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\nexport class MapOperator {\n constructor(project, thisArg) {\n this.project = project;\n this.thisArg = thisArg;\n }\n call(subscriber, source) {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\nclass MapSubscriber extends Subscriber {\n constructor(destination, project, thisArg) {\n super(destination);\n this.project = project;\n this.count = 0;\n this.thisArg = thisArg || this;\n }\n _next(value) {\n let result;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Subscriber } from './Subscriber';\nexport class OuterSubscriber extends Subscriber {\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.destination.next(innerValue);\n }\n notifyError(error, innerSub) {\n this.destination.error(error);\n }\n notifyComplete(innerSub) {\n this.destination.complete();\n }\n}\n","import { Subscriber } from './Subscriber';\nexport class InnerSubscriber extends Subscriber {\n constructor(parent, outerValue, outerIndex) {\n super();\n this.parent = parent;\n this.outerValue = outerValue;\n this.outerIndex = outerIndex;\n this.index = 0;\n }\n _next(value) {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);\n }\n _error(error) {\n this.parent.notifyError(error, this);\n this.unsubscribe();\n }\n _complete() {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n","import { hostReportError } from './hostReportError';\nexport const subscribeToPromise = promise => subscriber => {\n promise.then(value => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, err => subscriber.error(err)).then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport const iterator = getSymbolIterator();\nexport const $$iterator = iterator;\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\nexport const subscribeToIterable = iterable => subscriber => {\n const iterator = iterable[Symbol_iterator]();\n do {\n const item = iterator.next();\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n return subscriber;\n};\n","import { observable as Symbol_observable } from '../symbol/observable';\nexport const subscribeToObservable = obj => subscriber => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","export const isArrayLike = x => x && typeof x.length === 'number' && typeof x !== 'function';\n","export function isPromise(value) {\n return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';\n}\n","import { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport const subscribeTo = result => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.` + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","import { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeTo } from './subscribeTo';\nimport { Observable } from '../Observable';\nexport function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex)) {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n return subscribeTo(result)(innerSubscriber);\n}\n","import { isScheduler } from '../util/isScheduler';\nimport { isArray } from '../util/isArray';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { fromArray } from './fromArray';\nconst NONE = {};\nexport function combineLatest(...observables) {\n let resultSelector = null;\n let scheduler = null;\n if (isScheduler(observables[observables.length - 1])) {\n scheduler = observables.pop();\n }\n if (typeof observables[observables.length - 1] === 'function') {\n resultSelector = observables.pop();\n }\n if (observables.length === 1 && isArray(observables[0])) {\n observables = observables[0];\n }\n return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));\n}\nexport class CombineLatestOperator {\n constructor(resultSelector) {\n this.resultSelector = resultSelector;\n }\n call(subscriber, source) {\n return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));\n }\n}\nexport class CombineLatestSubscriber extends OuterSubscriber {\n constructor(destination, resultSelector) {\n super(destination);\n this.resultSelector = resultSelector;\n this.active = 0;\n this.values = [];\n this.observables = [];\n }\n _next(observable) {\n this.values.push(NONE);\n this.observables.push(observable);\n }\n _complete() {\n const observables = this.observables;\n const len = observables.length;\n if (len === 0) {\n this.destination.complete();\n } else {\n this.active = len;\n this.toRespond = len;\n for (let i = 0; i < len; i++) {\n const observable = observables[i];\n this.add(subscribeToResult(this, observable, observable, i));\n }\n }\n }\n notifyComplete(unused) {\n if ((this.active -= 1) === 0) {\n this.destination.complete();\n }\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n const values = this.values;\n const oldVal = values[outerIndex];\n const toRespond = !this.toRespond ? 0 : oldVal === NONE ? --this.toRespond : this.toRespond;\n values[outerIndex] = innerValue;\n if (toRespond === 0) {\n if (this.resultSelector) {\n this._tryResultSelector(values);\n } else {\n this.destination.next(values.slice());\n }\n }\n }\n _tryResultSelector(values) {\n let result;\n try {\n result = this.resultSelector.apply(this, values);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function scheduleObservable(input, scheduler) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) {\n sub.add(scheduler.schedule(() => subscriber.next(value)));\n },\n error(err) {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n },\n complete() {\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nexport function schedulePromise(input, scheduler) {\n return new Observable(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n }, err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n })));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nexport function scheduleIterable(input, scheduler) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(subscriber => {\n const sub = new Subscription();\n let iterator;\n sub.add(() => {\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value;\n let done;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { observable as Symbol_observable } from '../symbol/observable';\nexport function isInteropObservable(input) {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\nexport function isIterable(input) {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nexport function scheduled(input, scheduler) {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { scheduled } from '../scheduled/scheduled';\nexport function from(input, scheduler) {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","import { subscribeToResult } from '../util/subscribeToResult';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { map } from './map';\nimport { from } from '../observable/from';\nexport function mergeMap(project, resultSelector, concurrent = Number.POSITIVE_INFINITY) {\n if (typeof resultSelector === 'function') {\n return source => source.pipe(mergeMap((a, i) => from(project(a, i)).pipe(map((b, ii) => resultSelector(a, b, i, ii))), concurrent));\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return source => source.lift(new MergeMapOperator(project, concurrent));\n}\nexport class MergeMapOperator {\n constructor(project, concurrent = Number.POSITIVE_INFINITY) {\n this.project = project;\n this.concurrent = concurrent;\n }\n call(observer, source) {\n return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));\n }\n}\nexport class MergeMapSubscriber extends OuterSubscriber {\n constructor(destination, project, concurrent = Number.POSITIVE_INFINITY) {\n super(destination);\n this.project = project;\n this.concurrent = concurrent;\n this.hasCompleted = false;\n this.buffer = [];\n this.active = 0;\n this.index = 0;\n }\n _next(value) {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n _tryNext(value) {\n let result;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.active++;\n this._innerSub(result, value, index);\n }\n _innerSub(ish, value, index) {\n const innerSubscriber = new InnerSubscriber(this, value, index);\n const destination = this.destination;\n destination.add(innerSubscriber);\n const innerSubscription = subscribeToResult(this, ish, undefined, undefined, innerSubscriber);\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n }\n _complete() {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete();\n }\n this.unsubscribe();\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.destination.next(innerValue);\n }\n notifyComplete(innerSub) {\n const buffer = this.buffer;\n this.remove(innerSub);\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift());\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete();\n }\n }\n}\n","import { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nexport function mergeAll(concurrent = Number.POSITIVE_INFINITY) {\n return mergeMap(identity, concurrent);\n}\n","import { mergeAll } from './mergeAll';\nexport function concatAll() {\n return mergeAll(1);\n}\n","import { of } from './of';\nimport { concatAll } from '../operators/concatAll';\nexport function concat(...observables) {\n return concatAll()(of(...observables));\n}\n","import { Observable } from '../Observable';\nimport { from } from './from';\nimport { empty } from './empty';\nexport function defer(observableFactory) {\n return new Observable(subscriber => {\n let input;\n try {\n input = observableFactory();\n } catch (err) {\n subscriber.error(err);\n return undefined;\n }\n const source = input ? from(input) : empty();\n return source.subscribe(subscriber);\n });\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { map } from '../operators/map';\nimport { isObject } from '../util/isObject';\nimport { from } from './from';\nexport function forkJoin(...sources) {\n if (sources.length === 1) {\n const first = sources[0];\n if (isArray(first)) {\n return forkJoinInternal(first, null);\n }\n if (isObject(first) && Object.getPrototypeOf(first) === Object.prototype) {\n const keys = Object.keys(first);\n return forkJoinInternal(keys.map(key => first[key]), keys);\n }\n }\n if (typeof sources[sources.length - 1] === 'function') {\n const resultSelector = sources.pop();\n sources = sources.length === 1 && isArray(sources[0]) ? sources[0] : sources;\n return forkJoinInternal(sources, null).pipe(map(args => resultSelector(...args)));\n }\n return forkJoinInternal(sources, null);\n}\nfunction forkJoinInternal(sources, keys) {\n return new Observable(subscriber => {\n const len = sources.length;\n if (len === 0) {\n subscriber.complete();\n return;\n }\n const values = new Array(len);\n let completed = 0;\n let emitted = 0;\n for (let i = 0; i < len; i++) {\n const source = from(sources[i]);\n let hasValue = false;\n subscriber.add(source.subscribe({\n next: value => {\n if (!hasValue) {\n hasValue = true;\n emitted++;\n }\n values[i] = value;\n },\n error: err => subscriber.error(err),\n complete: () => {\n completed++;\n if (completed === len || !hasValue) {\n if (emitted === len) {\n subscriber.next(keys ? keys.reduce((result, key, i) => (result[key] = values[i], result), {}) : values);\n }\n subscriber.complete();\n }\n }\n }));\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { map } from '../operators/map';\nconst toString = (() => Object.prototype.toString)();\nexport function fromEvent(target, eventName, options, resultSelector) {\n if (isFunction(options)) {\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n return fromEvent(target, eventName, options).pipe(map(args => isArray(args) ? resultSelector(...args) : resultSelector(args)));\n }\n return new Observable(subscriber => {\n function handler(e) {\n if (arguments.length > 1) {\n subscriber.next(Array.prototype.slice.call(arguments));\n } else {\n subscriber.next(e);\n }\n }\n setupSubscription(target, eventName, handler, subscriber, options);\n });\n}\nfunction setupSubscription(sourceObj, eventName, handler, subscriber, options) {\n let unsubscribe;\n if (isEventTarget(sourceObj)) {\n const source = sourceObj;\n sourceObj.addEventListener(eventName, handler, options);\n unsubscribe = () => source.removeEventListener(eventName, handler, options);\n } else if (isJQueryStyleEventEmitter(sourceObj)) {\n const source = sourceObj;\n sourceObj.on(eventName, handler);\n unsubscribe = () => source.off(eventName, handler);\n } else if (isNodeStyleEventEmitter(sourceObj)) {\n const source = sourceObj;\n sourceObj.addListener(eventName, handler);\n unsubscribe = () => source.removeListener(eventName, handler);\n } else if (sourceObj && sourceObj.length) {\n for (let i = 0, len = sourceObj.length; i < len; i++) {\n setupSubscription(sourceObj[i], eventName, handler, subscriber, options);\n }\n } else {\n throw new TypeError('Invalid event target');\n }\n subscriber.add(unsubscribe);\n}\nfunction isNodeStyleEventEmitter(sourceObj) {\n return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';\n}\nfunction isJQueryStyleEventEmitter(sourceObj) {\n return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';\n}\nfunction isEventTarget(sourceObj) {\n return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';\n}\n","import { defer } from './defer';\nimport { EMPTY } from './empty';\nexport function iif(condition, trueResult = EMPTY, falseResult = EMPTY) {\n return defer(() => condition() ? trueResult : falseResult);\n}\n","import { isArray } from './isArray';\nexport function isNumeric(val) {\n return !isArray(val) && val - parseFloat(val) + 1 >= 0;\n}\n","import { Observable } from '../Observable';\nimport { isScheduler } from '../util/isScheduler';\nimport { mergeAll } from '../operators/mergeAll';\nimport { fromArray } from './fromArray';\nexport function merge(...observables) {\n let concurrent = Number.POSITIVE_INFINITY;\n let scheduler = null;\n let last = observables[observables.length - 1];\n if (isScheduler(last)) {\n scheduler = observables.pop();\n if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {\n concurrent = observables.pop();\n }\n } else if (typeof last === 'number') {\n concurrent = observables.pop();\n }\n if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {\n return observables[0];\n }\n return mergeAll(concurrent)(fromArray(observables, scheduler));\n}\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\nexport const NEVER = new Observable(noop);\nexport function never() {\n return NEVER;\n}\n","import { Subscriber } from '../Subscriber';\nexport function filter(predicate, thisArg) {\n return function filterOperatorFunction(source) {\n return source.lift(new FilterOperator(predicate, thisArg));\n };\n}\nclass FilterOperator {\n constructor(predicate, thisArg) {\n this.predicate = predicate;\n this.thisArg = thisArg;\n }\n call(subscriber, source) {\n return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n }\n}\nclass FilterSubscriber extends Subscriber {\n constructor(destination, predicate, thisArg) {\n super(destination);\n this.predicate = predicate;\n this.thisArg = thisArg;\n this.count = 0;\n }\n _next(value) {\n let result;\n try {\n result = this.predicate.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n if (result) {\n this.destination.next(value);\n }\n }\n}\n","import { isArray } from '../util/isArray';\nimport { fromArray } from './fromArray';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nexport function race(...observables) {\n if (observables.length === 1) {\n if (isArray(observables[0])) {\n observables = observables[0];\n } else {\n return observables[0];\n }\n }\n return fromArray(observables, undefined).lift(new RaceOperator());\n}\nexport class RaceOperator {\n call(subscriber, source) {\n return source.subscribe(new RaceSubscriber(subscriber));\n }\n}\nexport class RaceSubscriber extends OuterSubscriber {\n constructor(destination) {\n super(destination);\n this.hasFirst = false;\n this.observables = [];\n this.subscriptions = [];\n }\n _next(observable) {\n this.observables.push(observable);\n }\n _complete() {\n const observables = this.observables;\n const len = observables.length;\n if (len === 0) {\n this.destination.complete();\n } else {\n for (let i = 0; i < len && !this.hasFirst; i++) {\n let observable = observables[i];\n let subscription = subscribeToResult(this, observable, observable, i);\n if (this.subscriptions) {\n this.subscriptions.push(subscription);\n }\n this.add(subscription);\n }\n this.observables = null;\n }\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n if (!this.hasFirst) {\n this.hasFirst = true;\n for (let i = 0; i < this.subscriptions.length; i++) {\n if (i !== outerIndex) {\n let subscription = this.subscriptions[i];\n subscription.unsubscribe();\n this.remove(subscription);\n }\n }\n this.subscriptions = null;\n }\n this.destination.next(innerValue);\n }\n}\n","import { Observable } from '../Observable';\nimport { async } from '../scheduler/async';\nimport { isNumeric } from '../util/isNumeric';\nimport { isScheduler } from '../util/isScheduler';\nexport function timer(dueTime = 0, periodOrScheduler, scheduler) {\n let period = -1;\n if (isNumeric(periodOrScheduler)) {\n period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);\n } else if (isScheduler(periodOrScheduler)) {\n scheduler = periodOrScheduler;\n }\n if (!isScheduler(scheduler)) {\n scheduler = async;\n }\n return new Observable(subscriber => {\n const due = isNumeric(dueTime) ? dueTime : +dueTime - scheduler.now();\n return scheduler.schedule(dispatch, due, {\n index: 0,\n period,\n subscriber\n });\n });\n}\nfunction dispatch(state) {\n const {\n index,\n period,\n subscriber\n } = state;\n subscriber.next(index);\n if (subscriber.closed) {\n return;\n } else if (period === -1) {\n return subscriber.complete();\n }\n state.index = index + 1;\n this.schedule(state, period);\n}\n","import { fromArray } from './fromArray';\nimport { isArray } from '../util/isArray';\nimport { Subscriber } from '../Subscriber';\nimport { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { iterator as Symbol_iterator } from '../../internal/symbol/iterator';\nexport function zip(...observables) {\n const resultSelector = observables[observables.length - 1];\n if (typeof resultSelector === 'function') {\n observables.pop();\n }\n return fromArray(observables, undefined).lift(new ZipOperator(resultSelector));\n}\nexport class ZipOperator {\n constructor(resultSelector) {\n this.resultSelector = resultSelector;\n }\n call(subscriber, source) {\n return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));\n }\n}\nexport class ZipSubscriber extends Subscriber {\n constructor(destination, resultSelector, values = Object.create(null)) {\n super(destination);\n this.iterators = [];\n this.active = 0;\n this.resultSelector = typeof resultSelector === 'function' ? resultSelector : null;\n this.values = values;\n }\n _next(value) {\n const iterators = this.iterators;\n if (isArray(value)) {\n iterators.push(new StaticArrayIterator(value));\n } else if (typeof value[Symbol_iterator] === 'function') {\n iterators.push(new StaticIterator(value[Symbol_iterator]()));\n } else {\n iterators.push(new ZipBufferIterator(this.destination, this, value));\n }\n }\n _complete() {\n const iterators = this.iterators;\n const len = iterators.length;\n this.unsubscribe();\n if (len === 0) {\n this.destination.complete();\n return;\n }\n this.active = len;\n for (let i = 0; i < len; i++) {\n let iterator = iterators[i];\n if (iterator.stillUnsubscribed) {\n const destination = this.destination;\n destination.add(iterator.subscribe(iterator, i));\n } else {\n this.active--;\n }\n }\n }\n notifyInactive() {\n this.active--;\n if (this.active === 0) {\n this.destination.complete();\n }\n }\n checkIterators() {\n const iterators = this.iterators;\n const len = iterators.length;\n const destination = this.destination;\n for (let i = 0; i < len; i++) {\n let iterator = iterators[i];\n if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {\n return;\n }\n }\n let shouldComplete = false;\n const args = [];\n for (let i = 0; i < len; i++) {\n let iterator = iterators[i];\n let result = iterator.next();\n if (iterator.hasCompleted()) {\n shouldComplete = true;\n }\n if (result.done) {\n destination.complete();\n return;\n }\n args.push(result.value);\n }\n if (this.resultSelector) {\n this._tryresultSelector(args);\n } else {\n destination.next(args);\n }\n if (shouldComplete) {\n destination.complete();\n }\n }\n _tryresultSelector(args) {\n let result;\n try {\n result = this.resultSelector.apply(this, args);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\nclass StaticIterator {\n constructor(iterator) {\n this.iterator = iterator;\n this.nextResult = iterator.next();\n }\n hasValue() {\n return true;\n }\n next() {\n const result = this.nextResult;\n this.nextResult = this.iterator.next();\n return result;\n }\n hasCompleted() {\n const nextResult = this.nextResult;\n return nextResult && nextResult.done;\n }\n}\nclass StaticArrayIterator {\n constructor(array) {\n this.array = array;\n this.index = 0;\n this.length = 0;\n this.length = array.length;\n }\n [Symbol_iterator]() {\n return this;\n }\n next(value) {\n const i = this.index++;\n const array = this.array;\n return i < this.length ? {\n value: array[i],\n done: false\n } : {\n value: null,\n done: true\n };\n }\n hasValue() {\n return this.array.length > this.index;\n }\n hasCompleted() {\n return this.array.length === this.index;\n }\n}\nclass ZipBufferIterator extends OuterSubscriber {\n constructor(destination, parent, observable) {\n super(destination);\n this.parent = parent;\n this.observable = observable;\n this.stillUnsubscribed = true;\n this.buffer = [];\n this.isComplete = false;\n }\n [Symbol_iterator]() {\n return this;\n }\n next() {\n const buffer = this.buffer;\n if (buffer.length === 0 && this.isComplete) {\n return {\n value: null,\n done: true\n };\n } else {\n return {\n value: buffer.shift(),\n done: false\n };\n }\n }\n hasValue() {\n return this.buffer.length > 0;\n }\n hasCompleted() {\n return this.buffer.length === 0 && this.isComplete;\n }\n notifyComplete() {\n if (this.buffer.length > 0) {\n this.isComplete = true;\n this.parent.notifyInactive();\n } else {\n this.destination.complete();\n }\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.buffer.push(innerValue);\n this.parent.checkIterators();\n }\n subscribe(value, index) {\n return subscribeToResult(this, this.observable, this, index);\n }\n}\n","import { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nexport function catchError(selector) {\n return function catchErrorOperatorFunction(source) {\n const operator = new CatchOperator(selector);\n const caught = source.lift(operator);\n return operator.caught = caught;\n };\n}\nclass CatchOperator {\n constructor(selector) {\n this.selector = selector;\n }\n call(subscriber, source) {\n return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n }\n}\nclass CatchSubscriber extends OuterSubscriber {\n constructor(destination, selector, caught) {\n super(destination);\n this.selector = selector;\n this.caught = caught;\n }\n error(err) {\n if (!this.isStopped) {\n let result;\n try {\n result = this.selector(err, this.caught);\n } catch (err2) {\n super.error(err2);\n return;\n }\n this._unsubscribeAndRecycle();\n const innerSubscriber = new InnerSubscriber(this, undefined, undefined);\n this.add(innerSubscriber);\n const innerSubscription = subscribeToResult(this, result, undefined, undefined, innerSubscriber);\n if (innerSubscription !== innerSubscriber) {\n this.add(innerSubscription);\n }\n }\n }\n}\n","import { mergeMap } from './mergeMap';\nexport function concatMap(project, resultSelector) {\n return mergeMap(project, resultSelector, 1);\n}\n","import { Subscriber } from '../Subscriber';\nexport function defaultIfEmpty(defaultValue = null) {\n return source => source.lift(new DefaultIfEmptyOperator(defaultValue));\n}\nclass DefaultIfEmptyOperator {\n constructor(defaultValue) {\n this.defaultValue = defaultValue;\n }\n call(subscriber, source) {\n return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));\n }\n}\nclass DefaultIfEmptySubscriber extends Subscriber {\n constructor(destination, defaultValue) {\n super(destination);\n this.defaultValue = defaultValue;\n this.isEmpty = true;\n }\n _next(value) {\n this.isEmpty = false;\n this.destination.next(value);\n }\n _complete() {\n if (this.isEmpty) {\n this.destination.next(this.defaultValue);\n }\n this.destination.complete();\n }\n}\n","export function isDate(value) {\n return value instanceof Date && !isNaN(+value);\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Subscriber } from '../Subscriber';\nimport { Notification } from '../Notification';\nexport function delay(delay, scheduler = async) {\n const absoluteDelay = isDate(delay);\n const delayFor = absoluteDelay ? +delay - scheduler.now() : Math.abs(delay);\n return source => source.lift(new DelayOperator(delayFor, scheduler));\n}\nclass DelayOperator {\n constructor(delay, scheduler) {\n this.delay = delay;\n this.scheduler = scheduler;\n }\n call(subscriber, source) {\n return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n }\n}\nclass DelaySubscriber extends Subscriber {\n constructor(destination, delay, scheduler) {\n super(destination);\n this.delay = delay;\n this.scheduler = scheduler;\n this.queue = [];\n this.active = false;\n this.errored = false;\n }\n static dispatch(state) {\n const source = state.source;\n const queue = source.queue;\n const scheduler = state.scheduler;\n const destination = state.destination;\n while (queue.length > 0 && queue[0].time - scheduler.now() <= 0) {\n queue.shift().notification.observe(destination);\n }\n if (queue.length > 0) {\n const delay = Math.max(0, queue[0].time - scheduler.now());\n this.schedule(state, delay);\n } else {\n this.unsubscribe();\n source.active = false;\n }\n }\n _schedule(scheduler) {\n this.active = true;\n const destination = this.destination;\n destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {\n source: this,\n destination: this.destination,\n scheduler: scheduler\n }));\n }\n scheduleNotification(notification) {\n if (this.errored === true) {\n return;\n }\n const scheduler = this.scheduler;\n const message = new DelayMessage(scheduler.now() + this.delay, notification);\n this.queue.push(message);\n if (this.active === false) {\n this._schedule(scheduler);\n }\n }\n _next(value) {\n this.scheduleNotification(Notification.createNext(value));\n }\n _error(err) {\n this.errored = true;\n this.queue = [];\n this.destination.error(err);\n this.unsubscribe();\n }\n _complete() {\n this.scheduleNotification(Notification.createComplete());\n this.unsubscribe();\n }\n}\nclass DelayMessage {\n constructor(time, notification) {\n this.time = time;\n this.notification = notification;\n }\n}\n","import { Subscriber } from '../Subscriber';\nexport function distinctUntilChanged(compare, keySelector) {\n return source => source.lift(new DistinctUntilChangedOperator(compare, keySelector));\n}\nclass DistinctUntilChangedOperator {\n constructor(compare, keySelector) {\n this.compare = compare;\n this.keySelector = keySelector;\n }\n call(subscriber, source) {\n return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n }\n}\nclass DistinctUntilChangedSubscriber extends Subscriber {\n constructor(destination, compare, keySelector) {\n super(destination);\n this.keySelector = keySelector;\n this.hasKey = false;\n if (typeof compare === 'function') {\n this.compare = compare;\n }\n }\n compare(x, y) {\n return x === y;\n }\n _next(value) {\n let key;\n try {\n const {\n keySelector\n } = this;\n key = keySelector ? keySelector(value) : value;\n } catch (err) {\n return this.destination.error(err);\n }\n let result = false;\n if (this.hasKey) {\n try {\n const {\n compare\n } = this;\n result = compare(this.key, key);\n } catch (err) {\n return this.destination.error(err);\n }\n } else {\n this.hasKey = true;\n }\n if (!result) {\n this.key = key;\n this.destination.next(value);\n }\n }\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { Subscriber } from '../Subscriber';\nexport function throwIfEmpty(errorFactory = defaultErrorFactory) {\n return source => {\n return source.lift(new ThrowIfEmptyOperator(errorFactory));\n };\n}\nclass ThrowIfEmptyOperator {\n constructor(errorFactory) {\n this.errorFactory = errorFactory;\n }\n call(subscriber, source) {\n return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));\n }\n}\nclass ThrowIfEmptySubscriber extends Subscriber {\n constructor(destination, errorFactory) {\n super(destination);\n this.errorFactory = errorFactory;\n this.hasValue = false;\n }\n _next(value) {\n this.hasValue = true;\n this.destination.next(value);\n }\n _complete() {\n if (!this.hasValue) {\n let err;\n try {\n err = this.errorFactory();\n } catch (e) {\n err = e;\n }\n this.destination.error(err);\n } else {\n return this.destination.complete();\n }\n }\n}\nfunction defaultErrorFactory() {\n return new EmptyError();\n}\n","import { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nexport function take(count) {\n return source => {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeOperator(count));\n }\n };\n}\nclass TakeOperator {\n constructor(total) {\n this.total = total;\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError();\n }\n }\n call(subscriber, source) {\n return source.subscribe(new TakeSubscriber(subscriber, this.total));\n }\n}\nclass TakeSubscriber extends Subscriber {\n constructor(destination, total) {\n super(destination);\n this.total = total;\n this.count = 0;\n }\n _next(value) {\n const total = this.total;\n const count = ++this.count;\n if (count <= total) {\n this.destination.next(value);\n if (count === total) {\n this.destination.complete();\n this.unsubscribe();\n }\n }\n }\n}\n","import { concat } from '../observable/concat';\nimport { of } from '../observable/of';\nexport function endWith(...array) {\n return source => concat(source, of(...array));\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nexport function finalize(callback) {\n return source => source.lift(new FinallyOperator(callback));\n}\nclass FinallyOperator {\n constructor(callback) {\n this.callback = callback;\n }\n call(subscriber, source) {\n return source.subscribe(new FinallySubscriber(subscriber, this.callback));\n }\n}\nclass FinallySubscriber extends Subscriber {\n constructor(destination, callback) {\n super(destination);\n this.add(new Subscription(callback));\n }\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\nexport function first(predicate, defaultValue) {\n const hasDefaultValue = arguments.length >= 2;\n return source => source.pipe(predicate ? filter((v, i) => predicate(v, i, source)) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(() => new EmptyError()));\n}\n","import { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nexport function takeLast(count) {\n return function takeLastOperatorFunction(source) {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeLastOperator(count));\n }\n };\n}\nclass TakeLastOperator {\n constructor(total) {\n this.total = total;\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError();\n }\n }\n call(subscriber, source) {\n return source.subscribe(new TakeLastSubscriber(subscriber, this.total));\n }\n}\nclass TakeLastSubscriber extends Subscriber {\n constructor(destination, total) {\n super(destination);\n this.total = total;\n this.ring = new Array();\n this.count = 0;\n }\n _next(value) {\n const ring = this.ring;\n const total = this.total;\n const count = this.count++;\n if (ring.length < total) {\n ring.push(value);\n } else {\n const index = count % total;\n ring[index] = value;\n }\n }\n _complete() {\n const destination = this.destination;\n let count = this.count;\n if (count > 0) {\n const total = this.count >= this.total ? this.total : this.count;\n const ring = this.ring;\n for (let i = 0; i < total; i++) {\n const idx = count++ % total;\n destination.next(ring[idx]);\n }\n }\n destination.complete();\n }\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { filter } from './filter';\nimport { takeLast } from './takeLast';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { identity } from '../util/identity';\nexport function last(predicate, defaultValue) {\n const hasDefaultValue = arguments.length >= 2;\n return source => source.pipe(predicate ? filter((v, i) => predicate(v, i, source)) : identity, takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(() => new EmptyError()));\n}\n","import { Subscriber } from '../Subscriber';\nexport function mapTo(value) {\n return source => source.lift(new MapToOperator(value));\n}\nclass MapToOperator {\n constructor(value) {\n this.value = value;\n }\n call(subscriber, source) {\n return source.subscribe(new MapToSubscriber(subscriber, this.value));\n }\n}\nclass MapToSubscriber extends Subscriber {\n constructor(destination, value) {\n super(destination);\n this.value = value;\n }\n _next(x) {\n this.destination.next(this.value);\n }\n}\n","import { Subscriber } from '../Subscriber';\nexport function scan(accumulator, seed) {\n let hasSeed = false;\n if (arguments.length >= 2) {\n hasSeed = true;\n }\n return function scanOperatorFunction(source) {\n return source.lift(new ScanOperator(accumulator, seed, hasSeed));\n };\n}\nclass ScanOperator {\n constructor(accumulator, seed, hasSeed = false) {\n this.accumulator = accumulator;\n this.seed = seed;\n this.hasSeed = hasSeed;\n }\n call(subscriber, source) {\n return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));\n }\n}\nclass ScanSubscriber extends Subscriber {\n constructor(destination, accumulator, _seed, hasSeed) {\n super(destination);\n this.accumulator = accumulator;\n this._seed = _seed;\n this.hasSeed = hasSeed;\n this.index = 0;\n }\n get seed() {\n return this._seed;\n }\n set seed(value) {\n this.hasSeed = true;\n this._seed = value;\n }\n _next(value) {\n if (!this.hasSeed) {\n this.seed = value;\n this.destination.next(value);\n } else {\n return this._tryNext(value);\n }\n }\n _tryNext(value) {\n const index = this.index++;\n let result;\n try {\n result = this.accumulator(this.seed, value, index);\n } catch (err) {\n this.destination.error(err);\n }\n this.seed = result;\n this.destination.next(result);\n }\n}\n","import { map } from './map';\nexport function pluck(...properties) {\n const length = properties.length;\n if (length === 0) {\n throw new Error('list of properties cannot be empty.');\n }\n return source => map(plucker(properties, length))(source);\n}\nfunction plucker(props, length) {\n const mapper = x => {\n let currentProp = x;\n for (let i = 0; i < length; i++) {\n const p = currentProp[props[i]];\n if (typeof p !== 'undefined') {\n currentProp = p;\n } else {\n return undefined;\n }\n }\n return currentProp;\n };\n return mapper;\n}\n","import { ReplaySubject } from '../ReplaySubject';\nexport function shareReplay(configOrBufferSize, windowTime, scheduler) {\n let config;\n if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n config = configOrBufferSize;\n } else {\n config = {\n bufferSize: configOrBufferSize,\n windowTime,\n refCount: false,\n scheduler\n };\n }\n return source => source.lift(shareReplayOperator(config));\n}\nfunction shareReplayOperator({\n bufferSize = Number.POSITIVE_INFINITY,\n windowTime = Number.POSITIVE_INFINITY,\n refCount: useRefCount,\n scheduler\n}) {\n let subject;\n let refCount = 0;\n let subscription;\n let hasError = false;\n let isComplete = false;\n return function shareReplayOperation(source) {\n refCount++;\n if (!subject || hasError) {\n hasError = false;\n subject = new ReplaySubject(bufferSize, windowTime, scheduler);\n subscription = source.subscribe({\n next(value) {\n subject.next(value);\n },\n error(err) {\n hasError = true;\n subject.error(err);\n },\n complete() {\n isComplete = true;\n subscription = undefined;\n subject.complete();\n }\n });\n }\n const innerSub = subject.subscribe(this);\n this.add(() => {\n refCount--;\n innerSub.unsubscribe();\n if (subscription && !isComplete && useRefCount && refCount === 0) {\n subscription.unsubscribe();\n subscription = undefined;\n subject = undefined;\n }\n });\n };\n}\n","import { Subscriber } from '../Subscriber';\nexport function skip(count) {\n return source => source.lift(new SkipOperator(count));\n}\nclass SkipOperator {\n constructor(total) {\n this.total = total;\n }\n call(subscriber, source) {\n return source.subscribe(new SkipSubscriber(subscriber, this.total));\n }\n}\nclass SkipSubscriber extends Subscriber {\n constructor(destination, total) {\n super(destination);\n this.total = total;\n this.count = 0;\n }\n _next(x) {\n if (++this.count > this.total) {\n this.destination.next(x);\n }\n }\n}\n","import { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nexport function startWith(...array) {\n const scheduler = array[array.length - 1];\n if (isScheduler(scheduler)) {\n array.pop();\n return source => concat(array, source, scheduler);\n } else {\n return source => concat(array, source);\n }\n}\n","import { OuterSubscriber } from '../OuterSubscriber';\nimport { InnerSubscriber } from '../InnerSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nimport { map } from './map';\nimport { from } from '../observable/from';\nexport function switchMap(project, resultSelector) {\n if (typeof resultSelector === 'function') {\n return source => source.pipe(switchMap((a, i) => from(project(a, i)).pipe(map((b, ii) => resultSelector(a, b, i, ii)))));\n }\n return source => source.lift(new SwitchMapOperator(project));\n}\nclass SwitchMapOperator {\n constructor(project) {\n this.project = project;\n }\n call(subscriber, source) {\n return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n }\n}\nclass SwitchMapSubscriber extends OuterSubscriber {\n constructor(destination, project) {\n super(destination);\n this.project = project;\n this.index = 0;\n }\n _next(value) {\n let result;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (error) {\n this.destination.error(error);\n return;\n }\n this._innerSub(result, value, index);\n }\n _innerSub(result, value, index) {\n const innerSubscription = this.innerSubscription;\n if (innerSubscription) {\n innerSubscription.unsubscribe();\n }\n const innerSubscriber = new InnerSubscriber(this, value, index);\n const destination = this.destination;\n destination.add(innerSubscriber);\n this.innerSubscription = subscribeToResult(this, result, undefined, undefined, innerSubscriber);\n if (this.innerSubscription !== innerSubscriber) {\n destination.add(this.innerSubscription);\n }\n }\n _complete() {\n const {\n innerSubscription\n } = this;\n if (!innerSubscription || innerSubscription.closed) {\n super._complete();\n }\n this.unsubscribe();\n }\n _unsubscribe() {\n this.innerSubscription = null;\n }\n notifyComplete(innerSub) {\n const destination = this.destination;\n destination.remove(innerSub);\n this.innerSubscription = null;\n if (this.isStopped) {\n super._complete();\n }\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.destination.next(innerValue);\n }\n}\n","import { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nexport function takeUntil(notifier) {\n return source => source.lift(new TakeUntilOperator(notifier));\n}\nclass TakeUntilOperator {\n constructor(notifier) {\n this.notifier = notifier;\n }\n call(subscriber, source) {\n const takeUntilSubscriber = new TakeUntilSubscriber(subscriber);\n const notifierSubscription = subscribeToResult(takeUntilSubscriber, this.notifier);\n if (notifierSubscription && !takeUntilSubscriber.seenValue) {\n takeUntilSubscriber.add(notifierSubscription);\n return source.subscribe(takeUntilSubscriber);\n }\n return takeUntilSubscriber;\n }\n}\nclass TakeUntilSubscriber extends OuterSubscriber {\n constructor(destination) {\n super(destination);\n this.seenValue = false;\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.seenValue = true;\n this.complete();\n }\n notifyComplete() {}\n}\n","import { Subscriber } from '../Subscriber';\nimport { noop } from '../util/noop';\nimport { isFunction } from '../util/isFunction';\nexport function tap(nextOrObserver, error, complete) {\n return function tapOperatorFunction(source) {\n return source.lift(new DoOperator(nextOrObserver, error, complete));\n };\n}\nclass DoOperator {\n constructor(nextOrObserver, error, complete) {\n this.nextOrObserver = nextOrObserver;\n this.error = error;\n this.complete = complete;\n }\n call(subscriber, source) {\n return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n }\n}\nclass TapSubscriber extends Subscriber {\n constructor(destination, observerOrNext, error, complete) {\n super(destination);\n this._tapNext = noop;\n this._tapError = noop;\n this._tapComplete = noop;\n this._tapError = error || noop;\n this._tapComplete = complete || noop;\n if (isFunction(observerOrNext)) {\n this._context = this;\n this._tapNext = observerOrNext;\n } else if (observerOrNext) {\n this._context = observerOrNext;\n this._tapNext = observerOrNext.next || noop;\n this._tapError = observerOrNext.error || noop;\n this._tapComplete = observerOrNext.complete || noop;\n }\n }\n _next(value) {\n try {\n this._tapNext.call(this._context, value);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(value);\n }\n _error(err) {\n try {\n this._tapError.call(this._context, err);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.error(err);\n }\n _complete() {\n try {\n this._tapComplete.call(this._context);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n return this.destination.complete();\n }\n}\n","import { OuterSubscriber } from '../OuterSubscriber';\nimport { subscribeToResult } from '../util/subscribeToResult';\nexport function withLatestFrom(...args) {\n return source => {\n let project;\n if (typeof args[args.length - 1] === 'function') {\n project = args.pop();\n }\n const observables = args;\n return source.lift(new WithLatestFromOperator(observables, project));\n };\n}\nclass WithLatestFromOperator {\n constructor(observables, project) {\n this.observables = observables;\n this.project = project;\n }\n call(subscriber, source) {\n return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));\n }\n}\nclass WithLatestFromSubscriber extends OuterSubscriber {\n constructor(destination, observables, project) {\n super(destination);\n this.observables = observables;\n this.project = project;\n this.toRespond = [];\n const len = observables.length;\n this.values = new Array(len);\n for (let i = 0; i < len; i++) {\n this.toRespond.push(i);\n }\n for (let i = 0; i < len; i++) {\n let observable = observables[i];\n this.add(subscribeToResult(this, observable, observable, i));\n }\n }\n notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {\n this.values[outerIndex] = innerValue;\n const toRespond = this.toRespond;\n if (toRespond.length > 0) {\n const found = toRespond.indexOf(outerIndex);\n if (found !== -1) {\n toRespond.splice(found, 1);\n }\n }\n }\n notifyComplete() {}\n _next(value) {\n if (this.toRespond.length === 0) {\n const args = [value, ...this.values];\n if (this.project) {\n this._tryProject(args);\n } else {\n this.destination.next(args);\n }\n }\n }\n _tryProject(args) {\n let result;\n try {\n result = this.project.apply(this, args);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","/**\n * @license Angular v18.2.4\n * (c) 2010-2024 Google LLC. https://angular.io/\n * License: MIT\n */\n\nconst Attribute = {\n /**\n * The jsaction attribute defines a mapping of a DOM event to a\n * generic event (aka jsaction), to which the actual event handlers\n * that implement the behavior of the application are bound. The\n * value is a semicolon separated list of colon separated pairs of\n * an optional DOM event name and a jsaction name. If the optional\n * DOM event name is omitted, 'click' is assumed. The jsaction names\n * are dot separated pairs of a namespace and a simple jsaction\n * name.\n *\n * See grammar in README.md for expected syntax in the attribute value.\n */\n JSACTION: 'jsaction'\n};\n\n/** All properties that are used by jsaction. */\nconst Property = {\n /**\n * The parsed value of the jsaction attribute is stored in this\n * property on the DOM node. The parsed value is an Object. The\n * property names of the object are the events; the values are the\n * names of the actions. This property is attached even on nodes\n * that don't have a jsaction attribute as an optimization, because\n * property lookup is faster than attribute access.\n */\n JSACTION: '__jsaction',\n /**\n * The owner property references an a logical owner for a DOM node. JSAction\n * will follow this reference instead of parentNode when traversing the DOM\n * to find jsaction attributes. This allows overlaying a logical structure\n * over a document where the DOM structure can't reflect that structure.\n */\n OWNER: '__owner'\n};\n\n/**\n * Map from jsaction annotation to a parsed map from event name to action name.\n */\nconst parseCache = {};\n/**\n * Reads the jsaction parser cache from the given DOM Element.\n */\nfunction get(element) {\n return element[Property.JSACTION];\n}\n/**\n * Reads the jsaction parser cache for the given DOM element. If no cache is yet present,\n * creates an empty one.\n */\nfunction getDefaulted(element) {\n const cache = get(element) ?? {};\n set(element, cache);\n return cache;\n}\n/**\n * Writes the jsaction parser cache to the given DOM Element.\n */\nfunction set(element, actionMap) {\n element[Property.JSACTION] = actionMap;\n}\n/**\n * Looks up the parsed action map from the source jsaction attribute value.\n *\n * @param text Unparsed jsaction attribute value.\n * @return Parsed jsaction attribute value, if already present in the cache.\n */\nfunction getParsed(text) {\n return parseCache[text];\n}\n/**\n * Inserts the parse result for the given source jsaction value into the cache.\n *\n * @param text Unparsed jsaction attribute value.\n * @param parsed Attribute value parsed into the action map.\n */\nfunction setParsed(text, parsed) {\n parseCache[text] = parsed;\n}\n/**\n * Clears the jsaction parser cache from the given DOM Element.\n *\n * @param element .\n */\nfunction clear(element) {\n if (Property.JSACTION in element) {\n delete element[Property.JSACTION];\n }\n}\n\n/*\n * Names of events that are special to jsaction. These are not all\n * event types that are legal to use in either HTML or the addEvent()\n * API, but these are the ones that are treated specially. All other\n * DOM events can be used in either addEvent() or in the value of the\n * jsaction attribute. Beware of browser specific events or events\n * that don't bubble though: If they are not mentioned here, then\n * event contract doesn't work around their peculiarities.\n */\nconst EventType = {\n /**\n * Mouse middle click, introduced in Chrome 55 and not yet supported on\n * other browsers.\n */\n AUXCLICK: 'auxclick',\n /**\n * The change event fired by browsers when the `value` attribute of input,\n * select, and textarea elements are changed.\n */\n CHANGE: 'change',\n /**\n * The click event. In addEvent() refers to all click events, in the\n * jsaction attribute it refers to the unmodified click and Enter/Space\n * keypress events. In the latter case, a jsaction click will be triggered,\n * for accessibility reasons. See clickmod and clickonly, below.\n */\n CLICK: 'click',\n /**\n * Specifies the jsaction for a modified click event (i.e. a mouse\n * click with the modifier key Cmd/Ctrl pressed). This event isn't\n * separately enabled in addEvent(), because in the DOM, it's just a\n * click event.\n */\n CLICKMOD: 'clickmod',\n /**\n * Specifies the jsaction for a click-only event. Click-only doesn't take\n * into account the case where an element with focus receives an Enter/Space\n * keypress. This event isn't separately enabled in addEvent().\n */\n CLICKONLY: 'clickonly',\n /**\n * The dblclick event.\n */\n DBLCLICK: 'dblclick',\n /**\n * Focus doesn't bubble, but you can use it in addEvent() and\n * jsaction anyway. EventContract does the right thing under the\n * hood.\n */\n FOCUS: 'focus',\n /**\n * This event only exists in IE. For addEvent() and jsaction, use\n * focus instead; EventContract does the right thing even though\n * focus doesn't bubble.\n */\n FOCUSIN: 'focusin',\n /**\n * Analog to focus.\n */\n BLUR: 'blur',\n /**\n * Analog to focusin.\n */\n FOCUSOUT: 'focusout',\n /**\n * Submit doesn't bubble, so it cannot be used with event\n * contract. However, the browser helpfully fires a click event on\n * the submit button of a form (even if the form is not submitted by\n * a click on the submit button). So you should handle click on the\n * submit button instead.\n */\n SUBMIT: 'submit',\n /**\n * The keydown event. In addEvent() and non-click jsaction it represents the\n * regular DOM keydown event. It represents click actions in non-Gecko\n * browsers.\n */\n KEYDOWN: 'keydown',\n /**\n * The keypress event. In addEvent() and non-click jsaction it represents the\n * regular DOM keypress event. It represents click actions in Gecko browsers.\n */\n KEYPRESS: 'keypress',\n /**\n * The keyup event. In addEvent() and non-click jsaction it represents the\n * regular DOM keyup event. It represents click actions in non-Gecko\n * browsers.\n */\n KEYUP: 'keyup',\n /**\n * The mouseup event. Can either be used directly or used implicitly to\n * capture mouseup events. In addEvent(), it represents a regular DOM\n * mouseup event.\n */\n MOUSEUP: 'mouseup',\n /**\n * The mousedown event. Can either be used directly or used implicitly to\n * capture mouseenter events. In addEvent(), it represents a regular DOM\n * mouseover event.\n */\n MOUSEDOWN: 'mousedown',\n /**\n * The mouseover event. Can either be used directly or used implicitly to\n * capture mouseenter events. In addEvent(), it represents a regular DOM\n * mouseover event.\n */\n MOUSEOVER: 'mouseover',\n /**\n * The mouseout event. Can either be used directly or used implicitly to\n * capture mouseover events. In addEvent(), it represents a regular DOM\n * mouseout event.\n */\n MOUSEOUT: 'mouseout',\n /**\n * The mouseenter event. Does not bubble and fires individually on each\n * element being entered within a DOM tree.\n */\n MOUSEENTER: 'mouseenter',\n /**\n * The mouseleave event. Does not bubble and fires individually on each\n * element being entered within a DOM tree.\n */\n MOUSELEAVE: 'mouseleave',\n /**\n * The mousemove event.\n */\n MOUSEMOVE: 'mousemove',\n /**\n * The pointerup event. Can either be used directly or used implicitly to\n * capture pointerup events. In addEvent(), it represents a regular DOM\n * pointerup event.\n */\n POINTERUP: 'pointerup',\n /**\n * The pointerdown event. Can either be used directly or used implicitly to\n * capture pointerenter events. In addEvent(), it represents a regular DOM\n * mouseover event.\n */\n POINTERDOWN: 'pointerdown',\n /**\n * The pointerover event. Can either be used directly or used implicitly to\n * capture pointerenter events. In addEvent(), it represents a regular DOM\n * pointerover event.\n */\n POINTEROVER: 'pointerover',\n /**\n * The pointerout event. Can either be used directly or used implicitly to\n * capture pointerover events. In addEvent(), it represents a regular DOM\n * pointerout event.\n */\n POINTEROUT: 'pointerout',\n /**\n * The pointerenter event. Does not bubble and fires individually on each\n * element being entered within a DOM tree.\n */\n POINTERENTER: 'pointerenter',\n /**\n * The pointerleave event. Does not bubble and fires individually on each\n * element being entered within a DOM tree.\n */\n POINTERLEAVE: 'pointerleave',\n /**\n * The pointermove event.\n */\n POINTERMOVE: 'pointermove',\n /**\n * The pointercancel event.\n */\n POINTERCANCEL: 'pointercancel',\n /**\n * The gotpointercapture event is fired when\n * Element.setPointerCapture(pointerId) is called on a mouse input, or\n * implicitly when a touch input begins.\n */\n GOTPOINTERCAPTURE: 'gotpointercapture',\n /**\n * The lostpointercapture event is fired when\n * Element.releasePointerCapture(pointerId) is called, or implicitly after a\n * touch input ends.\n */\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n /**\n * The error event. The error event doesn't bubble, but you can use it in\n * addEvent() and jsaction anyway. EventContract does the right thing under\n * the hood (except in IE8 which does not use error events).\n */\n ERROR: 'error',\n /**\n * The load event. The load event doesn't bubble, but you can use it in\n * addEvent() and jsaction anyway. EventContract does the right thing\n * under the hood.\n */\n LOAD: 'load',\n /**\n * The unload event.\n */\n UNLOAD: 'unload',\n /**\n * The touchstart event. Bubbles, will only ever fire in browsers with\n * touch support.\n */\n TOUCHSTART: 'touchstart',\n /**\n * The touchend event. Bubbles, will only ever fire in browsers with\n * touch support.\n */\n TOUCHEND: 'touchend',\n /**\n * The touchmove event. Bubbles, will only ever fire in browsers with\n * touch support.\n */\n TOUCHMOVE: 'touchmove',\n /**\n * The input event.\n */\n INPUT: 'input',\n /**\n * The scroll event.\n */\n SCROLL: 'scroll',\n /**\n * The toggle event. The toggle event doesn't bubble, but you can use it in\n * addEvent() and jsaction anyway. EventContract does the right thing\n * under the hood.\n */\n TOGGLE: 'toggle',\n /**\n * A custom event. The actual custom event type is declared as the 'type'\n * field in the event details. Supported in Firefox 6+, IE 9+, and all Chrome\n * versions.\n *\n * This is an internal name. Users should use jsaction's fireCustomEvent to\n * fire custom events instead of relying on this type to create them.\n */\n CUSTOM: '_custom'\n};\n/** All event types that do not bubble or capture and need a polyfill. */\nconst MOUSE_SPECIAL_EVENT_TYPES = [EventType.MOUSEENTER, EventType.MOUSELEAVE, 'pointerenter', 'pointerleave'];\n/** All event types that are registered in the bubble phase. */\nconst 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',\n// Video events.\n'ended', 'loadedmetadata',\n// Page visibility events.\n'pagehide', 'pageshow', 'visibilitychange',\n// Content visibility events.\n'beforematch'];\n/** All event types that are registered in the capture phase. */\nconst CAPTURE_EVENT_TYPES = [EventType.FOCUS, EventType.BLUR, EventType.ERROR, EventType.LOAD, EventType.TOGGLE];\n/**\n * Whether or not an event type should be registered in the capture phase.\n * @param eventType\n * @returns bool\n */\nconst isCaptureEventType = eventType => CAPTURE_EVENT_TYPES.indexOf(eventType) >= 0;\n/** All event types that are registered early. */\nconst EARLY_EVENT_TYPES = BUBBLE_EVENT_TYPES.concat(CAPTURE_EVENT_TYPES);\n/**\n * Whether or not an event type is registered in the early contract.\n */\nconst isEarlyEventType = eventType => EARLY_EVENT_TYPES.indexOf(eventType) >= 0;\n\n/**\n * If on a Macintosh with an extended keyboard, the Enter key located in the\n * numeric pad has a different ASCII code.\n */\nconst MAC_ENTER = 3;\n/** The Enter key. */\nconst ENTER = 13;\n/** The Space key. */\nconst SPACE = 32;\n/** Special keycodes used by jsaction for the generic click action. */\nconst KeyCode = {\n MAC_ENTER,\n ENTER,\n SPACE\n};\n\n/**\n * Gets a browser event type, if it would differ from the JSAction event type.\n */\nfunction getBrowserEventType(eventType) {\n // Mouseenter and mouseleave events are not handled directly because they\n // are not available everywhere. In browsers where they are available, they\n // don't bubble and aren't visible at the container boundary. Instead, we\n // synthesize the mouseenter and mouseleave events from mouseover and\n // mouseout events, respectively. Cf. eventcontract.js.\n if (eventType === EventType.MOUSEENTER) {\n return EventType.MOUSEOVER;\n } else if (eventType === EventType.MOUSELEAVE) {\n return EventType.MOUSEOUT;\n } else if (eventType === EventType.POINTERENTER) {\n return EventType.POINTEROVER;\n } else if (eventType === EventType.POINTERLEAVE) {\n return EventType.POINTEROUT;\n }\n return eventType;\n}\n/**\n * Registers the event handler function with the given DOM element for\n * the given event type.\n *\n * @param element The element.\n * @param eventType The event type.\n * @param handler The handler function to install.\n * @return Information needed to uninstall the event handler eventually.\n */\nfunction addEventListener(element, eventType, handler) {\n // All event handlers are registered in the bubbling\n // phase.\n //\n // All browsers support focus and blur, but these events only are propagated\n // in the capture phase. Very legacy browsers do not support focusin or\n // focusout.\n //\n // It would be a bad idea to register all event handlers in the\n // capture phase because then regular onclick handlers would not be\n // executed at all on events that trigger a jsaction. That's not\n // entirely what we want, at least for now.\n //\n // Error and load events (i.e. on images) do not bubble so they are also\n // handled in the capture phase.\n let capture = false;\n if (isCaptureEventType(eventType)) {\n capture = true;\n }\n element.addEventListener(eventType, handler, capture);\n return {\n eventType,\n handler,\n capture\n };\n}\n/**\n * Removes the event handler for the given event from the element.\n * the given event type.\n *\n * @param element The element.\n * @param info The information needed to deregister the handler, as returned by\n * addEventListener(), above.\n */\nfunction removeEventListener(element, info) {\n if (element.removeEventListener) {\n element.removeEventListener(info.eventType, info.handler, info.capture);\n // `detachEvent` is an old DOM API.\n // tslint:disable-next-line:no-any\n } else if (element.detachEvent) {\n // `detachEvent` is an old DOM API.\n // tslint:disable-next-line:no-any\n element.detachEvent(`on${info.eventType}`, info.handler);\n }\n}\n/**\n * Cancels propagation of an event.\n * @param e The event to cancel propagation for.\n */\nfunction stopPropagation(e) {\n e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;\n}\n/**\n * Prevents the default action of an event.\n * @param e The event to prevent the default action for.\n */\nfunction preventDefault(e) {\n e.preventDefault ? e.preventDefault() : e.returnValue = false;\n}\n/**\n * Gets the target Element of the event. In Firefox, a text node may appear as\n * the target of the event, in which case we return the parent element of the\n * text node.\n * @param e The event to get the target of.\n * @return The target element.\n */\nfunction getTarget(e) {\n let el = e.target;\n // In Firefox, the event may have a text node as its target. We always\n // want the parent Element the text node belongs to, however.\n if (!el.getAttribute && el.parentNode) {\n el = el.parentNode;\n }\n return el;\n}\n/**\n * Whether we are on a Mac. Not pulling in useragent just for this.\n */\nlet isMac = typeof navigator !== 'undefined' && /Macintosh/.test(navigator.userAgent);\n/**\n * Determines and returns whether the given event (which is assumed to be a\n * click event) is a middle click.\n * NOTE: There is not a consistent way to identify middle click\n * http://www.unixpapa.com/js/mouse.html\n */\nfunction isMiddleClick(e) {\n return (\n // `which` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.which === 2 ||\n // `which` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.which == null &&\n // `button` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.button === 4 // middle click for IE\n );\n}\n/**\n * Determines and returns whether the given event (which is assumed\n * to be a click event) is modified. A middle click is considered a modified\n * click to retain the default browser action, which opens a link in a new tab.\n * @param e The event.\n * @return Whether the given event is modified.\n */\nfunction isModifiedClickEvent(e) {\n return (\n // `metaKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n isMac && e.metaKey ||\n // `ctrlKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n !isMac && e.ctrlKey || isMiddleClick(e) ||\n // `shiftKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.shiftKey\n );\n}\n/** Whether we are on WebKit (e.g., Chrome). */\nconst isWebKit = typeof navigator !== 'undefined' && !/Opera/.test(navigator.userAgent) && /WebKit/.test(navigator.userAgent);\n/** Whether we are on IE. */\nconst isIe = typeof navigator !== 'undefined' && (/MSIE/.test(navigator.userAgent) || /Trident/.test(navigator.userAgent));\n/** Whether we are on Gecko (e.g., Firefox). */\nconst isGecko = typeof navigator !== 'undefined' && !/Opera|WebKit/.test(navigator.userAgent) && /Gecko/.test(navigator.product);\n/**\n * Determines and returns whether the given element is a valid target for\n * keypress/keydown DOM events that act like regular DOM clicks.\n * @param el The element.\n * @return Whether the given element is a valid action key target.\n */\nfunction isValidActionKeyTarget(el) {\n if (!('getAttribute' in el)) {\n return false;\n }\n if (isTextControl(el)) {\n return false;\n }\n if (isNativelyActivatable(el)) {\n return false;\n }\n // `isContentEditable` is an old DOM API.\n // tslint:disable-next-line:no-any\n if (el.isContentEditable) {\n return false;\n }\n return true;\n}\n/**\n * Whether an event has a modifier key activated.\n * @param e The event.\n * @return True, if a modifier key is activated.\n */\nfunction hasModifierKey(e) {\n return (\n // `ctrlKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.ctrlKey ||\n // `shiftKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.shiftKey ||\n // `altKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.altKey ||\n // `metaKey` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.metaKey\n );\n}\n/**\n * Determines and returns whether the given event has a target that already\n * has event handlers attached because it is a native HTML control. Used to\n * determine if preventDefault should be called when isActionKeyEvent is true.\n * @param e The event.\n * @return If preventDefault should be called.\n */\nfunction shouldCallPreventDefaultOnNativeHtmlControl(e) {\n const el = getTarget(e);\n const tagName = el.tagName.toUpperCase();\n const role = (el.getAttribute('role') || '').toUpperCase();\n if (tagName === 'BUTTON' || role === 'BUTTON') {\n return true;\n }\n if (!isNativeHTMLControl(el)) {\n return false;\n }\n if (tagName === 'A') {\n return false;\n }\n /**\n * Fix for physical d-pads on feature phone platforms; the native event\n * (ie. isTrusted: true) needs to fire to show the OPTION list. See\n * b/135288469 for more info.\n */\n if (tagName === 'SELECT') {\n return false;\n }\n if (processSpace(el)) {\n return false;\n }\n if (isTextControl(el)) {\n return false;\n }\n return true;\n}\n/**\n * Determines and returns whether the given event acts like a regular DOM click,\n * and should be handled instead of the click. If this returns true, the caller\n * will call preventDefault() to prevent a possible duplicate event.\n * This is represented by a keypress (keydown on Gecko browsers) on Enter or\n * Space key.\n * @param e The event.\n * @return True, if the event emulates a DOM click.\n */\nfunction isActionKeyEvent(e) {\n let key =\n // `which` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.which ||\n // `keyCode` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.keyCode;\n if (!key && e.key) {\n key = ACTION_KEY_TO_KEYCODE[e.key];\n }\n if (isWebKit && key === KeyCode.MAC_ENTER) {\n key = KeyCode.ENTER;\n }\n if (key !== KeyCode.ENTER && key !== KeyCode.SPACE) {\n return false;\n }\n const el = getTarget(e);\n if (e.type !== EventType.KEYDOWN || !isValidActionKeyTarget(el) || hasModifierKey(e)) {\n return false;\n }\n // For , we must only handle the browser's native click\n // event, so that the browser can toggle the checkbox.\n if (processSpace(el) && key === KeyCode.SPACE) {\n return false;\n }\n // If this element is non-focusable, ignore stray keystrokes (b/18337209)\n // Sscreen readers can move without tab focus, so any tabIndex is focusable.\n // See B/21809604\n if (!isFocusable(el)) {\n return false;\n }\n const type = (el.getAttribute('role') || el.type || el.tagName).toUpperCase();\n const isSpecificTriggerKey = IDENTIFIER_TO_KEY_TRIGGER_MAPPING[type] % key === 0;\n const isDefaultTriggerKey = !(type in IDENTIFIER_TO_KEY_TRIGGER_MAPPING) && key === KeyCode.ENTER;\n const hasType = el.tagName.toUpperCase() !== 'INPUT' || !!el.type;\n return (isSpecificTriggerKey || isDefaultTriggerKey) && hasType;\n}\n/**\n * Checks whether a DOM element can receive keyboard focus.\n * This code is based on goog.dom.isFocusable, but simplified since we shouldn't\n * care about visibility if we're already handling a keyboard event.\n */\nfunction isFocusable(el) {\n return (el.tagName in NATIVELY_FOCUSABLE_ELEMENTS || hasSpecifiedTabIndex(el)) && !el.disabled;\n}\n/**\n * @param element Element to check.\n * @return Whether the element has a specified tab index.\n */\nfunction hasSpecifiedTabIndex(element) {\n // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),\n // which returns an object with a 'specified' property if tabIndex is\n // specified. This works on other browsers, too.\n const attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!\n return attrNode != null && attrNode.specified;\n}\n/** Element tagnames that are focusable by default. */\nconst NATIVELY_FOCUSABLE_ELEMENTS = {\n 'A': 1,\n 'INPUT': 1,\n 'TEXTAREA': 1,\n 'SELECT': 1,\n 'BUTTON': 1\n};\n/** @return True, if the Space key was pressed. */\nfunction isSpaceKeyEvent(e) {\n const key =\n // `which` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.which ||\n // `keyCode` is an old DOM API.\n // tslint:disable-next-line:no-any\n e.keyCode;\n const el = getTarget(e);\n const elementName = (el.type || el.tagName).toUpperCase();\n return key === KeyCode.SPACE && elementName !== 'CHECKBOX';\n}\n/**\n * Determines whether the event corresponds to a non-bubbling mouse\n * event type (mouseenter, mouseleave, pointerenter, and pointerleave).\n *\n * During mouseover (mouseenter) and pointerover (pointerenter), the\n * relatedTarget is the element being entered from. During mouseout (mouseleave)\n * and pointerout (pointerleave), the relatedTarget is the element being exited\n * to.\n *\n * In both cases, if relatedTarget is outside target, then the corresponding\n * special event has occurred, otherwise it hasn't.\n *\n * @param e The mouseover/mouseout event.\n * @param type The type of the mouse special event.\n * @param element The element on which the jsaction for the\n * mouseenter/mouseleave event is defined.\n * @return True if the event is a mouseenter/mouseleave event.\n */\nfunction isMouseSpecialEvent(e, type, element) {\n // `relatedTarget` is an old DOM API.\n // tslint:disable-next-line:no-any\n const related = e.relatedTarget;\n 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));\n}\n/**\n * Creates a new EventLike object for a mouseenter/mouseleave event that's\n * derived from the original corresponding mouseover/mouseout event.\n * @param e The event.\n * @param target The element on which the jsaction for the mouseenter/mouseleave\n * event is defined.\n * @return A modified event-like object copied from the event object passed into\n * this function.\n */\nfunction createMouseSpecialEvent(e, target) {\n // We have to create a copy of the event object because we need to mutate\n // its fields. We do this for the special mouse events because the event\n // target needs to be retargeted to the action element rather than the real\n // element (since we are simulating the special mouse events with mouseover/\n // mouseout).\n //\n // Since we're making a copy anyways, we might as well attempt to convert\n // this event into a pseudo-real mouseenter/mouseleave event by adjusting\n // its type.\n //\n // tslint:disable-next-line:no-any\n const copy = {};\n for (const property in e) {\n if (property === 'srcElement' || property === 'target') {\n continue;\n }\n const key = property;\n // Making a copy requires iterating through all properties of `Event`.\n // tslint:disable-next-line:no-dict-access-on-struct-type\n const value = e[key];\n if (typeof value === 'function') {\n continue;\n }\n // Value should be the expected type, but the value of `key` is not known\n // statically.\n // tslint:disable-next-line:no-any\n copy[key] = value;\n }\n if (e.type === EventType.MOUSEOVER) {\n copy['type'] = EventType.MOUSEENTER;\n } else if (e.type === EventType.MOUSEOUT) {\n copy['type'] = EventType.MOUSELEAVE;\n } else if (e.type === EventType.POINTEROVER) {\n copy['type'] = EventType.POINTERENTER;\n } else {\n copy['type'] = EventType.POINTERLEAVE;\n }\n copy['target'] = copy['srcElement'] = target;\n copy['bubbles'] = false;\n return copy;\n}\n/**\n * Returns touch data extracted from the touch event: clientX, clientY, screenX\n * and screenY. If the event has no touch information at all, the returned\n * value is null.\n *\n * The fields of this Object are unquoted.\n *\n * @param event A touch event.\n */\nfunction getTouchData(event) {\n const touch = event.changedTouches && event.changedTouches[0] || event.touches && event.touches[0];\n if (!touch) {\n return null;\n }\n return {\n clientX: touch.clientX,\n clientY: touch.clientY,\n screenX: touch.screenX,\n screenY: touch.screenY\n };\n}\n/**\n * Creates a new EventLike object for a \"click\" event that's derived from the\n * original corresponding \"touchend\" event for a fast-click implementation.\n *\n * It takes a touch event, adds common fields found in a click event and\n * changes the type to 'click', so that the resulting event looks more like\n * a real click event.\n *\n * @param event A touch event.\n * @return A modified event-like object copied from the event object passed into\n * this function.\n */\nfunction recreateTouchEventAsClick(event) {\n const click = {};\n click['originalEventType'] = event.type;\n click['type'] = EventType.CLICK;\n for (const property in event) {\n if (property === 'type' || property === 'srcElement') {\n continue;\n }\n const key = property;\n // Making a copy requires iterating through all properties of `TouchEvent`.\n // tslint:disable-next-line:no-dict-access-on-struct-type\n const value = event[key];\n if (typeof value === 'function') {\n continue;\n }\n // Value should be the expected type, but the value of `key` is not known\n // statically.\n // tslint:disable-next-line:no-any\n click[key] = value;\n }\n // Ensure that the event has the most recent timestamp. This timestamp\n // may be used in the future to validate or cancel subsequent click events.\n click['timeStamp'] = Date.now();\n // Emulate preventDefault and stopPropagation behavior\n click['defaultPrevented'] = false;\n click['preventDefault'] = syntheticPreventDefault;\n click['_propagationStopped'] = false;\n click['stopPropagation'] = syntheticStopPropagation;\n // Emulate click coordinates using touch info\n const touch = getTouchData(event);\n if (touch) {\n click['clientX'] = touch.clientX;\n click['clientY'] = touch.clientY;\n click['screenX'] = touch.screenX;\n click['screenY'] = touch.screenY;\n }\n return click;\n}\n/**\n * An implementation of \"preventDefault\" for a synthesized event. Simply\n * sets \"defaultPrevented\" property to true.\n */\nfunction syntheticPreventDefault() {\n this.defaultPrevented = true;\n}\n/**\n * An implementation of \"stopPropagation\" for a synthesized event. It simply\n * sets a synthetic non-standard \"_propagationStopped\" property to true.\n */\nfunction syntheticStopPropagation() {\n this._propagationStopped = true;\n}\n/**\n * Mapping of KeyboardEvent.key values to\n * KeyCode values.\n */\nconst ACTION_KEY_TO_KEYCODE = {\n 'Enter': KeyCode.ENTER,\n ' ': KeyCode.SPACE\n};\n/**\n * Mapping of HTML element identifiers (ARIA role, type, or tagName) to the\n * keys (enter and/or space) that should activate them. A value of zero means\n * that both should activate them.\n */\nconst IDENTIFIER_TO_KEY_TRIGGER_MAPPING = {\n 'A': KeyCode.ENTER,\n 'BUTTON': 0,\n 'CHECKBOX': KeyCode.SPACE,\n 'COMBOBOX': KeyCode.ENTER,\n 'FILE': 0,\n 'GRIDCELL': KeyCode.ENTER,\n 'LINK': KeyCode.ENTER,\n 'LISTBOX': KeyCode.ENTER,\n 'MENU': 0,\n 'MENUBAR': 0,\n 'MENUITEM': 0,\n 'MENUITEMCHECKBOX': 0,\n 'MENUITEMRADIO': 0,\n 'OPTION': 0,\n 'RADIO': KeyCode.SPACE,\n 'RADIOGROUP': KeyCode.SPACE,\n 'RESET': 0,\n 'SUBMIT': 0,\n 'SWITCH': KeyCode.SPACE,\n 'TAB': 0,\n 'TREE': KeyCode.ENTER,\n 'TREEITEM': KeyCode.ENTER\n};\n/**\n * Returns whether or not to process space based on the type of the element;\n * checks to make sure that type is not null.\n * @param element The element.\n * @return Whether or not to process space based on type.\n */\nfunction processSpace(element) {\n const type = (element.getAttribute('type') || element.tagName).toUpperCase();\n return type in PROCESS_SPACE;\n}\n/**\n * Returns whether or not the given element is a text control.\n * @param el The element.\n * @return Whether or not the given element is a text control.\n */\nfunction isTextControl(el) {\n const type = (el.getAttribute('type') || el.tagName).toUpperCase();\n return type in TEXT_CONTROLS;\n}\n/**\n * Returns if the given element is a native HTML control.\n * @param el The element.\n * @return If the given element is a native HTML control.\n */\nfunction isNativeHTMLControl(el) {\n return el.tagName.toUpperCase() in NATIVE_HTML_CONTROLS;\n}\n/**\n * Returns if the given element is natively activatable. Browsers emit click\n * events for natively activatable elements, even when activated via keyboard.\n * For these elements, we don't need to raise a11y click events.\n * @param el The element.\n * @return If the given element is a native HTML control.\n */\nfunction isNativelyActivatable(el) {\n return el.tagName.toUpperCase() === 'BUTTON' || !!el.type && el.type.toUpperCase() === 'FILE';\n}\n/**\n * HTML types (not ARIA roles) which will auto-trigger a click event for\n * the Space key, with side-effects. We will not call preventDefault if space is\n * pressed, nor will we raise a11y click events. For all other elements, we can\n * suppress the default event (which has no desired side-effects) and handle the\n * keydown ourselves.\n */\nconst PROCESS_SPACE = {\n 'CHECKBOX': true,\n 'FILE': true,\n 'OPTION': true,\n 'RADIO': true\n};\n/** TagNames and Input types for which to not process enter/space as click. */\nconst TEXT_CONTROLS = {\n 'COLOR': true,\n 'DATE': true,\n 'DATETIME': true,\n 'DATETIME-LOCAL': true,\n 'EMAIL': true,\n 'MONTH': true,\n 'NUMBER': true,\n 'PASSWORD': true,\n 'RANGE': true,\n 'SEARCH': true,\n 'TEL': true,\n 'TEXT': true,\n 'TEXTAREA': true,\n 'TIME': true,\n 'URL': true,\n 'WEEK': true\n};\n/** TagNames that are native HTML controls. */\nconst NATIVE_HTML_CONTROLS = {\n 'A': true,\n 'AREA': true,\n 'BUTTON': true,\n 'DIALOG': true,\n 'IMG': true,\n 'INPUT': true,\n 'LINK': true,\n 'MENU': true,\n 'OPTGROUP': true,\n 'OPTION': true,\n 'PROGRESS': true,\n 'SELECT': true,\n 'TEXTAREA': true\n};\n/** Exported for testing. */\nconst testing = {\n setIsMac(value) {\n isMac = value;\n }\n};\n\n/**\n * Whether the user agent is running on iOS.\n */\nconst isIos = typeof navigator !== 'undefined' && /iPhone|iPad|iPod/.test(navigator.userAgent);\n/**\n * A class representing a container node and all the event handlers\n * installed on it. Used so that handlers can be cleaned up if the\n * container is removed from the contract.\n */\nclass EventContractContainer {\n /**\n * @param element The container Element.\n */\n constructor(element) {\n this.element = element;\n /**\n * Array of event handlers and their corresponding event types that are\n * installed on this container.\n *\n */\n this.handlerInfos = [];\n }\n /**\n * Installs the provided installer on the element owned by this container,\n * and maintains a reference to resulting handler in order to remove it\n * later if desired.\n */\n addEventListener(eventType, getHandler) {\n // In iOS, event bubbling doesn't happen automatically in any DOM element,\n // unless it has an onclick attribute or DOM event handler attached to it.\n // This breaks JsAction in some cases. See \"Making Elements Clickable\"\n // section at http://goo.gl/2VoGnB.\n //\n // A workaround for this issue is to change the CSS cursor style to 'pointer'\n // for the container element, which magically turns on event bubbling. This\n // solution is described in the comments section at http://goo.gl/6pEO1z.\n //\n // We use a navigator.userAgent check here as this problem is present both\n // on Mobile Safari and thin WebKit wrappers, such as Chrome for iOS.\n if (isIos) {\n this.element.style.cursor = 'pointer';\n }\n this.handlerInfos.push(addEventListener(this.element, eventType, getHandler(this.element)));\n }\n /**\n * Removes all the handlers installed on this container.\n */\n cleanUp() {\n for (let i = 0; i < this.handlerInfos.length; i++) {\n removeEventListener(this.element, this.handlerInfos[i]);\n }\n this.handlerInfos = [];\n }\n}\nconst Char = {\n /**\n * The separator between the namespace and the action name in the\n * jsaction attribute value.\n */\n NAMESPACE_ACTION_SEPARATOR: '.',\n /**\n * The separator between the event name and action in the jsaction\n * attribute value.\n */\n EVENT_ACTION_SEPARATOR: ':'\n};\n\n/** Added for readability when accessing stable property names. */\nfunction getEventType(eventInfo) {\n return eventInfo.eventType;\n}\n/** Added for readability when accessing stable property names. */\nfunction setEventType(eventInfo, eventType) {\n eventInfo.eventType = eventType;\n}\n/** Added for readability when accessing stable property names. */\nfunction getEvent(eventInfo) {\n return eventInfo.event;\n}\n/** Added for readability when accessing stable property names. */\nfunction setEvent(eventInfo, event) {\n eventInfo.event = event;\n}\n/** Added for readability when accessing stable property names. */\nfunction getTargetElement(eventInfo) {\n return eventInfo.targetElement;\n}\n/** Added for readability when accessing stable property names. */\nfunction setTargetElement(eventInfo, targetElement) {\n eventInfo.targetElement = targetElement;\n}\n/** Added for readability when accessing stable property names. */\nfunction getContainer(eventInfo) {\n return eventInfo.eic;\n}\n/** Added for readability when accessing stable property names. */\nfunction setContainer(eventInfo, container) {\n eventInfo.eic = container;\n}\n/** Added for readability when accessing stable property names. */\nfunction getTimestamp(eventInfo) {\n return eventInfo.timeStamp;\n}\n/** Added for readability when accessing stable property names. */\nfunction setTimestamp(eventInfo, timestamp) {\n eventInfo.timeStamp = timestamp;\n}\n/** Added for readability when accessing stable property names. */\nfunction getAction(eventInfo) {\n return eventInfo.eia;\n}\n/** Added for readability when accessing stable property names. */\nfunction setAction(eventInfo, actionName, actionElement) {\n eventInfo.eia = [actionName, actionElement];\n}\n/** Added for readability when accessing stable property names. */\nfunction unsetAction(eventInfo) {\n eventInfo.eia = undefined;\n}\n/** Added for readability when accessing stable property names. */\nfunction getActionName(actionInfo) {\n return actionInfo[0];\n}\n/** Added for readability when accessing stable property names. */\nfunction getActionElement(actionInfo) {\n return actionInfo[1];\n}\n/** Added for readability when accessing stable property names. */\nfunction getIsReplay(eventInfo) {\n return eventInfo.eirp;\n}\n/** Added for readability when accessing stable property names. */\nfunction setIsReplay(eventInfo, replay) {\n eventInfo.eirp = replay;\n}\n/** Added for readability when accessing stable property names. */\nfunction getA11yClickKey(eventInfo) {\n return eventInfo.eiack;\n}\n/** Added for readability when accessing stable property names. */\nfunction setA11yClickKey(eventInfo, a11yClickKey) {\n eventInfo.eiack = a11yClickKey;\n}\n/** Added for readability when accessing stable property names. */\nfunction getResolved(eventInfo) {\n return eventInfo.eir;\n}\n/** Added for readability when accessing stable property names. */\nfunction setResolved(eventInfo, resolved) {\n eventInfo.eir = resolved;\n}\n/** Clones an `EventInfo` */\nfunction cloneEventInfo(eventInfo) {\n return {\n eventType: eventInfo.eventType,\n event: eventInfo.event,\n targetElement: eventInfo.targetElement,\n eic: eventInfo.eic,\n eia: eventInfo.eia,\n timeStamp: eventInfo.timeStamp,\n eirp: eventInfo.eirp,\n eiack: eventInfo.eiack,\n eir: eventInfo.eir\n };\n}\n/**\n * Utility function for creating an `EventInfo`.\n *\n * This can be used from code-size sensitive compilation units, as taking\n * parameters vs. an `Object` literal reduces code size.\n */\nfunction createEventInfoFromParameters(eventType, event, targetElement, container, timestamp, action, isReplay, a11yClickKey) {\n return {\n eventType,\n event,\n targetElement,\n eic: container,\n timeStamp: timestamp,\n eia: action,\n eirp: isReplay,\n eiack: a11yClickKey\n };\n}\n/**\n * Utility function for creating an `EventInfo`.\n *\n * This should be used in compilation units that are less sensitive to code\n * size.\n */\nfunction createEventInfo({\n eventType,\n event,\n targetElement,\n container,\n timestamp,\n action,\n isReplay,\n a11yClickKey\n}) {\n return {\n eventType,\n event,\n targetElement,\n eic: container,\n timeStamp: timestamp,\n eia: action ? [action.name, action.element] : undefined,\n eirp: isReplay,\n eiack: a11yClickKey\n };\n}\n/**\n * Utility class around an `EventInfo`.\n *\n * This should be used in compilation units that are less sensitive to code\n * size.\n */\nclass EventInfoWrapper {\n constructor(eventInfo) {\n this.eventInfo = eventInfo;\n }\n getEventType() {\n return getEventType(this.eventInfo);\n }\n setEventType(eventType) {\n setEventType(this.eventInfo, eventType);\n }\n getEvent() {\n return getEvent(this.eventInfo);\n }\n setEvent(event) {\n setEvent(this.eventInfo, event);\n }\n getTargetElement() {\n return getTargetElement(this.eventInfo);\n }\n setTargetElement(targetElement) {\n setTargetElement(this.eventInfo, targetElement);\n }\n getContainer() {\n return getContainer(this.eventInfo);\n }\n setContainer(container) {\n setContainer(this.eventInfo, container);\n }\n getTimestamp() {\n return getTimestamp(this.eventInfo);\n }\n setTimestamp(timestamp) {\n setTimestamp(this.eventInfo, timestamp);\n }\n getAction() {\n const action = getAction(this.eventInfo);\n if (!action) return undefined;\n return {\n name: action[0],\n element: action[1]\n };\n }\n setAction(action) {\n if (!action) {\n unsetAction(this.eventInfo);\n return;\n }\n setAction(this.eventInfo, action.name, action.element);\n }\n getIsReplay() {\n return getIsReplay(this.eventInfo);\n }\n setIsReplay(replay) {\n setIsReplay(this.eventInfo, replay);\n }\n getResolved() {\n return getResolved(this.eventInfo);\n }\n setResolved(resolved) {\n setResolved(this.eventInfo, resolved);\n }\n clone() {\n return new EventInfoWrapper(cloneEventInfo(this.eventInfo));\n }\n}\n\n/**\n * Since maps from event to action are immutable we can use a single map\n * to represent the empty map.\n */\nconst EMPTY_ACTION_MAP = {};\n/**\n * This regular expression matches a semicolon.\n */\nconst REGEXP_SEMICOLON = /\\s*;\\s*/;\n/** If no event type is defined, defaults to `click`. */\nconst DEFAULT_EVENT_TYPE = EventType.CLICK;\n/** Resolves actions for Events. */\nclass ActionResolver {\n constructor({\n syntheticMouseEventSupport = false,\n clickModSupport = true\n } = {}) {\n this.a11yClickSupport = false;\n this.clickModSupport = true;\n this.updateEventInfoForA11yClick = undefined;\n this.preventDefaultForA11yClick = undefined;\n this.populateClickOnlyAction = undefined;\n this.syntheticMouseEventSupport = syntheticMouseEventSupport;\n this.clickModSupport = clickModSupport;\n }\n resolveEventType(eventInfo) {\n // We distinguish modified and plain clicks in order to support the\n // default browser behavior of modified clicks on links; usually to\n // open the URL of the link in new tab or new window on ctrl/cmd\n // click. A DOM 'click' event is mapped to the jsaction 'click'\n // event iff there is no modifier present on the event. If there is\n // a modifier, it's mapped to 'clickmod' instead.\n //\n // It's allowed to omit the event in the jsaction attribute. In that\n // case, 'click' is assumed. Thus the following two are equivalent:\n //\n // \n // \n //\n // For unmodified clicks, EventContract invokes the jsaction\n // 'gna.fu'. For modified clicks, EventContract won't find a\n // suitable action and leave the event to be handled by the\n // browser.\n //\n // In order to also invoke a jsaction handler for a modifier click,\n // 'clickmod' needs to be used:\n //\n // \n //\n // EventContract invokes the jsaction 'gna.fu' for modified\n // clicks. Unmodified clicks are left to the browser.\n //\n // In order to set up the event contract to handle both clickonly and\n // clickmod, only addEvent(EventType.CLICK) is necessary.\n //\n // In order to set up the event contract to handle click,\n // addEvent() is necessary for CLICK, KEYDOWN, and KEYPRESS event types. If\n // a11y click support is enabled, addEvent() will set up the appropriate key\n // event handler automatically.\n if (this.clickModSupport && getEventType(eventInfo) === EventType.CLICK && isModifiedClickEvent(getEvent(eventInfo))) {\n setEventType(eventInfo, EventType.CLICKMOD);\n } else if (this.a11yClickSupport) {\n this.updateEventInfoForA11yClick(eventInfo);\n }\n }\n resolveAction(eventInfo) {\n if (getResolved(eventInfo)) {\n return;\n }\n this.populateAction(eventInfo, getTargetElement(eventInfo));\n setResolved(eventInfo, true);\n }\n resolveParentAction(eventInfo) {\n const action = getAction(eventInfo);\n const actionElement = action && getActionElement(action);\n unsetAction(eventInfo);\n const parentNode = actionElement && this.getParentNode(actionElement);\n if (!parentNode) {\n return;\n }\n this.populateAction(eventInfo, parentNode);\n }\n /**\n * Searches for a jsaction that the DOM event maps to and creates an\n * object containing event information used for dispatching by\n * jsaction.Dispatcher. This method populates the `action` and `actionElement`\n * fields of the EventInfo object passed in by finding the first\n * jsaction attribute above the target Node of the event, and below\n * the container Node, that specifies a jsaction for the event\n * type. If no such jsaction is found, then action is undefined.\n *\n * @param eventInfo `EventInfo` to set `action` and `actionElement` if an\n * action is found on any `Element` in the path of the `Event`.\n */\n populateAction(eventInfo, currentTarget) {\n let actionElement = currentTarget;\n while (actionElement && actionElement !== getContainer(eventInfo)) {\n if (actionElement.nodeType === Node.ELEMENT_NODE) {\n this.populateActionOnElement(actionElement, eventInfo);\n }\n if (getAction(eventInfo)) {\n // An event is handled by at most one jsaction. Thus we stop at the\n // first matching jsaction specified in a jsaction attribute up the\n // ancestor chain of the event target node.\n break;\n }\n actionElement = this.getParentNode(actionElement);\n }\n const action = getAction(eventInfo);\n if (!action) {\n // No action found.\n return;\n }\n if (this.a11yClickSupport) {\n this.preventDefaultForA11yClick(eventInfo);\n }\n // We attempt to handle the mouseenter/mouseleave events here by\n // detecting whether the mouseover/mouseout events correspond to\n // entering/leaving an element.\n if (this.syntheticMouseEventSupport) {\n if (getEventType(eventInfo) === EventType.MOUSEENTER || getEventType(eventInfo) === EventType.MOUSELEAVE || getEventType(eventInfo) === EventType.POINTERENTER || getEventType(eventInfo) === EventType.POINTERLEAVE) {\n // We attempt to handle the mouseenter/mouseleave events here by\n // detecting whether the mouseover/mouseout events correspond to\n // entering/leaving an element.\n if (isMouseSpecialEvent(getEvent(eventInfo), getEventType(eventInfo), getActionElement(action))) {\n // If both mouseover/mouseout and mouseenter/mouseleave events are\n // enabled, two separate handlers for mouseover/mouseout are\n // registered. Both handlers will see the same event instance\n // so we create a copy to avoid interfering with the dispatching of\n // the mouseover/mouseout event.\n const copiedEvent = createMouseSpecialEvent(getEvent(eventInfo), getActionElement(action));\n setEvent(eventInfo, copiedEvent);\n // Since the mouseenter/mouseleave events do not bubble, the target\n // of the event is technically the `actionElement` (the node with the\n // `jsaction` attribute)\n setTargetElement(eventInfo, getActionElement(action));\n } else {\n unsetAction(eventInfo);\n }\n }\n }\n }\n /**\n * Walk to the parent node, unless the node has a different owner in\n * which case we walk to the owner. Attempt to walk to host of a\n * shadow root if needed.\n */\n getParentNode(element) {\n const owner = element[Property.OWNER];\n if (owner) {\n return owner;\n }\n const parentNode = element.parentNode;\n if (parentNode?.nodeName === '#document-fragment') {\n return parentNode?.host ?? null;\n }\n return parentNode;\n }\n /**\n * Accesses the jsaction map on a node and retrieves the name of the\n * action the given event is mapped to, if any. It parses the\n * attribute value and stores it in a property on the node for\n * subsequent retrieval without re-parsing and re-accessing the\n * attribute.\n *\n * @param actionElement The DOM node to retrieve the jsaction map from.\n * @param eventInfo `EventInfo` to set `action` and `actionElement` if an\n * action is found on the `actionElement`.\n */\n populateActionOnElement(actionElement, eventInfo) {\n const actionMap = this.parseActions(actionElement);\n const actionName = actionMap[getEventType(eventInfo)];\n if (actionName !== undefined) {\n setAction(eventInfo, actionName, actionElement);\n }\n if (this.a11yClickSupport) {\n this.populateClickOnlyAction(actionElement, eventInfo, actionMap);\n }\n }\n /**\n * Parses and caches an element's jsaction element into a map.\n *\n * This is primarily for internal use.\n *\n * @param actionElement The DOM node to retrieve the jsaction map from.\n * @return Map from event to qualified name of the jsaction bound to it.\n */\n parseActions(actionElement) {\n let actionMap = get(actionElement);\n if (!actionMap) {\n const jsactionAttribute = actionElement.getAttribute(Attribute.JSACTION);\n if (!jsactionAttribute) {\n actionMap = EMPTY_ACTION_MAP;\n set(actionElement, actionMap);\n } else {\n actionMap = getParsed(jsactionAttribute);\n if (!actionMap) {\n actionMap = {};\n const values = jsactionAttribute.split(REGEXP_SEMICOLON);\n for (let idx = 0; idx < values.length; idx++) {\n const value = values[idx];\n if (!value) {\n continue;\n }\n const colon = value.indexOf(Char.EVENT_ACTION_SEPARATOR);\n const hasColon = colon !== -1;\n const type = hasColon ? value.substr(0, colon).trim() : DEFAULT_EVENT_TYPE;\n const action = hasColon ? value.substr(colon + 1).trim() : value;\n actionMap[type] = action;\n }\n setParsed(jsactionAttribute, actionMap);\n }\n set(actionElement, actionMap);\n }\n }\n return actionMap;\n }\n addA11yClickSupport(updateEventInfoForA11yClick, preventDefaultForA11yClick, populateClickOnlyAction) {\n this.a11yClickSupport = true;\n this.updateEventInfoForA11yClick = updateEventInfoForA11yClick;\n this.preventDefaultForA11yClick = preventDefaultForA11yClick;\n this.populateClickOnlyAction = populateClickOnlyAction;\n }\n}\n\n/**\n * @fileoverview An enum to control who can call certain jsaction APIs.\n */\nvar Restriction;\n(function (Restriction) {\n Restriction[Restriction[\"I_AM_THE_JSACTION_FRAMEWORK\"] = 0] = \"I_AM_THE_JSACTION_FRAMEWORK\";\n})(Restriction || (Restriction = {}));\n\n/**\n * Receives a DOM event, determines the jsaction associated with the source\n * element of the DOM event, and invokes the handler associated with the\n * jsaction.\n */\nclass Dispatcher {\n /**\n * Options are:\n * - `eventReplayer`: When the event contract dispatches replay events\n * to the Dispatcher, the Dispatcher collects them and in the next tick\n * dispatches them to the `eventReplayer`. Defaults to dispatching to `dispatchDelegate`.\n * @param dispatchDelegate A function that should handle dispatching an `EventInfoWrapper` to handlers.\n */\n constructor(dispatchDelegate, {\n actionResolver,\n eventReplayer\n } = {}) {\n this.dispatchDelegate = dispatchDelegate;\n /** Whether the event replay is scheduled. */\n this.eventReplayScheduled = false;\n /** The queue of events. */\n this.replayEventInfoWrappers = [];\n this.actionResolver = actionResolver;\n this.eventReplayer = eventReplayer;\n }\n /**\n * Receives an event or the event queue from the EventContract. The event\n * queue is copied and it attempts to replay.\n * If event info is passed in it looks for an action handler that can handle\n * the given event. If there is no handler registered queues the event and\n * checks if a loader is registered for the given namespace. If so, calls it.\n *\n * Alternatively, if in global dispatch mode, calls all registered global\n * handlers for the appropriate event type.\n *\n * The three functionalities of this call are deliberately not split into\n * three methods (and then declared as an abstract interface), because the\n * interface is used by EventContract, which lives in a different jsbinary.\n * Therefore the interface between the three is defined entirely in terms that\n * are invariant under jscompiler processing (Function and Array, as opposed\n * to a custom type with method names).\n *\n * @param eventInfo The info for the event that triggered this call or the\n * queue of events from EventContract.\n */\n dispatch(eventInfo) {\n const eventInfoWrapper = new EventInfoWrapper(eventInfo);\n this.actionResolver?.resolveEventType(eventInfo);\n this.actionResolver?.resolveAction(eventInfo);\n const action = eventInfoWrapper.getAction();\n if (action && shouldPreventDefaultBeforeDispatching(action.element, eventInfoWrapper)) {\n preventDefault(eventInfoWrapper.getEvent());\n }\n if (this.eventReplayer && eventInfoWrapper.getIsReplay()) {\n this.scheduleEventInfoWrapperReplay(eventInfoWrapper);\n return;\n }\n this.dispatchDelegate(eventInfoWrapper);\n }\n /**\n * Schedules an `EventInfoWrapper` for replay. The replaying will happen in its own\n * stack once the current flow cedes control. This is done to mimic\n * browser event handling.\n */\n scheduleEventInfoWrapperReplay(eventInfoWrapper) {\n this.replayEventInfoWrappers.push(eventInfoWrapper);\n if (this.eventReplayScheduled) {\n return;\n }\n this.eventReplayScheduled = true;\n Promise.resolve().then(() => {\n this.eventReplayScheduled = false;\n this.eventReplayer(this.replayEventInfoWrappers);\n });\n }\n}\n/**\n * Creates an `EventReplayer` that calls the `replay` function for every `eventInfoWrapper` in\n * the queue.\n */\nfunction createEventReplayer(replay) {\n return eventInfoWrappers => {\n for (const eventInfoWrapper of eventInfoWrappers) {\n replay(eventInfoWrapper);\n }\n };\n}\n/**\n * Returns true if the default action of this event should be prevented before\n * this event is dispatched.\n */\nfunction shouldPreventDefaultBeforeDispatching(actionElement, eventInfoWrapper) {\n // Prevent browser from following node links if a jsaction is present\n // and we are dispatching the action now. Note that the targetElement may be\n // a child of an anchor that has a jsaction attached. For that reason, we\n // need to check the actionElement rather than the targetElement.\n return actionElement.tagName === 'A' && (eventInfoWrapper.getEventType() === EventType.CLICK || eventInfoWrapper.getEventType() === EventType.CLICKMOD);\n}\n/**\n * Registers deferred functionality for an EventContract and a Jsaction\n * Dispatcher.\n */\nfunction registerDispatcher$2(eventContract, dispatcher) {\n eventContract.ecrd(eventInfo => {\n dispatcher.dispatch(eventInfo);\n }, Restriction.I_AM_THE_JSACTION_FRAMEWORK);\n}\n\n/** An internal symbol used to indicate whether propagation should be stopped or not. */\nconst PROPAGATION_STOPPED_SYMBOL = Symbol.for('propagationStopped');\n/** Extra event phases beyond what the browser provides. */\nconst EventPhase = {\n REPLAY: 101\n};\nconst 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`.';\nconst PREVENT_DEFAULT_ERROR_MESSAGE = `\\`preventDefault\\` called during event replay.`;\nconst 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.';\nconst COMPOSED_PATH_ERROR_MESSAGE = `\\`composedPath\\` called during event replay.`;\n/**\n * A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`,\n * `currentTarget`, etc.\n */\nclass EventDispatcher {\n constructor(dispatchDelegate, clickModSupport = true) {\n this.dispatchDelegate = dispatchDelegate;\n this.clickModSupport = clickModSupport;\n this.actionResolver = new ActionResolver({\n clickModSupport\n });\n this.dispatcher = new Dispatcher(eventInfoWrapper => {\n this.dispatchToDelegate(eventInfoWrapper);\n }, {\n actionResolver: this.actionResolver\n });\n }\n /**\n * The entrypoint for the `EventContract` dispatch.\n */\n dispatch(eventInfo) {\n this.dispatcher.dispatch(eventInfo);\n }\n /** Internal method that does basic disaptching. */\n dispatchToDelegate(eventInfoWrapper) {\n if (eventInfoWrapper.getIsReplay()) {\n prepareEventForReplay(eventInfoWrapper);\n }\n prepareEventForBubbling(eventInfoWrapper);\n while (eventInfoWrapper.getAction()) {\n prepareEventForDispatch(eventInfoWrapper);\n // If this is a capture event, ONLY dispatch if the action element is the target.\n if (isCaptureEventType(eventInfoWrapper.getEventType()) && eventInfoWrapper.getAction().element !== eventInfoWrapper.getTargetElement()) {\n return;\n }\n this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction().name);\n if (propagationStopped(eventInfoWrapper)) {\n return;\n }\n this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo);\n }\n }\n}\nfunction prepareEventForBubbling(eventInfoWrapper) {\n const event = eventInfoWrapper.getEvent();\n const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event);\n const stopPropagation = () => {\n event[PROPAGATION_STOPPED_SYMBOL] = true;\n originalStopPropagation();\n };\n patchEventInstance(event, 'stopPropagation', stopPropagation);\n patchEventInstance(event, 'stopImmediatePropagation', stopPropagation);\n}\nfunction propagationStopped(eventInfoWrapper) {\n const event = eventInfoWrapper.getEvent();\n return !!event[PROPAGATION_STOPPED_SYMBOL];\n}\nfunction prepareEventForReplay(eventInfoWrapper) {\n const event = eventInfoWrapper.getEvent();\n const target = eventInfoWrapper.getTargetElement();\n const originalPreventDefault = event.preventDefault.bind(event);\n patchEventInstance(event, 'target', target);\n patchEventInstance(event, 'eventPhase', EventPhase.REPLAY);\n patchEventInstance(event, 'preventDefault', () => {\n originalPreventDefault();\n throw new Error(PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''));\n });\n patchEventInstance(event, 'composedPath', () => {\n throw new Error(COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''));\n });\n}\nfunction prepareEventForDispatch(eventInfoWrapper) {\n const event = eventInfoWrapper.getEvent();\n const currentTarget = eventInfoWrapper.getAction()?.element;\n if (currentTarget) {\n patchEventInstance(event, 'currentTarget', currentTarget, {\n // `currentTarget` is going to get reassigned every dispatch.\n configurable: true\n });\n }\n}\n/**\n * Patch `Event` instance during non-standard `Event` dispatch. This patches just the `Event`\n * instance that the browser created, it does not patch global properties or methods.\n *\n * This is necessary because dispatching an `Event` outside of browser dispatch results in\n * incorrect properties and methods that need to be polyfilled or do not work.\n *\n * JSAction dispatch adds two extra \"phases\" to event dispatch:\n * 1. Event delegation - the event is being dispatched by a delegating event handler on a container\n * (typically `window.document.documentElement`), to a delegated event handler on some child\n * element. Certain `Event` properties will be unintuitive, such as `currentTarget`, which would\n * be the container rather than the child element. Bubbling would also not work. In order to\n * emulate the browser, these properties and methods on the `Event` are patched.\n * 2. Event replay - the event is being dispatched by the framework once the handlers have been\n * loaded (during hydration, or late-loaded). Certain `Event` properties can be unset by the\n * browser because the `Event` is no longer actively being dispatched, such as `target`. Other\n * methods have no effect because the `Event` has already been dispatched, such as\n * `preventDefault`. Bubbling would also not work. These properties and methods are patched,\n * either to fill in information that the browser may have removed, or to throw errors in methods\n * that no longer behave as expected.\n */\nfunction patchEventInstance(event, property, value, {\n configurable = false\n} = {}) {\n Object.defineProperty(event, property, {\n value,\n configurable\n });\n}\n/**\n * Registers deferred functionality for an EventContract and a Jsaction\n * Dispatcher.\n */\nfunction registerDispatcher$1(eventContract, dispatcher) {\n eventContract.ecrd(eventInfo => {\n dispatcher.dispatch(eventInfo);\n }, Restriction.I_AM_THE_JSACTION_FRAMEWORK);\n}\n\n/**\n * EarlyEventContract intercepts events in the bubbling phase at the\n * boundary of the document body. This mapping will be passed to the\n * late-loaded EventContract.\n */\nclass EarlyEventContract {\n constructor(dataContainer = window, container = window.document.documentElement) {\n this.dataContainer = dataContainer;\n dataContainer._ejsa = createEarlyJsactionData(container);\n }\n /**\n * Installs a list of event types for container .\n */\n addEvents(types, capture) {\n addEvents(this.dataContainer._ejsa, types, capture);\n }\n}\n/** Creates an `EarlyJsactionData` object. */\nfunction createEarlyJsactionData(container) {\n const q = [];\n const d = eventInfo => {\n q.push(eventInfo);\n };\n const h = event => {\n d(createEventInfoFromParameters(event.type, event, event.target, container, Date.now()));\n };\n return {\n c: container,\n q,\n et: [],\n etc: [],\n d,\n h\n };\n}\n/** Add all the events to the container stored in the `EarlyJsactionData`. */\nfunction addEvents(earlyJsactionData, types, capture) {\n for (let i = 0; i < types.length; i++) {\n const eventType = types[i];\n const eventTypes = capture ? earlyJsactionData.etc : earlyJsactionData.et;\n eventTypes.push(eventType);\n earlyJsactionData.c.addEventListener(eventType, earlyJsactionData.h, capture);\n }\n}\n/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */\nfunction getQueuedEventInfos(earlyJsactionData) {\n return earlyJsactionData?.q ?? [];\n}\n/** Register a different dispatcher function on the `EarlyJsactionData`. */\nfunction registerDispatcher(earlyJsactionData, dispatcher) {\n if (!earlyJsactionData) {\n return;\n }\n earlyJsactionData.d = dispatcher;\n}\n/** Removes all event listener handlers. */\nfunction removeAllEventListeners(earlyJsactionData) {\n if (!earlyJsactionData) {\n return;\n }\n removeEventListeners(earlyJsactionData.c, earlyJsactionData.et, earlyJsactionData.h);\n removeEventListeners(earlyJsactionData.c, earlyJsactionData.etc, earlyJsactionData.h, true);\n}\nfunction removeEventListeners(container, eventTypes, earlyEventHandler, capture) {\n for (let i = 0; i < eventTypes.length; i++) {\n container.removeEventListener(eventTypes[i], earlyEventHandler, /* useCapture */capture);\n }\n}\n\n/**\n * @define Support for the non-bubbling mouseenter and mouseleave events. This\n * flag can be overridden in a build rule.\n */\nconst MOUSE_SPECIAL_SUPPORT = false;\n\n/**\n * @fileoverview Implements the local event handling contract. This\n * allows DOM objects in a container that enters into this contract to\n * define event handlers which are executed in a local context.\n *\n * One EventContract instance can manage the contract for multiple\n * containers, which are added using the addContainer() method.\n *\n * Events can be registered using the addEvent() method.\n *\n * A Dispatcher is added using the registerDispatcher() method. Until there is\n * a dispatcher, events are queued. The idea is that the EventContract\n * class is inlined in the HTML of the top level page and instantiated\n * right after the start of . The Dispatcher class is contained\n * in the external deferred js, and instantiated and registered with\n * EventContract when the external javascript in the page loads. The\n * external javascript will also register the jsaction handlers, which\n * then pick up the queued events at the time of registration.\n *\n * Since this class is meant to be inlined in the main page HTML, the\n * size of the binary compiled from this file MUST be kept as small as\n * possible and thus its dependencies to a minimum.\n */\n/**\n * EventContract intercepts events in the bubbling phase at the\n * boundary of a container element, and maps them to generic actions\n * which are specified using the custom jsaction attribute in\n * HTML. Behavior of the application is then specified in terms of\n * handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.\n *\n * This has several benefits: (1) No DOM event handlers need to be\n * registered on the specific elements in the UI. (2) The set of\n * events that the application has to handle can be specified in terms\n * of the semantics of the application, rather than in terms of DOM\n * events. (3) Invocation of handlers can be delayed and handlers can\n * be delay loaded in a generic way.\n */\nclass EventContract {\n static {\n this.MOUSE_SPECIAL_SUPPORT = MOUSE_SPECIAL_SUPPORT;\n }\n constructor(containerManager) {\n /**\n * The DOM events which this contract covers. Used to prevent double\n * registration of event types. The value of the map is the\n * internally created DOM event handler function that handles the\n * DOM events. See addEvent().\n *\n */\n this.eventHandlers = {};\n this.browserEventTypeToExtraEventTypes = {};\n /**\n * The dispatcher function. Events are passed to this function for\n * handling once it was set using the registerDispatcher() method. This is\n * done because the function is passed from another jsbinary, so passing the\n * instance and invoking the method here would require to leave the method\n * unobfuscated.\n */\n this.dispatcher = null;\n /**\n * The list of suspended `EventInfo` that will be dispatched\n * as soon as the `Dispatcher` is registered.\n */\n this.queuedEventInfos = [];\n this.containerManager = containerManager;\n }\n handleEvent(eventType, event, container) {\n const eventInfo = createEventInfoFromParameters( /* eventType= */eventType, /* event= */event, /* targetElement= */event.target, /* container= */container, /* timestamp= */Date.now());\n this.handleEventInfo(eventInfo);\n }\n /**\n * Handle an `EventInfo`.\n */\n handleEventInfo(eventInfo) {\n if (!this.dispatcher) {\n // All events are queued when the dispatcher isn't yet loaded.\n setIsReplay(eventInfo, true);\n this.queuedEventInfos?.push(eventInfo);\n return;\n }\n this.dispatcher(eventInfo);\n }\n /**\n * Enables jsaction handlers to be called for the event type given by\n * name.\n *\n * If the event is already registered, this does nothing.\n *\n * @param prefixedEventType If supplied, this event is used in\n * the actual browser event registration instead of the name that is\n * exposed to jsaction. Use this if you e.g. want users to be able\n * to subscribe to jsaction=\"transitionEnd:foo\" while the underlying\n * event is webkitTransitionEnd in one browser and mozTransitionEnd\n * in another.\n */\n addEvent(eventType, prefixedEventType) {\n if (eventType in this.eventHandlers || !this.containerManager) {\n return;\n }\n if (!EventContract.MOUSE_SPECIAL_SUPPORT && MOUSE_SPECIAL_EVENT_TYPES.indexOf(eventType) >= 0) {\n return;\n }\n const eventHandler = (eventType, event, container) => {\n this.handleEvent(eventType, event, container);\n };\n // Store the callback to allow us to replay events.\n this.eventHandlers[eventType] = eventHandler;\n const browserEventType = getBrowserEventType(prefixedEventType || eventType);\n if (browserEventType !== eventType) {\n const eventTypes = this.browserEventTypeToExtraEventTypes[browserEventType] || [];\n eventTypes.push(eventType);\n this.browserEventTypeToExtraEventTypes[browserEventType] = eventTypes;\n }\n this.containerManager.addEventListener(browserEventType, element => {\n return event => {\n eventHandler(eventType, event, element);\n };\n });\n }\n /**\n * Gets the queued early events and replay them using the appropriate handler\n * in the provided event contract. Once all the events are replayed, it cleans\n * up the early contract.\n */\n replayEarlyEvents(earlyJsactionData = window._ejsa) {\n // Check if the early contract is present and prevent calling this function\n // more than once.\n if (!earlyJsactionData) {\n return;\n }\n // Replay the early contract events.\n this.replayEarlyEventInfos(earlyJsactionData.q);\n // Clean up the early contract.\n removeAllEventListeners(earlyJsactionData);\n delete window._ejsa;\n }\n /**\n * Replays all the early `EventInfo` objects, dispatching them through the normal\n * `EventContract` flow.\n */\n replayEarlyEventInfos(earlyEventInfos) {\n for (let i = 0; i < earlyEventInfos.length; i++) {\n const earlyEventInfo = earlyEventInfos[i];\n const eventTypes = this.getEventTypesForBrowserEventType(earlyEventInfo.eventType);\n for (let j = 0; j < eventTypes.length; j++) {\n const eventInfo = cloneEventInfo(earlyEventInfo);\n // EventInfo eventType maps to JSAction's internal event type,\n // rather than the browser event type.\n setEventType(eventInfo, eventTypes[j]);\n this.handleEventInfo(eventInfo);\n }\n }\n }\n /**\n * Returns all JSAction event types that have been registered for a given\n * browser event type.\n */\n getEventTypesForBrowserEventType(browserEventType) {\n const eventTypes = [];\n if (this.eventHandlers[browserEventType]) {\n eventTypes.push(browserEventType);\n }\n if (this.browserEventTypeToExtraEventTypes[browserEventType]) {\n eventTypes.push(...this.browserEventTypeToExtraEventTypes[browserEventType]);\n }\n return eventTypes;\n }\n /**\n * Returns the event handler function for a given event type.\n */\n handler(eventType) {\n return this.eventHandlers[eventType];\n }\n /**\n * Cleans up the event contract. This resets all of the `EventContract`'s\n * internal state. Users are responsible for not using this `EventContract`\n * after it has been cleaned up.\n */\n cleanUp() {\n this.containerManager.cleanUp();\n this.containerManager = null;\n this.eventHandlers = {};\n this.browserEventTypeToExtraEventTypes = {};\n this.dispatcher = null;\n this.queuedEventInfos = [];\n }\n /**\n * Register a dispatcher function. Event info of each event mapped to\n * a jsaction is passed for handling to this callback. The queued\n * events are passed as well to the dispatcher for later replaying\n * once the dispatcher is registered. Clears the event queue to null.\n *\n * @param dispatcher The dispatcher function.\n * @param restriction\n */\n registerDispatcher(dispatcher, restriction) {\n this.ecrd(dispatcher, restriction);\n }\n /**\n * Unrenamed alias for registerDispatcher. Necessary for any codebases that\n * split the `EventContract` and `Dispatcher` code into different compilation\n * units.\n */\n ecrd(dispatcher, restriction) {\n this.dispatcher = dispatcher;\n if (this.queuedEventInfos?.length) {\n for (let i = 0; i < this.queuedEventInfos.length; i++) {\n this.handleEventInfo(this.queuedEventInfos[i]);\n }\n this.queuedEventInfos = null;\n }\n }\n}\n\n/**\n * Creates an `EarlyJsactionData`, adds events to it, and populates it on a nested object on\n * the window.\n */\nfunction bootstrapAppScopedEarlyEventContract(container, appId, bubbleEventTypes, captureEventTypes, dataContainer = window) {\n const earlyJsactionData = createEarlyJsactionData(container);\n if (!dataContainer._ejsas) {\n dataContainer._ejsas = {};\n }\n dataContainer._ejsas[appId] = earlyJsactionData;\n addEvents(earlyJsactionData, bubbleEventTypes);\n addEvents(earlyJsactionData, captureEventTypes, /* capture= */true);\n}\n/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */\nfunction getAppScopedQueuedEventInfos(appId, dataContainer = window) {\n return getQueuedEventInfos(dataContainer._ejsas?.[appId]);\n}\n/**\n * Registers a dispatcher function on the `EarlyJsactionData` present on the nested object on the\n * window.\n */\nfunction registerAppScopedDispatcher(restriction, appId, dispatcher, dataContainer = window) {\n registerDispatcher(dataContainer._ejsas?.[appId], dispatcher);\n}\n/** Removes all event listener handlers. */\nfunction removeAllAppScopedEventListeners(appId, dataContainer = window) {\n removeAllEventListeners(dataContainer._ejsas?.[appId]);\n}\n/** Clear the early event contract. */\nfunction clearAppScopedEarlyEventContract(appId, dataContainer = window) {\n if (!dataContainer._ejsas) {\n return;\n }\n dataContainer._ejsas[appId] = undefined;\n}\nexport { Attribute, EventContract, EventContractContainer, EventDispatcher, EventInfoWrapper, EventPhase, bootstrapAppScopedEarlyEventContract, clearAppScopedEarlyEventContract, getDefaulted as getActionCache, getAppScopedQueuedEventInfos, isCaptureEventType, isEarlyEventType, registerAppScopedDispatcher, registerDispatcher$1 as registerDispatcher, removeAllAppScopedEventListeners };\n","/**\n * @license Angular v18.2.4\n * (c) 2010-2024 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport { SIGNAL_NODE as SIGNAL_NODE$1, signalSetFn as signalSetFn$1, producerAccessed as producerAccessed$1, SIGNAL as SIGNAL$1, getActiveConsumer as getActiveConsumer$1, setActiveConsumer as setActiveConsumer$1, consumerDestroy as consumerDestroy$1, REACTIVE_NODE as REACTIVE_NODE$1, consumerBeforeComputation as consumerBeforeComputation$1, consumerAfterComputation as consumerAfterComputation$1, consumerPollProducersForChange as consumerPollProducersForChange$1, createSignal as createSignal$1, signalUpdateFn as signalUpdateFn$1, createComputed as createComputed$1, setThrowInvalidWriteToSignalError as setThrowInvalidWriteToSignalError$1, createWatch as createWatch$1 } from '@angular/core/primitives/signals';\nimport { BehaviorSubject, Subject, Subscription } from 'rxjs';\nimport { map, first } from 'rxjs/operators';\nimport { Attribute as Attribute$1, isEarlyEventType, getActionCache, EventContract, EventContractContainer, EventDispatcher, registerDispatcher, getAppScopedQueuedEventInfos, clearAppScopedEarlyEventContract, isCaptureEventType } from '@angular/core/primitives/event-dispatch';\n\n/**\n * Base URL for the error details page.\n *\n * Keep this constant in sync across:\n * - packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts\n * - packages/core/src/error_details_base_url.ts\n */\nconst ERROR_DETAILS_PAGE_BASE_URL = 'https://angular.dev/errors';\n/**\n * URL for the XSS security documentation.\n */\nconst XSS_SECURITY_URL = 'https://g.co/ng/security#xss';\n\n/**\n * Class that represents a runtime error.\n * Formats and outputs the error message in a consistent way.\n *\n * Example:\n * ```\n * throw new RuntimeError(\n * RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,\n * ngDevMode && 'Injector has already been destroyed.');\n * ```\n *\n * Note: the `message` argument contains a descriptive error message as a string in development\n * mode (when the `ngDevMode` is defined). In production mode (after tree-shaking pass), the\n * `message` argument becomes `false`, thus we account for it in the typings and the runtime\n * logic.\n */\nclass RuntimeError extends Error {\n constructor(code, message) {\n super(formatRuntimeError(code, message));\n this.code = code;\n }\n}\n/**\n * Called to format a runtime error.\n * See additional info on the `message` argument type in the `RuntimeError` class description.\n */\nfunction formatRuntimeError(code, message) {\n // Error code might be a negative number, which is a special marker that instructs the logic to\n // generate a link to the error details page on angular.io.\n // We also prepend `0` to non-compile-time errors.\n const fullCode = `NG0${Math.abs(code)}`;\n let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;\n if (ngDevMode && code < 0) {\n const addPeriodSeparator = !errorMessage.match(/[.,;!?\\n]$/);\n const separator = addPeriodSeparator ? '.' : '';\n errorMessage = `${errorMessage}${separator} Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/${fullCode}`;\n }\n return errorMessage;\n}\nconst REQUIRED_UNSET_VALUE = /* @__PURE__ */Symbol('InputSignalNode#UNSET');\n// Note: Using an IIFE here to ensure that the spread assignment is not considered\n// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.\n// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.\nconst INPUT_SIGNAL_NODE = /* @__PURE__ */(() => {\n return {\n ...SIGNAL_NODE$1,\n transformFn: undefined,\n applyValueToInputSignal(node, value) {\n signalSetFn$1(node, value);\n }\n };\n})();\nconst ɵINPUT_SIGNAL_BRAND_READ_TYPE = /* @__PURE__ */Symbol();\nconst ɵINPUT_SIGNAL_BRAND_WRITE_TYPE = /* @__PURE__ */Symbol();\n/**\n * Creates an input signal.\n *\n * @param initialValue The initial value.\n * Can be set to {@link REQUIRED_UNSET_VALUE} for required inputs.\n * @param options Additional options for the input. e.g. a transform, or an alias.\n */\nfunction createInputSignal(initialValue, options) {\n const node = Object.create(INPUT_SIGNAL_NODE);\n node.value = initialValue;\n // Perf note: Always set `transformFn` here to ensure that `node` always\n // has the same v8 class shape, allowing monomorphic reads on input signals.\n node.transformFn = options?.transform;\n function inputValueFn() {\n // Record that someone looked at this signal.\n producerAccessed$1(node);\n if (node.value === REQUIRED_UNSET_VALUE) {\n throw new RuntimeError(-950 /* RuntimeErrorCode.REQUIRED_INPUT_NO_VALUE */, ngDevMode && 'Input is required but no value is available yet.');\n }\n return node.value;\n }\n inputValueFn[SIGNAL$1] = node;\n if (ngDevMode) {\n inputValueFn.toString = () => `[Input Signal: ${inputValueFn()}]`;\n }\n return inputValueFn;\n}\n\n/**\n * Convince closure compiler that the wrapped function has no side-effects.\n *\n * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to\n * allow us to execute a function but have closure compiler mark the call as no-side-effects.\n * It is important that the return value for the `noSideEffects` function be assigned\n * to something which is retained otherwise the call to `noSideEffects` will be removed by closure\n * compiler.\n */\nfunction noSideEffects(fn) {\n return {\n toString: fn\n }.toString();\n}\nconst ANNOTATIONS = '__annotations__';\nconst PARAMETERS = '__parameters__';\nconst PROP_METADATA = '__prop__metadata__';\n/**\n * @suppress {globalThis}\n */\nfunction makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {\n return noSideEffects(() => {\n const metaCtor = makeMetadataCtor(props);\n function DecoratorFactory(...args) {\n if (this instanceof DecoratorFactory) {\n metaCtor.call(this, ...args);\n return this;\n }\n const annotationInstance = new DecoratorFactory(...args);\n return function TypeDecorator(cls) {\n if (typeFn) typeFn(cls, ...args);\n // Use of Object.defineProperty is important since it creates non-enumerable property which\n // prevents the property is copied during subclassing.\n const annotations = cls.hasOwnProperty(ANNOTATIONS) ? cls[ANNOTATIONS] : Object.defineProperty(cls, ANNOTATIONS, {\n value: []\n })[ANNOTATIONS];\n annotations.push(annotationInstance);\n if (additionalProcessing) additionalProcessing(cls);\n return cls;\n };\n }\n if (parentClass) {\n DecoratorFactory.prototype = Object.create(parentClass.prototype);\n }\n DecoratorFactory.prototype.ngMetadataName = name;\n DecoratorFactory.annotationCls = DecoratorFactory;\n return DecoratorFactory;\n });\n}\nfunction makeMetadataCtor(props) {\n return function ctor(...args) {\n if (props) {\n const values = props(...args);\n for (const propName in values) {\n this[propName] = values[propName];\n }\n }\n };\n}\nfunction makeParamDecorator(name, props, parentClass) {\n return noSideEffects(() => {\n const metaCtor = makeMetadataCtor(props);\n function ParamDecoratorFactory(...args) {\n if (this instanceof ParamDecoratorFactory) {\n metaCtor.apply(this, args);\n return this;\n }\n const annotationInstance = new ParamDecoratorFactory(...args);\n ParamDecorator.annotation = annotationInstance;\n return ParamDecorator;\n function ParamDecorator(cls, unusedKey, index) {\n // Use of Object.defineProperty is important since it creates non-enumerable property which\n // prevents the property is copied during subclassing.\n const parameters = cls.hasOwnProperty(PARAMETERS) ? cls[PARAMETERS] : Object.defineProperty(cls, PARAMETERS, {\n value: []\n })[PARAMETERS];\n // there might be gaps if some in between parameters do not have annotations.\n // we pad with nulls.\n while (parameters.length <= index) {\n parameters.push(null);\n }\n (parameters[index] = parameters[index] || []).push(annotationInstance);\n return cls;\n }\n }\n if (parentClass) {\n ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);\n }\n ParamDecoratorFactory.prototype.ngMetadataName = name;\n ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;\n return ParamDecoratorFactory;\n });\n}\nfunction makePropDecorator(name, props, parentClass, additionalProcessing) {\n return noSideEffects(() => {\n const metaCtor = makeMetadataCtor(props);\n function PropDecoratorFactory(...args) {\n if (this instanceof PropDecoratorFactory) {\n metaCtor.apply(this, args);\n return this;\n }\n const decoratorInstance = new PropDecoratorFactory(...args);\n function PropDecorator(target, name) {\n // target is undefined with standard decorators. This case is not supported and will throw\n // if this decorator is used in JIT mode with standard decorators.\n if (target === undefined) {\n throw new Error('Standard Angular field decorators are not supported in JIT mode.');\n }\n const constructor = target.constructor;\n // Use of Object.defineProperty is important because it creates a non-enumerable property\n // which prevents the property from being copied during subclassing.\n const meta = constructor.hasOwnProperty(PROP_METADATA) ? constructor[PROP_METADATA] : Object.defineProperty(constructor, PROP_METADATA, {\n value: {}\n })[PROP_METADATA];\n meta[name] = meta.hasOwnProperty(name) && meta[name] || [];\n meta[name].unshift(decoratorInstance);\n if (additionalProcessing) additionalProcessing(target, name, ...args);\n }\n return PropDecorator;\n }\n if (parentClass) {\n PropDecoratorFactory.prototype = Object.create(parentClass.prototype);\n }\n PropDecoratorFactory.prototype.ngMetadataName = name;\n PropDecoratorFactory.annotationCls = PropDecoratorFactory;\n return PropDecoratorFactory;\n });\n}\nconst _global = globalThis;\nfunction ngDevModeResetPerfCounters() {\n const locationString = typeof location !== 'undefined' ? location.toString() : '';\n const newCounters = {\n namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,\n firstCreatePass: 0,\n tNode: 0,\n tView: 0,\n rendererCreateTextNode: 0,\n rendererSetText: 0,\n rendererCreateElement: 0,\n rendererAddEventListener: 0,\n rendererSetAttribute: 0,\n rendererRemoveAttribute: 0,\n rendererSetProperty: 0,\n rendererSetClassName: 0,\n rendererAddClass: 0,\n rendererRemoveClass: 0,\n rendererSetStyle: 0,\n rendererRemoveStyle: 0,\n rendererDestroy: 0,\n rendererDestroyNode: 0,\n rendererMoveNode: 0,\n rendererRemoveNode: 0,\n rendererAppendChild: 0,\n rendererInsertBefore: 0,\n rendererCreateComment: 0,\n hydratedNodes: 0,\n hydratedComponents: 0,\n dehydratedViewsRemoved: 0,\n dehydratedViewsCleanupRuns: 0,\n componentsSkippedHydration: 0\n };\n // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.\n const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;\n if (!allowNgDevModeTrue) {\n _global['ngDevMode'] = false;\n } else {\n if (typeof _global['ngDevMode'] !== 'object') {\n _global['ngDevMode'] = {};\n }\n Object.assign(_global['ngDevMode'], newCounters);\n }\n return newCounters;\n}\n/**\n * This function checks to see if the `ngDevMode` has been set. If yes,\n * then we honor it, otherwise we default to dev mode with additional checks.\n *\n * The idea is that unless we are doing production build where we explicitly\n * set `ngDevMode == false` we should be helping the developer by providing\n * as much early warning and errors as possible.\n *\n * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions\n * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode\n * is defined for the entire instruction set.\n *\n * When checking `ngDevMode` on toplevel, always init it before referencing it\n * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can\n * get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.\n *\n * Details on possible values for `ngDevMode` can be found on its docstring.\n *\n * NOTE:\n * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.\n */\nfunction initNgDevMode() {\n // The below checks are to ensure that calling `initNgDevMode` multiple times does not\n // reset the counters.\n // If the `ngDevMode` is not an object, then it means we have not created the perf counters\n // yet.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (typeof ngDevMode !== 'object' || Object.keys(ngDevMode).length === 0) {\n ngDevModeResetPerfCounters();\n }\n return typeof ngDevMode !== 'undefined' && !!ngDevMode;\n }\n return false;\n}\nfunction getClosureSafeProperty(objWithPropertyToExtract) {\n for (let key in objWithPropertyToExtract) {\n if (objWithPropertyToExtract[key] === getClosureSafeProperty) {\n return key;\n }\n }\n throw Error('Could not find renamed property on target object.');\n}\n/**\n * Sets properties on a target object from a source object, but only if\n * the property doesn't already exist on the target object.\n * @param target The target to set properties on\n * @param source The source of the property keys and values to set\n */\nfunction fillProperties(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}\nfunction stringify(token) {\n if (typeof token === 'string') {\n return token;\n }\n if (Array.isArray(token)) {\n return '[' + token.map(stringify).join(', ') + ']';\n }\n if (token == null) {\n return '' + token;\n }\n if (token.overriddenName) {\n return `${token.overriddenName}`;\n }\n if (token.name) {\n return `${token.name}`;\n }\n const res = token.toString();\n if (res == null) {\n return '' + res;\n }\n const newLineIndex = res.indexOf('\\n');\n return newLineIndex === -1 ? res : res.substring(0, newLineIndex);\n}\n/**\n * Concatenates two strings with separator, allocating new strings only when necessary.\n *\n * @param before before string.\n * @param separator separator string.\n * @param after after string.\n * @returns concatenated string.\n */\nfunction concatStringsWithSpace(before, after) {\n return before == null || before === '' ? after === null ? '' : after : after == null || after === '' ? before : before + ' ' + after;\n}\n/**\n * Ellipses the string in the middle when longer than the max length\n *\n * @param string\n * @param maxLength of the output string\n * @returns ellipsed string with ... in the middle\n */\nfunction truncateMiddle(str, maxLength = 100) {\n if (!str || maxLength < 1 || str.length <= maxLength) return str;\n if (maxLength == 1) return str.substring(0, 1) + '...';\n const halfLimit = Math.round(maxLength / 2);\n return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);\n}\nconst __forward_ref__ = getClosureSafeProperty({\n __forward_ref__: getClosureSafeProperty\n});\n/**\n * Allows to refer to references which are not yet defined.\n *\n * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of\n * DI is declared, but not yet defined. It is also used when the `token` which we use when creating\n * a query is not yet defined.\n *\n * `forwardRef` is also used to break circularities in standalone components imports.\n *\n * @usageNotes\n * ### Circular dependency example\n * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}\n *\n * ### Circular standalone reference import example\n * ```ts\n * @Component({\n * standalone: true,\n * imports: [ChildComponent],\n * selector: 'app-parent',\n * template: ``,\n * })\n * export class ParentComponent {\n * @Input() hideParent: boolean;\n * }\n *\n *\n * @Component({\n * standalone: true,\n * imports: [CommonModule, forwardRef(() => ParentComponent)],\n * selector: 'app-child',\n * template: ``,\n * })\n * export class ChildComponent {\n * @Input() hideParent: boolean;\n * }\n * ```\n *\n * @publicApi\n */\nfunction forwardRef(forwardRefFn) {\n forwardRefFn.__forward_ref__ = forwardRef;\n forwardRefFn.toString = function () {\n return stringify(this());\n };\n return forwardRefFn;\n}\n/**\n * Lazily retrieves the reference value from a forwardRef.\n *\n * Acts as the identity function when given a non-forward-ref value.\n *\n * @usageNotes\n * ### Example\n *\n * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}\n *\n * @see {@link forwardRef}\n * @publicApi\n */\nfunction resolveForwardRef(type) {\n return isForwardRef(type) ? type() : type;\n}\n/** Checks whether a function is wrapped by a `forwardRef`. */\nfunction isForwardRef(fn) {\n return typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) && fn.__forward_ref__ === forwardRef;\n}\n\n// The functions in this file verify that the assumptions we are making\nfunction assertNumber(actual, msg) {\n if (!(typeof actual === 'number')) {\n throwError(msg, typeof actual, 'number', '===');\n }\n}\nfunction assertNumberInRange(actual, minInclusive, maxInclusive) {\n assertNumber(actual, 'Expected a number');\n assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');\n assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');\n}\nfunction assertString(actual, msg) {\n if (!(typeof actual === 'string')) {\n throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');\n }\n}\nfunction assertFunction(actual, msg) {\n if (!(typeof actual === 'function')) {\n throwError(msg, actual === null ? 'null' : typeof actual, 'function', '===');\n }\n}\nfunction assertEqual(actual, expected, msg) {\n if (!(actual == expected)) {\n throwError(msg, actual, expected, '==');\n }\n}\nfunction assertNotEqual(actual, expected, msg) {\n if (!(actual != expected)) {\n throwError(msg, actual, expected, '!=');\n }\n}\nfunction assertSame(actual, expected, msg) {\n if (!(actual === expected)) {\n throwError(msg, actual, expected, '===');\n }\n}\nfunction assertNotSame(actual, expected, msg) {\n if (!(actual !== expected)) {\n throwError(msg, actual, expected, '!==');\n }\n}\nfunction assertLessThan(actual, expected, msg) {\n if (!(actual < expected)) {\n throwError(msg, actual, expected, '<');\n }\n}\nfunction assertLessThanOrEqual(actual, expected, msg) {\n if (!(actual <= expected)) {\n throwError(msg, actual, expected, '<=');\n }\n}\nfunction assertGreaterThan(actual, expected, msg) {\n if (!(actual > expected)) {\n throwError(msg, actual, expected, '>');\n }\n}\nfunction assertGreaterThanOrEqual(actual, expected, msg) {\n if (!(actual >= expected)) {\n throwError(msg, actual, expected, '>=');\n }\n}\nfunction assertNotDefined(actual, msg) {\n if (actual != null) {\n throwError(msg, actual, null, '==');\n }\n}\nfunction assertDefined(actual, msg) {\n if (actual == null) {\n throwError(msg, actual, null, '!=');\n }\n}\nfunction throwError(msg, actual, expected, comparison) {\n throw new Error(`ASSERTION ERROR: ${msg}` + (comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));\n}\nfunction assertDomNode(node) {\n if (!(node instanceof Node)) {\n throwError(`The provided value must be an instance of a DOM Node but got ${stringify(node)}`);\n }\n}\nfunction assertElement(node) {\n if (!(node instanceof Element)) {\n throwError(`The provided value must be an element but got ${stringify(node)}`);\n }\n}\nfunction assertIndexInRange(arr, index) {\n assertDefined(arr, 'Array must be defined.');\n const maxLen = arr.length;\n if (index < 0 || index >= maxLen) {\n throwError(`Index expected to be less than ${maxLen} but got ${index}`);\n }\n}\nfunction assertOneOf(value, ...validValues) {\n if (validValues.indexOf(value) !== -1) return true;\n throwError(`Expected value to be one of ${JSON.stringify(validValues)} but was ${JSON.stringify(value)}.`);\n}\nfunction assertNotReactive(fn) {\n if (getActiveConsumer$1() !== null) {\n throwError(`${fn}() should never be called in a reactive context.`);\n }\n}\n\n/**\n * Construct an injectable definition which defines how a token will be constructed by the DI\n * system, and in which injectors (if any) it will be available.\n *\n * This should be assigned to a static `ɵprov` field on a type, which will then be an\n * `InjectableType`.\n *\n * Options:\n * * `providedIn` determines which injectors will include the injectable, by either associating it\n * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be\n * provided in the `'root'` injector, which will be the application-level injector in most apps.\n * * `factory` gives the zero argument function which will create an instance of the injectable.\n * The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection\n * of dependencies.\n *\n * @codeGenApi\n * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.\n */\nfunction ɵɵdefineInjectable(opts) {\n return {\n token: opts.token,\n providedIn: opts.providedIn || null,\n factory: opts.factory,\n value: undefined\n };\n}\n/**\n * @deprecated in v8, delete after v10. This API should be used only by generated code, and that\n * code should now use ɵɵdefineInjectable instead.\n * @publicApi\n */\nconst defineInjectable = ɵɵdefineInjectable;\n/**\n * Construct an `InjectorDef` which configures an injector.\n *\n * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an\n * `InjectorType`.\n *\n * Options:\n *\n * * `providers`: an optional array of providers to add to the injector. Each provider must\n * either have a factory or point to a type which has a `ɵprov` static property (the\n * type must be an `InjectableType`).\n * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s\n * whose providers will also be added to the injector. Locally provided types will override\n * providers from imports.\n *\n * @codeGenApi\n */\nfunction ɵɵdefineInjector(options) {\n return {\n providers: options.providers || [],\n imports: options.imports || []\n };\n}\n/**\n * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading\n * inherited value.\n *\n * @param type A type which may have its own (non-inherited) `ɵprov`.\n */\nfunction getInjectableDef(type) {\n return getOwnDefinition(type, NG_PROV_DEF) || getOwnDefinition(type, NG_INJECTABLE_DEF);\n}\nfunction isInjectable(type) {\n return getInjectableDef(type) !== null;\n}\n/**\n * Return definition only if it is defined directly on `type` and is not inherited from a base\n * class of `type`.\n */\nfunction getOwnDefinition(type, field) {\n return type.hasOwnProperty(field) ? type[field] : null;\n}\n/**\n * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.\n *\n * @param type A type which may have `ɵprov`, via inheritance.\n *\n * @deprecated Will be removed in a future version of Angular, where an error will occur in the\n * scenario if we find the `ɵprov` on an ancestor only.\n */\nfunction getInheritedInjectableDef(type) {\n const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF]);\n if (def) {\n 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.`);\n return def;\n } else {\n return null;\n }\n}\n/**\n * Read the injector def type in a way which is immune to accidentally reading inherited value.\n *\n * @param type type which may have an injector def (`ɵinj`)\n */\nfunction getInjectorDef(type) {\n return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF)) ? type[NG_INJ_DEF] : null;\n}\nconst NG_PROV_DEF = getClosureSafeProperty({\n ɵprov: getClosureSafeProperty\n});\nconst NG_INJ_DEF = getClosureSafeProperty({\n ɵinj: getClosureSafeProperty\n});\n// We need to keep these around so we can read off old defs if new defs are unavailable\nconst NG_INJECTABLE_DEF = getClosureSafeProperty({\n ngInjectableDef: getClosureSafeProperty\n});\nconst NG_INJECTOR_DEF = getClosureSafeProperty({\n ngInjectorDef: getClosureSafeProperty\n});\n\n/**\n * Creates a token that can be used in a DI Provider.\n *\n * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a\n * runtime representation) such as when injecting an interface, callable type, array or\n * parameterized type.\n *\n * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by\n * the `Injector`. This provides an additional level of type safety.\n *\n *
\n *\n * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the\n * provider and the injection call. Creating a new instance of `InjectionToken` in different places,\n * even with the same description, will be treated as different tokens by Angular's DI system,\n * leading to a `NullInjectorError`.\n *\n *
\n *\n * \n *\n * When creating an `InjectionToken`, you can optionally specify a factory function which returns\n * (possibly by creating) a default value of the parameterized type `T`. This sets up the\n * `InjectionToken` using this factory as a provider as if it was defined explicitly in the\n * application's root injector. If the factory function, which takes zero arguments, needs to inject\n * dependencies, it can do so using the [`inject`](api/core/inject) function.\n * As you can see in the Tree-shakable InjectionToken example below.\n *\n * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which\n * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:\n * this option is now deprecated). As mentioned above, `'root'` is the default value for\n * `providedIn`.\n *\n * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.\n *\n * @usageNotes\n * ### Basic Examples\n *\n * ### Plain InjectionToken\n *\n * {@example core/di/ts/injector_spec.ts region='InjectionToken'}\n *\n * ### Tree-shakable InjectionToken\n *\n * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}\n *\n * @publicApi\n */\nclass InjectionToken {\n /**\n * @param _desc Description for the token,\n * used only for debugging purposes,\n * it should but does not need to be unique\n * @param options Options for the token's usage, as described above\n */\n constructor(_desc, options) {\n this._desc = _desc;\n /** @internal */\n this.ngMetadataName = 'InjectionToken';\n this.ɵprov = undefined;\n if (typeof options == 'number') {\n (typeof ngDevMode === 'undefined' || ngDevMode) && assertLessThan(options, 0, 'Only negative numbers are supported here');\n // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.\n // See `InjectorMarkers`\n this.__NG_ELEMENT_ID__ = options;\n } else if (options !== undefined) {\n this.ɵprov = ɵɵdefineInjectable({\n token: this,\n providedIn: options.providedIn || 'root',\n factory: options.factory\n });\n }\n }\n /**\n * @internal\n */\n get multi() {\n return this;\n }\n toString() {\n return `InjectionToken ${this._desc}`;\n }\n}\nlet _injectorProfilerContext;\nfunction getInjectorProfilerContext() {\n !ngDevMode && throwError('getInjectorProfilerContext should never be called in production mode');\n return _injectorProfilerContext;\n}\nfunction setInjectorProfilerContext(context) {\n !ngDevMode && throwError('setInjectorProfilerContext should never be called in production mode');\n const previous = _injectorProfilerContext;\n _injectorProfilerContext = context;\n return previous;\n}\nlet injectorProfilerCallback = null;\n/**\n * Sets the callback function which will be invoked during certain DI events within the\n * runtime (for example: injecting services, creating injectable instances, configuring providers)\n *\n * Warning: this function is *INTERNAL* and should not be relied upon in application's code.\n * The contract of the function might be changed in any release and/or the function can be removed\n * completely.\n *\n * @param profiler function provided by the caller or null value to disable profiling.\n */\nconst setInjectorProfiler = injectorProfiler => {\n !ngDevMode && throwError('setInjectorProfiler should never be called in production mode');\n injectorProfilerCallback = injectorProfiler;\n};\n/**\n * Injector profiler function which emits on DI events executed by the runtime.\n *\n * @param event InjectorProfilerEvent corresponding to the DI event being emitted\n */\nfunction injectorProfiler(event) {\n !ngDevMode && throwError('Injector profiler should never be called in production mode');\n if (injectorProfilerCallback != null /* both `null` and `undefined` */) {\n injectorProfilerCallback(event);\n }\n}\n/**\n * Emits an InjectorProfilerEventType.ProviderConfigured to the injector profiler. The data in the\n * emitted event includes the raw provider, as well as the token that provider is providing.\n *\n * @param eventProvider A provider object\n */\nfunction emitProviderConfiguredEvent(eventProvider, isViewProvider = false) {\n !ngDevMode && throwError('Injector profiler should never be called in production mode');\n let token;\n // if the provider is a TypeProvider (typeof provider is function) then the token is the\n // provider itself\n if (typeof eventProvider === 'function') {\n token = eventProvider;\n }\n // if the provider is an injection token, then the token is the injection token.\n else if (eventProvider instanceof InjectionToken) {\n token = eventProvider;\n }\n // in all other cases we can access the token via the `provide` property of the provider\n else {\n token = resolveForwardRef(eventProvider.provide);\n }\n let provider = eventProvider;\n // Injection tokens may define their own default provider which gets attached to the token itself\n // as `ɵprov`. In this case, we want to emit the provider that is attached to the token, not the\n // token itself.\n if (eventProvider instanceof InjectionToken) {\n provider = eventProvider.ɵprov || eventProvider;\n }\n injectorProfiler({\n type: 2 /* InjectorProfilerEventType.ProviderConfigured */,\n context: getInjectorProfilerContext(),\n providerRecord: {\n token,\n provider,\n isViewProvider\n }\n });\n}\n/**\n * Emits an event to the injector profiler with the instance that was created. Note that\n * the injector associated with this emission can be accessed by using getDebugInjectContext()\n *\n * @param instance an object created by an injector\n */\nfunction emitInstanceCreatedByInjectorEvent(instance) {\n !ngDevMode && throwError('Injector profiler should never be called in production mode');\n injectorProfiler({\n type: 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */,\n context: getInjectorProfilerContext(),\n instance: {\n value: instance\n }\n });\n}\n/**\n * @param token DI token associated with injected service\n * @param value the instance of the injected service (i.e the result of `inject(token)`)\n * @param flags the flags that the token was injected with\n */\nfunction emitInjectEvent(token, value, flags) {\n !ngDevMode && throwError('Injector profiler should never be called in production mode');\n injectorProfiler({\n type: 0 /* InjectorProfilerEventType.Inject */,\n context: getInjectorProfilerContext(),\n service: {\n token,\n value,\n flags\n }\n });\n}\nfunction runInInjectorProfilerContext(injector, token, callback) {\n !ngDevMode && throwError('runInInjectorProfilerContext should never be called in production mode');\n const prevInjectContext = setInjectorProfilerContext({\n injector,\n token\n });\n try {\n callback();\n } finally {\n setInjectorProfilerContext(prevInjectContext);\n }\n}\nfunction isEnvironmentProviders(value) {\n return value && !!value.ɵproviders;\n}\nconst NG_COMP_DEF = getClosureSafeProperty({\n ɵcmp: getClosureSafeProperty\n});\nconst NG_DIR_DEF = getClosureSafeProperty({\n ɵdir: getClosureSafeProperty\n});\nconst NG_PIPE_DEF = getClosureSafeProperty({\n ɵpipe: getClosureSafeProperty\n});\nconst NG_MOD_DEF = getClosureSafeProperty({\n ɵmod: getClosureSafeProperty\n});\nconst NG_FACTORY_DEF = getClosureSafeProperty({\n ɵfac: getClosureSafeProperty\n});\n/**\n * If a directive is diPublic, bloomAdd sets a property on the type with this constant as\n * the key and the directive's unique ID as the value. This allows us to map directives to their\n * bloom filter bit for DI.\n */\n// TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.\nconst NG_ELEMENT_ID = getClosureSafeProperty({\n __NG_ELEMENT_ID__: getClosureSafeProperty\n});\n/**\n * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`:\n * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution\n * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function.\n *\n * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and\n * improve tree-shaking.\n */\nconst NG_ENV_ID = getClosureSafeProperty({\n __NG_ENV_ID__: getClosureSafeProperty\n});\n\n/**\n * Used for stringify render output in Ivy.\n * Important! This function is very performance-sensitive and we should\n * be extra careful not to introduce megamorphic reads in it.\n * Check `core/test/render3/perf/render_stringify` for benchmarks and alternate implementations.\n */\nfunction renderStringify(value) {\n if (typeof value === 'string') return value;\n if (value == null) return '';\n // Use `String` so that it invokes the `toString` method of the value. Note that this\n // appears to be faster than calling `value.toString` (see `render_stringify` benchmark).\n return String(value);\n}\n/**\n * Used to stringify a value so that it can be displayed in an error message.\n *\n * Important! This function contains a megamorphic read and should only be\n * used for error messages.\n */\nfunction stringifyForError(value) {\n if (typeof value === 'function') return value.name || value.toString();\n if (typeof value === 'object' && value != null && typeof value.type === 'function') {\n return value.type.name || value.type.toString();\n }\n return renderStringify(value);\n}\n/**\n * Used to stringify a `Type` and including the file path and line number in which it is defined, if\n * possible, for better debugging experience.\n *\n * Important! This function contains a megamorphic read and should only be used for error messages.\n */\nfunction debugStringifyTypeForError(type) {\n // TODO(pmvald): Do some refactoring so that we can use getComponentDef here without creating\n // circular deps.\n let componentDef = type[NG_COMP_DEF] || null;\n if (componentDef !== null && componentDef.debugInfo) {\n return stringifyTypeFromDebugInfo(componentDef.debugInfo);\n }\n return stringifyForError(type);\n}\n// TODO(pmvald): Do some refactoring so that we can use the type ClassDebugInfo for the param\n// debugInfo here without creating circular deps.\nfunction stringifyTypeFromDebugInfo(debugInfo) {\n if (!debugInfo.filePath || !debugInfo.lineNumber) {\n return debugInfo.className;\n } else {\n return `${debugInfo.className} (at ${debugInfo.filePath}:${debugInfo.lineNumber})`;\n }\n}\n\n/** Called when directives inject each other (creating a circular dependency) */\nfunction throwCyclicDependencyError(token, path) {\n const depPath = path ? `. Dependency path: ${path.join(' > ')} > ${token}` : '';\n throw new RuntimeError(-200 /* RuntimeErrorCode.CYCLIC_DI_DEPENDENCY */, ngDevMode ? `Circular dependency in DI detected for ${token}${depPath}` : token);\n}\nfunction throwMixedMultiProviderError() {\n throw new Error(`Cannot mix multi providers and regular providers`);\n}\nfunction throwInvalidProviderError(ngModuleType, providers, provider) {\n if (ngModuleType && providers) {\n const providerDetail = providers.map(v => v == provider ? '?' + provider + '?' : '...');\n throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}' - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`);\n } else if (isEnvironmentProviders(provider)) {\n if (provider.ɵfromNgModule) {\n 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.`);\n } else {\n 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.`);\n }\n } else {\n throw new Error('Invalid provider');\n }\n}\n/** Throws an error when a token is not found in DI. */\nfunction throwProviderNotFoundError(token, injectorName) {\n const errorMessage = ngDevMode && `No provider for ${stringifyForError(token)} found${injectorName ? ` in ${injectorName}` : ''}`;\n throw new RuntimeError(-201 /* RuntimeErrorCode.PROVIDER_NOT_FOUND */, errorMessage);\n}\n\n/**\n * Injection flags for DI.\n *\n * @publicApi\n * @deprecated use an options object for [`inject`](api/core/inject) instead.\n */\nvar InjectFlags;\n(function (InjectFlags) {\n // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer\n // writes exports of it into ngfactory files.\n /** Check self and check parent injector if needed */\n InjectFlags[InjectFlags[\"Default\"] = 0] = \"Default\";\n /**\n * Specifies that an injector should retrieve a dependency from any injector until reaching the\n * host element of the current component. (Only used with Element Injector)\n */\n InjectFlags[InjectFlags[\"Host\"] = 1] = \"Host\";\n /** Don't ascend to ancestors of the node requesting injection. */\n InjectFlags[InjectFlags[\"Self\"] = 2] = \"Self\";\n /** Skip the node that is requesting injection. */\n InjectFlags[InjectFlags[\"SkipSelf\"] = 4] = \"SkipSelf\";\n /** Inject `defaultValue` instead if token not found. */\n InjectFlags[InjectFlags[\"Optional\"] = 8] = \"Optional\";\n})(InjectFlags || (InjectFlags = {}));\n\n/**\n * Current implementation of inject.\n *\n * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed\n * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this\n * way for two reasons:\n * 1. `Injector` should not depend on ivy logic.\n * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.\n */\nlet _injectImplementation;\nfunction getInjectImplementation() {\n return _injectImplementation;\n}\n/**\n * Sets the current inject implementation.\n */\nfunction setInjectImplementation(impl) {\n const previous = _injectImplementation;\n _injectImplementation = impl;\n return previous;\n}\n/**\n * Injects `root` tokens in limp mode.\n *\n * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to\n * `\"root\"`. This is known as the limp mode injection. In such case the value is stored in the\n * injectable definition.\n */\nfunction injectRootLimpMode(token, notFoundValue, flags) {\n const injectableDef = getInjectableDef(token);\n if (injectableDef && injectableDef.providedIn == 'root') {\n return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() : injectableDef.value;\n }\n if (flags & InjectFlags.Optional) return null;\n if (notFoundValue !== undefined) return notFoundValue;\n throwProviderNotFoundError(token, 'Injector');\n}\n/**\n * Assert that `_injectImplementation` is not `fn`.\n *\n * This is useful, to prevent infinite recursion.\n *\n * @param fn Function which it should not equal to\n */\nfunction assertInjectImplementationNotEqual(fn) {\n ngDevMode && assertNotEqual(_injectImplementation, fn, 'Calling ɵɵinject would cause infinite recursion');\n}\nconst _THROW_IF_NOT_FOUND = {};\nconst THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;\n/*\n * Name of a property (that we patch onto DI decorator), which is used as an annotation of which\n * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators\n * in the code, thus making them tree-shakable.\n */\nconst DI_DECORATOR_FLAG = '__NG_DI_FLAG__';\nconst NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';\nconst NG_TOKEN_PATH = 'ngTokenPath';\nconst NEW_LINE = /\\n/gm;\nconst NO_NEW_LINE = 'ɵ';\nconst SOURCE = '__source';\n/**\n * Current injector value used by `inject`.\n * - `undefined`: it is an error to call `inject`\n * - `null`: `inject` can be called but there is no injector (limp-mode).\n * - Injector instance: Use the injector for resolution.\n */\nlet _currentInjector = undefined;\nfunction getCurrentInjector() {\n return _currentInjector;\n}\nfunction setCurrentInjector(injector) {\n const former = _currentInjector;\n _currentInjector = injector;\n return former;\n}\nfunction injectInjectorOnly(token, flags = InjectFlags.Default) {\n if (_currentInjector === undefined) {\n 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\\`.`);\n } else if (_currentInjector === null) {\n return injectRootLimpMode(token, undefined, flags);\n } else {\n const value = _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);\n ngDevMode && emitInjectEvent(token, value, flags);\n return value;\n }\n}\nfunction ɵɵinject(token, flags = InjectFlags.Default) {\n return (getInjectImplementation() || injectInjectorOnly)(resolveForwardRef(token), flags);\n}\n/**\n * Throws an error indicating that a factory function could not be generated by the compiler for a\n * particular class.\n *\n * The name of the class is not mentioned here, but will be in the generated factory function name\n * and thus in the stack trace.\n *\n * @codeGenApi\n */\nfunction ɵɵinvalidFactoryDep(index) {\n 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.\nThis can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.\n\nPlease 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.`);\n}\n/**\n * Injects a token from the currently active injector.\n * `inject` is only supported in an [injection context](guide/di/dependency-injection-context). It\n * can be used during:\n * - Construction (via the `constructor`) of a class being instantiated by the DI system, such\n * as an `@Injectable` or `@Component`.\n * - In the initializer for fields of such classes.\n * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.\n * - In the `factory` function specified for an `InjectionToken`.\n * - In a stackframe of a function call in a DI context\n *\n * @param token A token that represents a dependency that should be injected.\n * @param flags Optional flags that control how injection is executed.\n * The flags correspond to injection strategies that can be specified with\n * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`.\n * @returns the injected value if operation is successful, `null` otherwise.\n * @throws if called outside of a supported context.\n *\n * @usageNotes\n * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a\n * field initializer:\n *\n * ```typescript\n * @Injectable({providedIn: 'root'})\n * export class Car {\n * radio: Radio|undefined;\n * // OK: field initializer\n * spareTyre = inject(Tyre);\n *\n * constructor() {\n * // OK: constructor body\n * this.radio = inject(Radio);\n * }\n * }\n * ```\n *\n * It is also legal to call `inject` from a provider's factory:\n *\n * ```typescript\n * providers: [\n * {provide: Car, useFactory: () => {\n * // OK: a class factory\n * const engine = inject(Engine);\n * return new Car(engine);\n * }}\n * ]\n * ```\n *\n * Calls to the `inject()` function outside of the class creation context will result in error. Most\n * notably, calls to `inject()` are disallowed after a class instance was created, in methods\n * (including lifecycle hooks):\n *\n * ```typescript\n * @Component({ ... })\n * export class CarComponent {\n * ngOnInit() {\n * // ERROR: too late, the component instance was already created\n * const engine = inject(Engine);\n * engine.start();\n * }\n * }\n * ```\n *\n * @publicApi\n */\nfunction inject(token, flags = InjectFlags.Default) {\n // The `as any` here _shouldn't_ be necessary, but without it JSCompiler\n // throws a disambiguation error due to the multiple signatures.\n return ɵɵinject(token, convertToBitFlags(flags));\n}\n// Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`).\nfunction convertToBitFlags(flags) {\n if (typeof flags === 'undefined' || typeof flags === 'number') {\n return flags;\n }\n // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in\n // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from\n // `InjectOptions` to `InjectFlags`.\n return 0 /* InternalInjectFlags.Default */ | (\n // comment to force a line break in the formatter\n flags.optional && 8 /* InternalInjectFlags.Optional */) | (flags.host && 1 /* InternalInjectFlags.Host */) | (flags.self && 2 /* InternalInjectFlags.Self */) | (flags.skipSelf && 4 /* InternalInjectFlags.SkipSelf */);\n}\nfunction injectArgs(types) {\n const args = [];\n for (let i = 0; i < types.length; i++) {\n const arg = resolveForwardRef(types[i]);\n if (Array.isArray(arg)) {\n if (arg.length === 0) {\n throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && 'Arguments array must have arguments.');\n }\n let type = undefined;\n let flags = InjectFlags.Default;\n for (let j = 0; j < arg.length; j++) {\n const meta = arg[j];\n const flag = getInjectFlag(meta);\n if (typeof flag === 'number') {\n // Special case when we handle @Inject decorator.\n if (flag === -1 /* DecoratorFlags.Inject */) {\n type = meta.token;\n } else {\n flags |= flag;\n }\n } else {\n type = meta;\n }\n }\n args.push(ɵɵinject(type, flags));\n } else {\n args.push(ɵɵinject(arg));\n }\n }\n return args;\n}\n/**\n * Attaches a given InjectFlag to a given decorator using monkey-patching.\n * Since DI decorators can be used in providers `deps` array (when provider is configured using\n * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we\n * attach the flag to make it available both as a static property and as a field on decorator\n * instance.\n *\n * @param decorator Provided DI decorator.\n * @param flag InjectFlag that should be applied.\n */\nfunction attachInjectFlag(decorator, flag) {\n decorator[DI_DECORATOR_FLAG] = flag;\n decorator.prototype[DI_DECORATOR_FLAG] = flag;\n return decorator;\n}\n/**\n * Reads monkey-patched property that contains InjectFlag attached to a decorator.\n *\n * @param token Token that may contain monkey-patched DI flags property.\n */\nfunction getInjectFlag(token) {\n return token[DI_DECORATOR_FLAG];\n}\nfunction catchInjectorError(e, token, injectorErrorName, source) {\n const tokenPath = e[NG_TEMP_TOKEN_PATH];\n if (token[SOURCE]) {\n tokenPath.unshift(token[SOURCE]);\n }\n e.message = formatError('\\n' + e.message, tokenPath, injectorErrorName, source);\n e[NG_TOKEN_PATH] = tokenPath;\n e[NG_TEMP_TOKEN_PATH] = null;\n throw e;\n}\nfunction formatError(text, obj, injectorErrorName, source = null) {\n text = text && text.charAt(0) === '\\n' && text.charAt(1) == NO_NEW_LINE ? text.slice(2) : text;\n let context = stringify(obj);\n if (Array.isArray(obj)) {\n context = obj.map(stringify).join(' -> ');\n } else if (typeof obj === 'object') {\n let parts = [];\n for (let key in obj) {\n if (obj.hasOwnProperty(key)) {\n let value = obj[key];\n parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));\n }\n }\n context = `{${parts.join(', ')}}`;\n }\n return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\\n ')}`;\n}\n\n/**\n * Inject decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Inject = attachInjectFlag(\n// Disable tslint because `DecoratorFlags` is a const enum which gets inlined.\nmakeParamDecorator('Inject', token => ({\n token\n})), -1 /* DecoratorFlags.Inject */);\n/**\n * Optional decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Optional =\n// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.\n// tslint:disable-next-line: no-toplevel-property-access\nattachInjectFlag(makeParamDecorator('Optional'), 8 /* InternalInjectFlags.Optional */);\n/**\n * Self decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Self =\n// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.\n// tslint:disable-next-line: no-toplevel-property-access\nattachInjectFlag(makeParamDecorator('Self'), 2 /* InternalInjectFlags.Self */);\n/**\n * `SkipSelf` decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst SkipSelf =\n// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.\n// tslint:disable-next-line: no-toplevel-property-access\nattachInjectFlag(makeParamDecorator('SkipSelf'), 4 /* InternalInjectFlags.SkipSelf */);\n/**\n * Host decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Host =\n// Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.\n// tslint:disable-next-line: no-toplevel-property-access\nattachInjectFlag(makeParamDecorator('Host'), 1 /* InternalInjectFlags.Host */);\nfunction getFactoryDef(type, throwNotFound) {\n const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);\n if (!hasFactoryDef && throwNotFound === true && ngDevMode) {\n throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);\n }\n return hasFactoryDef ? type[NG_FACTORY_DEF] : null;\n}\n\n/**\n * Determines if the contents of two arrays is identical\n *\n * @param a first array\n * @param b second array\n * @param identityAccessor Optional function for extracting stable object identity from a value in\n * the array.\n */\nfunction arrayEquals(a, b, identityAccessor) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n let valueA = a[i];\n let valueB = b[i];\n if (identityAccessor) {\n valueA = identityAccessor(valueA);\n valueB = identityAccessor(valueB);\n }\n if (valueB !== valueA) {\n return false;\n }\n }\n return true;\n}\n/**\n * Flattens an array.\n */\nfunction flatten(list) {\n return list.flat(Number.POSITIVE_INFINITY);\n}\nfunction deepForEach(input, fn) {\n input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value));\n}\nfunction addToArray(arr, index, value) {\n // perf: array.push is faster than array.splice!\n if (index >= arr.length) {\n arr.push(value);\n } else {\n arr.splice(index, 0, value);\n }\n}\nfunction removeFromArray(arr, index) {\n // perf: array.pop is faster than array.splice!\n if (index >= arr.length - 1) {\n return arr.pop();\n } else {\n return arr.splice(index, 1)[0];\n }\n}\nfunction newArray(size, value) {\n const list = [];\n for (let i = 0; i < size; i++) {\n list.push(value);\n }\n return list;\n}\n/**\n * Remove item from array (Same as `Array.splice()` but faster.)\n *\n * `Array.splice()` is not as fast because it has to allocate an array for the elements which were\n * removed. This causes memory pressure and slows down code when most of the time we don't\n * care about the deleted items array.\n *\n * https://jsperf.com/fast-array-splice (About 20x faster)\n *\n * @param array Array to splice\n * @param index Index of element in array to remove.\n * @param count Number of items to remove.\n */\nfunction arraySplice(array, index, count) {\n const length = array.length - count;\n while (index < length) {\n array[index] = array[index + count];\n index++;\n }\n while (count--) {\n array.pop(); // shrink the array\n }\n}\n/**\n * Same as `Array.splice(index, 0, value)` but faster.\n *\n * `Array.splice()` is not fast because it has to allocate an array for the elements which were\n * removed. This causes memory pressure and slows down code when most of the time we don't\n * care about the deleted items array.\n *\n * @param array Array to splice.\n * @param index Index in array where the `value` should be added.\n * @param value Value to add to array.\n */\nfunction arrayInsert(array, index, value) {\n ngDevMode && assertLessThanOrEqual(index, array.length, \"Can't insert past array end.\");\n let end = array.length;\n while (end > index) {\n const previousEnd = end - 1;\n array[end] = array[previousEnd];\n end = previousEnd;\n }\n array[index] = value;\n}\n/**\n * Same as `Array.splice2(index, 0, value1, value2)` but faster.\n *\n * `Array.splice()` is not fast because it has to allocate an array for the elements which were\n * removed. This causes memory pressure and slows down code when most of the time we don't\n * care about the deleted items array.\n *\n * @param array Array to splice.\n * @param index Index in array where the `value` should be added.\n * @param value1 Value to add to array.\n * @param value2 Value to add to array.\n */\nfunction arrayInsert2(array, index, value1, value2) {\n ngDevMode && assertLessThanOrEqual(index, array.length, \"Can't insert past array end.\");\n let end = array.length;\n if (end == index) {\n // inserting at the end.\n array.push(value1, value2);\n } else if (end === 1) {\n // corner case when we have less items in array than we have items to insert.\n array.push(value2, array[0]);\n array[0] = value1;\n } else {\n end--;\n array.push(array[end - 1], array[end]);\n while (end > index) {\n const previousEnd = end - 2;\n array[end] = array[previousEnd];\n end--;\n }\n array[index] = value1;\n array[index + 1] = value2;\n }\n}\n/**\n * Get an index of an `value` in a sorted `array`.\n *\n * NOTE:\n * - This uses binary search algorithm for fast removals.\n *\n * @param array A sorted array to binary search.\n * @param value The value to look for.\n * @returns index of the value.\n * - positive index if value found.\n * - negative index if value not found. (`~index` to get the value where it should have been\n * located)\n */\nfunction arrayIndexOfSorted(array, value) {\n return _arrayIndexOfSorted(array, value, 0);\n}\n/**\n * Set a `value` for a `key`.\n *\n * @param keyValueArray to modify.\n * @param key The key to locate or create.\n * @param value The value to set for a `key`.\n * @returns index (always even) of where the value vas set.\n */\nfunction keyValueArraySet(keyValueArray, key, value) {\n let index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it set it.\n keyValueArray[index | 1] = value;\n } else {\n index = ~index;\n arrayInsert2(keyValueArray, index, key, value);\n }\n return index;\n}\n/**\n * Retrieve a `value` for a `key` (on `undefined` if not found.)\n *\n * @param keyValueArray to search.\n * @param key The key to locate.\n * @return The `value` stored at the `key` location or `undefined if not found.\n */\nfunction keyValueArrayGet(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it retrieve it.\n return keyValueArray[index | 1];\n }\n return undefined;\n}\n/**\n * Retrieve a `key` index value in the array or `-1` if not found.\n *\n * @param keyValueArray to search.\n * @param key The key to locate.\n * @returns index of where the key is (or should have been.)\n * - positive (even) index if key found.\n * - negative index if key not found. (`~index` (even) to get the index where it should have\n * been inserted.)\n */\nfunction keyValueArrayIndexOf(keyValueArray, key) {\n return _arrayIndexOfSorted(keyValueArray, key, 1);\n}\n/**\n * Delete a `key` (and `value`) from the `KeyValueArray`.\n *\n * @param keyValueArray to modify.\n * @param key The key to locate or delete (if exist).\n * @returns index of where the key was (or should have been.)\n * - positive (even) index if key found and deleted.\n * - negative index if key not found. (`~index` (even) to get the index where it should have\n * been.)\n */\nfunction keyValueArrayDelete(keyValueArray, key) {\n const index = keyValueArrayIndexOf(keyValueArray, key);\n if (index >= 0) {\n // if we found it remove it.\n arraySplice(keyValueArray, index, 2);\n }\n return index;\n}\n/**\n * INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.\n *\n * NOTE:\n * - This uses binary search algorithm for fast removals.\n *\n * @param array A sorted array to binary search.\n * @param value The value to look for.\n * @param shift grouping shift.\n * - `0` means look at every location\n * - `1` means only look at every other (even) location (the odd locations are to be ignored as\n * they are values.)\n * @returns index of the value.\n * - positive index if value found.\n * - negative index if value not found. (`~index` to get the value where it should have been\n * inserted)\n */\nfunction _arrayIndexOfSorted(array, value, shift) {\n ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');\n let start = 0;\n let end = array.length >> shift;\n while (end !== start) {\n const middle = start + (end - start >> 1); // find the middle.\n const current = array[middle << shift];\n if (value === current) {\n return middle << shift;\n } else if (current > value) {\n end = middle;\n } else {\n start = middle + 1; // We already searched middle so make it non-inclusive by adding 1\n }\n }\n return ~(end << shift);\n}\n\n/**\n * This file contains reuseable \"empty\" symbols that can be used as default return values\n * in different parts of the rendering code. Because the same symbols are returned, this\n * allows for identity checks against these values to be consistently used by the framework\n * code.\n */\nconst EMPTY_OBJ = {};\nconst EMPTY_ARRAY = [];\n// freezing the values prevents any code from accidentally inserting new values in\nif ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {\n // These property accesses can be ignored because ngDevMode will be set to false\n // when optimizing code and the whole if statement will be dropped.\n // tslint:disable-next-line:no-toplevel-property-access\n Object.freeze(EMPTY_OBJ);\n // tslint:disable-next-line:no-toplevel-property-access\n Object.freeze(EMPTY_ARRAY);\n}\n\n/**\n * A multi-provider token for initialization functions that will run upon construction of an\n * environment injector.\n *\n * Note: As opposed to the `APP_INITIALIZER` token, the `ENVIRONMENT_INITIALIZER` functions are not awaited,\n * hence they should not be `async`.\n *\n * @publicApi\n */\nconst ENVIRONMENT_INITIALIZER = new InjectionToken(ngDevMode ? 'ENVIRONMENT_INITIALIZER' : '');\n\n/**\n * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.\n *\n * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a\n * project.\n *\n * @publicApi\n */\nconst INJECTOR$1 = new InjectionToken(ngDevMode ? 'INJECTOR' : '',\n// Disable tslint because this is const enum which gets inlined not top level prop access.\n// tslint:disable-next-line: no-toplevel-property-access\n-1 /* InjectorMarkers.Injector */);\nconst INJECTOR_DEF_TYPES = new InjectionToken(ngDevMode ? 'INJECTOR_DEF_TYPES' : '');\nclass NullInjector {\n get(token, notFoundValue = THROW_IF_NOT_FOUND) {\n if (notFoundValue === THROW_IF_NOT_FOUND) {\n const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);\n error.name = 'NullInjectorError';\n throw error;\n }\n return notFoundValue;\n }\n}\n\n/**\n * The strategy that the default change detector uses to detect changes.\n * When set, takes effect the next time change detection is triggered.\n *\n * @see [Change detection usage](/api/core/ChangeDetectorRef?tab=usage-notes)\n * @see [Skipping component subtrees](/best-practices/skipping-subtrees)\n *\n * @publicApi\n */\nvar ChangeDetectionStrategy;\n(function (ChangeDetectionStrategy) {\n /**\n * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated\n * until reactivated by setting the strategy to `Default` (`CheckAlways`).\n * Change detection can still be explicitly invoked.\n * This strategy applies to all child directives and cannot be overridden.\n */\n ChangeDetectionStrategy[ChangeDetectionStrategy[\"OnPush\"] = 0] = \"OnPush\";\n /**\n * Use the default `CheckAlways` strategy, in which change detection is automatic until\n * explicitly deactivated.\n */\n ChangeDetectionStrategy[ChangeDetectionStrategy[\"Default\"] = 1] = \"Default\";\n})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));\n\n/**\n * Defines the CSS styles encapsulation policies for the {@link Component} decorator's\n * `encapsulation` option.\n *\n * See {@link Component#encapsulation encapsulation}.\n *\n * @usageNotes\n * ### Example\n *\n * {@example core/ts/metadata/encapsulation.ts region='longform'}\n *\n * @publicApi\n */\nvar ViewEncapsulation$1;\n(function (ViewEncapsulation) {\n // TODO: consider making `ViewEncapsulation` a `const enum` instead. See\n // https://github.com/angular/angular/issues/44119 for additional information.\n /**\n * Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the\n * component's host element and applying the same attribute to all the CSS selectors provided\n * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}.\n *\n * This is the default option.\n */\n ViewEncapsulation[ViewEncapsulation[\"Emulated\"] = 0] = \"Emulated\";\n // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.\n /**\n * Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided\n * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable\n * to any HTML element of the application regardless of their host Component.\n */\n ViewEncapsulation[ViewEncapsulation[\"None\"] = 2] = \"None\";\n /**\n * Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates\n * a ShadowRoot for the component's host element which is then used to encapsulate\n * all the Component's styling.\n */\n ViewEncapsulation[ViewEncapsulation[\"ShadowDom\"] = 3] = \"ShadowDom\";\n})(ViewEncapsulation$1 || (ViewEncapsulation$1 = {}));\n\n/** Flags describing an input for a directive. */\nvar InputFlags;\n(function (InputFlags) {\n InputFlags[InputFlags[\"None\"] = 0] = \"None\";\n InputFlags[InputFlags[\"SignalBased\"] = 1] = \"SignalBased\";\n InputFlags[InputFlags[\"HasDecoratorInputTransform\"] = 2] = \"HasDecoratorInputTransform\";\n})(InputFlags || (InputFlags = {}));\n\n/**\n * Returns an index of `classToSearch` in `className` taking token boundaries into account.\n *\n * `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)\n *\n * @param className A string containing classes (whitespace separated)\n * @param classToSearch A class name to locate\n * @param startingIndex Starting location of search\n * @returns an index of the located class (or -1 if not found)\n */\nfunction classIndexOf(className, classToSearch, startingIndex) {\n ngDevMode && assertNotEqual(classToSearch, '', 'can not look for \"\" string.');\n let end = className.length;\n while (true) {\n const foundIndex = className.indexOf(classToSearch, startingIndex);\n if (foundIndex === -1) return foundIndex;\n if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* CharCode.SPACE */) {\n // Ensure that it has leading whitespace\n const length = classToSearch.length;\n if (foundIndex + length === end || className.charCodeAt(foundIndex + length) <= 32 /* CharCode.SPACE */) {\n // Ensure that it has trailing whitespace\n return foundIndex;\n }\n }\n // False positive, keep searching from where we left off.\n startingIndex = foundIndex + 1;\n }\n}\n\n/**\n * Assigns all attribute values to the provided element via the inferred renderer.\n *\n * This function accepts two forms of attribute entries:\n *\n * default: (key, value):\n * attrs = [key1, value1, key2, value2]\n *\n * namespaced: (NAMESPACE_MARKER, uri, name, value)\n * attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]\n *\n * The `attrs` array can contain a mix of both the default and namespaced entries.\n * The \"default\" values are set without a marker, but if the function comes across\n * a marker value then it will attempt to set a namespaced value. If the marker is\n * not of a namespaced value then the function will quit and return the index value\n * where it stopped during the iteration of the attrs array.\n *\n * See [AttributeMarker] to understand what the namespace marker value is.\n *\n * Note that this instruction does not support assigning style and class values to\n * an element. See `elementStart` and `elementHostAttrs` to learn how styling values\n * are applied to an element.\n * @param renderer The renderer to be used\n * @param native The element that the attributes will be assigned to\n * @param attrs The attribute array of values that will be assigned to the element\n * @returns the index value that was last accessed in the attributes array\n */\nfunction setUpAttributes(renderer, native, attrs) {\n let i = 0;\n while (i < attrs.length) {\n const value = attrs[i];\n if (typeof value === 'number') {\n // only namespaces are supported. Other value types (such as style/class\n // entries) are not supported in this function.\n if (value !== 0 /* AttributeMarker.NamespaceURI */) {\n break;\n }\n // we just landed on the marker value ... therefore\n // we should skip to the next entry\n i++;\n const namespaceURI = attrs[i++];\n const attrName = attrs[i++];\n const attrVal = attrs[i++];\n ngDevMode && ngDevMode.rendererSetAttribute++;\n renderer.setAttribute(native, attrName, attrVal, namespaceURI);\n } else {\n // attrName is string;\n const attrName = value;\n const attrVal = attrs[++i];\n // Standard attributes\n ngDevMode && ngDevMode.rendererSetAttribute++;\n if (isAnimationProp(attrName)) {\n renderer.setProperty(native, attrName, attrVal);\n } else {\n renderer.setAttribute(native, attrName, attrVal);\n }\n i++;\n }\n }\n // another piece of code may iterate over the same attributes array. Therefore\n // it may be helpful to return the exact spot where the attributes array exited\n // whether by running into an unsupported marker or if all the static values were\n // iterated over.\n return i;\n}\n/**\n * Test whether the given value is a marker that indicates that the following\n * attribute values in a `TAttributes` array are only the names of attributes,\n * and not name-value pairs.\n * @param marker The attribute marker to test.\n * @returns true if the marker is a \"name-only\" marker (e.g. `Bindings`, `Template` or `I18n`).\n */\nfunction isNameOnlyAttributeMarker(marker) {\n return marker === 3 /* AttributeMarker.Bindings */ || marker === 4 /* AttributeMarker.Template */ || marker === 6 /* AttributeMarker.I18n */;\n}\nfunction isAnimationProp(name) {\n // Perf note: accessing charCodeAt to check for the first character of a string is faster as\n // compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that\n // charCodeAt doesn't allocate memory to return a substring.\n return name.charCodeAt(0) === 64 /* CharCode.AT_SIGN */;\n}\n/**\n * Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.\n *\n * This merge function keeps the order of attrs same.\n *\n * @param dst Location of where the merged `TAttributes` should end up.\n * @param src `TAttributes` which should be appended to `dst`\n */\nfunction mergeHostAttrs(dst, src) {\n if (src === null || src.length === 0) {\n // do nothing\n } else if (dst === null || dst.length === 0) {\n // We have source, but dst is empty, just make a copy.\n dst = src.slice();\n } else {\n let srcMarker = -1 /* AttributeMarker.ImplicitAttributes */;\n for (let i = 0; i < src.length; i++) {\n const item = src[i];\n if (typeof item === 'number') {\n srcMarker = item;\n } else {\n if (srcMarker === 0 /* AttributeMarker.NamespaceURI */) {\n // Case where we need to consume `key1`, `key2`, `value` items.\n } else if (srcMarker === -1 /* AttributeMarker.ImplicitAttributes */ || srcMarker === 2 /* AttributeMarker.Styles */) {\n // Case where we have to consume `key1` and `value` only.\n mergeHostAttribute(dst, srcMarker, item, null, src[++i]);\n } else {\n // Case where we have to consume `key1` only.\n mergeHostAttribute(dst, srcMarker, item, null, null);\n }\n }\n }\n }\n return dst;\n}\n/**\n * Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.\n *\n * @param dst `TAttributes` to append to.\n * @param marker Region where the `key`/`value` should be added.\n * @param key1 Key to add to `TAttributes`\n * @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)\n * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.\n */\nfunction mergeHostAttribute(dst, marker, key1, key2, value) {\n let i = 0;\n // Assume that new markers will be inserted at the end.\n let markerInsertPosition = dst.length;\n // scan until correct type.\n if (marker === -1 /* AttributeMarker.ImplicitAttributes */) {\n markerInsertPosition = -1;\n } else {\n while (i < dst.length) {\n const dstValue = dst[i++];\n if (typeof dstValue === 'number') {\n if (dstValue === marker) {\n markerInsertPosition = -1;\n break;\n } else if (dstValue > marker) {\n // We need to save this as we want the markers to be inserted in specific order.\n markerInsertPosition = i - 1;\n break;\n }\n }\n }\n }\n // search until you find place of insertion\n while (i < dst.length) {\n const item = dst[i];\n if (typeof item === 'number') {\n // since `i` started as the index after the marker, we did not find it if we are at the next\n // marker\n break;\n } else if (item === key1) {\n // We already have same token\n if (key2 === null) {\n if (value !== null) {\n dst[i + 1] = value;\n }\n return;\n } else if (key2 === dst[i + 1]) {\n dst[i + 2] = value;\n return;\n }\n }\n // Increment counter.\n i++;\n if (key2 !== null) i++;\n if (value !== null) i++;\n }\n // insert at location.\n if (markerInsertPosition !== -1) {\n dst.splice(markerInsertPosition, 0, marker);\n i = markerInsertPosition + 1;\n }\n dst.splice(i++, 0, key1);\n if (key2 !== null) {\n dst.splice(i++, 0, key2);\n }\n if (value !== null) {\n dst.splice(i++, 0, value);\n }\n}\nconst NG_TEMPLATE_SELECTOR = 'ng-template';\n/**\n * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)\n *\n * @param tNode static data of the node to match\n * @param attrs `TAttributes` to search through.\n * @param cssClassToMatch class to match (lowercase)\n * @param isProjectionMode Whether or not class matching should look into the attribute `class` in\n * addition to the `AttributeMarker.Classes`.\n */\nfunction isCssClassMatching(tNode, attrs, cssClassToMatch, isProjectionMode) {\n ngDevMode && assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');\n let i = 0;\n if (isProjectionMode) {\n for (; i < attrs.length && typeof attrs[i] === 'string'; i += 2) {\n // Search for an implicit `class` attribute and check if its value matches `cssClassToMatch`.\n if (attrs[i] === 'class' && classIndexOf(attrs[i + 1].toLowerCase(), cssClassToMatch, 0) !== -1) {\n return true;\n }\n }\n } else if (isInlineTemplate(tNode)) {\n // Matching directives (i.e. when not matching for projection mode) should not consider the\n // class bindings that are present on inline templates, as those class bindings only target\n // the root node of the template, not the template itself.\n return false;\n }\n // Resume the search for classes after the `Classes` marker.\n i = attrs.indexOf(1 /* AttributeMarker.Classes */, i);\n if (i > -1) {\n // We found the classes section. Start searching for the class.\n let item;\n while (++i < attrs.length && typeof (item = attrs[i]) === 'string') {\n if (item.toLowerCase() === cssClassToMatch) {\n return true;\n }\n }\n }\n return false;\n}\n/**\n * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).\n *\n * @param tNode current TNode\n */\nfunction isInlineTemplate(tNode) {\n return tNode.type === 4 /* TNodeType.Container */ && tNode.value !== NG_TEMPLATE_SELECTOR;\n}\n/**\n * Function that checks whether a given tNode matches tag-based selector and has a valid type.\n *\n * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular\n * directive matching mode:\n * - in the \"directive matching\" mode we do _not_ take TContainer's tagName into account if it is\n * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a\n * tag name was extracted from * syntax so we would match the same directive twice);\n * - in the \"projection\" mode, we use a tag name potentially extracted from the * syntax processing\n * (applicable to TNodeType.Container only).\n */\nfunction hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {\n const tagNameToCompare = tNode.type === 4 /* TNodeType.Container */ && !isProjectionMode ? NG_TEMPLATE_SELECTOR : tNode.value;\n return currentSelector === tagNameToCompare;\n}\n/**\n * A utility function to match an Ivy node static data against a simple CSS selector\n *\n * @param tNode static data of the node to match\n * @param selector The selector to try matching against the node.\n * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing\n * directive matching.\n * @returns true if node matches the selector.\n */\nfunction isNodeMatchingSelector(tNode, selector, isProjectionMode) {\n ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');\n let mode = 4 /* SelectorFlags.ELEMENT */;\n const nodeAttrs = tNode.attrs;\n // Find the index of first attribute that has no value, only a name.\n const nameOnlyMarkerIdx = nodeAttrs !== null ? getNameOnlyMarkerIndex(nodeAttrs) : 0;\n // When processing \":not\" selectors, we skip to the next \":not\" if the\n // current one doesn't match\n let skipToNextSelector = false;\n for (let i = 0; i < selector.length; i++) {\n const current = selector[i];\n if (typeof current === 'number') {\n // If we finish processing a :not selector and it hasn't failed, return false\n if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {\n return false;\n }\n // If we are skipping to the next :not() and this mode flag is positive,\n // it's a part of the current :not() selector, and we should keep skipping\n if (skipToNextSelector && isPositive(current)) continue;\n skipToNextSelector = false;\n mode = current | mode & 1 /* SelectorFlags.NOT */;\n continue;\n }\n if (skipToNextSelector) continue;\n if (mode & 4 /* SelectorFlags.ELEMENT */) {\n mode = 2 /* SelectorFlags.ATTRIBUTE */ | mode & 1 /* SelectorFlags.NOT */;\n if (current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode) || current === '' && selector.length === 1) {\n if (isPositive(mode)) return false;\n skipToNextSelector = true;\n }\n } else if (mode & 8 /* SelectorFlags.CLASS */) {\n if (nodeAttrs === null || !isCssClassMatching(tNode, nodeAttrs, current, isProjectionMode)) {\n if (isPositive(mode)) return false;\n skipToNextSelector = true;\n }\n } else {\n const selectorAttrValue = selector[++i];\n const attrIndexInNode = findAttrIndexInNode(current, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);\n if (attrIndexInNode === -1) {\n if (isPositive(mode)) return false;\n skipToNextSelector = true;\n continue;\n }\n if (selectorAttrValue !== '') {\n let nodeAttrValue;\n if (attrIndexInNode > nameOnlyMarkerIdx) {\n nodeAttrValue = '';\n } else {\n ngDevMode && assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* AttributeMarker.NamespaceURI */, 'We do not match directives on namespaced attributes');\n // we lowercase the attribute value to be able to match\n // selectors without case-sensitivity\n // (selectors are already in lowercase when generated)\n nodeAttrValue = nodeAttrs[attrIndexInNode + 1].toLowerCase();\n }\n if (mode & 2 /* SelectorFlags.ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {\n if (isPositive(mode)) return false;\n skipToNextSelector = true;\n }\n }\n }\n }\n return isPositive(mode) || skipToNextSelector;\n}\nfunction isPositive(mode) {\n return (mode & 1 /* SelectorFlags.NOT */) === 0;\n}\n/**\n * Examines the attribute's definition array for a node to find the index of the\n * attribute that matches the given `name`.\n *\n * NOTE: This will not match namespaced attributes.\n *\n * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.\n * The following table summarizes which types of attributes we attempt to match:\n *\n * ===========================================================================================================\n * Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n\n * Attributes\n * ===========================================================================================================\n * Inline + Projection | YES | YES | NO | YES\n * -----------------------------------------------------------------------------------------------------------\n * Inline + Directive | NO | NO | YES | NO\n * -----------------------------------------------------------------------------------------------------------\n * Non-inline + Projection | YES | YES | NO | YES\n * -----------------------------------------------------------------------------------------------------------\n * Non-inline + Directive | YES | YES | NO | YES\n * ===========================================================================================================\n *\n * @param name the name of the attribute to find\n * @param attrs the attribute array to examine\n * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)\n * rather than a manually expanded template node (e.g ``).\n * @param isProjectionMode true if we are matching against content projection otherwise we are\n * matching against directives.\n */\nfunction findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {\n if (attrs === null) return -1;\n let i = 0;\n if (isProjectionMode || !isInlineTemplate) {\n let bindingsMode = false;\n while (i < attrs.length) {\n const maybeAttrName = attrs[i];\n if (maybeAttrName === name) {\n return i;\n } else if (maybeAttrName === 3 /* AttributeMarker.Bindings */ || maybeAttrName === 6 /* AttributeMarker.I18n */) {\n bindingsMode = true;\n } else if (maybeAttrName === 1 /* AttributeMarker.Classes */ || maybeAttrName === 2 /* AttributeMarker.Styles */) {\n let value = attrs[++i];\n // We should skip classes here because we have a separate mechanism for\n // matching classes in projection mode.\n while (typeof value === 'string') {\n value = attrs[++i];\n }\n continue;\n } else if (maybeAttrName === 4 /* AttributeMarker.Template */) {\n // We do not care about Template attributes in this scenario.\n break;\n } else if (maybeAttrName === 0 /* AttributeMarker.NamespaceURI */) {\n // Skip the whole namespaced attribute and value. This is by design.\n i += 4;\n continue;\n }\n // In binding mode there are only names, rather than name-value pairs.\n i += bindingsMode ? 1 : 2;\n }\n // We did not match the attribute\n return -1;\n } else {\n return matchTemplateAttribute(attrs, name);\n }\n}\nfunction isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {\n for (let i = 0; i < selector.length; i++) {\n if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {\n return true;\n }\n }\n return false;\n}\nfunction getProjectAsAttrValue(tNode) {\n const nodeAttrs = tNode.attrs;\n if (nodeAttrs != null) {\n const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* AttributeMarker.ProjectAs */);\n // only check for ngProjectAs in attribute names, don't accidentally match attribute's value\n // (attribute names are stored at even indexes)\n if ((ngProjectAsAttrIdx & 1) === 0) {\n return nodeAttrs[ngProjectAsAttrIdx + 1];\n }\n }\n return null;\n}\nfunction getNameOnlyMarkerIndex(nodeAttrs) {\n for (let i = 0; i < nodeAttrs.length; i++) {\n const nodeAttr = nodeAttrs[i];\n if (isNameOnlyAttributeMarker(nodeAttr)) {\n return i;\n }\n }\n return nodeAttrs.length;\n}\nfunction matchTemplateAttribute(attrs, name) {\n let i = attrs.indexOf(4 /* AttributeMarker.Template */);\n if (i > -1) {\n i++;\n while (i < attrs.length) {\n const attr = attrs[i];\n // Return in case we checked all template attrs and are switching to the next section in the\n // attrs array (that starts with a number that represents an attribute marker).\n if (typeof attr === 'number') return -1;\n if (attr === name) return i;\n i++;\n }\n }\n return -1;\n}\n/**\n * Checks whether a selector is inside a CssSelectorList\n * @param selector Selector to be checked.\n * @param list List in which to look for the selector.\n */\nfunction isSelectorInSelectorList(selector, list) {\n selectorListLoop: for (let i = 0; i < list.length; i++) {\n const currentSelectorInList = list[i];\n if (selector.length !== currentSelectorInList.length) {\n continue;\n }\n for (let j = 0; j < selector.length; j++) {\n if (selector[j] !== currentSelectorInList[j]) {\n continue selectorListLoop;\n }\n }\n return true;\n }\n return false;\n}\nfunction maybeWrapInNotSelector(isNegativeMode, chunk) {\n return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;\n}\nfunction stringifyCSSSelector(selector) {\n let result = selector[0];\n let i = 1;\n let mode = 2 /* SelectorFlags.ATTRIBUTE */;\n let currentChunk = '';\n let isNegativeMode = false;\n while (i < selector.length) {\n let valueOrMarker = selector[i];\n if (typeof valueOrMarker === 'string') {\n if (mode & 2 /* SelectorFlags.ATTRIBUTE */) {\n const attrValue = selector[++i];\n currentChunk += '[' + valueOrMarker + (attrValue.length > 0 ? '=\"' + attrValue + '\"' : '') + ']';\n } else if (mode & 8 /* SelectorFlags.CLASS */) {\n currentChunk += '.' + valueOrMarker;\n } else if (mode & 4 /* SelectorFlags.ELEMENT */) {\n currentChunk += ' ' + valueOrMarker;\n }\n } else {\n //\n // Append current chunk to the final result in case we come across SelectorFlag, which\n // indicates that the previous section of a selector is over. We need to accumulate content\n // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.\n // ```\n // ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']\n // ```\n // should be transformed to `.classA :not(.classB .classC)`.\n //\n // Note: for negative selector part, we accumulate content between flags until we find the\n // next negative flag. This is needed to support a case where `:not()` rule contains more than\n // one chunk, e.g. the following selector:\n // ```\n // ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']\n // ```\n // should be stringified to `:not(p.foo) :not(.bar)`\n //\n if (currentChunk !== '' && !isPositive(valueOrMarker)) {\n result += maybeWrapInNotSelector(isNegativeMode, currentChunk);\n currentChunk = '';\n }\n mode = valueOrMarker;\n // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative\n // mode is maintained for remaining chunks of a selector.\n isNegativeMode = isNegativeMode || !isPositive(mode);\n }\n i++;\n }\n if (currentChunk !== '') {\n result += maybeWrapInNotSelector(isNegativeMode, currentChunk);\n }\n return result;\n}\n/**\n * Generates string representation of CSS selector in parsed form.\n *\n * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing\n * additional parsing at runtime (for example, for directive matching). However in some cases (for\n * example, while bootstrapping a component), a string version of the selector is required to query\n * for the host element on the page. This function takes the parsed form of a selector and returns\n * its string representation.\n *\n * @param selectorList selector in parsed form\n * @returns string representation of a given selector\n */\nfunction stringifyCSSSelectorList(selectorList) {\n return selectorList.map(stringifyCSSSelector).join(',');\n}\n/**\n * Extracts attributes and classes information from a given CSS selector.\n *\n * This function is used while creating a component dynamically. In this case, the host element\n * (that is created dynamically) should contain attributes and classes specified in component's CSS\n * selector.\n *\n * @param selector CSS selector in parsed form (in a form of array)\n * @returns object with `attrs` and `classes` fields that contain extracted information\n */\nfunction extractAttrsAndClassesFromSelector(selector) {\n const attrs = [];\n const classes = [];\n let i = 1;\n let mode = 2 /* SelectorFlags.ATTRIBUTE */;\n while (i < selector.length) {\n let valueOrMarker = selector[i];\n if (typeof valueOrMarker === 'string') {\n if (mode === 2 /* SelectorFlags.ATTRIBUTE */) {\n if (valueOrMarker !== '') {\n attrs.push(valueOrMarker, selector[++i]);\n }\n } else if (mode === 8 /* SelectorFlags.CLASS */) {\n classes.push(valueOrMarker);\n }\n } else {\n // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative\n // mode is maintained for remaining chunks of a selector. Since attributes and classes are\n // extracted only for \"positive\" part of the selector, we can stop here.\n if (!isPositive(mode)) break;\n mode = valueOrMarker;\n }\n i++;\n }\n return {\n attrs,\n classes\n };\n}\n\n/**\n * Create a component definition object.\n *\n *\n * # Example\n * ```\n * class MyComponent {\n * // Generated by Angular Template Compiler\n * // [Symbol] syntax will not be supported by TypeScript until v2.7\n * static ɵcmp = defineComponent({\n * ...\n * });\n * }\n * ```\n * @codeGenApi\n */\nfunction ɵɵdefineComponent(componentDefinition) {\n return noSideEffects(() => {\n // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.\n // See the `initNgDevMode` docstring for more information.\n (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();\n const baseDef = getNgDirectiveDef(componentDefinition);\n const def = {\n ...baseDef,\n decls: componentDefinition.decls,\n vars: componentDefinition.vars,\n template: componentDefinition.template,\n consts: componentDefinition.consts || null,\n ngContentSelectors: componentDefinition.ngContentSelectors,\n onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,\n directiveDefs: null,\n // assigned in noSideEffects\n pipeDefs: null,\n // assigned in noSideEffects\n dependencies: baseDef.standalone && componentDefinition.dependencies || null,\n getStandaloneInjector: null,\n signals: componentDefinition.signals ?? false,\n data: componentDefinition.data || {},\n encapsulation: componentDefinition.encapsulation || ViewEncapsulation$1.Emulated,\n styles: componentDefinition.styles || EMPTY_ARRAY,\n _: null,\n schemas: componentDefinition.schemas || null,\n tView: null,\n id: ''\n };\n initFeatures(def);\n const dependencies = componentDefinition.dependencies;\n def.directiveDefs = extractDefListOrFactory(dependencies, /* pipeDef */false);\n def.pipeDefs = extractDefListOrFactory(dependencies, /* pipeDef */true);\n def.id = getComponentId(def);\n return def;\n });\n}\nfunction extractDirectiveDef(type) {\n return getComponentDef(type) || getDirectiveDef(type);\n}\nfunction nonNull(value) {\n return value !== null;\n}\n/**\n * @codeGenApi\n */\nfunction ɵɵdefineNgModule(def) {\n return noSideEffects(() => {\n const res = {\n type: def.type,\n bootstrap: def.bootstrap || EMPTY_ARRAY,\n declarations: def.declarations || EMPTY_ARRAY,\n imports: def.imports || EMPTY_ARRAY,\n exports: def.exports || EMPTY_ARRAY,\n transitiveCompileScopes: null,\n schemas: def.schemas || null,\n id: def.id || null\n };\n return res;\n });\n}\nfunction parseAndConvertBindingsForDefinition(obj, declaredInputs) {\n if (obj == null) return EMPTY_OBJ;\n const newLookup = {};\n for (const minifiedKey in obj) {\n if (obj.hasOwnProperty(minifiedKey)) {\n const value = obj[minifiedKey];\n let publicName;\n let declaredName;\n let inputFlags = InputFlags.None;\n if (Array.isArray(value)) {\n inputFlags = value[0];\n publicName = value[1];\n declaredName = value[2] ?? publicName; // declared name might not be set to save bytes.\n } else {\n publicName = value;\n declaredName = value;\n }\n // For inputs, capture the declared name, or if some flags are set.\n if (declaredInputs) {\n // Perf note: An array is only allocated for the input if there are flags.\n newLookup[publicName] = inputFlags !== InputFlags.None ? [minifiedKey, inputFlags] : minifiedKey;\n declaredInputs[publicName] = declaredName;\n } else {\n newLookup[publicName] = minifiedKey;\n }\n }\n }\n return newLookup;\n}\n/**\n * Create a directive definition object.\n *\n * # Example\n * ```ts\n * class MyDirective {\n * // Generated by Angular Template Compiler\n * // [Symbol] syntax will not be supported by TypeScript until v2.7\n * static ɵdir = ɵɵdefineDirective({\n * ...\n * });\n * }\n * ```\n *\n * @codeGenApi\n */\nfunction ɵɵdefineDirective(directiveDefinition) {\n return noSideEffects(() => {\n const def = getNgDirectiveDef(directiveDefinition);\n initFeatures(def);\n return def;\n });\n}\n/**\n * Create a pipe definition object.\n *\n * # Example\n * ```\n * class MyPipe implements PipeTransform {\n * // Generated by Angular Template Compiler\n * static ɵpipe = definePipe({\n * ...\n * });\n * }\n * ```\n * @param pipeDef Pipe definition generated by the compiler\n *\n * @codeGenApi\n */\nfunction ɵɵdefinePipe(pipeDef) {\n return {\n type: pipeDef.type,\n name: pipeDef.name,\n factory: null,\n pure: pipeDef.pure !== false,\n standalone: pipeDef.standalone === true,\n onDestroy: pipeDef.type.prototype.ngOnDestroy || null\n };\n}\n/**\n * The following getter methods retrieve the definition from the type. Currently the retrieval\n * honors inheritance, but in the future we may change the rule to require that definitions are\n * explicit. This would require some sort of migration strategy.\n */\nfunction getComponentDef(type) {\n return type[NG_COMP_DEF] || null;\n}\nfunction getDirectiveDef(type) {\n return type[NG_DIR_DEF] || null;\n}\nfunction getPipeDef$1(type) {\n return type[NG_PIPE_DEF] || null;\n}\n/**\n * Checks whether a given Component, Directive or Pipe is marked as standalone.\n * This will return false if passed anything other than a Component, Directive, or Pipe class\n * See [this guide](guide/components/importing) for additional information:\n *\n * @param type A reference to a Component, Directive or Pipe.\n * @publicApi\n */\nfunction isStandalone(type) {\n const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);\n return def !== null ? def.standalone : false;\n}\nfunction getNgModuleDef(type, throwNotFound) {\n const ngModuleDef = type[NG_MOD_DEF] || null;\n if (!ngModuleDef && throwNotFound === true) {\n throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);\n }\n return ngModuleDef;\n}\nfunction getNgDirectiveDef(directiveDefinition) {\n const declaredInputs = {};\n return {\n type: directiveDefinition.type,\n providersResolver: null,\n factory: null,\n hostBindings: directiveDefinition.hostBindings || null,\n hostVars: directiveDefinition.hostVars || 0,\n hostAttrs: directiveDefinition.hostAttrs || null,\n contentQueries: directiveDefinition.contentQueries || null,\n declaredInputs: declaredInputs,\n inputTransforms: null,\n inputConfig: directiveDefinition.inputs || EMPTY_OBJ,\n exportAs: directiveDefinition.exportAs || null,\n standalone: directiveDefinition.standalone === true,\n signals: directiveDefinition.signals === true,\n selectors: directiveDefinition.selectors || EMPTY_ARRAY,\n viewQuery: directiveDefinition.viewQuery || null,\n features: directiveDefinition.features || null,\n setInput: null,\n findHostDirectiveDefs: null,\n hostDirectives: null,\n inputs: parseAndConvertBindingsForDefinition(directiveDefinition.inputs, declaredInputs),\n outputs: parseAndConvertBindingsForDefinition(directiveDefinition.outputs),\n debugInfo: null\n };\n}\nfunction initFeatures(definition) {\n definition.features?.forEach(fn => fn(definition));\n}\nfunction extractDefListOrFactory(dependencies, pipeDef) {\n if (!dependencies) {\n return null;\n }\n const defExtractor = pipeDef ? getPipeDef$1 : extractDirectiveDef;\n return () => (typeof dependencies === 'function' ? dependencies() : dependencies).map(dep => defExtractor(dep)).filter(nonNull);\n}\n/**\n * A map that contains the generated component IDs and type.\n */\nconst GENERATED_COMP_IDS = new Map();\n/**\n * A method can returns a component ID from the component definition using a variant of DJB2 hash\n * algorithm.\n */\nfunction getComponentId(componentDef) {\n let hash = 0;\n // We cannot rely solely on the component selector as the same selector can be used in different\n // modules.\n //\n // `componentDef.style` is not used, due to it causing inconsistencies. Ex: when server\n // component styles has no sourcemaps and browsers do.\n //\n // Example:\n // https://github.com/angular/components/blob/d9f82c8f95309e77a6d82fd574c65871e91354c2/src/material/core/option/option.ts#L248\n // https://github.com/angular/components/blob/285f46dc2b4c5b127d356cb7c4714b221f03ce50/src/material/legacy-core/option/option.ts#L32\n 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),\n // We cannot use 'componentDef.type.name' as the name of the symbol will change and will not\n // match in the server and browser bundles.\n Object.getOwnPropertyNames(componentDef.type.prototype), !!componentDef.contentQueries, !!componentDef.viewQuery].join('|');\n for (const char of hashSelectors) {\n hash = Math.imul(31, hash) + char.charCodeAt(0) << 0;\n }\n // Force positive number hash.\n // 2147483647 = equivalent of Integer.MAX_VALUE.\n hash += 2147483647 + 1;\n const compId = 'c' + hash;\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (GENERATED_COMP_IDS.has(compId)) {\n const previousCompDefType = GENERATED_COMP_IDS.get(compId);\n if (previousCompDefType !== componentDef.type) {\n 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.`));\n }\n } else {\n GENERATED_COMP_IDS.set(compId, componentDef.type);\n }\n }\n return compId;\n}\n\n/**\n * Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally\n * referenced in `@Component` in a component injector.\n */\nfunction makeEnvironmentProviders(providers) {\n return {\n ɵproviders: providers\n };\n}\n/**\n * Collects providers from all NgModules and standalone components, including transitively imported\n * ones.\n *\n * Providers extracted via `importProvidersFrom` are only usable in an application injector or\n * another environment injector (such as a route injector). They should not be used in component\n * providers.\n *\n * More information about standalone components can be found in [this\n * guide](guide/components/importing).\n *\n * @usageNotes\n * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:\n *\n * ```typescript\n * await bootstrapApplication(RootComponent, {\n * providers: [\n * importProvidersFrom(NgModuleOne, NgModuleTwo)\n * ]\n * });\n * ```\n *\n * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a\n * standalone component is used:\n *\n * ```typescript\n * export const ROUTES: Route[] = [\n * {\n * path: 'foo',\n * providers: [\n * importProvidersFrom(NgModuleOne, NgModuleTwo)\n * ],\n * component: YourStandaloneComponent\n * }\n * ];\n * ```\n *\n * @returns Collected providers from the specified list of types.\n * @publicApi\n */\nfunction importProvidersFrom(...sources) {\n return {\n ɵproviders: internalImportProvidersFrom(true, sources),\n ɵfromNgModule: true\n };\n}\nfunction internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {\n const providersOut = [];\n const dedup = new Set(); // already seen types\n let injectorTypesWithProviders;\n const collectProviders = provider => {\n providersOut.push(provider);\n };\n deepForEach(sources, source => {\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) {\n const cmpDef = getComponentDef(source);\n if (cmpDef?.standalone) {\n throw new RuntimeError(800 /* RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE */, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component \"${stringifyForError(source)}\"`);\n }\n }\n // Narrow `source` to access the internal type analogue for `ModuleWithProviders`.\n const internalSource = source;\n if (walkProviderTree(internalSource, collectProviders, [], dedup)) {\n injectorTypesWithProviders ||= [];\n injectorTypesWithProviders.push(internalSource);\n }\n });\n // Collect all providers from `ModuleWithProviders` types.\n if (injectorTypesWithProviders !== undefined) {\n processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders);\n }\n return providersOut;\n}\n/**\n * Collects all providers from the list of `ModuleWithProviders` and appends them to the provided\n * array.\n */\nfunction processInjectorTypesWithProviders(typesWithProviders, visitor) {\n for (let i = 0; i < typesWithProviders.length; i++) {\n const {\n ngModule,\n providers\n } = typesWithProviders[i];\n deepForEachProvider(providers, provider => {\n ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule);\n visitor(provider, ngModule);\n });\n }\n}\n/**\n * The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone\n * `ComponentType`, and all of its transitive providers and collects providers.\n *\n * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,\n * the function will return \"true\" to indicate that the providers of the type definition need\n * to be processed. This allows us to process providers of injector types after all imports of\n * an injector definition are processed. (following View Engine semantics: see FW-1349)\n */\nfunction walkProviderTree(container, visitor, parents, dedup) {\n container = resolveForwardRef(container);\n if (!container) return false;\n // The actual type which had the definition. Usually `container`, but may be an unwrapped type\n // from `InjectorTypeWithProviders`.\n let defType = null;\n let injDef = getInjectorDef(container);\n const cmpDef = !injDef && getComponentDef(container);\n if (!injDef && !cmpDef) {\n // `container` is not an injector type or a component type. It might be:\n // * An `InjectorTypeWithProviders` that wraps an injector type.\n // * A standalone directive or pipe that got pulled in from a standalone component's\n // dependencies.\n // Try to unwrap it as an `InjectorTypeWithProviders` first.\n const ngModule = container.ngModule;\n injDef = getInjectorDef(ngModule);\n if (injDef) {\n defType = ngModule;\n } else {\n // Not a component or injector type, so ignore it.\n return false;\n }\n } else if (cmpDef && !cmpDef.standalone) {\n return false;\n } else {\n defType = container;\n }\n // Check for circular dependencies.\n if (ngDevMode && parents.indexOf(defType) !== -1) {\n const defName = stringify(defType);\n const path = parents.map(stringify);\n throwCyclicDependencyError(defName, path);\n }\n // Check for multiple imports of the same module\n const isDuplicate = dedup.has(defType);\n if (cmpDef) {\n if (isDuplicate) {\n // This component definition has already been processed.\n return false;\n }\n dedup.add(defType);\n if (cmpDef.dependencies) {\n const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies;\n for (const dep of deps) {\n walkProviderTree(dep, visitor, parents, dedup);\n }\n }\n } else if (injDef) {\n // First, include providers from any imports.\n if (injDef.imports != null && !isDuplicate) {\n // Before processing defType's imports, add it to the set of parents. This way, if it ends\n // up deeply importing itself, this can be detected.\n ngDevMode && parents.push(defType);\n // Add it to the set of dedups. This way we can detect multiple imports of the same module\n dedup.add(defType);\n let importTypesWithProviders;\n try {\n deepForEach(injDef.imports, imported => {\n if (walkProviderTree(imported, visitor, parents, dedup)) {\n importTypesWithProviders ||= [];\n // If the processed import is an injector type with providers, we store it in the\n // list of import types with providers, so that we can process those afterwards.\n importTypesWithProviders.push(imported);\n }\n });\n } finally {\n // Remove it from the parents set when finished.\n ngDevMode && parents.pop();\n }\n // Imports which are declared with providers (TypeWithProviders) need to be processed\n // after all imported modules are processed. This is similar to how View Engine\n // processes/merges module imports in the metadata resolver. See: FW-1349.\n if (importTypesWithProviders !== undefined) {\n processInjectorTypesWithProviders(importTypesWithProviders, visitor);\n }\n }\n if (!isDuplicate) {\n // Track the InjectorType and add a provider for it.\n // It's important that this is done after the def's imports.\n const factory = getFactoryDef(defType) || (() => new defType());\n // Append extra providers to make more info available for consumers (to retrieve an injector\n // type), as well as internally (to calculate an injection scope correctly and eagerly\n // instantiate a `defType` when an injector is created).\n // Provider to create `defType` using its factory.\n visitor({\n provide: defType,\n useFactory: factory,\n deps: EMPTY_ARRAY\n }, defType);\n // Make this `defType` available to an internal logic that calculates injector scope.\n visitor({\n provide: INJECTOR_DEF_TYPES,\n useValue: defType,\n multi: true\n }, defType);\n // Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`.\n visitor({\n provide: ENVIRONMENT_INITIALIZER,\n useValue: () => ɵɵinject(defType),\n multi: true\n }, defType);\n }\n // Next, include providers listed on the definition itself.\n const defProviders = injDef.providers;\n if (defProviders != null && !isDuplicate) {\n const injectorType = container;\n deepForEachProvider(defProviders, provider => {\n ngDevMode && validateProvider(provider, defProviders, injectorType);\n visitor(provider, injectorType);\n });\n }\n } else {\n // Should not happen, but just in case.\n return false;\n }\n return defType !== container && container.providers !== undefined;\n}\nfunction validateProvider(provider, providers, containerType) {\n if (isTypeProvider(provider) || isValueProvider(provider) || isFactoryProvider(provider) || isExistingProvider(provider)) {\n return;\n }\n // Here we expect the provider to be a `useClass` provider (by elimination).\n const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));\n if (!classRef) {\n throwInvalidProviderError(containerType, providers, provider);\n }\n}\nfunction deepForEachProvider(providers, fn) {\n for (let provider of providers) {\n if (isEnvironmentProviders(provider)) {\n provider = provider.ɵproviders;\n }\n if (Array.isArray(provider)) {\n deepForEachProvider(provider, fn);\n } else {\n fn(provider);\n }\n }\n}\nconst USE_VALUE$1 = getClosureSafeProperty({\n provide: String,\n useValue: getClosureSafeProperty\n});\nfunction isValueProvider(value) {\n return value !== null && typeof value == 'object' && USE_VALUE$1 in value;\n}\nfunction isExistingProvider(value) {\n return !!(value && value.useExisting);\n}\nfunction isFactoryProvider(value) {\n return !!(value && value.useFactory);\n}\nfunction isTypeProvider(value) {\n return typeof value === 'function';\n}\nfunction isClassProvider(value) {\n return !!value.useClass;\n}\n\n/**\n * An internal token whose presence in an injector indicates that the injector should treat itself\n * as a root scoped injector when processing requests for unknown tokens which may indicate\n * they are provided in the root scope.\n */\nconst INJECTOR_SCOPE = new InjectionToken(ngDevMode ? 'Set Injector scope.' : '');\n\n/**\n * Marker which indicates that a value has not yet been created from the factory function.\n */\nconst NOT_YET = {};\n/**\n * Marker which indicates that the factory function for a token is in the process of being called.\n *\n * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates\n * injection of a dependency has recursively attempted to inject the original token, and there is\n * a circular dependency among the providers.\n */\nconst CIRCULAR = {};\n/**\n * A lazily initialized NullInjector.\n */\nlet NULL_INJECTOR = undefined;\nfunction getNullInjector() {\n if (NULL_INJECTOR === undefined) {\n NULL_INJECTOR = new NullInjector();\n }\n return NULL_INJECTOR;\n}\n/**\n * An `Injector` that's part of the environment injector hierarchy, which exists outside of the\n * component tree.\n */\nclass EnvironmentInjector {}\nclass R3Injector extends EnvironmentInjector {\n /**\n * Flag indicating that this injector was previously destroyed.\n */\n get destroyed() {\n return this._destroyed;\n }\n constructor(providers, parent, source, scopes) {\n super();\n this.parent = parent;\n this.source = source;\n this.scopes = scopes;\n /**\n * Map of tokens to records which contain the instances of those tokens.\n * - `null` value implies that we don't have the record. Used by tree-shakable injectors\n * to prevent further searches.\n */\n this.records = new Map();\n /**\n * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.\n */\n this._ngOnDestroyHooks = new Set();\n this._onDestroyHooks = [];\n this._destroyed = false;\n // Start off by creating Records for every provider.\n forEachSingleProvider(providers, provider => this.processProvider(provider));\n // Make sure the INJECTOR token provides this injector.\n this.records.set(INJECTOR$1, makeRecord(undefined, this));\n // And `EnvironmentInjector` if the current injector is supposed to be env-scoped.\n if (scopes.has('environment')) {\n this.records.set(EnvironmentInjector, makeRecord(undefined, this));\n }\n // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide\n // any injectable scoped to APP_ROOT_SCOPE.\n const record = this.records.get(INJECTOR_SCOPE);\n if (record != null && typeof record.value === 'string') {\n this.scopes.add(record.value);\n }\n this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));\n }\n /**\n * Destroy the injector and release references to every instance or provider associated with it.\n *\n * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a\n * hook was found.\n */\n destroy() {\n this.assertNotDestroyed();\n // Set destroyed = true first, in case lifecycle hooks re-enter destroy().\n this._destroyed = true;\n const prevConsumer = setActiveConsumer$1(null);\n try {\n // Call all the lifecycle hooks.\n for (const service of this._ngOnDestroyHooks) {\n service.ngOnDestroy();\n }\n const onDestroyHooks = this._onDestroyHooks;\n // Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister\n // themselves from mutating the array during iteration.\n this._onDestroyHooks = [];\n for (const hook of onDestroyHooks) {\n hook();\n }\n } finally {\n // Release all references.\n this.records.clear();\n this._ngOnDestroyHooks.clear();\n this.injectorDefTypes.clear();\n setActiveConsumer$1(prevConsumer);\n }\n }\n onDestroy(callback) {\n this.assertNotDestroyed();\n this._onDestroyHooks.push(callback);\n return () => this.removeOnDestroy(callback);\n }\n runInContext(fn) {\n this.assertNotDestroyed();\n const previousInjector = setCurrentInjector(this);\n const previousInjectImplementation = setInjectImplementation(undefined);\n let prevInjectContext;\n if (ngDevMode) {\n prevInjectContext = setInjectorProfilerContext({\n injector: this,\n token: null\n });\n }\n try {\n return fn();\n } finally {\n setCurrentInjector(previousInjector);\n setInjectImplementation(previousInjectImplementation);\n ngDevMode && setInjectorProfilerContext(prevInjectContext);\n }\n }\n get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {\n this.assertNotDestroyed();\n if (token.hasOwnProperty(NG_ENV_ID)) {\n return token[NG_ENV_ID](this);\n }\n flags = convertToBitFlags(flags);\n // Set the injection context.\n let prevInjectContext;\n if (ngDevMode) {\n prevInjectContext = setInjectorProfilerContext({\n injector: this,\n token: token\n });\n }\n const previousInjector = setCurrentInjector(this);\n const previousInjectImplementation = setInjectImplementation(undefined);\n try {\n // Check for the SkipSelf flag.\n if (!(flags & InjectFlags.SkipSelf)) {\n // SkipSelf isn't set, check if the record belongs to this injector.\n let record = this.records.get(token);\n if (record === undefined) {\n // No record, but maybe the token is scoped to this injector. Look for an injectable\n // def with a scope matching this injector.\n const def = couldBeInjectableType(token) && getInjectableDef(token);\n if (def && this.injectableDefInScope(def)) {\n // Found an injectable def and it's scoped to this injector. Pretend as if it was here\n // all along.\n if (ngDevMode) {\n runInInjectorProfilerContext(this, token, () => {\n emitProviderConfiguredEvent(token);\n });\n }\n record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);\n } else {\n record = null;\n }\n this.records.set(token, record);\n }\n // If a record was found, get the instance for it and return it.\n if (record != null /* NOT null || undefined */) {\n return this.hydrate(token, record);\n }\n }\n // Select the next injector based on the Self flag - if self is set, the next injector is\n // the NullInjector, otherwise it's the parent.\n const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();\n // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue\n // is undefined, the value is null, otherwise it's the notFoundValue.\n notFoundValue = flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND ? null : notFoundValue;\n return nextInjector.get(token, notFoundValue);\n } catch (e) {\n if (e.name === 'NullInjectorError') {\n const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];\n path.unshift(stringify(token));\n if (previousInjector) {\n // We still have a parent injector, keep throwing\n throw e;\n } else {\n // Format & throw the final error message when we don't have any previous injector\n return catchInjectorError(e, token, 'R3InjectorError', this.source);\n }\n } else {\n throw e;\n }\n } finally {\n // Lastly, restore the previous injection context.\n setInjectImplementation(previousInjectImplementation);\n setCurrentInjector(previousInjector);\n ngDevMode && setInjectorProfilerContext(prevInjectContext);\n }\n }\n /** @internal */\n resolveInjectorInitializers() {\n const prevConsumer = setActiveConsumer$1(null);\n const previousInjector = setCurrentInjector(this);\n const previousInjectImplementation = setInjectImplementation(undefined);\n let prevInjectContext;\n if (ngDevMode) {\n prevInjectContext = setInjectorProfilerContext({\n injector: this,\n token: null\n });\n }\n try {\n const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);\n if (ngDevMode && !Array.isArray(initializers)) {\n 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.');\n }\n for (const initializer of initializers) {\n initializer();\n }\n } finally {\n setCurrentInjector(previousInjector);\n setInjectImplementation(previousInjectImplementation);\n ngDevMode && setInjectorProfilerContext(prevInjectContext);\n setActiveConsumer$1(prevConsumer);\n }\n }\n toString() {\n const tokens = [];\n const records = this.records;\n for (const token of records.keys()) {\n tokens.push(stringify(token));\n }\n return `R3Injector[${tokens.join(', ')}]`;\n }\n assertNotDestroyed() {\n if (this._destroyed) {\n throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, ngDevMode && 'Injector has already been destroyed.');\n }\n }\n /**\n * Process a `SingleProvider` and add it.\n */\n processProvider(provider) {\n // Determine the token from the provider. Either it's its own token, or has a {provide: ...}\n // property.\n provider = resolveForwardRef(provider);\n let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);\n // Construct a `Record` for the provider.\n const record = providerToRecord(provider);\n if (ngDevMode) {\n runInInjectorProfilerContext(this, token, () => {\n // Emit InjectorProfilerEventType.Create if provider is a value provider because\n // these are the only providers that do not go through the value hydration logic\n // where this event would normally be emitted from.\n if (isValueProvider(provider)) {\n emitInstanceCreatedByInjectorEvent(provider.useValue);\n }\n emitProviderConfiguredEvent(provider);\n });\n }\n if (!isTypeProvider(provider) && provider.multi === true) {\n // If the provider indicates that it's a multi-provider, process it specially.\n // First check whether it's been defined already.\n let multiRecord = this.records.get(token);\n if (multiRecord) {\n // It has. Throw a nice error if\n if (ngDevMode && multiRecord.multi === undefined) {\n throwMixedMultiProviderError();\n }\n } else {\n multiRecord = makeRecord(undefined, NOT_YET, true);\n multiRecord.factory = () => injectArgs(multiRecord.multi);\n this.records.set(token, multiRecord);\n }\n token = provider;\n multiRecord.multi.push(provider);\n } else {\n if (ngDevMode) {\n const existing = this.records.get(token);\n if (existing && existing.multi !== undefined) {\n throwMixedMultiProviderError();\n }\n }\n }\n this.records.set(token, record);\n }\n hydrate(token, record) {\n const prevConsumer = setActiveConsumer$1(null);\n try {\n if (ngDevMode && record.value === CIRCULAR) {\n throwCyclicDependencyError(stringify(token));\n } else if (record.value === NOT_YET) {\n record.value = CIRCULAR;\n if (ngDevMode) {\n runInInjectorProfilerContext(this, token, () => {\n record.value = record.factory();\n emitInstanceCreatedByInjectorEvent(record.value);\n });\n } else {\n record.value = record.factory();\n }\n }\n if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {\n this._ngOnDestroyHooks.add(record.value);\n }\n return record.value;\n } finally {\n setActiveConsumer$1(prevConsumer);\n }\n }\n injectableDefInScope(def) {\n if (!def.providedIn) {\n return false;\n }\n const providedIn = resolveForwardRef(def.providedIn);\n if (typeof providedIn === 'string') {\n return providedIn === 'any' || this.scopes.has(providedIn);\n } else {\n return this.injectorDefTypes.has(providedIn);\n }\n }\n removeOnDestroy(callback) {\n const destroyCBIdx = this._onDestroyHooks.indexOf(callback);\n if (destroyCBIdx !== -1) {\n this._onDestroyHooks.splice(destroyCBIdx, 1);\n }\n }\n}\nfunction injectableDefOrInjectorDefFactory(token) {\n // Most tokens will have an injectable def directly on them, which specifies a factory directly.\n const injectableDef = getInjectableDef(token);\n const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);\n if (factory !== null) {\n return factory;\n }\n // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.\n // If it's missing that, it's an error.\n if (token instanceof InjectionToken) {\n throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`);\n }\n // Undecorated types can sometimes be created if they have no constructor arguments.\n if (token instanceof Function) {\n return getUndecoratedInjectableFactory(token);\n }\n // There was no way to resolve a factory for this token.\n throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'unreachable');\n}\nfunction getUndecoratedInjectableFactory(token) {\n // If the token has parameters then it has dependencies that we cannot resolve implicitly.\n const paramLength = token.length;\n if (paramLength > 0) {\n throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Can't resolve all parameters for ${stringify(token)}: (${newArray(paramLength, '?').join(', ')}).`);\n }\n // The constructor function appears to have no parameters.\n // This might be because it inherits from a super-class. In which case, use an injectable\n // def from an ancestor if there is one.\n // Otherwise this really is a simple class with no dependencies, so return a factory that\n // just instantiates the zero-arg constructor.\n const inheritedInjectableDef = getInheritedInjectableDef(token);\n if (inheritedInjectableDef !== null) {\n return () => inheritedInjectableDef.factory(token);\n } else {\n return () => new token();\n }\n}\nfunction providerToRecord(provider) {\n if (isValueProvider(provider)) {\n return makeRecord(undefined, provider.useValue);\n } else {\n const factory = providerToFactory(provider);\n return makeRecord(factory, NOT_YET);\n }\n}\n/**\n * Converts a `SingleProvider` into a factory function.\n *\n * @param provider provider to convert to factory\n */\nfunction providerToFactory(provider, ngModuleType, providers) {\n let factory = undefined;\n if (ngDevMode && isEnvironmentProviders(provider)) {\n throwInvalidProviderError(undefined, providers, provider);\n }\n if (isTypeProvider(provider)) {\n const unwrappedProvider = resolveForwardRef(provider);\n return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);\n } else {\n if (isValueProvider(provider)) {\n factory = () => resolveForwardRef(provider.useValue);\n } else if (isFactoryProvider(provider)) {\n factory = () => provider.useFactory(...injectArgs(provider.deps || []));\n } else if (isExistingProvider(provider)) {\n factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));\n } else {\n const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));\n if (ngDevMode && !classRef) {\n throwInvalidProviderError(ngModuleType, providers, provider);\n }\n if (hasDeps(provider)) {\n factory = () => new classRef(...injectArgs(provider.deps));\n } else {\n return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);\n }\n }\n }\n return factory;\n}\nfunction makeRecord(factory, value, multi = false) {\n return {\n factory: factory,\n value: value,\n multi: multi ? [] : undefined\n };\n}\nfunction hasDeps(value) {\n return !!value.deps;\n}\nfunction hasOnDestroy(value) {\n return value !== null && typeof value === 'object' && typeof value.ngOnDestroy === 'function';\n}\nfunction couldBeInjectableType(value) {\n return typeof value === 'function' || typeof value === 'object' && value instanceof InjectionToken;\n}\nfunction forEachSingleProvider(providers, fn) {\n for (const provider of providers) {\n if (Array.isArray(provider)) {\n forEachSingleProvider(provider, fn);\n } else if (provider && isEnvironmentProviders(provider)) {\n forEachSingleProvider(provider.ɵproviders, fn);\n } else {\n fn(provider);\n }\n }\n}\n\n/**\n * Runs the given function in the [context](guide/di/dependency-injection-context) of the given\n * `Injector`.\n *\n * Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies\n * from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in\n * any asynchronous callbacks or after any `await` points.\n *\n * @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`\n * is executing\n * @param fn the closure to be run in the context of `injector`\n * @returns the return value of the function, if any\n * @publicApi\n */\nfunction runInInjectionContext(injector, fn) {\n if (injector instanceof R3Injector) {\n injector.assertNotDestroyed();\n }\n let prevInjectorProfilerContext;\n if (ngDevMode) {\n prevInjectorProfilerContext = setInjectorProfilerContext({\n injector,\n token: null\n });\n }\n const prevInjector = setCurrentInjector(injector);\n const previousInjectImplementation = setInjectImplementation(undefined);\n try {\n return fn();\n } finally {\n setCurrentInjector(prevInjector);\n ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext);\n setInjectImplementation(previousInjectImplementation);\n }\n}\n/**\n * Whether the current stack frame is inside an injection context.\n */\nfunction isInInjectionContext() {\n return getInjectImplementation() !== undefined || getCurrentInjector() != null;\n}\n/**\n * Asserts that the current stack frame is within an [injection\n * context](guide/di/dependency-injection-context) and has access to `inject`.\n *\n * @param debugFn a reference to the function making the assertion (used for the error message).\n *\n * @publicApi\n */\nfunction assertInInjectionContext(debugFn) {\n // Taking a `Function` instead of a string name here prevents the unminified name of the function\n // from being retained in the bundle regardless of minification.\n if (!isInInjectionContext()) {\n 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`');\n }\n}\nvar FactoryTarget;\n(function (FactoryTarget) {\n FactoryTarget[FactoryTarget[\"Directive\"] = 0] = \"Directive\";\n FactoryTarget[FactoryTarget[\"Component\"] = 1] = \"Component\";\n FactoryTarget[FactoryTarget[\"Injectable\"] = 2] = \"Injectable\";\n FactoryTarget[FactoryTarget[\"Pipe\"] = 3] = \"Pipe\";\n FactoryTarget[FactoryTarget[\"NgModule\"] = 4] = \"NgModule\";\n})(FactoryTarget || (FactoryTarget = {}));\nvar R3TemplateDependencyKind;\n(function (R3TemplateDependencyKind) {\n R3TemplateDependencyKind[R3TemplateDependencyKind[\"Directive\"] = 0] = \"Directive\";\n R3TemplateDependencyKind[R3TemplateDependencyKind[\"Pipe\"] = 1] = \"Pipe\";\n R3TemplateDependencyKind[R3TemplateDependencyKind[\"NgModule\"] = 2] = \"NgModule\";\n})(R3TemplateDependencyKind || (R3TemplateDependencyKind = {}));\nvar ViewEncapsulation;\n(function (ViewEncapsulation) {\n ViewEncapsulation[ViewEncapsulation[\"Emulated\"] = 0] = \"Emulated\";\n // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.\n ViewEncapsulation[ViewEncapsulation[\"None\"] = 2] = \"None\";\n ViewEncapsulation[ViewEncapsulation[\"ShadowDom\"] = 3] = \"ShadowDom\";\n})(ViewEncapsulation || (ViewEncapsulation = {}));\nfunction getCompilerFacade(request) {\n const globalNg = _global['ng'];\n if (globalNg && globalNg.ɵcompilerFacade) {\n return globalNg.ɵcompilerFacade;\n }\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // Log the type as an error so that a developer can easily navigate to the type from the\n // console.\n console.error(`JIT compilation failed for ${request.kind}`, request.type);\n let message = `The ${request.kind} '${request.type.name}' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.\\n\\n`;\n if (request.usage === 1 /* JitCompilerUsage.PartialDeclaration */) {\n message += `The ${request.kind} is part of a library that has been partially compiled.\\n`;\n message += `However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.\\n`;\n message += '\\n';\n message += `Ideally, the library is processed using the Angular Linker to become fully AOT compiled.\\n`;\n } else {\n message += `JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.\\n`;\n }\n message += `Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',\\n`;\n message += `or manually provide the compiler with 'import \"@angular/compiler\";' before bootstrapping.`;\n throw new Error(message);\n } else {\n throw new Error('JIT compiler unavailable');\n }\n}\n\n/**\n * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.\n *\n * This should be kept up to date with the public exports of @angular/core.\n */\nconst angularCoreDiEnv = {\n 'ɵɵdefineInjectable': ɵɵdefineInjectable,\n 'ɵɵdefineInjector': ɵɵdefineInjector,\n 'ɵɵinject': ɵɵinject,\n 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,\n 'resolveForwardRef': resolveForwardRef\n};\n\n/**\n * @description\n *\n * Represents a type that a Component or other object is instances of.\n *\n * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by\n * the `MyCustomComponent` constructor function.\n *\n * @publicApi\n */\nconst Type = Function;\nfunction isType(v) {\n return typeof v === 'function';\n}\n\n/*\n * #########################\n * Attention: These Regular expressions have to hold even if the code is minified!\n * ##########################\n */\n/**\n * Regular expression that detects pass-through constructors for ES5 output. This Regex\n * intends to capture the common delegation pattern emitted by TypeScript and Babel. Also\n * it intends to capture the pattern where existing constructors have been downleveled from\n * ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.\n *\n * ```\n * function MyClass() {\n * var _this = _super.apply(this, arguments) || this;\n * ```\n *\n * downleveled to ES5 with `downlevelIteration` for TypeScript < 4.2:\n * ```\n * function MyClass() {\n * var _this = _super.apply(this, __spread(arguments)) || this;\n * ```\n *\n * or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2:\n * ```\n * function MyClass() {\n * var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;\n * ```\n *\n * More details can be found in: https://github.com/angular/angular/issues/38453.\n */\nconst ES5_DELEGATE_CTOR = /^function\\s+\\S+\\(\\)\\s*{[\\s\\S]+\\.apply\\(this,\\s*(arguments|(?:[^()]+\\(\\[\\],)?[^()]+\\(arguments\\).*)\\)/;\n/** Regular expression that detects ES2015 classes which extend from other classes. */\nconst ES2015_INHERITED_CLASS = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{/;\n/**\n * Regular expression that detects ES2015 classes which extend from other classes and\n * have an explicit constructor defined.\n */\nconst ES2015_INHERITED_CLASS_WITH_CTOR = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(/;\n/**\n * Regular expression that detects ES2015 classes which extend from other classes\n * and inherit a constructor.\n */\nconst ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\\s+[A-Za-z\\d$_]*\\s*extends\\s+[^{]+{[\\s\\S]*constructor\\s*\\(\\)\\s*{[^}]*super\\(\\.\\.\\.arguments\\)/;\n/**\n * Determine whether a stringified type is a class which delegates its constructor\n * to its parent.\n *\n * This is not trivial since compiled code can actually contain a constructor function\n * even if the original source code did not. For instance, when the child class contains\n * an initialized instance property.\n */\nfunction isDelegateCtor(typeStr) {\n 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);\n}\nclass ReflectionCapabilities {\n constructor(reflect) {\n this._reflect = reflect || _global['Reflect'];\n }\n factory(t) {\n return (...args) => new t(...args);\n }\n /** @internal */\n _zipTypesAndAnnotations(paramTypes, paramAnnotations) {\n let result;\n if (typeof paramTypes === 'undefined') {\n result = newArray(paramAnnotations.length);\n } else {\n result = newArray(paramTypes.length);\n }\n for (let i = 0; i < result.length; i++) {\n // TS outputs Object for parameters without types, while Traceur omits\n // the annotations. For now we preserve the Traceur behavior to aid\n // migration, but this can be revisited.\n if (typeof paramTypes === 'undefined') {\n result[i] = [];\n } else if (paramTypes[i] && paramTypes[i] != Object) {\n result[i] = [paramTypes[i]];\n } else {\n result[i] = [];\n }\n if (paramAnnotations && paramAnnotations[i] != null) {\n result[i] = result[i].concat(paramAnnotations[i]);\n }\n }\n return result;\n }\n _ownParameters(type, parentCtor) {\n const typeStr = type.toString();\n // If we have no decorators, we only have function.length as metadata.\n // In that case, to detect whether a child class declared an own constructor or not,\n // we need to look inside of that constructor to check whether it is\n // just calling the parent.\n // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439\n // that sets 'design:paramtypes' to []\n // if a class inherits from another class but has no ctor declared itself.\n if (isDelegateCtor(typeStr)) {\n return null;\n }\n // Prefer the direct API.\n if (type.parameters && type.parameters !== parentCtor.parameters) {\n return type.parameters;\n }\n // API of tsickle for lowering decorators to properties on the class.\n const tsickleCtorParams = type.ctorParameters;\n if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {\n // Newer tsickle uses a function closure\n // Retain the non-function case for compatibility with older tsickle\n const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;\n const paramTypes = ctorParameters.map(ctorParam => ctorParam && ctorParam.type);\n const paramAnnotations = ctorParameters.map(ctorParam => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n // API for metadata created by invoking the decorators.\n const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];\n const paramTypes = this._reflect && this._reflect.getOwnMetadata && this._reflect.getOwnMetadata('design:paramtypes', type);\n if (paramTypes || paramAnnotations) {\n return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);\n }\n // If a class has no decorators, at least create metadata\n // based on function.length.\n // Note: We know that this is a real constructor as we checked\n // the content of the constructor above.\n return newArray(type.length);\n }\n parameters(type) {\n // Note: only report metadata if we have at least one class decorator\n // to stay in sync with the static reflector.\n if (!isType(type)) {\n return [];\n }\n const parentCtor = getParentCtor(type);\n let parameters = this._ownParameters(type, parentCtor);\n if (!parameters && parentCtor !== Object) {\n parameters = this.parameters(parentCtor);\n }\n return parameters || [];\n }\n _ownAnnotations(typeOrFunc, parentCtor) {\n // Prefer the direct API.\n if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {\n let annotations = typeOrFunc.annotations;\n if (typeof annotations === 'function' && annotations.annotations) {\n annotations = annotations.annotations;\n }\n return annotations;\n }\n // API of tsickle for lowering decorators to properties on the class.\n if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {\n return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);\n }\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {\n return typeOrFunc[ANNOTATIONS];\n }\n return null;\n }\n annotations(typeOrFunc) {\n if (!isType(typeOrFunc)) {\n return [];\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];\n const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];\n return parentAnnotations.concat(ownAnnotations);\n }\n _ownPropMetadata(typeOrFunc, parentCtor) {\n // Prefer the direct API.\n if (typeOrFunc.propMetadata && typeOrFunc.propMetadata !== parentCtor.propMetadata) {\n let propMetadata = typeOrFunc.propMetadata;\n if (typeof propMetadata === 'function' && propMetadata.propMetadata) {\n propMetadata = propMetadata.propMetadata;\n }\n return propMetadata;\n }\n // API of tsickle for lowering decorators to properties on the class.\n if (typeOrFunc.propDecorators && typeOrFunc.propDecorators !== parentCtor.propDecorators) {\n const propDecorators = typeOrFunc.propDecorators;\n const propMetadata = {};\n Object.keys(propDecorators).forEach(prop => {\n propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);\n });\n return propMetadata;\n }\n // API for metadata created by invoking the decorators.\n if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {\n return typeOrFunc[PROP_METADATA];\n }\n return null;\n }\n propMetadata(typeOrFunc) {\n if (!isType(typeOrFunc)) {\n return {};\n }\n const parentCtor = getParentCtor(typeOrFunc);\n const propMetadata = {};\n if (parentCtor !== Object) {\n const parentPropMetadata = this.propMetadata(parentCtor);\n Object.keys(parentPropMetadata).forEach(propName => {\n propMetadata[propName] = parentPropMetadata[propName];\n });\n }\n const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);\n if (ownPropMetadata) {\n Object.keys(ownPropMetadata).forEach(propName => {\n const decorators = [];\n if (propMetadata.hasOwnProperty(propName)) {\n decorators.push(...propMetadata[propName]);\n }\n decorators.push(...ownPropMetadata[propName]);\n propMetadata[propName] = decorators;\n });\n }\n return propMetadata;\n }\n ownPropMetadata(typeOrFunc) {\n if (!isType(typeOrFunc)) {\n return {};\n }\n return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};\n }\n hasLifecycleHook(type, lcProperty) {\n return type instanceof Type && lcProperty in type.prototype;\n }\n}\nfunction convertTsickleDecoratorIntoMetadata(decoratorInvocations) {\n if (!decoratorInvocations) {\n return [];\n }\n return decoratorInvocations.map(decoratorInvocation => {\n const decoratorType = decoratorInvocation.type;\n const annotationCls = decoratorType.annotationCls;\n const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];\n return new annotationCls(...annotationArgs);\n });\n}\nfunction getParentCtor(ctor) {\n const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;\n const parentCtor = parentProto ? parentProto.constructor : null;\n // Note: We always use `Object` as the null value\n // to simplify checking later on.\n return parentCtor || Object;\n}\n\n// Below are constants for LView indices to help us look up LView members\n// without having to remember the specific indices.\n// Uglify will inline these when minifying so there shouldn't be a cost.\nconst HOST = 0;\nconst TVIEW = 1;\n// Shared with LContainer\nconst FLAGS = 2;\nconst PARENT = 3;\nconst NEXT = 4;\nconst T_HOST = 5;\n// End shared with LContainer\nconst HYDRATION = 6;\nconst CLEANUP = 7;\nconst CONTEXT = 8;\nconst INJECTOR = 9;\nconst ENVIRONMENT = 10;\nconst RENDERER = 11;\nconst CHILD_HEAD = 12;\nconst CHILD_TAIL = 13;\n// FIXME(misko): Investigate if the three declarations aren't all same thing.\nconst DECLARATION_VIEW = 14;\nconst DECLARATION_COMPONENT_VIEW = 15;\nconst DECLARATION_LCONTAINER = 16;\nconst PREORDER_HOOK_FLAGS = 17;\nconst QUERIES = 18;\nconst ID = 19;\nconst EMBEDDED_VIEW_INJECTOR = 20;\nconst ON_DESTROY_HOOKS = 21;\nconst EFFECTS_TO_SCHEDULE = 22;\nconst REACTIVE_TEMPLATE_CONSUMER = 23;\n/**\n * Size of LView's header. Necessary to adjust for it when setting slots.\n *\n * IMPORTANT: `HEADER_OFFSET` should only be referred to the in the `ɵɵ*` instructions to translate\n * instruction index into `LView` index. All other indexes should be in the `LView` index space and\n * there should be no need to refer to `HEADER_OFFSET` anywhere else.\n */\nconst HEADER_OFFSET = 25;\n\n/**\n * Special location which allows easy identification of type. If we have an array which was\n * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is\n * `LContainer`.\n */\nconst TYPE = 1;\n/**\n * Below are constants for LContainer indices to help us look up LContainer members\n * without having to remember the specific indices.\n * Uglify will inline these when minifying so there shouldn't be a cost.\n */\n// FLAGS, PARENT, NEXT, and T_HOST are indices 2, 3, 4, and 5\n// As we already have these constants in LView, we don't need to re-create them.\nconst DEHYDRATED_VIEWS = 6;\nconst NATIVE = 7;\nconst VIEW_REFS = 8;\nconst MOVED_VIEWS = 9;\n/**\n * Size of LContainer's header. Represents the index after which all views in the\n * container will be inserted. We need to keep a record of current views so we know\n * which views are already in the DOM (and don't need to be re-added) and so we can\n * remove views from the DOM when they are no longer required.\n */\nconst CONTAINER_HEADER_OFFSET = 10;\n/** Flags associated with an LContainer (saved in LContainer[FLAGS]) */\nvar LContainerFlags;\n(function (LContainerFlags) {\n LContainerFlags[LContainerFlags[\"None\"] = 0] = \"None\";\n /**\n * Flag to signify that this `LContainer` may have transplanted views which need to be change\n * detected. (see: `LView[DECLARATION_COMPONENT_VIEW])`.\n *\n * This flag, once set, is never unset for the `LContainer`.\n */\n LContainerFlags[LContainerFlags[\"HasTransplantedViews\"] = 2] = \"HasTransplantedViews\";\n})(LContainerFlags || (LContainerFlags = {}));\n\n/**\n * True if `value` is `LView`.\n * @param value wrapped value of `RNode`, `LView`, `LContainer`\n */\nfunction isLView(value) {\n return Array.isArray(value) && typeof value[TYPE] === 'object';\n}\n/**\n * True if `value` is `LContainer`.\n * @param value wrapped value of `RNode`, `LView`, `LContainer`\n */\nfunction isLContainer(value) {\n return Array.isArray(value) && value[TYPE] === true;\n}\nfunction isContentQueryHost(tNode) {\n return (tNode.flags & 4 /* TNodeFlags.hasContentQuery */) !== 0;\n}\nfunction isComponentHost(tNode) {\n return tNode.componentOffset > -1;\n}\nfunction isDirectiveHost(tNode) {\n return (tNode.flags & 1 /* TNodeFlags.isDirectiveHost */) === 1 /* TNodeFlags.isDirectiveHost */;\n}\nfunction isComponentDef(def) {\n return !!def.template;\n}\nfunction isRootView(target) {\n return (target[FLAGS] & 512 /* LViewFlags.IsRoot */) !== 0;\n}\nfunction isProjectionTNode(tNode) {\n return (tNode.type & 16 /* TNodeType.Projection */) === 16 /* TNodeType.Projection */;\n}\nfunction hasI18n(lView) {\n return (lView[FLAGS] & 32 /* LViewFlags.HasI18n */) === 32 /* LViewFlags.HasI18n */;\n}\nfunction isDestroyed(lView) {\n return (lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */;\n}\n\n// [Assert functions do not constraint type when they are guarded by a truthy\n// expression.](https://github.com/microsoft/TypeScript/issues/37295)\nfunction assertTNodeForLView(tNode, lView) {\n assertTNodeForTView(tNode, lView[TVIEW]);\n}\nfunction assertTNodeForTView(tNode, tView) {\n assertTNode(tNode);\n const tData = tView.data;\n for (let i = HEADER_OFFSET; i < tData.length; i++) {\n if (tData[i] === tNode) {\n return;\n }\n }\n throwError('This TNode does not belong to this TView.');\n}\nfunction assertTNode(tNode) {\n assertDefined(tNode, 'TNode must be defined');\n if (!(tNode && typeof tNode === 'object' && tNode.hasOwnProperty('directiveStylingLast'))) {\n throwError('Not of type TNode, got: ' + tNode);\n }\n}\nfunction assertTIcu(tIcu) {\n assertDefined(tIcu, 'Expected TIcu to be defined');\n if (!(typeof tIcu.currentCaseLViewIndex === 'number')) {\n throwError('Object is not of TIcu type.');\n }\n}\nfunction assertComponentType(actual, msg = \"Type passed in is not ComponentType, it does not have 'ɵcmp' property.\") {\n if (!getComponentDef(actual)) {\n throwError(msg);\n }\n}\nfunction assertNgModuleType(actual, msg = \"Type passed in is not NgModuleType, it does not have 'ɵmod' property.\") {\n if (!getNgModuleDef(actual)) {\n throwError(msg);\n }\n}\nfunction assertCurrentTNodeIsParent(isParent) {\n assertEqual(isParent, true, 'currentTNode should be a parent');\n}\nfunction assertHasParent(tNode) {\n assertDefined(tNode, 'currentTNode should exist!');\n assertDefined(tNode.parent, 'currentTNode should have a parent');\n}\nfunction assertLContainer(value) {\n assertDefined(value, 'LContainer must be defined');\n assertEqual(isLContainer(value), true, 'Expecting LContainer');\n}\nfunction assertLViewOrUndefined(value) {\n value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');\n}\nfunction assertLView(value) {\n assertDefined(value, 'LView must be defined');\n assertEqual(isLView(value), true, 'Expecting LView');\n}\nfunction assertFirstCreatePass(tView, errMessage) {\n assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');\n}\nfunction assertFirstUpdatePass(tView, errMessage) {\n assertEqual(tView.firstUpdatePass, true, errMessage || 'Should only be called in first update pass.');\n}\n/**\n * This is a basic sanity check that an object is probably a directive def. DirectiveDef is\n * an interface, so we can't do a direct instanceof check.\n */\nfunction assertDirectiveDef(obj) {\n if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {\n throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);\n }\n}\nfunction assertIndexInDeclRange(tView, index) {\n assertBetween(HEADER_OFFSET, tView.bindingStartIndex, index);\n}\nfunction assertIndexInExpandoRange(lView, index) {\n const tView = lView[1];\n assertBetween(tView.expandoStartIndex, lView.length, index);\n}\nfunction assertBetween(lower, upper, index) {\n if (!(lower <= index && index < upper)) {\n throwError(`Index out of range (expecting ${lower} <= ${index} < ${upper})`);\n }\n}\nfunction assertProjectionSlots(lView, errMessage) {\n assertDefined(lView[DECLARATION_COMPONENT_VIEW], 'Component views should exist.');\n assertDefined(lView[DECLARATION_COMPONENT_VIEW][T_HOST].projection, errMessage || 'Components with projection nodes () must have projection slots defined.');\n}\nfunction assertParentView(lView, errMessage) {\n assertDefined(lView, errMessage || \"Component views should always have a parent view (component's host view)\");\n}\nfunction assertNoDuplicateDirectives(directives) {\n // The array needs at least two elements in order to have duplicates.\n if (directives.length < 2) {\n return;\n }\n const seenDirectives = new Set();\n for (const current of directives) {\n if (seenDirectives.has(current)) {\n 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.`);\n }\n seenDirectives.add(current);\n }\n}\n/**\n * This is a basic sanity check that the `injectorIndex` seems to point to what looks like a\n * NodeInjector data structure.\n *\n * @param lView `LView` which should be checked.\n * @param injectorIndex index into the `LView` where the `NodeInjector` is expected.\n */\nfunction assertNodeInjector(lView, injectorIndex) {\n assertIndexInExpandoRange(lView, injectorIndex);\n assertIndexInExpandoRange(lView, injectorIndex + 8 /* NodeInjectorOffset.PARENT */);\n assertNumber(lView[injectorIndex + 0], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 1], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 2], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 3], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 4], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 5], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 6], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 7], 'injectorIndex should point to a bloom filter');\n assertNumber(lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */], 'injectorIndex should point to parent injector');\n}\n\n/**\n * Represents a basic change from a previous to a new value for a single\n * property on a directive instance. Passed as a value in a\n * {@link SimpleChanges} object to the `ngOnChanges` hook.\n *\n * @see {@link OnChanges}\n *\n * @publicApi\n */\nclass SimpleChange {\n constructor(previousValue, currentValue, firstChange) {\n this.previousValue = previousValue;\n this.currentValue = currentValue;\n this.firstChange = firstChange;\n }\n /**\n * Check whether the new value is the first value assigned.\n */\n isFirstChange() {\n return this.firstChange;\n }\n}\nfunction applyValueToInputField(instance, inputSignalNode, privateName, value) {\n if (inputSignalNode !== null) {\n inputSignalNode.applyValueToInputSignal(inputSignalNode, value);\n } else {\n instance[privateName] = value;\n }\n}\n\n/**\n * The NgOnChangesFeature decorates a component with support for the ngOnChanges\n * lifecycle hook, so it should be included in any component that implements\n * that hook.\n *\n * If the component or directive uses inheritance, the NgOnChangesFeature MUST\n * be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise\n * inherited properties will not be propagated to the ngOnChanges lifecycle\n * hook.\n *\n * Example usage:\n *\n * ```\n * static ɵcmp = defineComponent({\n * ...\n * inputs: {name: 'publicName'},\n * features: [NgOnChangesFeature]\n * });\n * ```\n *\n * @codeGenApi\n */\nfunction ɵɵNgOnChangesFeature() {\n return NgOnChangesFeatureImpl;\n}\nfunction NgOnChangesFeatureImpl(definition) {\n if (definition.type.prototype.ngOnChanges) {\n definition.setInput = ngOnChangesSetInput;\n }\n return rememberChangeHistoryAndInvokeOnChangesHook;\n}\n// This option ensures that the ngOnChanges lifecycle hook will be inherited\n// from superclasses (in InheritDefinitionFeature).\n/** @nocollapse */\n// tslint:disable-next-line:no-toplevel-property-access\nɵɵNgOnChangesFeature.ngInherit = true;\n/**\n * This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate\n * `ngOnChanges`.\n *\n * The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are\n * found it invokes `ngOnChanges` on the component instance.\n *\n * @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,\n * it is guaranteed to be called with component instance.\n */\nfunction rememberChangeHistoryAndInvokeOnChangesHook() {\n const simpleChangesStore = getSimpleChangesStore(this);\n const current = simpleChangesStore?.current;\n if (current) {\n const previous = simpleChangesStore.previous;\n if (previous === EMPTY_OBJ) {\n simpleChangesStore.previous = current;\n } else {\n // New changes are copied to the previous store, so that we don't lose history for inputs\n // which were not changed this time\n for (let key in current) {\n previous[key] = current[key];\n }\n }\n simpleChangesStore.current = null;\n this.ngOnChanges(current);\n }\n}\nfunction ngOnChangesSetInput(instance, inputSignalNode, value, publicName, privateName) {\n const declaredName = this.declaredInputs[publicName];\n ngDevMode && assertString(declaredName, 'Name of input in ngOnChanges has to be a string');\n const simpleChangesStore = getSimpleChangesStore(instance) || setSimpleChangesStore(instance, {\n previous: EMPTY_OBJ,\n current: null\n });\n const current = simpleChangesStore.current || (simpleChangesStore.current = {});\n const previous = simpleChangesStore.previous;\n const previousChange = previous[declaredName];\n current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);\n applyValueToInputField(instance, inputSignalNode, privateName, value);\n}\nconst SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';\nfunction getSimpleChangesStore(instance) {\n return instance[SIMPLE_CHANGES_STORE] || null;\n}\nfunction setSimpleChangesStore(instance, store) {\n return instance[SIMPLE_CHANGES_STORE] = store;\n}\nlet profilerCallback = null;\n/**\n * Sets the callback function which will be invoked before and after performing certain actions at\n * runtime (for example, before and after running change detection).\n *\n * Warning: this function is *INTERNAL* and should not be relied upon in application's code.\n * The contract of the function might be changed in any release and/or the function can be removed\n * completely.\n *\n * @param profiler function provided by the caller or null value to disable profiling.\n */\nconst setProfiler = profiler => {\n profilerCallback = profiler;\n};\n/**\n * Profiler function which wraps user code executed by the runtime.\n *\n * @param event ProfilerEvent corresponding to the execution context\n * @param instance component instance\n * @param hookOrListener lifecycle hook function or output listener. The value depends on the\n * execution context\n * @returns\n */\nconst profiler = function (event, instance, hookOrListener) {\n if (profilerCallback != null /* both `null` and `undefined` */) {\n profilerCallback(event, instance, hookOrListener);\n }\n};\nconst SVG_NAMESPACE = 'svg';\nconst MATH_ML_NAMESPACE = 'math';\n\n/**\n * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)\n * in same location in `LView`. This is because we don't want to pre-allocate space for it\n * because the storage is sparse. This file contains utilities for dealing with such data types.\n *\n * How do we know what is stored at a given location in `LView`.\n * - `Array.isArray(value) === false` => `RNode` (The normal storage value)\n * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.\n * - `typeof value[TYPE] === 'object'` => `LView`\n * - This happens when we have a component at a given location\n * - `typeof value[TYPE] === true` => `LContainer`\n * - This happens when we have `LContainer` binding at a given location.\n *\n *\n * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.\n */\n/**\n * Returns `RNode`.\n * @param value wrapped value of `RNode`, `LView`, `LContainer`\n */\nfunction unwrapRNode(value) {\n while (Array.isArray(value)) {\n value = value[HOST];\n }\n return value;\n}\n/**\n * Returns `LView` or `null` if not found.\n * @param value wrapped value of `RNode`, `LView`, `LContainer`\n */\nfunction unwrapLView(value) {\n while (Array.isArray(value)) {\n // This check is same as `isLView()` but we don't call at as we don't want to call\n // `Array.isArray()` twice and give JITer more work for inlining.\n if (typeof value[TYPE] === 'object') return value;\n value = value[HOST];\n }\n return null;\n}\n/**\n * Retrieves an element value from the provided `viewData`, by unwrapping\n * from any containers, component views, or style contexts.\n */\nfunction getNativeByIndex(index, lView) {\n ngDevMode && assertIndexInRange(lView, index);\n ngDevMode && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Expected to be past HEADER_OFFSET');\n return unwrapRNode(lView[index]);\n}\n/**\n * Retrieve an `RNode` for a given `TNode` and `LView`.\n *\n * This function guarantees in dev mode to retrieve a non-null `RNode`.\n *\n * @param tNode\n * @param lView\n */\nfunction getNativeByTNode(tNode, lView) {\n ngDevMode && assertTNodeForLView(tNode, lView);\n ngDevMode && assertIndexInRange(lView, tNode.index);\n const node = unwrapRNode(lView[tNode.index]);\n return node;\n}\n/**\n * Retrieve an `RNode` or `null` for a given `TNode` and `LView`.\n *\n * Some `TNode`s don't have associated `RNode`s. For example `Projection`\n *\n * @param tNode\n * @param lView\n */\nfunction getNativeByTNodeOrNull(tNode, lView) {\n const index = tNode === null ? -1 : tNode.index;\n if (index !== -1) {\n ngDevMode && assertTNodeForLView(tNode, lView);\n const node = unwrapRNode(lView[index]);\n return node;\n }\n return null;\n}\n// fixme(misko): The return Type should be `TNode|null`\nfunction getTNode(tView, index) {\n ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');\n ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');\n const tNode = tView.data[index];\n ngDevMode && tNode !== null && assertTNode(tNode);\n return tNode;\n}\n/** Retrieves a value from any `LView` or `TData`. */\nfunction load(view, index) {\n ngDevMode && assertIndexInRange(view, index);\n return view[index];\n}\nfunction getComponentLViewByIndex(nodeIndex, hostView) {\n // Could be an LView or an LContainer. If LContainer, unwrap to find LView.\n ngDevMode && assertIndexInRange(hostView, nodeIndex);\n const slotValue = hostView[nodeIndex];\n const lView = isLView(slotValue) ? slotValue : slotValue[HOST];\n return lView;\n}\n/** Checks whether a given view is in creation mode */\nfunction isCreationMode(view) {\n return (view[FLAGS] & 4 /* LViewFlags.CreationMode */) === 4 /* LViewFlags.CreationMode */;\n}\n/**\n * Returns a boolean for whether the view is attached to the change detection tree.\n *\n * Note: This determines whether a view should be checked, not whether it's inserted\n * into a container. For that, you'll want `viewAttachedToContainer` below.\n */\nfunction viewAttachedToChangeDetector(view) {\n return (view[FLAGS] & 128 /* LViewFlags.Attached */) === 128 /* LViewFlags.Attached */;\n}\n/** Returns a boolean for whether the view is attached to a container. */\nfunction viewAttachedToContainer(view) {\n return isLContainer(view[PARENT]);\n}\nfunction getConstant(consts, index) {\n if (index === null || index === undefined) return null;\n ngDevMode && assertIndexInRange(consts, index);\n return consts[index];\n}\n/**\n * Resets the pre-order hook flags of the view.\n * @param lView the LView on which the flags are reset\n */\nfunction resetPreOrderHookFlags(lView) {\n lView[PREORDER_HOOK_FLAGS] = 0;\n}\n/**\n * Adds the `RefreshView` flag from the lView and updates HAS_CHILD_VIEWS_TO_REFRESH flag of\n * parents.\n */\nfunction markViewForRefresh(lView) {\n if (lView[FLAGS] & 1024 /* LViewFlags.RefreshView */) {\n return;\n }\n lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;\n if (viewAttachedToChangeDetector(lView)) {\n markAncestorsForTraversal(lView);\n }\n}\n/**\n * Walks up the LView hierarchy.\n * @param nestingLevel Number of times to walk up in hierarchy.\n * @param currentView View from which to start the lookup.\n */\nfunction walkUpViews(nestingLevel, currentView) {\n while (nestingLevel > 0) {\n ngDevMode && assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');\n currentView = currentView[DECLARATION_VIEW];\n nestingLevel--;\n }\n return currentView;\n}\nfunction requiresRefreshOrTraversal(lView) {\n return !!(lView[FLAGS] & (1024 /* LViewFlags.RefreshView */ | 8192 /* LViewFlags.HasChildViewsToRefresh */) || lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty);\n}\n/**\n * Updates the `HasChildViewsToRefresh` flag on the parents of the `LView` as well as the\n * parents above.\n */\nfunction updateAncestorTraversalFlagsOnAttach(lView) {\n lView[ENVIRONMENT].changeDetectionScheduler?.notify(8 /* NotificationSource.ViewAttached */);\n if (lView[FLAGS] & 64 /* LViewFlags.Dirty */) {\n lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;\n }\n if (requiresRefreshOrTraversal(lView)) {\n markAncestorsForTraversal(lView);\n }\n}\n/**\n * Ensures views above the given `lView` are traversed during change detection even when they are\n * not dirty.\n *\n * This is done by setting the `HAS_CHILD_VIEWS_TO_REFRESH` flag up to the root, stopping when the\n * flag is already `true` or the `lView` is detached.\n */\nfunction markAncestorsForTraversal(lView) {\n lView[ENVIRONMENT].changeDetectionScheduler?.notify(0 /* NotificationSource.MarkAncestorsForTraversal */);\n let parent = getLViewParent(lView);\n while (parent !== null) {\n // We stop adding markers to the ancestors once we reach one that already has the marker. This\n // is to avoid needlessly traversing all the way to the root when the marker already exists.\n if (parent[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */) {\n break;\n }\n parent[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;\n if (!viewAttachedToChangeDetector(parent)) {\n break;\n }\n parent = getLViewParent(parent);\n }\n}\n/**\n * Stores a LView-specific destroy callback.\n */\nfunction storeLViewOnDestroy(lView, onDestroyCallback) {\n if ((lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */) {\n throw new RuntimeError(911 /* RuntimeErrorCode.VIEW_ALREADY_DESTROYED */, ngDevMode && 'View has already been destroyed.');\n }\n if (lView[ON_DESTROY_HOOKS] === null) {\n lView[ON_DESTROY_HOOKS] = [];\n }\n lView[ON_DESTROY_HOOKS].push(onDestroyCallback);\n}\n/**\n * Removes previously registered LView-specific destroy callback.\n */\nfunction removeLViewOnDestroy(lView, onDestroyCallback) {\n if (lView[ON_DESTROY_HOOKS] === null) return;\n const destroyCBIdx = lView[ON_DESTROY_HOOKS].indexOf(onDestroyCallback);\n if (destroyCBIdx !== -1) {\n lView[ON_DESTROY_HOOKS].splice(destroyCBIdx, 1);\n }\n}\n/**\n * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of\n * that LContainer, which is an LView\n * @param lView the lView whose parent to get\n */\nfunction getLViewParent(lView) {\n ngDevMode && assertLView(lView);\n const parent = lView[PARENT];\n return isLContainer(parent) ? parent[PARENT] : parent;\n}\nconst instructionState = {\n lFrame: createLFrame(null),\n bindingsEnabled: true,\n skipHydrationRootTNode: null\n};\nvar CheckNoChangesMode;\n(function (CheckNoChangesMode) {\n CheckNoChangesMode[CheckNoChangesMode[\"Off\"] = 0] = \"Off\";\n CheckNoChangesMode[CheckNoChangesMode[\"Exhaustive\"] = 1] = \"Exhaustive\";\n CheckNoChangesMode[CheckNoChangesMode[\"OnlyDirtyViews\"] = 2] = \"OnlyDirtyViews\";\n})(CheckNoChangesMode || (CheckNoChangesMode = {}));\n/**\n * In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.\n *\n * Necessary to support ChangeDetectorRef.checkNoChanges().\n *\n * The `checkNoChanges` function is invoked only in ngDevMode=true and verifies that no unintended\n * changes exist in the change detector or its children.\n */\nlet _checkNoChangesMode = 0; /* CheckNoChangesMode.Off */\n/**\n * Flag used to indicate that we are in the middle running change detection on a view\n *\n * @see detectChangesInViewWhileDirty\n */\nlet _isRefreshingViews = false;\n/**\n * Returns true if the instruction state stack is empty.\n *\n * Intended to be called from tests only (tree shaken otherwise).\n */\nfunction specOnlyIsInstructionStateEmpty() {\n return instructionState.lFrame.parent === null;\n}\nfunction getElementDepthCount() {\n return instructionState.lFrame.elementDepthCount;\n}\nfunction increaseElementDepthCount() {\n instructionState.lFrame.elementDepthCount++;\n}\nfunction decreaseElementDepthCount() {\n instructionState.lFrame.elementDepthCount--;\n}\nfunction getBindingsEnabled() {\n return instructionState.bindingsEnabled;\n}\n/**\n * Returns true if currently inside a skip hydration block.\n * @returns boolean\n */\nfunction isInSkipHydrationBlock$1() {\n return instructionState.skipHydrationRootTNode !== null;\n}\n/**\n * Returns true if this is the root TNode of the skip hydration block.\n * @param tNode the current TNode\n * @returns boolean\n */\nfunction isSkipHydrationRootTNode(tNode) {\n return instructionState.skipHydrationRootTNode === tNode;\n}\n/**\n * Enables directive matching on elements.\n *\n * * Example:\n * ```\n * \n * Should match component / directive.\n * \n *
\n * \n * \n * Should not match component / directive because we are in ngNonBindable.\n * \n * \n *
\n * ```\n *\n * @codeGenApi\n */\nfunction ɵɵenableBindings() {\n instructionState.bindingsEnabled = true;\n}\n/**\n * Sets a flag to specify that the TNode is in a skip hydration block.\n * @param tNode the current TNode\n */\nfunction enterSkipHydrationBlock(tNode) {\n instructionState.skipHydrationRootTNode = tNode;\n}\n/**\n * Disables directive matching on element.\n *\n * * Example:\n * ```\n * \n * Should match component / directive.\n * \n *
\n * \n * \n * Should not match component / directive because we are in ngNonBindable.\n * \n * \n *
\n * ```\n *\n * @codeGenApi\n */\nfunction ɵɵdisableBindings() {\n instructionState.bindingsEnabled = false;\n}\n/**\n * Clears the root skip hydration node when leaving a skip hydration block.\n */\nfunction leaveSkipHydrationBlock() {\n instructionState.skipHydrationRootTNode = null;\n}\n/**\n * Return the current `LView`.\n */\nfunction getLView() {\n return instructionState.lFrame.lView;\n}\n/**\n * Return the current `TView`.\n */\nfunction getTView() {\n return instructionState.lFrame.tView;\n}\n/**\n * Restores `contextViewData` to the given OpaqueViewState instance.\n *\n * Used in conjunction with the getCurrentView() instruction to save a snapshot\n * of the current view and restore it when listeners are invoked. This allows\n * walking the declaration view tree in listeners to get vars from parent views.\n *\n * @param viewToRestore The OpaqueViewState instance to restore.\n * @returns Context of the restored OpaqueViewState instance.\n *\n * @codeGenApi\n */\nfunction ɵɵrestoreView(viewToRestore) {\n instructionState.lFrame.contextLView = viewToRestore;\n return viewToRestore[CONTEXT];\n}\n/**\n * Clears the view set in `ɵɵrestoreView` from memory. Returns the passed in\n * value so that it can be used as a return value of an instruction.\n *\n * @codeGenApi\n */\nfunction ɵɵresetView(value) {\n instructionState.lFrame.contextLView = null;\n return value;\n}\nfunction getCurrentTNode() {\n let currentTNode = getCurrentTNodePlaceholderOk();\n while (currentTNode !== null && currentTNode.type === 64 /* TNodeType.Placeholder */) {\n currentTNode = currentTNode.parent;\n }\n return currentTNode;\n}\nfunction getCurrentTNodePlaceholderOk() {\n return instructionState.lFrame.currentTNode;\n}\nfunction getCurrentParentTNode() {\n const lFrame = instructionState.lFrame;\n const currentTNode = lFrame.currentTNode;\n return lFrame.isParent ? currentTNode : currentTNode.parent;\n}\nfunction setCurrentTNode(tNode, isParent) {\n ngDevMode && tNode && assertTNodeForTView(tNode, instructionState.lFrame.tView);\n const lFrame = instructionState.lFrame;\n lFrame.currentTNode = tNode;\n lFrame.isParent = isParent;\n}\nfunction isCurrentTNodeParent() {\n return instructionState.lFrame.isParent;\n}\nfunction setCurrentTNodeAsNotParent() {\n instructionState.lFrame.isParent = false;\n}\nfunction getContextLView() {\n const contextLView = instructionState.lFrame.contextLView;\n ngDevMode && assertDefined(contextLView, 'contextLView must be defined.');\n return contextLView;\n}\nfunction isInCheckNoChangesMode() {\n !ngDevMode && throwError('Must never be called in production mode');\n return _checkNoChangesMode !== CheckNoChangesMode.Off;\n}\nfunction isExhaustiveCheckNoChanges() {\n !ngDevMode && throwError('Must never be called in production mode');\n return _checkNoChangesMode === CheckNoChangesMode.Exhaustive;\n}\nfunction setIsInCheckNoChangesMode(mode) {\n !ngDevMode && throwError('Must never be called in production mode');\n _checkNoChangesMode = mode;\n}\nfunction isRefreshingViews() {\n return _isRefreshingViews;\n}\nfunction setIsRefreshingViews(mode) {\n _isRefreshingViews = mode;\n}\n// top level variables should not be exported for performance reasons (PERF_NOTES.md)\nfunction getBindingRoot() {\n const lFrame = instructionState.lFrame;\n let index = lFrame.bindingRootIndex;\n if (index === -1) {\n index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;\n }\n return index;\n}\nfunction getBindingIndex() {\n return instructionState.lFrame.bindingIndex;\n}\nfunction setBindingIndex(value) {\n return instructionState.lFrame.bindingIndex = value;\n}\nfunction nextBindingIndex() {\n return instructionState.lFrame.bindingIndex++;\n}\nfunction incrementBindingIndex(count) {\n const lFrame = instructionState.lFrame;\n const index = lFrame.bindingIndex;\n lFrame.bindingIndex = lFrame.bindingIndex + count;\n return index;\n}\nfunction isInI18nBlock() {\n return instructionState.lFrame.inI18n;\n}\nfunction setInI18nBlock(isInI18nBlock) {\n instructionState.lFrame.inI18n = isInI18nBlock;\n}\n/**\n * Set a new binding root index so that host template functions can execute.\n *\n * Bindings inside the host template are 0 index. But because we don't know ahead of time\n * how many host bindings we have we can't pre-compute them. For this reason they are all\n * 0 index and we just shift the root so that they match next available location in the LView.\n *\n * @param bindingRootIndex Root index for `hostBindings`\n * @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive\n * whose `hostBindings` are being processed.\n */\nfunction setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {\n const lFrame = instructionState.lFrame;\n lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;\n setCurrentDirectiveIndex(currentDirectiveIndex);\n}\n/**\n * When host binding is executing this points to the directive index.\n * `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`\n * `LView[getCurrentDirectiveIndex()]` is directive instance.\n */\nfunction getCurrentDirectiveIndex() {\n return instructionState.lFrame.currentDirectiveIndex;\n}\n/**\n * Sets an index of a directive whose `hostBindings` are being processed.\n *\n * @param currentDirectiveIndex `TData` index where current directive instance can be found.\n */\nfunction setCurrentDirectiveIndex(currentDirectiveIndex) {\n instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;\n}\n/**\n * Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being\n * executed.\n *\n * @param tData Current `TData` where the `DirectiveDef` will be looked up at.\n */\nfunction getCurrentDirectiveDef(tData) {\n const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;\n return currentDirectiveIndex === -1 ? null : tData[currentDirectiveIndex];\n}\nfunction getCurrentQueryIndex() {\n return instructionState.lFrame.currentQueryIndex;\n}\nfunction setCurrentQueryIndex(value) {\n instructionState.lFrame.currentQueryIndex = value;\n}\n/**\n * Returns a `TNode` of the location where the current `LView` is declared at.\n *\n * @param lView an `LView` that we want to find parent `TNode` for.\n */\nfunction getDeclarationTNode(lView) {\n const tView = lView[TVIEW];\n // Return the declaration parent for embedded views\n if (tView.type === 2 /* TViewType.Embedded */) {\n ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');\n return tView.declTNode;\n }\n // Components don't have `TView.declTNode` because each instance of component could be\n // inserted in different location, hence `TView.declTNode` is meaningless.\n // Falling back to `T_HOST` in case we cross component boundary.\n if (tView.type === 1 /* TViewType.Component */) {\n return lView[T_HOST];\n }\n // Remaining TNode type is `TViewType.Root` which doesn't have a parent TNode.\n return null;\n}\n/**\n * This is a light weight version of the `enterView` which is needed by the DI system.\n *\n * @param lView `LView` location of the DI context.\n * @param tNode `TNode` for DI context\n * @param flags DI context flags. if `SkipSelf` flag is set than we walk up the declaration\n * tree from `tNode` until we find parent declared `TElementNode`.\n * @returns `true` if we have successfully entered DI associated with `tNode` (or with declared\n * `TNode` if `flags` has `SkipSelf`). Failing to enter DI implies that no associated\n * `NodeInjector` can be found and we should instead use `ModuleInjector`.\n * - If `true` than this call must be fallowed by `leaveDI`\n * - If `false` than this call failed and we should NOT call `leaveDI`\n */\nfunction enterDI(lView, tNode, flags) {\n ngDevMode && assertLViewOrUndefined(lView);\n if (flags & InjectFlags.SkipSelf) {\n ngDevMode && assertTNodeForTView(tNode, lView[TVIEW]);\n let parentTNode = tNode;\n let parentLView = lView;\n while (true) {\n ngDevMode && assertDefined(parentTNode, 'Parent TNode should be defined');\n parentTNode = parentTNode.parent;\n if (parentTNode === null && !(flags & InjectFlags.Host)) {\n parentTNode = getDeclarationTNode(parentLView);\n if (parentTNode === null) break;\n // In this case, a parent exists and is definitely an element. So it will definitely\n // have an existing lView as the declaration view, which is why we can assume it's defined.\n ngDevMode && assertDefined(parentLView, 'Parent LView should be defined');\n parentLView = parentLView[DECLARATION_VIEW];\n // In Ivy there are Comment nodes that correspond to ngIf and NgFor embedded directives\n // We want to skip those and look only at Elements and ElementContainers to ensure\n // we're looking at true parent nodes, and not content or other types.\n if (parentTNode.type & (2 /* TNodeType.Element */ | 8 /* TNodeType.ElementContainer */)) {\n break;\n }\n } else {\n break;\n }\n }\n if (parentTNode === null) {\n // If we failed to find a parent TNode this means that we should use module injector.\n return false;\n } else {\n tNode = parentTNode;\n lView = parentLView;\n }\n }\n ngDevMode && assertTNodeForLView(tNode, lView);\n const lFrame = instructionState.lFrame = allocLFrame();\n lFrame.currentTNode = tNode;\n lFrame.lView = lView;\n return true;\n}\n/**\n * Swap the current lView with a new lView.\n *\n * For performance reasons we store the lView in the top level of the module.\n * This way we minimize the number of properties to read. Whenever a new view\n * is entered we have to store the lView for later, and when the view is\n * exited the state has to be restored\n *\n * @param newView New lView to become active\n * @returns the previously active lView;\n */\nfunction enterView(newView) {\n ngDevMode && assertNotEqual(newView[0], newView[1], '????');\n ngDevMode && assertLViewOrUndefined(newView);\n const newLFrame = allocLFrame();\n if (ngDevMode) {\n assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');\n assertEqual(newLFrame.lView, null, 'Expected clean LFrame');\n assertEqual(newLFrame.tView, null, 'Expected clean LFrame');\n assertEqual(newLFrame.selectedIndex, -1, 'Expected clean LFrame');\n assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');\n assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');\n assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');\n assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');\n assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');\n }\n const tView = newView[TVIEW];\n instructionState.lFrame = newLFrame;\n ngDevMode && tView.firstChild && assertTNodeForTView(tView.firstChild, tView);\n newLFrame.currentTNode = tView.firstChild;\n newLFrame.lView = newView;\n newLFrame.tView = tView;\n newLFrame.contextLView = newView;\n newLFrame.bindingIndex = tView.bindingStartIndex;\n newLFrame.inI18n = false;\n}\n/**\n * Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.\n */\nfunction allocLFrame() {\n const currentLFrame = instructionState.lFrame;\n const childLFrame = currentLFrame === null ? null : currentLFrame.child;\n const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;\n return newLFrame;\n}\nfunction createLFrame(parent) {\n const lFrame = {\n currentTNode: null,\n isParent: true,\n lView: null,\n tView: null,\n selectedIndex: -1,\n contextLView: null,\n elementDepthCount: 0,\n currentNamespace: null,\n currentDirectiveIndex: -1,\n bindingRootIndex: -1,\n bindingIndex: -1,\n currentQueryIndex: 0,\n parent: parent,\n child: null,\n inI18n: false\n };\n parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.\n return lFrame;\n}\n/**\n * A lightweight version of leave which is used with DI.\n *\n * This function only resets `currentTNode` and `LView` as those are the only properties\n * used with DI (`enterDI()`).\n *\n * NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where\n * as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.\n */\nfunction leaveViewLight() {\n const oldLFrame = instructionState.lFrame;\n instructionState.lFrame = oldLFrame.parent;\n oldLFrame.currentTNode = null;\n oldLFrame.lView = null;\n return oldLFrame;\n}\n/**\n * This is a lightweight version of the `leaveView` which is needed by the DI system.\n *\n * NOTE: this function is an alias so that we can change the type of the function to have `void`\n * return type.\n */\nconst leaveDI = leaveViewLight;\n/**\n * Leave the current `LView`\n *\n * This pops the `LFrame` with the associated `LView` from the stack.\n *\n * IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is\n * because for performance reasons we don't release `LFrame` but rather keep it for next use.\n */\nfunction leaveView() {\n const oldLFrame = leaveViewLight();\n oldLFrame.isParent = true;\n oldLFrame.tView = null;\n oldLFrame.selectedIndex = -1;\n oldLFrame.contextLView = null;\n oldLFrame.elementDepthCount = 0;\n oldLFrame.currentDirectiveIndex = -1;\n oldLFrame.currentNamespace = null;\n oldLFrame.bindingRootIndex = -1;\n oldLFrame.bindingIndex = -1;\n oldLFrame.currentQueryIndex = 0;\n}\nfunction nextContextImpl(level) {\n const contextLView = instructionState.lFrame.contextLView = walkUpViews(level, instructionState.lFrame.contextLView);\n return contextLView[CONTEXT];\n}\n/**\n * Gets the currently selected element index.\n *\n * Used with {@link property} instruction (and more in the future) to identify the index in the\n * current `LView` to act on.\n */\nfunction getSelectedIndex() {\n return instructionState.lFrame.selectedIndex;\n}\n/**\n * Sets the most recent index passed to {@link select}\n *\n * Used with {@link property} instruction (and more in the future) to identify the index in the\n * current `LView` to act on.\n *\n * (Note that if an \"exit function\" was set earlier (via `setElementExitFn()`) then that will be\n * run if and when the provided `index` value is different from the current selected index value.)\n */\nfunction setSelectedIndex(index) {\n ngDevMode && index !== -1 && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Index must be past HEADER_OFFSET (or -1).');\n ngDevMode && assertLessThan(index, instructionState.lFrame.lView.length, \"Can't set index passed end of LView\");\n instructionState.lFrame.selectedIndex = index;\n}\n/**\n * Gets the `tNode` that represents currently selected element.\n */\nfunction getSelectedTNode() {\n const lFrame = instructionState.lFrame;\n return getTNode(lFrame.tView, lFrame.selectedIndex);\n}\n/**\n * Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.\n *\n * @codeGenApi\n */\nfunction ɵɵnamespaceSVG() {\n instructionState.lFrame.currentNamespace = SVG_NAMESPACE;\n}\n/**\n * Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.\n *\n * @codeGenApi\n */\nfunction ɵɵnamespaceMathML() {\n instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;\n}\n/**\n * Sets the namespace used to create elements to `null`, which forces element creation to use\n * `createElement` rather than `createElementNS`.\n *\n * @codeGenApi\n */\nfunction ɵɵnamespaceHTML() {\n namespaceHTMLInternal();\n}\n/**\n * Sets the namespace used to create elements to `null`, which forces element creation to use\n * `createElement` rather than `createElementNS`.\n */\nfunction namespaceHTMLInternal() {\n instructionState.lFrame.currentNamespace = null;\n}\nfunction getNamespace$1() {\n return instructionState.lFrame.currentNamespace;\n}\nlet _wasLastNodeCreated = true;\n/**\n * Retrieves a global flag that indicates whether the most recent DOM node\n * was created or hydrated.\n */\nfunction wasLastNodeCreated() {\n return _wasLastNodeCreated;\n}\n/**\n * Sets a global flag to indicate whether the most recent DOM node\n * was created or hydrated.\n */\nfunction lastNodeWasCreated(flag) {\n _wasLastNodeCreated = flag;\n}\n\n/**\n * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.\n *\n * Must be run *only* on the first template pass.\n *\n * Sets up the pre-order hooks on the provided `tView`,\n * see {@link HookData} for details about the data structure.\n *\n * @param directiveIndex The index of the directive in LView\n * @param directiveDef The definition containing the hooks to setup in tView\n * @param tView The current TView\n */\nfunction registerPreOrderHooks(directiveIndex, directiveDef, tView) {\n ngDevMode && assertFirstCreatePass(tView);\n const {\n ngOnChanges,\n ngOnInit,\n ngDoCheck\n } = directiveDef.type.prototype;\n if (ngOnChanges) {\n const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef);\n (tView.preOrderHooks ??= []).push(directiveIndex, wrappedOnChanges);\n (tView.preOrderCheckHooks ??= []).push(directiveIndex, wrappedOnChanges);\n }\n if (ngOnInit) {\n (tView.preOrderHooks ??= []).push(0 - directiveIndex, ngOnInit);\n }\n if (ngDoCheck) {\n (tView.preOrderHooks ??= []).push(directiveIndex, ngDoCheck);\n (tView.preOrderCheckHooks ??= []).push(directiveIndex, ngDoCheck);\n }\n}\n/**\n *\n * Loops through the directives on the provided `tNode` and queues hooks to be\n * run that are not initialization hooks.\n *\n * Should be executed during `elementEnd()` and similar to\n * preserve hook execution order. Content, view, and destroy hooks for projected\n * components and directives must be called *before* their hosts.\n *\n * Sets up the content, view, and destroy hooks on the provided `tView`,\n * see {@link HookData} for details about the data structure.\n *\n * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up\n * separately at `elementStart`.\n *\n * @param tView The current TView\n * @param tNode The TNode whose directives are to be searched for hooks to queue\n */\nfunction registerPostOrderHooks(tView, tNode) {\n ngDevMode && assertFirstCreatePass(tView);\n // It's necessary to loop through the directives at elementEnd() (rather than processing in\n // directiveCreate) so we can preserve the current hook order. Content, view, and destroy\n // hooks for projected components and directives must be called *before* their hosts.\n for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {\n const directiveDef = tView.data[i];\n ngDevMode && assertDefined(directiveDef, 'Expecting DirectiveDef');\n const lifecycleHooks = directiveDef.type.prototype;\n const {\n ngAfterContentInit,\n ngAfterContentChecked,\n ngAfterViewInit,\n ngAfterViewChecked,\n ngOnDestroy\n } = lifecycleHooks;\n if (ngAfterContentInit) {\n (tView.contentHooks ??= []).push(-i, ngAfterContentInit);\n }\n if (ngAfterContentChecked) {\n (tView.contentHooks ??= []).push(i, ngAfterContentChecked);\n (tView.contentCheckHooks ??= []).push(i, ngAfterContentChecked);\n }\n if (ngAfterViewInit) {\n (tView.viewHooks ??= []).push(-i, ngAfterViewInit);\n }\n if (ngAfterViewChecked) {\n (tView.viewHooks ??= []).push(i, ngAfterViewChecked);\n (tView.viewCheckHooks ??= []).push(i, ngAfterViewChecked);\n }\n if (ngOnDestroy != null) {\n (tView.destroyHooks ??= []).push(i, ngOnDestroy);\n }\n }\n}\n/**\n * Executing hooks requires complex logic as we need to deal with 2 constraints.\n *\n * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only\n * once, across many change detection cycles. This must be true even if some hooks throw, or if\n * some recursively trigger a change detection cycle.\n * To solve that, it is required to track the state of the execution of these init hooks.\n * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},\n * and the index within that phase. They can be seen as a cursor in the following structure:\n * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]\n * They are stored as flags in LView[FLAGS].\n *\n * 2. Pre-order hooks can be executed in batches, because of the select instruction.\n * To be able to pause and resume their execution, we also need some state about the hook's array\n * that is being processed:\n * - the index of the next hook to be executed\n * - the number of init hooks already found in the processed part of the array\n * They are stored as flags in LView[PREORDER_HOOK_FLAGS].\n */\n/**\n * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were\n * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read\n * / write of the init-hooks related flags.\n * @param lView The LView where hooks are defined\n * @param hooks Hooks to be run\n * @param nodeIndex 3 cases depending on the value:\n * - undefined: all hooks from the array should be executed (post-order case)\n * - null: execute hooks only from the saved index until the end of the array (pre-order case, when\n * flushing the remaining hooks)\n * - number: execute hooks only from the saved index until that node index exclusive (pre-order\n * case, when executing select(number))\n */\nfunction executeCheckHooks(lView, hooks, nodeIndex) {\n callHooks(lView, hooks, 3 /* InitPhaseState.InitPhaseCompleted */, nodeIndex);\n}\n/**\n * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,\n * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.\n * @param lView The LView where hooks are defined\n * @param hooks Hooks to be run\n * @param initPhase A phase for which hooks should be run\n * @param nodeIndex 3 cases depending on the value:\n * - undefined: all hooks from the array should be executed (post-order case)\n * - null: execute hooks only from the saved index until the end of the array (pre-order case, when\n * flushing the remaining hooks)\n * - number: execute hooks only from the saved index until that node index exclusive (pre-order\n * case, when executing select(number))\n */\nfunction executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {\n ngDevMode && assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');\n if ((lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {\n callHooks(lView, hooks, initPhase, nodeIndex);\n }\n}\nfunction incrementInitPhaseFlags(lView, initPhase) {\n ngDevMode && assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');\n let flags = lView[FLAGS];\n if ((flags & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {\n flags &= 16383 /* LViewFlags.IndexWithinInitPhaseReset */;\n flags += 1 /* LViewFlags.InitPhaseStateIncrementer */;\n lView[FLAGS] = flags;\n }\n}\n/**\n * Calls lifecycle hooks with their contexts, skipping init hooks if it's not\n * the first LView pass\n *\n * @param currentView The current view\n * @param arr The array in which the hooks are found\n * @param initPhaseState the current state of the init phase\n * @param currentNodeIndex 3 cases depending on the value:\n * - undefined: all hooks from the array should be executed (post-order case)\n * - null: execute hooks only from the saved index until the end of the array (pre-order case, when\n * flushing the remaining hooks)\n * - number: execute hooks only from the saved index until that node index exclusive (pre-order\n * case, when executing select(number))\n */\nfunction callHooks(currentView, arr, initPhase, currentNodeIndex) {\n ngDevMode && assertEqual(isInCheckNoChangesMode(), false, 'Hooks should never be run when in check no changes mode.');\n const startIndex = currentNodeIndex !== undefined ? currentView[PREORDER_HOOK_FLAGS] & 65535 /* PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask */ : 0;\n const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;\n const max = arr.length - 1; // Stop the loop at length - 1, because we look for the hook at i + 1\n let lastNodeIndexFound = 0;\n for (let i = startIndex; i < max; i++) {\n const hook = arr[i + 1];\n if (typeof hook === 'number') {\n lastNodeIndexFound = arr[i];\n if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {\n break;\n }\n } else {\n const isInitHook = arr[i] < 0;\n if (isInitHook) {\n currentView[PREORDER_HOOK_FLAGS] += 65536 /* PreOrderHookFlags.NumberOfInitHooksCalledIncrementer */;\n }\n if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {\n callHook(currentView, initPhase, arr, i);\n currentView[PREORDER_HOOK_FLAGS] = (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* PreOrderHookFlags.NumberOfInitHooksCalledMask */) + i + 2;\n }\n i++;\n }\n }\n}\n/**\n * Executes a single lifecycle hook, making sure that:\n * - it is called in the non-reactive context;\n * - profiling data are registered.\n */\nfunction callHookInternal(directive, hook) {\n profiler(4 /* ProfilerEvent.LifecycleHookStart */, directive, hook);\n const prevConsumer = setActiveConsumer$1(null);\n try {\n hook.call(directive);\n } finally {\n setActiveConsumer$1(prevConsumer);\n profiler(5 /* ProfilerEvent.LifecycleHookEnd */, directive, hook);\n }\n}\n/**\n * Execute one hook against the current `LView`.\n *\n * @param currentView The current view\n * @param initPhaseState the current state of the init phase\n * @param arr The array in which the hooks are found\n * @param i The current index within the hook data array\n */\nfunction callHook(currentView, initPhase, arr, i) {\n const isInitHook = arr[i] < 0;\n const hook = arr[i + 1];\n const directiveIndex = isInitHook ? -arr[i] : arr[i];\n const directive = currentView[directiveIndex];\n if (isInitHook) {\n const indexWithintInitPhase = currentView[FLAGS] >> 14 /* LViewFlags.IndexWithinInitPhaseShift */;\n // The init phase state must be always checked here as it may have been recursively updated.\n if (indexWithintInitPhase < currentView[PREORDER_HOOK_FLAGS] >> 16 /* PreOrderHookFlags.NumberOfInitHooksCalledShift */ && (currentView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {\n currentView[FLAGS] += 16384 /* LViewFlags.IndexWithinInitPhaseIncrementer */;\n callHookInternal(directive, hook);\n }\n } else {\n callHookInternal(directive, hook);\n }\n}\nconst NO_PARENT_INJECTOR = -1;\n/**\n * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in\n * `TView.data`. This allows us to store information about the current node's tokens (which\n * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be\n * shared, so they live in `LView`).\n *\n * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter\n * determines whether a directive is available on the associated node or not. This prevents us\n * from searching the directives array at this level unless it's probable the directive is in it.\n *\n * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.\n *\n * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed\n * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`\n * will differ based on where it is flattened into the main array, so it's not possible to know\n * the indices ahead of time and save their types here. The interfaces are still included here\n * for documentation purposes.\n *\n * export interface LInjector extends Array {\n *\n * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)\n * [0]: number;\n *\n * // Cumulative bloom for directive IDs 32-63\n * [1]: number;\n *\n * // Cumulative bloom for directive IDs 64-95\n * [2]: number;\n *\n * // Cumulative bloom for directive IDs 96-127\n * [3]: number;\n *\n * // Cumulative bloom for directive IDs 128-159\n * [4]: number;\n *\n * // Cumulative bloom for directive IDs 160 - 191\n * [5]: number;\n *\n * // Cumulative bloom for directive IDs 192 - 223\n * [6]: number;\n *\n * // Cumulative bloom for directive IDs 224 - 255\n * [7]: number;\n *\n * // We need to store a reference to the injector's parent so DI can keep looking up\n * // the injector tree until it finds the dependency it's looking for.\n * [PARENT_INJECTOR]: number;\n * }\n *\n * export interface TInjector extends Array {\n *\n * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)\n * [0]: number;\n *\n * // Shared node bloom for directive IDs 32-63\n * [1]: number;\n *\n * // Shared node bloom for directive IDs 64-95\n * [2]: number;\n *\n * // Shared node bloom for directive IDs 96-127\n * [3]: number;\n *\n * // Shared node bloom for directive IDs 128-159\n * [4]: number;\n *\n * // Shared node bloom for directive IDs 160 - 191\n * [5]: number;\n *\n * // Shared node bloom for directive IDs 192 - 223\n * [6]: number;\n *\n * // Shared node bloom for directive IDs 224 - 255\n * [7]: number;\n *\n * // Necessary to find directive indices for a particular node.\n * [TNODE]: TElementNode|TElementContainerNode|TContainerNode;\n * }\n */\n/**\n * Factory for creating instances of injectors in the NodeInjector.\n *\n * This factory is complicated by the fact that it can resolve `multi` factories as well.\n *\n * NOTE: Some of the fields are optional which means that this class has two hidden classes.\n * - One without `multi` support (most common)\n * - One with `multi` values, (rare).\n *\n * Since VMs can cache up to 4 inline hidden classes this is OK.\n *\n * - Single factory: Only `resolving` and `factory` is defined.\n * - `providers` factory: `componentProviders` is a number and `index = -1`.\n * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.\n */\nclass NodeInjectorFactory {\n constructor(\n /**\n * Factory to invoke in order to create a new instance.\n */\n factory,\n /**\n * Set to `true` if the token is declared in `viewProviders` (or if it is component).\n */\n isViewProvider, injectImplementation) {\n this.factory = factory;\n /**\n * Marker set to true during factory invocation to see if we get into recursive loop.\n * Recursive loop causes an error to be displayed.\n */\n this.resolving = false;\n ngDevMode && assertDefined(factory, 'Factory not specified');\n ngDevMode && assertEqual(typeof factory, 'function', 'Expected factory function.');\n this.canSeeViewProviders = isViewProvider;\n this.injectImpl = injectImplementation;\n }\n}\nfunction isFactory(obj) {\n return obj instanceof NodeInjectorFactory;\n}\n\n/**\n * Converts `TNodeType` into human readable text.\n * Make sure this matches with `TNodeType`\n */\nfunction toTNodeTypeAsString(tNodeType) {\n let text = '';\n tNodeType & 1 /* TNodeType.Text */ && (text += '|Text');\n tNodeType & 2 /* TNodeType.Element */ && (text += '|Element');\n tNodeType & 4 /* TNodeType.Container */ && (text += '|Container');\n tNodeType & 8 /* TNodeType.ElementContainer */ && (text += '|ElementContainer');\n tNodeType & 16 /* TNodeType.Projection */ && (text += '|Projection');\n tNodeType & 32 /* TNodeType.Icu */ && (text += '|IcuContainer');\n tNodeType & 64 /* TNodeType.Placeholder */ && (text += '|Placeholder');\n tNodeType & 128 /* TNodeType.LetDeclaration */ && (text += '|LetDeclaration');\n return text.length > 0 ? text.substring(1) : text;\n}\n/**\n * Helper function to detect if a given value matches a `TNode` shape.\n *\n * The logic uses the `insertBeforeIndex` and its possible values as\n * a way to differentiate a TNode shape from other types of objects\n * within the `TView.data`. This is not a perfect check, but it can\n * be a reasonable differentiator, since we control the shapes of objects\n * within `TView.data`.\n */\nfunction isTNodeShape(value) {\n return value != null && typeof value === 'object' && (value.insertBeforeIndex === null || typeof value.insertBeforeIndex === 'number' || Array.isArray(value.insertBeforeIndex));\n}\n/**\n * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding.\n *\n * ```\n *
\n * ```\n * and\n * ```\n * @Directive({\n * })\n * class MyDirective {\n * @Input()\n * class: string;\n * }\n * ```\n *\n * In the above case it is necessary to write the reconciled styling information into the\n * directive's input.\n *\n * @param tNode\n */\nfunction hasClassInput(tNode) {\n return (tNode.flags & 8 /* TNodeFlags.hasClassInput */) !== 0;\n}\n/**\n * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding.\n *\n * ```\n *
\n * ```\n * and\n * ```\n * @Directive({\n * })\n * class MyDirective {\n * @Input()\n * class: string;\n * }\n * ```\n *\n * In the above case it is necessary to write the reconciled styling information into the\n * directive's input.\n *\n * @param tNode\n */\nfunction hasStyleInput(tNode) {\n return (tNode.flags & 16 /* TNodeFlags.hasStyleInput */) !== 0;\n}\nfunction assertTNodeType(tNode, expectedTypes, message) {\n assertDefined(tNode, 'should be called with a TNode');\n if ((tNode.type & expectedTypes) === 0) {\n throwError(message || `Expected [${toTNodeTypeAsString(expectedTypes)}] but got ${toTNodeTypeAsString(tNode.type)}.`);\n }\n}\nfunction assertPureTNodeType(type) {\n 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 */)) {\n throwError(`Expected TNodeType to have only a single type selected, but got ${toTNodeTypeAsString(type)}.`);\n }\n}\n\n// This default value is when checking the hierarchy for a token.\n//\n// It means both:\n// - the token is not provided by the current injector,\n// - only the element injectors should be checked (ie do not check module injectors\n//\n// mod1\n// /\n// el1 mod2\n// \\ /\n// el2\n//\n// When requesting el2.injector.get(token), we should check in the following order and return the\n// first found value:\n// - el2.injector.get(token, default)\n// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module\n// - mod2.injector.get(token, default)\nconst NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};\n\n/**\n * Injector that looks up a value using a specific injector, before falling back to the module\n * injector. Used primarily when creating components or embedded views dynamically.\n */\nclass ChainedInjector {\n constructor(injector, parentInjector) {\n this.injector = injector;\n this.parentInjector = parentInjector;\n }\n get(token, notFoundValue, flags) {\n flags = convertToBitFlags(flags);\n const value = this.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);\n if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR || notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {\n // Return the value from the root element injector when\n // - it provides it\n // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)\n // - the module injector should not be checked\n // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)\n return value;\n }\n return this.parentInjector.get(token, notFoundValue, flags);\n }\n}\n\n/// Parent Injector Utils ///////////////////////////////////////////////////////////////\nfunction hasParentInjector(parentLocation) {\n return parentLocation !== NO_PARENT_INJECTOR;\n}\nfunction getParentInjectorIndex(parentLocation) {\n if (ngDevMode) {\n assertNumber(parentLocation, 'Number expected');\n assertNotEqual(parentLocation, -1, 'Not a valid state.');\n const parentInjectorIndex = parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;\n assertGreaterThan(parentInjectorIndex, HEADER_OFFSET, 'Parent injector must be pointing past HEADER_OFFSET.');\n }\n return parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;\n}\nfunction getParentInjectorViewOffset(parentLocation) {\n return parentLocation >> 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;\n}\n/**\n * Unwraps a parent injector location number to find the view offset from the current injector,\n * then walks up the declaration view tree until the view is found that contains the parent\n * injector.\n *\n * @param location The location of the parent injector, which contains the view offset\n * @param startView The LView instance from which to start walking up the view tree\n * @returns The LView instance that contains the parent injector\n */\nfunction getParentInjectorView(location, startView) {\n let viewOffset = getParentInjectorViewOffset(location);\n let parentView = startView;\n // For most cases, the parent injector can be found on the host node (e.g. for component\n // or container), but we must keep the loop here to support the rarer case of deeply nested\n // tags or inline views, where the parent injector might live many views\n // above the child injector.\n while (viewOffset > 0) {\n parentView = parentView[DECLARATION_VIEW];\n viewOffset--;\n }\n return parentView;\n}\n/**\n * Detects whether an injector is an instance of a `ChainedInjector`,\n * created based on the `OutletInjector`.\n */\nfunction isRouterOutletInjector(currentInjector) {\n return currentInjector instanceof ChainedInjector && typeof currentInjector.injector.__ngOutletInjector === 'function';\n}\n\n/**\n * Defines if the call to `inject` should include `viewProviders` in its resolution.\n *\n * This is set to true when we try to instantiate a component. This value is reset in\n * `getNodeInjectable` to a value which matches the declaration location of the token about to be\n * instantiated. This is done so that if we are injecting a token which was declared outside of\n * `viewProviders` we don't accidentally pull `viewProviders` in.\n *\n * Example:\n *\n * ```\n * @Injectable()\n * class MyService {\n * constructor(public value: String) {}\n * }\n *\n * @Component({\n * providers: [\n * MyService,\n * {provide: String, value: 'providers' }\n * ]\n * viewProviders: [\n * {provide: String, value: 'viewProviders'}\n * ]\n * })\n * class MyComponent {\n * constructor(myService: MyService, value: String) {\n * // We expect that Component can see into `viewProviders`.\n * expect(value).toEqual('viewProviders');\n * // `MyService` was not declared in `viewProviders` hence it can't see it.\n * expect(myService.value).toEqual('providers');\n * }\n * }\n *\n * ```\n */\nlet includeViewProviders = true;\nfunction setIncludeViewProviders(v) {\n const oldValue = includeViewProviders;\n includeViewProviders = v;\n return oldValue;\n}\n/**\n * The number of slots in each bloom filter (used by DI). The larger this number, the fewer\n * directives that will share slots, and thus, the fewer false positives when checking for\n * the existence of a directive.\n */\nconst BLOOM_SIZE = 256;\nconst BLOOM_MASK = BLOOM_SIZE - 1;\n/**\n * The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits,\n * so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash\n * number.\n */\nconst BLOOM_BUCKET_BITS = 5;\n/** Counter used to generate unique IDs for directives. */\nlet nextNgElementId = 0;\n/** Value used when something wasn't found by an injector. */\nconst NOT_FOUND = {};\n/**\n * Registers this directive as present in its node's injector by flipping the directive's\n * corresponding bit in the injector's bloom filter.\n *\n * @param injectorIndex The index of the node injector where this token should be registered\n * @param tView The TView for the injector's bloom filters\n * @param type The directive token to register\n */\nfunction bloomAdd(injectorIndex, tView, type) {\n ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');\n let id;\n if (typeof type === 'string') {\n id = type.charCodeAt(0) || 0;\n } else if (type.hasOwnProperty(NG_ELEMENT_ID)) {\n id = type[NG_ELEMENT_ID];\n }\n // Set a unique ID on the directive type, so if something tries to inject the directive,\n // we can easily retrieve the ID and hash it into the bloom bit that should be checked.\n if (id == null) {\n id = type[NG_ELEMENT_ID] = nextNgElementId++;\n }\n // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),\n // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.\n const bloomHash = id & BLOOM_MASK;\n // Create a mask that targets the specific bit associated with the directive.\n // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding\n // to bit positions 0 - 31 in a 32 bit integer.\n const mask = 1 << bloomHash;\n // Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`.\n // Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask\n // should be written to.\n tView.data[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask;\n}\n/**\n * Creates (or gets an existing) injector for a given element or container.\n *\n * @param tNode for which an injector should be retrieved / created.\n * @param lView View where the node is stored\n * @returns Node injector\n */\nfunction getOrCreateNodeInjectorForNode(tNode, lView) {\n const existingInjectorIndex = getInjectorIndex(tNode, lView);\n if (existingInjectorIndex !== -1) {\n return existingInjectorIndex;\n }\n const tView = lView[TVIEW];\n if (tView.firstCreatePass) {\n tNode.injectorIndex = lView.length;\n insertBloom(tView.data, tNode); // foundation for node bloom\n insertBloom(lView, null); // foundation for cumulative bloom\n insertBloom(tView.blueprint, null);\n }\n const parentLoc = getParentInjectorLocation(tNode, lView);\n const injectorIndex = tNode.injectorIndex;\n // If a parent injector can't be found, its location is set to -1.\n // In that case, we don't need to set up a cumulative bloom\n if (hasParentInjector(parentLoc)) {\n const parentIndex = getParentInjectorIndex(parentLoc);\n const parentLView = getParentInjectorView(parentLoc, lView);\n const parentData = parentLView[TVIEW].data;\n // Creates a cumulative bloom filter that merges the parent's bloom filter\n // and its own cumulative bloom (which contains tokens for all ancestors)\n for (let i = 0; i < 8 /* NodeInjectorOffset.BLOOM_SIZE */; i++) {\n lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];\n }\n }\n lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */] = parentLoc;\n return injectorIndex;\n}\nfunction insertBloom(arr, footer) {\n arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);\n}\nfunction getInjectorIndex(tNode, lView) {\n if (tNode.injectorIndex === -1 ||\n // If the injector index is the same as its parent's injector index, then the index has been\n // copied down from the parent node. No injector has been created yet on this node.\n tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex ||\n // After the first template pass, the injector index might exist but the parent values\n // might not have been calculated yet for this instance\n lView[tNode.injectorIndex + 8 /* NodeInjectorOffset.PARENT */] === null) {\n return -1;\n } else {\n ngDevMode && assertIndexInRange(lView, tNode.injectorIndex);\n return tNode.injectorIndex;\n }\n}\n/**\n * Finds the index of the parent injector, with a view offset if applicable. Used to set the\n * parent injector initially.\n *\n * @returns Returns a number that is the combination of the number of LViews that we have to go up\n * to find the LView containing the parent inject AND the index of the injector within that LView.\n */\nfunction getParentInjectorLocation(tNode, lView) {\n if (tNode.parent && tNode.parent.injectorIndex !== -1) {\n // If we have a parent `TNode` and there is an injector associated with it we are done, because\n // the parent injector is within the current `LView`.\n return tNode.parent.injectorIndex; // ViewOffset is 0\n }\n // When parent injector location is computed it may be outside of the current view. (ie it could\n // be pointing to a declared parent location). This variable stores number of declaration parents\n // we need to walk up in order to find the parent injector location.\n let declarationViewOffset = 0;\n let parentTNode = null;\n let lViewCursor = lView;\n // The parent injector is not in the current `LView`. We will have to walk the declared parent\n // `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent\n // `NodeInjector`.\n while (lViewCursor !== null) {\n parentTNode = getTNodeFromLView(lViewCursor);\n if (parentTNode === null) {\n // If we have no parent, than we are done.\n return NO_PARENT_INJECTOR;\n }\n ngDevMode && parentTNode && assertTNodeForLView(parentTNode, lViewCursor[DECLARATION_VIEW]);\n // Every iteration of the loop requires that we go to the declared parent.\n declarationViewOffset++;\n lViewCursor = lViewCursor[DECLARATION_VIEW];\n if (parentTNode.injectorIndex !== -1) {\n // We found a NodeInjector which points to something.\n return parentTNode.injectorIndex | declarationViewOffset << 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;\n }\n }\n return NO_PARENT_INJECTOR;\n}\n/**\n * Makes a type or an injection token public to the DI system by adding it to an\n * injector's bloom filter.\n *\n * @param di The node injector in which a directive will be added\n * @param token The type or the injection token to be made public\n */\nfunction diPublicInInjector(injectorIndex, tView, token) {\n bloomAdd(injectorIndex, tView, token);\n}\n/**\n * Inject static attribute value into directive constructor.\n *\n * This method is used with `factory` functions which are generated as part of\n * `defineDirective` or `defineComponent`. The method retrieves the static value\n * of an attribute. (Dynamic attributes are not supported since they are not resolved\n * at the time of injection and can change over time.)\n *\n * # Example\n * Given:\n * ```\n * @Component(...)\n * class MyComponent {\n * constructor(@Attribute('title') title: string) { ... }\n * }\n * ```\n * When instantiated with\n * ```\n * \n * ```\n *\n * Then factory method generated is:\n * ```\n * MyComponent.ɵcmp = defineComponent({\n * factory: () => new MyComponent(injectAttribute('title'))\n * ...\n * })\n * ```\n *\n * @publicApi\n */\nfunction injectAttributeImpl(tNode, attrNameToInject) {\n ngDevMode && assertTNodeType(tNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);\n ngDevMode && assertDefined(tNode, 'expecting tNode');\n if (attrNameToInject === 'class') {\n return tNode.classes;\n }\n if (attrNameToInject === 'style') {\n return tNode.styles;\n }\n const attrs = tNode.attrs;\n if (attrs) {\n const attrsLength = attrs.length;\n let i = 0;\n while (i < attrsLength) {\n const value = attrs[i];\n // If we hit a `Bindings` or `Template` marker then we are done.\n if (isNameOnlyAttributeMarker(value)) break;\n // Skip namespaced attributes\n if (value === 0 /* AttributeMarker.NamespaceURI */) {\n // we skip the next two values\n // as namespaced attributes looks like\n // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',\n // 'existValue', ...]\n i = i + 2;\n } else if (typeof value === 'number') {\n // Skip to the first value of the marked attribute.\n i++;\n while (i < attrsLength && typeof attrs[i] === 'string') {\n i++;\n }\n } else if (value === attrNameToInject) {\n return attrs[i + 1];\n } else {\n i = i + 2;\n }\n }\n }\n return null;\n}\nfunction notFoundValueOrThrow(notFoundValue, token, flags) {\n if (flags & InjectFlags.Optional || notFoundValue !== undefined) {\n return notFoundValue;\n } else {\n throwProviderNotFoundError(token, 'NodeInjector');\n }\n}\n/**\n * Returns the value associated to the given token from the ModuleInjector or throws exception\n *\n * @param lView The `LView` that contains the `tNode`\n * @param token The token to look for\n * @param flags Injection flags\n * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`\n * @returns the value from the injector or throws an exception\n */\nfunction lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue) {\n if (flags & InjectFlags.Optional && notFoundValue === undefined) {\n // This must be set or the NullInjector will throw for optional deps\n notFoundValue = null;\n }\n if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {\n const moduleInjector = lView[INJECTOR];\n // switch to `injectInjectorOnly` implementation for module injector, since module injector\n // should not have access to Component/Directive DI scope (that may happen through\n // `directiveInject` implementation)\n const previousInjectImplementation = setInjectImplementation(undefined);\n try {\n if (moduleInjector) {\n return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);\n } else {\n return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);\n }\n } finally {\n setInjectImplementation(previousInjectImplementation);\n }\n }\n return notFoundValueOrThrow(notFoundValue, token, flags);\n}\n/**\n * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.\n *\n * Look for the injector providing the token by walking up the node injector tree and then\n * the module injector tree.\n *\n * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom\n * filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)\n *\n * @param tNode The Node where the search for the injector should start\n * @param lView The `LView` that contains the `tNode`\n * @param token The token to look for\n * @param flags Injection flags\n * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`\n * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided\n */\nfunction getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {\n if (tNode !== null) {\n // If the view or any of its ancestors have an embedded\n // view injector, we have to look it up there first.\n if (lView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&\n // The token must be present on the current node injector when the `Self`\n // flag is set, so the lookup on embedded view injector(s) can be skipped.\n !(flags & InjectFlags.Self)) {\n const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, NOT_FOUND);\n if (embeddedInjectorValue !== NOT_FOUND) {\n return embeddedInjectorValue;\n }\n }\n // Otherwise try the node injector.\n const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND);\n if (value !== NOT_FOUND) {\n return value;\n }\n }\n // Finally, fall back to the module injector.\n return lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);\n}\n/**\n * Returns the value associated to the given token from the node injector.\n *\n * @param tNode The Node where the search for the injector should start\n * @param lView The `LView` that contains the `tNode`\n * @param token The token to look for\n * @param flags Injection flags\n * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`\n * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided\n */\nfunction lookupTokenUsingNodeInjector(tNode, lView, token, flags, notFoundValue) {\n const bloomHash = bloomHashBitOrFactory(token);\n // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef\n // so just call the factory function to create it.\n if (typeof bloomHash === 'function') {\n if (!enterDI(lView, tNode, flags)) {\n // Failed to enter DI, try module injector instead. If a token is injected with the @Host\n // flag, the module injector is not searched for that token in Ivy.\n return flags & InjectFlags.Host ? notFoundValueOrThrow(notFoundValue, token, flags) : lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);\n }\n try {\n let value;\n if (ngDevMode) {\n runInInjectorProfilerContext(new NodeInjector(getCurrentTNode(), getLView()), token, () => {\n value = bloomHash(flags);\n if (value != null) {\n emitInstanceCreatedByInjectorEvent(value);\n }\n });\n } else {\n value = bloomHash(flags);\n }\n if (value == null && !(flags & InjectFlags.Optional)) {\n throwProviderNotFoundError(token);\n } else {\n return value;\n }\n } finally {\n leaveDI();\n }\n } else if (typeof bloomHash === 'number') {\n // A reference to the previous injector TView that was found while climbing the element\n // injector tree. This is used to know if viewProviders can be accessed on the current\n // injector.\n let previousTView = null;\n let injectorIndex = getInjectorIndex(tNode, lView);\n let parentLocation = NO_PARENT_INJECTOR;\n let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;\n // If we should skip this injector, or if there is no injector on this node, start by\n // searching the parent injector.\n if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {\n parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) : lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];\n if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) {\n injectorIndex = -1;\n } else {\n previousTView = lView[TVIEW];\n injectorIndex = getParentInjectorIndex(parentLocation);\n lView = getParentInjectorView(parentLocation, lView);\n }\n }\n // Traverse up the injector tree until we find a potential match or until we know there\n // *isn't* a match.\n while (injectorIndex !== -1) {\n ngDevMode && assertNodeInjector(lView, injectorIndex);\n // Check the current injector. If it matches, see if it contains token.\n const tView = lView[TVIEW];\n ngDevMode && assertTNodeForLView(tView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */], lView);\n if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {\n // At this point, we have an injector which *may* contain the token, so we step through\n // the providers and directives associated with the injector's corresponding node to get\n // the instance.\n const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);\n if (instance !== NOT_FOUND) {\n return instance;\n }\n }\n parentLocation = lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];\n if (parentLocation !== NO_PARENT_INJECTOR && shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */] === hostTElementNode) && bloomHasToken(bloomHash, injectorIndex, lView)) {\n // The def wasn't found anywhere on this node, so it was a false positive.\n // Traverse up the tree and continue searching.\n previousTView = tView;\n injectorIndex = getParentInjectorIndex(parentLocation);\n lView = getParentInjectorView(parentLocation, lView);\n } else {\n // If we should not search parent OR If the ancestor bloom filter value does not have the\n // bit corresponding to the directive we can give up on traversing up to find the specific\n // injector.\n injectorIndex = -1;\n }\n }\n }\n return notFoundValue;\n}\nfunction searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {\n const currentTView = lView[TVIEW];\n const tNode = currentTView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];\n // First, we need to determine if view providers can be accessed by the starting element.\n // There are two possibilities\n const canAccessViewProviders = previousTView == null ?\n // 1) This is the first invocation `previousTView == null` which means that we are at the\n // `TNode` of where injector is starting to look. In such a case the only time we are allowed\n // to look into the ViewProviders is if:\n // - we are on a component\n // - AND the injector set `includeViewProviders` to true (implying that the token can see\n // ViewProviders because it is the Component or a Service which itself was declared in\n // ViewProviders)\n isComponentHost(tNode) && includeViewProviders :\n // 2) `previousTView != null` which means that we are now walking across the parent nodes.\n // In such a case we are only allowed to look into the ViewProviders if:\n // - We just crossed from child View to Parent View `previousTView != currentTView`\n // - AND the parent TNode is an Element.\n // This means that we just came from the Component's View and therefore are allowed to see\n // into the ViewProviders.\n previousTView != currentTView && (tNode.type & 3 /* TNodeType.AnyRNode */) !== 0;\n // This special case happens when there is a @host on the inject and when we are searching\n // on the host element node.\n const isHostSpecialCase = flags & InjectFlags.Host && hostTElementNode === tNode;\n const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);\n if (injectableIdx !== null) {\n return getNodeInjectable(lView, currentTView, injectableIdx, tNode);\n } else {\n return NOT_FOUND;\n }\n}\n/**\n * Searches for the given token among the node's directives and providers.\n *\n * @param tNode TNode on which directives are present.\n * @param tView The tView we are currently processing\n * @param token Provider token or type of a directive to look for.\n * @param canAccessViewProviders Whether view providers should be considered.\n * @param isHostSpecialCase Whether the host special case applies.\n * @returns Index of a found directive or provider, or null when none found.\n */\nfunction locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {\n const nodeProviderIndexes = tNode.providerIndexes;\n const tInjectables = tView.data;\n const injectablesStart = nodeProviderIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;\n const directivesStart = tNode.directiveStart;\n const directiveEnd = tNode.directiveEnd;\n const cptViewProvidersCount = nodeProviderIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;\n const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;\n // When the host special case applies, only the viewProviders and the component are visible\n const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;\n for (let i = startingIndex; i < endIndex; i++) {\n const providerTokenOrDef = tInjectables[i];\n if (i < directivesStart && token === providerTokenOrDef || i >= directivesStart && providerTokenOrDef.type === token) {\n return i;\n }\n }\n if (isHostSpecialCase) {\n const dirDef = tInjectables[directivesStart];\n if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {\n return directivesStart;\n }\n }\n return null;\n}\n/**\n * Retrieve or instantiate the injectable from the `LView` at particular `index`.\n *\n * This function checks to see if the value has already been instantiated and if so returns the\n * cached `injectable`. Otherwise if it detects that the value is still a factory it\n * instantiates the `injectable` and caches the value.\n */\nfunction getNodeInjectable(lView, tView, index, tNode) {\n let value = lView[index];\n const tData = tView.data;\n if (isFactory(value)) {\n const factory = value;\n if (factory.resolving) {\n throwCyclicDependencyError(stringifyForError(tData[index]));\n }\n const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);\n factory.resolving = true;\n let prevInjectContext;\n if (ngDevMode) {\n // tData indexes mirror the concrete instances in its corresponding LView.\n // lView[index] here is either the injectable instace itself or a factory,\n // therefore tData[index] is the constructor of that injectable or a\n // definition object that contains the constructor in a `.type` field.\n const token = tData[index].type || tData[index];\n const injector = new NodeInjector(tNode, lView);\n prevInjectContext = setInjectorProfilerContext({\n injector,\n token\n });\n }\n const previousInjectImplementation = factory.injectImpl ? setInjectImplementation(factory.injectImpl) : null;\n const success = enterDI(lView, tNode, InjectFlags.Default);\n ngDevMode && assertEqual(success, true, \"Because flags do not contain `SkipSelf' we expect this to always succeed.\");\n try {\n value = lView[index] = factory.factory(undefined, tData, lView, tNode);\n ngDevMode && emitInstanceCreatedByInjectorEvent(value);\n // This code path is hit for both directives and providers.\n // For perf reasons, we want to avoid searching for hooks on providers.\n // It does no harm to try (the hooks just won't exist), but the extra\n // checks are unnecessary and this is a hot path. So we check to see\n // if the index of the dependency is in the directive range for this\n // tNode. If it's not, we know it's a provider and skip hook registration.\n if (tView.firstCreatePass && index >= tNode.directiveStart) {\n ngDevMode && assertDirectiveDef(tData[index]);\n registerPreOrderHooks(index, tData[index], tView);\n }\n } finally {\n ngDevMode && setInjectorProfilerContext(prevInjectContext);\n previousInjectImplementation !== null && setInjectImplementation(previousInjectImplementation);\n setIncludeViewProviders(previousIncludeViewProviders);\n factory.resolving = false;\n leaveDI();\n }\n }\n return value;\n}\n/**\n * Returns the bit in an injector's bloom filter that should be used to determine whether or not\n * the directive might be provided by the injector.\n *\n * When a directive is public, it is added to the bloom filter and given a unique ID that can be\n * retrieved on the Type. When the directive isn't public or the token is not a directive `null`\n * is returned as the node injector can not possibly provide that token.\n *\n * @param token the injection token\n * @returns the matching bit to check in the bloom filter or `null` if the token is not known.\n * When the returned value is negative then it represents special values such as `Injector`.\n */\nfunction bloomHashBitOrFactory(token) {\n ngDevMode && assertDefined(token, 'token must be defined');\n if (typeof token === 'string') {\n return token.charCodeAt(0) || 0;\n }\n const tokenId =\n // First check with `hasOwnProperty` so we don't get an inherited ID.\n token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;\n // Negative token IDs are used for special objects such as `Injector`\n if (typeof tokenId === 'number') {\n if (tokenId >= 0) {\n return tokenId & BLOOM_MASK;\n } else {\n ngDevMode && assertEqual(tokenId, -1 /* InjectorMarkers.Injector */, 'Expecting to get Special Injector Id');\n return createNodeInjector;\n }\n } else {\n return tokenId;\n }\n}\nfunction bloomHasToken(bloomHash, injectorIndex, injectorView) {\n // Create a mask that targets the specific bit associated with the directive we're looking for.\n // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding\n // to bit positions 0 - 31 in a 32 bit integer.\n const mask = 1 << bloomHash;\n // Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of\n // `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset\n // that should be used.\n const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)];\n // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,\n // this injector is a potential match.\n return !!(value & mask);\n}\n/** Returns true if flags prevent parent injector from being searched for tokens */\nfunction shouldSearchParent(flags, isFirstHostTNode) {\n return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);\n}\nfunction getNodeInjectorLView(nodeInjector) {\n return nodeInjector._lView;\n}\nfunction getNodeInjectorTNode(nodeInjector) {\n return nodeInjector._tNode;\n}\nclass NodeInjector {\n constructor(_tNode, _lView) {\n this._tNode = _tNode;\n this._lView = _lView;\n }\n get(token, notFoundValue, flags) {\n return getOrCreateInjectable(this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue);\n }\n}\n/** Creates a `NodeInjector` for the current node. */\nfunction createNodeInjector() {\n return new NodeInjector(getCurrentTNode(), getLView());\n}\n/**\n * @codeGenApi\n */\nfunction ɵɵgetInheritedFactory(type) {\n return noSideEffects(() => {\n const ownConstructor = type.prototype.constructor;\n const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor);\n const objectPrototype = Object.prototype;\n let parent = Object.getPrototypeOf(type.prototype).constructor;\n // Go up the prototype until we hit `Object`.\n while (parent && parent !== objectPrototype) {\n const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent);\n // If we hit something that has a factory and the factory isn't the same as the type,\n // we've found the inherited factory. Note the check that the factory isn't the type's\n // own factory is redundant in most cases, but if the user has custom decorators on the\n // class, this lookup will start one level down in the prototype chain, causing us to\n // find the own factory first and potentially triggering an infinite loop downstream.\n if (factory && factory !== ownFactory) {\n return factory;\n }\n parent = Object.getPrototypeOf(parent);\n }\n // There is no factory defined. Either this was improper usage of inheritance\n // (no Angular decorator on the superclass) or there is no constructor at all\n // in the inheritance chain. Since the two cases cannot be distinguished, the\n // latter has to be assumed.\n return t => new t();\n });\n}\nfunction getFactoryOf(type) {\n if (isForwardRef(type)) {\n return () => {\n const factory = getFactoryOf(resolveForwardRef(type));\n return factory && factory();\n };\n }\n return getFactoryDef(type);\n}\n/**\n * Returns a value from the closest embedded or node injector.\n *\n * @param tNode The Node where the search for the injector should start\n * @param lView The `LView` that contains the `tNode`\n * @param token The token to look for\n * @param flags Injection flags\n * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`\n * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided\n */\nfunction lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, notFoundValue) {\n let currentTNode = tNode;\n let currentLView = lView;\n // When an LView with an embedded view injector is inserted, it'll likely be interlaced with\n // nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector).\n // Since the bloom filters for the node injectors have already been constructed and we don't\n // have a way of extracting the records from an injector, the only way to maintain the correct\n // hierarchy when resolving the value is to walk it node-by-node while attempting to resolve\n // the token at each level.\n while (currentTNode !== null && currentLView !== null && currentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ && !(currentLView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {\n ngDevMode && assertTNodeForLView(currentTNode, currentLView);\n // Note that this lookup on the node injector is using the `Self` flag, because\n // we don't want the node injector to look at any parent injectors since we\n // may hit the embedded view injector first.\n const nodeInjectorValue = lookupTokenUsingNodeInjector(currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND);\n if (nodeInjectorValue !== NOT_FOUND) {\n return nodeInjectorValue;\n }\n // Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191\n let parentTNode = currentTNode.parent;\n // `TNode.parent` includes the parent within the current view only. If it doesn't exist,\n // it means that we've hit the view boundary and we need to go up to the next view.\n if (!parentTNode) {\n // Before we go to the next LView, check if the token exists on the current embedded injector.\n const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR];\n if (embeddedViewInjector) {\n const embeddedViewInjectorValue = embeddedViewInjector.get(token, NOT_FOUND, flags);\n if (embeddedViewInjectorValue !== NOT_FOUND) {\n return embeddedViewInjectorValue;\n }\n }\n // Otherwise keep going up the tree.\n parentTNode = getTNodeFromLView(currentLView);\n currentLView = currentLView[DECLARATION_VIEW];\n }\n currentTNode = parentTNode;\n }\n return notFoundValue;\n}\n/** Gets the TNode associated with an LView inside of the declaration view. */\nfunction getTNodeFromLView(lView) {\n const tView = lView[TVIEW];\n const tViewType = tView.type;\n // The parent pointer differs based on `TView.type`.\n if (tViewType === 2 /* TViewType.Embedded */) {\n ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');\n return tView.declTNode;\n } else if (tViewType === 1 /* TViewType.Component */) {\n // Components don't have `TView.declTNode` because each instance of component could be\n // inserted in different location, hence `TView.declTNode` is meaningless.\n return lView[T_HOST];\n }\n return null;\n}\n\n/**\n * Facade for the attribute injection from DI.\n *\n * @codeGenApi\n */\nfunction ɵɵinjectAttribute(attrNameToInject) {\n return injectAttributeImpl(getCurrentTNode(), attrNameToInject);\n}\n\n/**\n * Attribute decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Attribute = makeParamDecorator('Attribute', attributeName => ({\n attributeName,\n __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName)\n}));\nlet _reflect = null;\nfunction getReflect() {\n return _reflect = _reflect || new ReflectionCapabilities();\n}\nfunction reflectDependencies(type) {\n return convertDependencies(getReflect().parameters(type));\n}\nfunction convertDependencies(deps) {\n return deps.map(dep => reflectDependency(dep));\n}\nfunction reflectDependency(dep) {\n const meta = {\n token: null,\n attribute: null,\n host: false,\n optional: false,\n self: false,\n skipSelf: false\n };\n if (Array.isArray(dep) && dep.length > 0) {\n for (let j = 0; j < dep.length; j++) {\n const param = dep[j];\n if (param === undefined) {\n // param may be undefined if type of dep is not set by ngtsc\n continue;\n }\n const proto = Object.getPrototypeOf(param);\n if (param instanceof Optional || proto.ngMetadataName === 'Optional') {\n meta.optional = true;\n } else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {\n meta.skipSelf = true;\n } else if (param instanceof Self || proto.ngMetadataName === 'Self') {\n meta.self = true;\n } else if (param instanceof Host || proto.ngMetadataName === 'Host') {\n meta.host = true;\n } else if (param instanceof Inject) {\n meta.token = param.token;\n } else if (param instanceof Attribute) {\n if (param.attributeName === undefined) {\n throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Attribute name must be defined.`);\n }\n meta.attribute = param.attributeName;\n } else {\n meta.token = param;\n }\n }\n } else if (dep === undefined || Array.isArray(dep) && dep.length === 0) {\n meta.token = null;\n } else {\n meta.token = dep;\n }\n return meta;\n}\n\n/**\n * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting\n * injectable def (`ɵprov`) onto the injectable type.\n */\nfunction compileInjectable(type, meta) {\n let ngInjectableDef = null;\n let ngFactoryDef = null;\n // if NG_PROV_DEF is already defined on this class then don't overwrite it\n if (!type.hasOwnProperty(NG_PROV_DEF)) {\n Object.defineProperty(type, NG_PROV_DEF, {\n get: () => {\n if (ngInjectableDef === null) {\n const compiler = getCompilerFacade({\n usage: 0 /* JitCompilerUsage.Decorator */,\n kind: 'injectable',\n type\n });\n ngInjectableDef = compiler.compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta));\n }\n return ngInjectableDef;\n }\n });\n }\n // if NG_FACTORY_DEF is already defined on this class then don't overwrite it\n if (!type.hasOwnProperty(NG_FACTORY_DEF)) {\n Object.defineProperty(type, NG_FACTORY_DEF, {\n get: () => {\n if (ngFactoryDef === null) {\n const compiler = getCompilerFacade({\n usage: 0 /* JitCompilerUsage.Decorator */,\n kind: 'injectable',\n type\n });\n ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {\n name: type.name,\n type,\n typeArgumentCount: 0,\n // In JIT mode types are not available nor used.\n deps: reflectDependencies(type),\n target: compiler.FactoryTarget.Injectable\n });\n }\n return ngFactoryDef;\n },\n // Leave this configurable so that the factories from directives or pipes can take precedence.\n configurable: true\n });\n }\n}\nconst USE_VALUE = getClosureSafeProperty({\n provide: String,\n useValue: getClosureSafeProperty\n});\nfunction isUseClassProvider(meta) {\n return meta.useClass !== undefined;\n}\nfunction isUseValueProvider(meta) {\n return USE_VALUE in meta;\n}\nfunction isUseFactoryProvider(meta) {\n return meta.useFactory !== undefined;\n}\nfunction isUseExistingProvider(meta) {\n return meta.useExisting !== undefined;\n}\nfunction getInjectableMetadata(type, srcMeta) {\n // Allow the compilation of a class with a `@Injectable()` decorator without parameters\n const meta = srcMeta || {\n providedIn: null\n };\n const compilerMeta = {\n name: type.name,\n type: type,\n typeArgumentCount: 0,\n providedIn: meta.providedIn\n };\n if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {\n compilerMeta.deps = convertDependencies(meta.deps);\n }\n // Check to see if the user explicitly provided a `useXxxx` property.\n if (isUseClassProvider(meta)) {\n compilerMeta.useClass = meta.useClass;\n } else if (isUseValueProvider(meta)) {\n compilerMeta.useValue = meta.useValue;\n } else if (isUseFactoryProvider(meta)) {\n compilerMeta.useFactory = meta.useFactory;\n } else if (isUseExistingProvider(meta)) {\n compilerMeta.useExisting = meta.useExisting;\n }\n return compilerMeta;\n}\n\n/**\n * Injectable decorator and metadata.\n *\n * @Annotation\n * @publicApi\n */\nconst Injectable = makeDecorator('Injectable', undefined, undefined, undefined, (type, meta) => compileInjectable(type, meta));\n\n/**\n * Create a new `Injector` which is configured using a `defType` of `InjectorType`s.\n */\nfunction createInjector(defType, parent = null, additionalProviders = null, name) {\n const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);\n injector.resolveInjectorInitializers();\n return injector;\n}\n/**\n * Creates a new injector without eagerly resolving its injector types. Can be used in places\n * where resolving the injector types immediately can lead to an infinite loop. The injector types\n * should be resolved at a later point by calling `_resolveInjectorDefTypes`.\n */\nfunction createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {\n const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)];\n name = name || (typeof defType === 'object' ? undefined : stringify(defType));\n return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);\n}\n\n/**\n * Concrete injectors implement this interface. Injectors are configured\n * with [providers](guide/di/dependency-injection-providers) that associate\n * dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).\n *\n * @see [DI Providers](guide/di/dependency-injection-providers).\n * @see {@link StaticProvider}\n *\n * @usageNotes\n *\n * The following example creates a service injector instance.\n *\n * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}\n *\n * ### Usage example\n *\n * {@example core/di/ts/injector_spec.ts region='Injector'}\n *\n * `Injector` returns itself when given `Injector` as a token:\n *\n * {@example core/di/ts/injector_spec.ts region='injectInjector'}\n *\n * @publicApi\n */\nclass Injector {\n static {\n this.THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;\n }\n static {\n this.NULL = new NullInjector();\n }\n static create(options, parent) {\n if (Array.isArray(options)) {\n return createInjector({\n name: ''\n }, parent, options, '');\n } else {\n const name = options.name ?? '';\n return createInjector({\n name\n }, options.parent, options.providers, name);\n }\n }\n /** @nocollapse */\n static {\n this.ɵprov = ɵɵdefineInjectable({\n token: Injector,\n providedIn: 'any',\n factory: () => ɵɵinject(INJECTOR$1)\n });\n }\n /**\n * @internal\n * @nocollapse\n */\n static {\n this.__NG_ELEMENT_ID__ = -1 /* InjectorMarkers.Injector */;\n }\n}\n\n/*!\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n/**\n * Creates a token that can be used to inject static attributes of the host node.\n *\n * @usageNotes\n * ### Injecting an attribute that is known to exist\n * ```typescript\n * @Directive()\n * class MyDir {\n * attr: string = inject(new HostAttributeToken('some-attr'));\n * }\n * ```\n *\n * ### Optionally injecting an attribute\n * ```typescript\n * @Directive()\n * class MyDir {\n * attr: string | null = inject(new HostAttributeToken('some-attr'), {optional: true});\n * }\n * ```\n * @publicApi\n */\nclass HostAttributeToken {\n constructor(attributeName) {\n this.attributeName = attributeName;\n /** @internal */\n this.__NG_ELEMENT_ID__ = () => ɵɵinjectAttribute(this.attributeName);\n }\n toString() {\n return `HostAttributeToken ${this.attributeName}`;\n }\n}\n\n/**\n * A token that can be used to inject the tag name of the host node.\n *\n * @usageNotes\n * ### Injecting a tag name that is known to exist\n * ```typescript\n * @Directive()\n * class MyDir {\n * tagName: string = inject(HOST_TAG_NAME);\n * }\n * ```\n *\n * ### Optionally injecting a tag name\n * ```typescript\n * @Directive()\n * class MyDir {\n * tagName: string | null = inject(HOST_TAG_NAME, {optional: true});\n * }\n * ```\n * @publicApi\n */\nconst HOST_TAG_NAME = new InjectionToken(ngDevMode ? 'HOST_TAG_NAME' : '');\n// HOST_TAG_NAME should be resolved at the current node, similar to e.g. ElementRef,\n// so we manually specify __NG_ELEMENT_ID__ here, instead of using a factory.\n// tslint:disable-next-line:no-toplevel-property-access\nHOST_TAG_NAME.__NG_ELEMENT_ID__ = flags => {\n const tNode = getCurrentTNode();\n if (tNode === null) {\n 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)');\n }\n if (tNode.type & 2 /* TNodeType.Element */) {\n return tNode.value;\n }\n if (flags & InjectFlags.Optional) {\n return null;\n }\n 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.`);\n};\nfunction getDevModeNodeName(tNode) {\n if (tNode.type & 8 /* TNodeType.ElementContainer */) {\n return 'an ';\n } else if (tNode.type & 4 /* TNodeType.Container */) {\n return 'an ';\n } else if (tNode.type & 128 /* TNodeType.LetDeclaration */) {\n return 'an @let declaration';\n } else {\n return 'a node';\n }\n}\n\n/**\n * @module\n * @description\n * The `di` module provides dependency injection container services.\n */\n\n/**\n * This file should not be necessary because node resolution should just default to `./di/index`!\n *\n * However it does not seem to work and it breaks:\n * - //packages/animations/browser/test:test_web_chromium-local\n * - //packages/compiler-cli/test:extract_i18n\n * - //packages/compiler-cli/test:ngc\n * - //packages/compiler-cli/test:perform_watch\n * - //packages/compiler-cli/test/diagnostics:check_types\n * - //packages/compiler-cli/test/transformers:test\n * - //packages/compiler/test:test\n * - //tools/public_api_guard:core_api\n *\n * Remove this file once the above is solved or wait until `ngc` is deleted and then it should be\n * safe to delete this file.\n */\n\nconst ERROR_ORIGINAL_ERROR = 'ngOriginalError';\nfunction wrappedError(message, originalError) {\n const msg = `${message} caused by: ${originalError instanceof Error ? originalError.message : originalError}`;\n const error = Error(msg);\n error[ERROR_ORIGINAL_ERROR] = originalError;\n return error;\n}\nfunction getOriginalError(error) {\n return error[ERROR_ORIGINAL_ERROR];\n}\nconst SCHEDULE_IN_ROOT_ZONE_DEFAULT = true;\n\n/**\n * `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.\n * The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`\n * is injected in a component or directive, the callbacks run when that component or\n * directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.\n *\n * @publicApi\n */\nclass DestroyRef {\n /**\n * @internal\n * @nocollapse\n */\n static {\n this.__NG_ELEMENT_ID__ = injectDestroyRef;\n }\n /**\n * @internal\n * @nocollapse\n */\n static {\n this.__NG_ENV_ID__ = injector => injector;\n }\n}\nclass NodeInjectorDestroyRef extends DestroyRef {\n constructor(_lView) {\n super();\n this._lView = _lView;\n }\n onDestroy(callback) {\n storeLViewOnDestroy(this._lView, callback);\n return () => removeLViewOnDestroy(this._lView, callback);\n }\n}\nfunction injectDestroyRef() {\n return new NodeInjectorDestroyRef(getLView());\n}\n\n/**\n * Internal implementation of the pending tasks service.\n */\nclass PendingTasks {\n constructor() {\n this.taskId = 0;\n this.pendingTasks = new Set();\n this.hasPendingTasks = new BehaviorSubject(false);\n }\n get _hasPendingTasks() {\n return this.hasPendingTasks.value;\n }\n add() {\n if (!this._hasPendingTasks) {\n this.hasPendingTasks.next(true);\n }\n const taskId = this.taskId++;\n this.pendingTasks.add(taskId);\n return taskId;\n }\n remove(taskId) {\n this.pendingTasks.delete(taskId);\n if (this.pendingTasks.size === 0 && this._hasPendingTasks) {\n this.hasPendingTasks.next(false);\n }\n }\n ngOnDestroy() {\n this.pendingTasks.clear();\n if (this._hasPendingTasks) {\n this.hasPendingTasks.next(false);\n }\n }\n /** @nocollapse */\n static {\n this.ɵprov = ɵɵdefineInjectable({\n token: PendingTasks,\n providedIn: 'root',\n factory: () => new PendingTasks()\n });\n }\n}\n/**\n * Experimental service that keeps track of pending tasks contributing to the stableness of Angular\n * application. While several existing Angular services (ex.: `HttpClient`) will internally manage\n * tasks influencing stability, this API gives control over stability to library and application\n * developers for specific cases not covered by Angular internals.\n *\n * The concept of stability comes into play in several important scenarios:\n * - SSR process needs to wait for the application stability before serializing and sending rendered\n * HTML;\n * - tests might want to delay assertions until the application becomes stable;\n *\n * @usageNotes\n * ```typescript\n * const pendingTasks = inject(ExperimentalPendingTasks);\n * const taskCleanup = pendingTasks.add();\n * // do work that should block application's stability and then:\n * taskCleanup();\n * ```\n *\n * This API is experimental. Neither the shape, nor the underlying behavior is stable and can change\n * in patch versions. We will iterate on the exact API based on the feedback and our understanding\n * of the problem and solution space.\n *\n * @publicApi\n * @experimental\n */\nclass ExperimentalPendingTasks {\n constructor() {\n this.internalPendingTasks = inject(PendingTasks);\n }\n /**\n * Adds a new task that should block application's stability.\n * @returns A cleanup function that removes a task when called.\n */\n add() {\n const taskId = this.internalPendingTasks.add();\n return () => this.internalPendingTasks.remove(taskId);\n }\n /** @nocollapse */\n static {\n this.ɵprov = ɵɵdefineInjectable({\n token: ExperimentalPendingTasks,\n providedIn: 'root',\n factory: () => new ExperimentalPendingTasks()\n });\n }\n}\nclass EventEmitter_ extends Subject {\n constructor(isAsync = false) {\n super();\n this.destroyRef = undefined;\n this.pendingTasks = undefined;\n this.__isAsync = isAsync;\n // Attempt to retrieve a `DestroyRef` and `PendingTasks` optionally.\n // For backwards compatibility reasons, this cannot be required.\n if (isInInjectionContext()) {\n this.destroyRef = inject(DestroyRef, {\n optional: true\n }) ?? undefined;\n this.pendingTasks = inject(PendingTasks, {\n optional: true\n }) ?? undefined;\n }\n }\n emit(value) {\n const prevConsumer = setActiveConsumer$1(null);\n try {\n super.next(value);\n } finally {\n setActiveConsumer$1(prevConsumer);\n }\n }\n subscribe(observerOrNext, error, complete) {\n let nextFn = observerOrNext;\n let errorFn = error || (() => null);\n let completeFn = complete;\n if (observerOrNext && typeof observerOrNext === 'object') {\n const observer = observerOrNext;\n nextFn = observer.next?.bind(observer);\n errorFn = observer.error?.bind(observer);\n completeFn = observer.complete?.bind(observer);\n }\n if (this.__isAsync) {\n errorFn = this.wrapInTimeout(errorFn);\n if (nextFn) {\n nextFn = this.wrapInTimeout(nextFn);\n }\n if (completeFn) {\n completeFn = this.wrapInTimeout(completeFn);\n }\n }\n const sink = super.subscribe({\n next: nextFn,\n error: errorFn,\n complete: completeFn\n });\n if (observerOrNext instanceof Subscription) {\n observerOrNext.add(sink);\n }\n return sink;\n }\n wrapInTimeout(fn) {\n return value => {\n const taskId = this.pendingTasks?.add();\n setTimeout(() => {\n fn(value);\n if (taskId !== undefined) {\n this.pendingTasks?.remove(taskId);\n }\n });\n };\n }\n}\n/**\n * @publicApi\n */\nconst EventEmitter = EventEmitter_;\nfunction noop(...args) {\n // Do nothing.\n}\n\n/**\n * Gets a scheduling function that runs the callback after the first of setTimeout and\n * requestAnimationFrame resolves.\n *\n * - `requestAnimationFrame` ensures that change detection runs ahead of a browser repaint.\n * This ensures that the create and update passes of a change detection always happen\n * in the same frame.\n * - When the browser is resource-starved, `rAF` can execute _before_ a `setTimeout` because\n * rendering is a very high priority process. This means that `setTimeout` cannot guarantee\n * same-frame create and update pass, when `setTimeout` is used to schedule the update phase.\n * - While `rAF` gives us the desirable same-frame updates, it has two limitations that\n * prevent it from being used alone. First, it does not run in background tabs, which would\n * prevent Angular from initializing an application when opened in a new tab (for example).\n * Second, repeated calls to requestAnimationFrame will execute at the refresh rate of the\n * hardware (~16ms for a 60Hz display). This would cause significant slowdown of tests that\n * are written with several updates and asserts in the form of \"update; await stable; assert;\".\n * - Both `setTimeout` and `rAF` are able to \"coalesce\" several events from a single user\n * interaction into a single change detection. Importantly, this reduces view tree traversals when\n * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would\n * then be interleaves between each event.\n *\n * By running change detection after the first of `setTimeout` and `rAF` to execute, we get the\n * best of both worlds.\n *\n * @returns a function to cancel the scheduled callback\n */\nfunction scheduleCallbackWithRafRace(callback) {\n let timeoutId;\n let animationFrameId;\n function cleanup() {\n callback = noop;\n try {\n if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(animationFrameId);\n }\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n } catch {\n // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched\n // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op.\n }\n }\n timeoutId = setTimeout(() => {\n callback();\n cleanup();\n });\n if (typeof requestAnimationFrame === 'function') {\n animationFrameId = requestAnimationFrame(() => {\n callback();\n cleanup();\n });\n }\n return () => cleanup();\n}\nfunction scheduleCallbackWithMicrotask(callback) {\n queueMicrotask(() => callback());\n return () => {\n callback = noop;\n };\n}\nclass AsyncStackTaggingZoneSpec {\n constructor(namePrefix, consoleAsyncStackTaggingImpl = console) {\n this.name = 'asyncStackTagging for ' + namePrefix;\n this.createTask = consoleAsyncStackTaggingImpl?.createTask ?? (() => null);\n }\n onScheduleTask(delegate, _current, target, task) {\n task.consoleTask = this.createTask(`Zone - ${task.source || task.type}`);\n return delegate.scheduleTask(target, task);\n }\n onInvokeTask(delegate, _currentZone, targetZone, task, applyThis, applyArgs) {\n let ret;\n if (task.consoleTask) {\n ret = task.consoleTask.run(() => delegate.invokeTask(targetZone, task, applyThis, applyArgs));\n } else {\n ret = delegate.invokeTask(targetZone, task, applyThis, applyArgs);\n }\n return ret;\n }\n}\nconst isAngularZoneProperty = 'isAngularZone';\nconst angularZoneInstanceIdProperty = isAngularZoneProperty + '_ID';\nlet ngZoneInstanceId = 0;\n/**\n * An injectable service for executing work inside or outside of the Angular zone.\n *\n * The most common use of this service is to optimize performance when starting a work consisting of\n * one or more asynchronous tasks that don't require UI updates or error handling to be handled by\n * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks\n * can reenter the Angular zone via {@link #run}.\n *\n * \n *\n * @usageNotes\n * ### Example\n *\n * ```\n * import {Component, NgZone} from '@angular/core';\n * import {NgIf} from '@angular/common';\n *\n * @Component({\n * selector: 'ng-zone-demo',\n * template: `\n *

Demo: NgZone

\n *\n *

Progress: {{progress}}%

\n *

= 100\">Done processing {{label}} of Angular zone!

\n *\n * \n * \n * `,\n * })\n * export class NgZoneDemo {\n * progress: number = 0;\n * label: string;\n *\n * constructor(private _ngZone: NgZone) {}\n *\n * // Loop inside the Angular zone\n * // so the UI DOES refresh after each setTimeout cycle\n * processWithinAngularZone() {\n * this.label = 'inside';\n * this.progress = 0;\n * this._increaseProgress(() => console.log('Inside Done!'));\n * }\n *\n * // Loop outside of the Angular zone\n * // so the UI DOES NOT refresh after each setTimeout cycle\n * processOutsideOfAngularZone() {\n * this.label = 'outside';\n * this.progress = 0;\n * this._ngZone.runOutsideAngular(() => {\n * this._increaseProgress(() => {\n * // reenter the Angular zone and display done\n * this._ngZone.run(() => { console.log('Outside Done!'); });\n * });\n * });\n * }\n *\n * _increaseProgress(doneCallback: () => void) {\n * this.progress += 1;\n * console.log(`Current progress: ${this.progress}%`);\n *\n * if (this.progress < 100) {\n * window.setTimeout(() => this._increaseProgress(doneCallback), 10);\n * } else {\n * doneCallback();\n * }\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass NgZone {\n constructor(options) {\n this.hasPendingMacrotasks = false;\n this.hasPendingMicrotasks = false;\n /**\n * Whether there are no outstanding microtasks or macrotasks.\n */\n this.isStable = true;\n /**\n * Notifies when code enters Angular Zone. This gets fired first on VM Turn.\n */\n this.onUnstable = new EventEmitter(false);\n /**\n * Notifies when there is no more microtasks enqueued in the current VM Turn.\n * This is a hint for Angular to do change detection, which may enqueue more microtasks.\n * For this reason this event can fire multiple times per VM Turn.\n */\n this.onMicrotaskEmpty = new EventEmitter(false);\n /**\n * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which\n * implies we are about to relinquish VM turn.\n * This event gets called just once.\n */\n this.onStable = new EventEmitter(false);\n /**\n * Notifies that an error has been delivered.\n */\n this.onError = new EventEmitter(false);\n const {\n enableLongStackTrace = false,\n shouldCoalesceEventChangeDetection = false,\n shouldCoalesceRunChangeDetection = false,\n scheduleInRootZone = SCHEDULE_IN_ROOT_ZONE_DEFAULT\n } = options;\n if (typeof Zone == 'undefined') {\n throw new RuntimeError(908 /* RuntimeErrorCode.MISSING_ZONEJS */, ngDevMode && `In this configuration Angular requires Zone.js`);\n }\n Zone.assertZonePatched();\n const self = this;\n self._nesting = 0;\n self._outer = self._inner = Zone.current;\n // AsyncStackTaggingZoneSpec provides `linked stack traces` to show\n // where the async operation is scheduled. For more details, refer\n // to this article, https://developer.chrome.com/blog/devtools-better-angular-debugging/\n // And we only import this AsyncStackTaggingZoneSpec in development mode,\n // in the production mode, the AsyncStackTaggingZoneSpec will be tree shaken away.\n if (ngDevMode) {\n self._inner = self._inner.fork(new AsyncStackTaggingZoneSpec('Angular'));\n }\n if (Zone['TaskTrackingZoneSpec']) {\n self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']());\n }\n if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {\n self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);\n }\n // if shouldCoalesceRunChangeDetection is true, all tasks including event tasks will be\n // coalesced, so shouldCoalesceEventChangeDetection option is not necessary and can be skipped.\n self.shouldCoalesceEventChangeDetection = !shouldCoalesceRunChangeDetection && shouldCoalesceEventChangeDetection;\n self.shouldCoalesceRunChangeDetection = shouldCoalesceRunChangeDetection;\n self.callbackScheduled = false;\n self.scheduleInRootZone = scheduleInRootZone;\n forkInnerZoneWithAngularBehavior(self);\n }\n /**\n This method checks whether the method call happens within an Angular Zone instance.\n */\n static isInAngularZone() {\n // Zone needs to be checked, because this method might be called even when NoopNgZone is used.\n return typeof Zone !== 'undefined' && Zone.current.get(isAngularZoneProperty) === true;\n }\n /**\n Assures that the method is called within the Angular Zone, otherwise throws an error.\n */\n static assertInAngularZone() {\n if (!NgZone.isInAngularZone()) {\n throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to be in Angular Zone, but it is not!');\n }\n }\n /**\n Assures that the method is called outside of the Angular Zone, otherwise throws an error.\n */\n static assertNotInAngularZone() {\n if (NgZone.isInAngularZone()) {\n throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to not be in Angular Zone, but it is!');\n }\n }\n /**\n * Executes the `fn` function synchronously within the Angular zone and returns value returned by\n * the function.\n *\n * Running functions via `run` allows you to reenter Angular zone from a task that was executed\n * outside of the Angular zone (typically started via {@link #runOutsideAngular}).\n *\n * Any future tasks or microtasks scheduled from within this function will continue executing from\n * within the Angular zone.\n *\n * If a synchronous error happens it will be rethrown and not reported via `onError`.\n */\n run(fn, applyThis, applyArgs) {\n return this._inner.run(fn, applyThis, applyArgs);\n }\n /**\n * Executes the `fn` function synchronously within the Angular zone as a task and returns value\n * returned by the function.\n *\n * Running functions via `run` allows you to reenter Angular zone from a task that was executed\n * outside of the Angular zone (typically started via {@link #runOutsideAngular}).\n *\n * Any future tasks or microtasks scheduled from within this function will continue executing from\n * within the Angular zone.\n *\n * If a synchronous error happens it will be rethrown and not reported via `onError`.\n */\n runTask(fn, applyThis, applyArgs, name) {\n const zone = this._inner;\n const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop, noop);\n try {\n return zone.runTask(task, applyThis, applyArgs);\n } finally {\n zone.cancelTask(task);\n }\n }\n /**\n * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not\n * rethrown.\n */\n runGuarded(fn, applyThis, applyArgs) {\n return this._inner.runGuarded(fn, applyThis, applyArgs);\n }\n /**\n * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by\n * the function.\n *\n * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do\n * work that\n * doesn't trigger Angular change-detection or is subject to Angular's error handling.\n *\n * Any future tasks or microtasks scheduled from within this function will continue executing from\n * outside of the Angular zone.\n *\n * Use {@link #run} to reenter the Angular zone and do work that updates the application model.\n */\n runOutsideAngular(fn) {\n return this._outer.run(fn);\n }\n}\nconst EMPTY_PAYLOAD = {};\nfunction checkStable(zone) {\n // TODO: @JiaLiPassion, should check zone.isCheckStableRunning to prevent\n // re-entry. The case is:\n //\n // @Component({...})\n // export class AppComponent {\n // constructor(private ngZone: NgZone) {\n // this.ngZone.onStable.subscribe(() => {\n // this.ngZone.run(() => console.log('stable'););\n // });\n // }\n //\n // The onStable subscriber run another function inside ngZone\n // which causes `checkStable()` re-entry.\n // But this fix causes some issues in g3, so this fix will be\n // launched in another PR.\n if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {\n try {\n zone._nesting++;\n zone.onMicrotaskEmpty.emit(null);\n } finally {\n zone._nesting--;\n if (!zone.hasPendingMicrotasks) {\n try {\n zone.runOutsideAngular(() => zone.onStable.emit(null));\n } finally {\n zone.isStable = true;\n }\n }\n }\n }\n}\nfunction delayChangeDetectionForEvents(zone) {\n /**\n * We also need to check _nesting here\n * Consider the following case with shouldCoalesceRunChangeDetection = true\n *\n * ngZone.run(() => {});\n * ngZone.run(() => {});\n *\n * We want the two `ngZone.run()` only trigger one change detection\n * when shouldCoalesceRunChangeDetection is true.\n * And because in this case, change detection run in async way(requestAnimationFrame),\n * so we also need to check the _nesting here to prevent multiple\n * change detections.\n */\n if (zone.isCheckStableRunning || zone.callbackScheduled) {\n return;\n }\n zone.callbackScheduled = true;\n function scheduleCheckStable() {\n scheduleCallbackWithRafRace(() => {\n zone.callbackScheduled = false;\n updateMicroTaskStatus(zone);\n zone.isCheckStableRunning = true;\n checkStable(zone);\n zone.isCheckStableRunning = false;\n });\n }\n if (zone.scheduleInRootZone) {\n Zone.root.run(() => {\n scheduleCheckStable();\n });\n } else {\n zone._outer.run(() => {\n scheduleCheckStable();\n });\n }\n updateMicroTaskStatus(zone);\n}\nfunction forkInnerZoneWithAngularBehavior(zone) {\n const delayChangeDetectionForEventsDelegate = () => {\n delayChangeDetectionForEvents(zone);\n };\n const instanceId = ngZoneInstanceId++;\n zone._inner = zone._inner.fork({\n name: 'angular',\n properties: {\n [isAngularZoneProperty]: true,\n [angularZoneInstanceIdProperty]: instanceId,\n [angularZoneInstanceIdProperty + instanceId]: true\n },\n onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {\n // Prevent triggering change detection when the flag is detected.\n if (shouldBeIgnoredByZone(applyArgs)) {\n return delegate.invokeTask(target, task, applyThis, applyArgs);\n }\n try {\n onEnter(zone);\n return delegate.invokeTask(target, task, applyThis, applyArgs);\n } finally {\n if (zone.shouldCoalesceEventChangeDetection && task.type === 'eventTask' || zone.shouldCoalesceRunChangeDetection) {\n delayChangeDetectionForEventsDelegate();\n }\n onLeave(zone);\n }\n },\n onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {\n try {\n onEnter(zone);\n return delegate.invoke(target, callback, applyThis, applyArgs, source);\n } finally {\n if (zone.shouldCoalesceRunChangeDetection &&\n // Do not delay change detection when the task is the scheduler's tick.\n // We need to synchronously trigger the stability logic so that the\n // zone-based scheduler can prevent a duplicate ApplicationRef.tick\n // by first checking if the scheduler tick is running. This does seem a bit roundabout,\n // but we _do_ still want to trigger all the correct events when we exit the zone.run\n // (`onMicrotaskEmpty` and `onStable` _should_ emit; developers can have code which\n // relies on these events happening after change detection runs).\n // Note: `zone.callbackScheduled` is already in delayChangeDetectionForEventsDelegate\n // but is added here as well to prevent reads of applyArgs when not necessary\n !zone.callbackScheduled && !isSchedulerTick(applyArgs)) {\n delayChangeDetectionForEventsDelegate();\n }\n onLeave(zone);\n }\n },\n onHasTask: (delegate, current, target, hasTaskState) => {\n delegate.hasTask(target, hasTaskState);\n if (current === target) {\n // We are only interested in hasTask events which originate from our zone\n // (A child hasTask event is not interesting to us)\n if (hasTaskState.change == 'microTask') {\n zone._hasPendingMicrotasks = hasTaskState.microTask;\n updateMicroTaskStatus(zone);\n checkStable(zone);\n } else if (hasTaskState.change == 'macroTask') {\n zone.hasPendingMacrotasks = hasTaskState.macroTask;\n }\n }\n },\n onHandleError: (delegate, current, target, error) => {\n delegate.handleError(target, error);\n zone.runOutsideAngular(() => zone.onError.emit(error));\n return false;\n }\n });\n}\nfunction updateMicroTaskStatus(zone) {\n if (zone._hasPendingMicrotasks || (zone.shouldCoalesceEventChangeDetection || zone.shouldCoalesceRunChangeDetection) && zone.callbackScheduled === true) {\n zone.hasPendingMicrotasks = true;\n } else {\n zone.hasPendingMicrotasks = false;\n }\n}\nfunction onEnter(zone) {\n zone._nesting++;\n if (zone.isStable) {\n zone.isStable = false;\n zone.onUnstable.emit(null);\n }\n}\nfunction onLeave(zone) {\n zone._nesting--;\n checkStable(zone);\n}\n/**\n * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls\n * to framework to perform rendering.\n */\nclass NoopNgZone {\n constructor() {\n this.hasPendingMicrotasks = false;\n this.hasPendingMacrotasks = false;\n this.isStable = true;\n this.onUnstable = new EventEmitter();\n this.onMicrotaskEmpty = new EventEmitter();\n this.onStable = new EventEmitter();\n this.onError = new EventEmitter();\n }\n run(fn, applyThis, applyArgs) {\n return fn.apply(applyThis, applyArgs);\n }\n runGuarded(fn, applyThis, applyArgs) {\n return fn.apply(applyThis, applyArgs);\n }\n runOutsideAngular(fn) {\n return fn();\n }\n runTask(fn, applyThis, applyArgs, name) {\n return fn.apply(applyThis, applyArgs);\n }\n}\nfunction shouldBeIgnoredByZone(applyArgs) {\n return hasApplyArgsData(applyArgs, '__ignore_ng_zone__');\n}\nfunction isSchedulerTick(applyArgs) {\n return hasApplyArgsData(applyArgs, '__scheduler_tick__');\n}\nfunction hasApplyArgsData(applyArgs, key) {\n if (!Array.isArray(applyArgs)) {\n return false;\n }\n // We should only ever get 1 arg passed through to invokeTask.\n // Short circuit here incase that behavior changes.\n if (applyArgs.length !== 1) {\n return false;\n }\n return applyArgs[0]?.data?.[key] === true;\n}\nfunction getNgZone(ngZoneToUse = 'zone.js', options) {\n if (ngZoneToUse === 'noop') {\n return new NoopNgZone();\n }\n if (ngZoneToUse === 'zone.js') {\n return new NgZone(options);\n }\n return ngZoneToUse;\n}\n\n// Public API for Zone\n\n/**\n * Provides a hook for centralized exception handling.\n *\n * The default implementation of `ErrorHandler` prints error messages to the `console`. To\n * intercept error handling, write a custom exception handler that replaces this default as\n * appropriate for your app.\n *\n * @usageNotes\n * ### Example\n *\n * ```\n * class MyErrorHandler implements ErrorHandler {\n * handleError(error) {\n * // do something with the exception\n * }\n * }\n *\n * @NgModule({\n * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]\n * })\n * class MyModule {}\n * ```\n *\n * @publicApi\n */\nclass ErrorHandler {\n constructor() {\n /**\n * @internal\n */\n this._console = console;\n }\n handleError(error) {\n const originalError = this._findOriginalError(error);\n this._console.error('ERROR', error);\n if (originalError) {\n this._console.error('ORIGINAL ERROR', originalError);\n }\n }\n /** @internal */\n _findOriginalError(error) {\n let e = error && getOriginalError(error);\n while (e && getOriginalError(e)) {\n e = getOriginalError(e);\n }\n return e || null;\n }\n}\n/**\n * `InjectionToken` used to configure how to call the `ErrorHandler`.\n *\n * `NgZone` is provided by default today so the default (and only) implementation for this\n * is calling `ErrorHandler.handleError` outside of the Angular zone.\n */\nconst INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '', {\n providedIn: 'root',\n factory: () => {\n const zone = inject(NgZone);\n const userErrorHandler = inject(ErrorHandler);\n return e => zone.runOutsideAngular(() => userErrorHandler.handleError(e));\n }\n});\n\n/**\n * An `OutputEmitterRef` is created by the `output()` function and can be\n * used to emit values to consumers of your directive or component.\n *\n * Consumers of your directive/component can bind to the output and\n * subscribe to changes via the bound event syntax. For example:\n *\n * ```html\n * \n * ```\n *\n * @developerPreview\n */\nclass OutputEmitterRef {\n constructor() {\n this.destroyed = false;\n this.listeners = null;\n this.errorHandler = inject(ErrorHandler, {\n optional: true\n });\n /** @internal */\n this.destroyRef = inject(DestroyRef);\n // Clean-up all listeners and mark as destroyed upon destroy.\n this.destroyRef.onDestroy(() => {\n this.destroyed = true;\n this.listeners = null;\n });\n }\n subscribe(callback) {\n if (this.destroyed) {\n throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode && 'Unexpected subscription to destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');\n }\n (this.listeners ??= []).push(callback);\n return {\n unsubscribe: () => {\n const idx = this.listeners?.indexOf(callback);\n if (idx !== undefined && idx !== -1) {\n this.listeners?.splice(idx, 1);\n }\n }\n };\n }\n /** Emits a new value to the output. */\n emit(value) {\n if (this.destroyed) {\n throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode && 'Unexpected emit for destroyed `OutputRef`. ' + 'The owning directive/component is destroyed.');\n }\n if (this.listeners === null) {\n return;\n }\n const previousConsumer = setActiveConsumer$1(null);\n try {\n for (const listenerFn of this.listeners) {\n try {\n listenerFn(value);\n } catch (err) {\n this.errorHandler?.handleError(err);\n }\n }\n } finally {\n setActiveConsumer$1(previousConsumer);\n }\n }\n}\n/** Gets the owning `DestroyRef` for the given output. */\nfunction getOutputDestroyRef(ref) {\n return ref.destroyRef;\n}\n\n/**\n * The `output` function allows declaration of Angular outputs in\n * directives and components.\n *\n * You can use outputs to emit values to parent directives and component.\n * Parents can subscribe to changes via:\n *\n * - template event bindings. For example, `(myOutput)=\"doSomething($event)\"`\n * - programmatic subscription by using `OutputRef#subscribe`.\n *\n * @usageNotes\n *\n * To use `output()`, import the function from `@angular/core`.\n *\n * ```ts\n * import {output} from '@angular/core';\n * ```\n *\n * Inside your component, introduce a new class member and initialize\n * it with a call to `output`.\n *\n * ```ts\n * @Directive({\n * ...\n * })\n * export class MyDir {\n * nameChange = output(); // OutputEmitterRef\n * onClick = output(); // OutputEmitterRef\n * }\n * ```\n *\n * You can emit values to consumers of your directive, by using\n * the `emit` method from `OutputEmitterRef`.\n *\n * ```ts\n * updateName(newName: string): void {\n * this.nameChange.emit(newName);\n * }\n * ```\n *\n * @developerPreview\n * @initializerApiFunction {\"showTypesInSignaturePreview\": true}\n */\nfunction output(opts) {\n ngDevMode && assertInInjectionContext(output);\n return new OutputEmitterRef();\n}\nfunction inputFunction(initialValue, opts) {\n ngDevMode && assertInInjectionContext(input);\n return createInputSignal(initialValue, opts);\n}\nfunction inputRequiredFunction(opts) {\n ngDevMode && assertInInjectionContext(input);\n return createInputSignal(REQUIRED_UNSET_VALUE, opts);\n}\n/**\n * The `input` function allows declaration of Angular inputs in directives\n * and components.\n *\n * There are two variants of inputs that can be declared:\n *\n * 1. **Optional inputs** with an initial value.\n * 2. **Required inputs** that consumers need to set.\n *\n * By default, the `input` function will declare optional inputs that\n * always have an initial value. Required inputs can be declared\n * using the `input.required()` function.\n *\n * Inputs are signals. The values of an input are exposed as a `Signal`.\n * The signal always holds the latest value of the input that is bound\n * from the parent.\n *\n * @usageNotes\n * To use signal-based inputs, import `input` from `@angular/core`.\n *\n * ```\n * import {input} from '@angular/core`;\n * ```\n *\n * Inside your component, introduce a new class member and initialize\n * it with a call to `input` or `input.required`.\n *\n * ```ts\n * @Component({\n * ...\n * })\n * export class UserProfileComponent {\n * firstName = input(); // Signal\n * lastName = input.required(); // Signal\n * age = input(0) // Signal\n * }\n * ```\n *\n * Inside your component template, you can display values of the inputs\n * by calling the signal.\n *\n * ```html\n * {{firstName()}}\n * ```\n *\n * @developerPreview\n * @initializerApiFunction\n */\nconst input = (() => {\n // Note: This may be considered a side-effect, but nothing will depend on\n // this assignment, unless this `input` constant export is accessed. It's a\n // self-contained side effect that is local to the user facing`input` export.\n inputFunction.required = inputRequiredFunction;\n return inputFunction;\n})();\n\n/**\n * Creates an ElementRef from the most recent node.\n *\n * @returns The ElementRef instance to use\n */\nfunction injectElementRef() {\n return createElementRef(getCurrentTNode(), getLView());\n}\n/**\n * Creates an ElementRef given a node.\n *\n * @param tNode The node for which you'd like an ElementRef\n * @param lView The view to which the node belongs\n * @returns The ElementRef instance to use\n */\nfunction createElementRef(tNode, lView) {\n return new ElementRef(getNativeByTNode(tNode, lView));\n}\n/**\n * A wrapper around a native element inside of a View.\n *\n * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM\n * element.\n *\n * @security Permitting direct access to the DOM can make your application more vulnerable to\n * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the\n * [Security Guide](https://g.co/ng/security).\n *\n * @publicApi\n */\n// Note: We don't expose things like `Injector`, `ViewContainer`, ... here,\n// i.e. users have to ask for what they need. With that, we can build better analysis tools\n// and could do better codegen in the future.\nclass ElementRef {\n constructor(nativeElement) {\n this.nativeElement = nativeElement;\n }\n /**\n * @internal\n * @nocollapse\n */\n static {\n this.__NG_ELEMENT_ID__ = injectElementRef;\n }\n}\n/**\n * Unwraps `ElementRef` and return the `nativeElement`.\n *\n * @param value value to unwrap\n * @returns `nativeElement` if `ElementRef` otherwise returns value as is.\n */\nfunction unwrapElementRef(value) {\n return value instanceof ElementRef ? value.nativeElement : value;\n}\nfunction symbolIterator() {\n // @ts-expect-error accessing a private member\n return this._results[Symbol.iterator]();\n}\n/**\n * An unmodifiable list of items that Angular keeps up to date when the state\n * of the application changes.\n *\n * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}\n * provide.\n *\n * Implements an iterable interface, therefore it can be used in both ES6\n * javascript `for (var i of items)` loops as well as in Angular templates with\n * `*ngFor=\"let i of myList\"`.\n *\n * Changes can be observed by subscribing to the changes `Observable`.\n *\n * NOTE: In the future this class will implement an `Observable` interface.\n *\n * @usageNotes\n * ### Example\n * ```typescript\n * @Component({...})\n * class Container {\n * @ViewChildren(Item) items:QueryList;\n * }\n * ```\n *\n * @publicApi\n */\nclass QueryList {\n static {\n Symbol.iterator;\n }\n /**\n * Returns `Observable` of `QueryList` notifying the subscriber of changes.\n */\n get changes() {\n return this._changes ??= new EventEmitter();\n }\n /**\n * @param emitDistinctChangesOnly Whether `QueryList.changes` should fire only when actual change\n * has occurred. Or if it should fire when query is recomputed. (recomputing could resolve in\n * the same result)\n */\n constructor(_emitDistinctChangesOnly = false) {\n this._emitDistinctChangesOnly = _emitDistinctChangesOnly;\n this.dirty = true;\n this._onDirty = undefined;\n this._results = [];\n this._changesDetected = false;\n this._changes = undefined;\n this.length = 0;\n this.first = undefined;\n this.last = undefined;\n // This function should be declared on the prototype, but doing so there will cause the class\n // declaration to have side-effects and become not tree-shakable. For this reason we do it in\n // the constructor.\n // [Symbol.iterator](): Iterator { ... }\n const proto = QueryList.prototype;\n if (!proto[Symbol.iterator]) proto[Symbol.iterator] = symbolIterator;\n }\n /**\n * Returns the QueryList entry at `index`.\n */\n get(index) {\n return this._results[index];\n }\n /**\n * See\n * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)\n */\n map(fn) {\n return this._results.map(fn);\n }\n filter(fn) {\n return this._results.filter(fn);\n }\n /**\n * See\n * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)\n */\n find(fn) {\n return this._results.find(fn);\n }\n /**\n * See\n * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)\n */\n reduce(fn, init) {\n return this._results.reduce(fn, init);\n }\n /**\n * See\n * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n */\n forEach(fn) {\n this._results.forEach(fn);\n }\n /**\n * See\n * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)\n */\n some(fn) {\n return this._results.some(fn);\n }\n /**\n * Returns a copy of the internal results list as an Array.\n */\n toArray() {\n return this._results.slice();\n }\n toString() {\n return this._results.toString();\n }\n /**\n * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that\n * on change detection, it will not notify of changes to the queries, unless a new change\n * occurs.\n *\n * @param resultsTree The query results to store\n * @param identityAccessor Optional function for extracting stable object identity from a value\n * in the array. This function is executed for each element of the query result list while\n * comparing current query list with the new one (provided as a first argument of the `reset`\n * function) to detect if the lists are different. If the function is not provided, elements\n * are compared as is (without any pre-processing).\n */\n reset(resultsTree, identityAccessor) {\n this.dirty = false;\n const newResultFlat = flatten(resultsTree);\n if (this._changesDetected = !arrayEquals(this._results, newResultFlat, identityAccessor)) {\n this._results = newResultFlat;\n this.length = newResultFlat.length;\n this.last = newResultFlat[this.length - 1];\n this.first = newResultFlat[0];\n }\n }\n /**\n * Triggers a change event by emitting on the `changes` {@link EventEmitter}.\n */\n notifyOnChanges() {\n if (this._changes !== undefined && (this._changesDetected || !this._emitDistinctChangesOnly)) this._changes.emit(this);\n }\n /** @internal */\n onDirty(cb) {\n this._onDirty = cb;\n }\n /** internal */\n setDirty() {\n this.dirty = true;\n this._onDirty?.();\n }\n /** internal */\n destroy() {\n if (this._changes !== undefined) {\n this._changes.complete();\n this._changes.unsubscribe();\n }\n }\n}\n\n/**\n * The name of an attribute that can be added to the hydration boundary node\n * (component host node) to disable hydration for the content within that boundary.\n */\nconst SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';\n/** Lowercase name of the `ngSkipHydration` attribute used for case-insensitive comparisons. */\nconst SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = 'ngskiphydration';\n/**\n * Helper function to check if a given TNode has the 'ngSkipHydration' attribute.\n */\nfunction hasSkipHydrationAttrOnTNode(tNode) {\n const attrs = tNode.mergedAttrs;\n if (attrs === null) return false;\n // only ever look at the attribute name and skip the values\n for (let i = 0; i < attrs.length; i += 2) {\n const value = attrs[i];\n // This is a marker, which means that the static attributes section is over,\n // so we can exit early.\n if (typeof value === 'number') return false;\n if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) {\n return true;\n }\n }\n return false;\n}\n/**\n * Helper function to check if a given RElement has the 'ngSkipHydration' attribute.\n */\nfunction hasSkipHydrationAttrOnRElement(rNode) {\n return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME);\n}\n/**\n * Checks whether a TNode has a flag to indicate that it's a part of\n * a skip hydration block.\n */\nfunction hasInSkipHydrationBlockFlag(tNode) {\n return (tNode.flags & 128 /* TNodeFlags.inSkipHydrationBlock */) === 128 /* TNodeFlags.inSkipHydrationBlock */;\n}\n/**\n * Helper function that determines if a given node is within a skip hydration block\n * by navigating up the TNode tree to see if any parent nodes have skip hydration\n * attribute.\n */\nfunction isInSkipHydrationBlock(tNode) {\n if (hasInSkipHydrationBlockFlag(tNode)) {\n return true;\n }\n let currentTNode = tNode.parent;\n while (currentTNode) {\n if (hasInSkipHydrationBlockFlag(tNode) || hasSkipHydrationAttrOnTNode(currentTNode)) {\n return true;\n }\n currentTNode = currentTNode.parent;\n }\n return false;\n}\n/**\n * Check if an i18n block is in a skip hydration section by looking at a parent TNode\n * to determine if this TNode is in a skip hydration section or the TNode has\n * the `ngSkipHydration` attribute.\n */\nfunction isI18nInSkipHydrationBlock(parentTNode) {\n return hasInSkipHydrationBlockFlag(parentTNode) || hasSkipHydrationAttrOnTNode(parentTNode) || isInSkipHydrationBlock(parentTNode);\n}\n\n// Keeps track of the currently-active LViews.\nconst TRACKED_LVIEWS = new Map();\n// Used for generating unique IDs for LViews.\nlet uniqueIdCounter = 0;\n/** Gets a unique ID that can be assigned to an LView. */\nfunction getUniqueLViewId() {\n return uniqueIdCounter++;\n}\n/** Starts tracking an LView. */\nfunction registerLView(lView) {\n ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered');\n TRACKED_LVIEWS.set(lView[ID], lView);\n}\n/** Gets an LView by its unique ID. */\nfunction getLViewById(id) {\n ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number');\n return TRACKED_LVIEWS.get(id) || null;\n}\n/** Stops tracking an LView. */\nfunction unregisterLView(lView) {\n ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID');\n TRACKED_LVIEWS.delete(lView[ID]);\n}\n\n/**\n * The internal view context which is specific to a given DOM element, directive or\n * component instance. Each value in here (besides the LView and element node details)\n * can be present, null or undefined. If undefined then it implies the value has not been\n * looked up yet, otherwise, if null, then a lookup was executed and nothing was found.\n *\n * Each value will get filled when the respective value is examined within the getContext\n * function. The component, element and each directive instance will share the same instance\n * of the context.\n */\nclass LContext {\n /** Component's parent view data. */\n get lView() {\n return getLViewById(this.lViewId);\n }\n constructor(\n /**\n * ID of the component's parent view data.\n */\n lViewId,\n /**\n * The index instance of the node.\n */\n nodeIndex,\n /**\n * The instance of the DOM node that is attached to the lNode.\n */\n native) {\n this.lViewId = lViewId;\n this.nodeIndex = nodeIndex;\n this.native = native;\n }\n}\n\n/**\n * Returns the matching `LContext` data for a given DOM node, directive or component instance.\n *\n * This function will examine the provided DOM element, component, or directive instance\\'s\n * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched\n * value will be that of the newly created `LContext`.\n *\n * If the monkey-patched value is the `LView` instance then the context value for that\n * target will be created and the monkey-patch reference will be updated. Therefore when this\n * function is called it may mutate the provided element\\'s, component\\'s or any of the associated\n * directive\\'s monkey-patch values.\n *\n * If the monkey-patch value is not detected then the code will walk up the DOM until an element\n * is found which contains a monkey-patch reference. When that occurs then the provided element\n * will be updated with a new context (which is then returned). If the monkey-patch value is not\n * detected for a component/directive instance then it will throw an error (all components and\n * directives should be automatically monkey-patched by ivy).\n *\n * @param target Component, Directive or DOM Node.\n */\nfunction getLContext(target) {\n let mpValue = readPatchedData(target);\n if (mpValue) {\n // only when it's an array is it considered an LView instance\n // ... otherwise it's an already constructed LContext instance\n if (isLView(mpValue)) {\n const lView = mpValue;\n let nodeIndex;\n let component = undefined;\n let directives = undefined;\n if (isComponentInstance(target)) {\n nodeIndex = findViaComponent(lView, target);\n if (nodeIndex == -1) {\n throw new Error('The provided component was not found in the application');\n }\n component = target;\n } else if (isDirectiveInstance(target)) {\n nodeIndex = findViaDirective(lView, target);\n if (nodeIndex == -1) {\n throw new Error('The provided directive was not found in the application');\n }\n directives = getDirectivesAtNodeIndex(nodeIndex, lView);\n } else {\n nodeIndex = findViaNativeElement(lView, target);\n if (nodeIndex == -1) {\n return null;\n }\n }\n // the goal is not to fill the entire context full of data because the lookups\n // are expensive. Instead, only the target data (the element, component, container, ICU\n // expression or directive details) are filled into the context. If called multiple times\n // with different target values then the missing target data will be filled in.\n const native = unwrapRNode(lView[nodeIndex]);\n const existingCtx = readPatchedData(native);\n const context = existingCtx && !Array.isArray(existingCtx) ? existingCtx : createLContext(lView, nodeIndex, native);\n // only when the component has been discovered then update the monkey-patch\n if (component && context.component === undefined) {\n context.component = component;\n attachPatchData(context.component, context);\n }\n // only when the directives have been discovered then update the monkey-patch\n if (directives && context.directives === undefined) {\n context.directives = directives;\n for (let i = 0; i < directives.length; i++) {\n attachPatchData(directives[i], context);\n }\n }\n attachPatchData(context.native, context);\n mpValue = context;\n }\n } else {\n const rElement = target;\n ngDevMode && assertDomNode(rElement);\n // if the context is not found then we need to traverse upwards up the DOM\n // to find the nearest element that has already been monkey patched with data\n let parent = rElement;\n while (parent = parent.parentNode) {\n const parentContext = readPatchedData(parent);\n if (parentContext) {\n const lView = Array.isArray(parentContext) ? parentContext : parentContext.lView;\n // the edge of the app was also reached here through another means\n // (maybe because the DOM was changed manually).\n if (!lView) {\n return null;\n }\n const index = findViaNativeElement(lView, rElement);\n if (index >= 0) {\n const native = unwrapRNode(lView[index]);\n const context = createLContext(lView, index, native);\n attachPatchData(native, context);\n mpValue = context;\n break;\n }\n }\n }\n }\n return mpValue || null;\n}\n/**\n * Creates an empty instance of a `LContext` context\n */\nfunction createLContext(lView, nodeIndex, native) {\n return new LContext(lView[ID], nodeIndex, native);\n}\n/**\n * Takes a component instance and returns the view for that component.\n *\n * @param componentInstance\n * @returns The component's view\n */\nfunction getComponentViewByInstance(componentInstance) {\n let patchedData = readPatchedData(componentInstance);\n let lView;\n if (isLView(patchedData)) {\n const contextLView = patchedData;\n const nodeIndex = findViaComponent(contextLView, componentInstance);\n lView = getComponentLViewByIndex(nodeIndex, contextLView);\n const context = createLContext(contextLView, nodeIndex, lView[HOST]);\n context.component = componentInstance;\n attachPatchData(componentInstance, context);\n attachPatchData(context.native, context);\n } else {\n const context = patchedData;\n const contextLView = context.lView;\n ngDevMode && assertLView(contextLView);\n lView = getComponentLViewByIndex(context.nodeIndex, contextLView);\n }\n return lView;\n}\n/**\n * This property will be monkey-patched on elements, components and directives.\n */\nconst MONKEY_PATCH_KEY_NAME = '__ngContext__';\nfunction attachLViewId(target, data) {\n target[MONKEY_PATCH_KEY_NAME] = data[ID];\n}\n/**\n * Returns the monkey-patch value data present on the target (which could be\n * a component, directive or a DOM node).\n */\nfunction readLView(target) {\n const data = readPatchedData(target);\n if (isLView(data)) {\n return data;\n }\n return data ? data.lView : null;\n}\n/**\n * Assigns the given data to the given target (which could be a component,\n * directive or DOM node instance) using monkey-patching.\n */\nfunction attachPatchData(target, data) {\n ngDevMode && assertDefined(target, 'Target expected');\n // Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this\n // for `LView`, because we have control over when an `LView` is created and destroyed, whereas\n // we can't know when to remove an `LContext`.\n if (isLView(data)) {\n target[MONKEY_PATCH_KEY_NAME] = data[ID];\n registerLView(data);\n } else {\n target[MONKEY_PATCH_KEY_NAME] = data;\n }\n}\n/**\n * Returns the monkey-patch value data present on the target (which could be\n * a component, directive or a DOM node).\n */\nfunction readPatchedData(target) {\n ngDevMode && assertDefined(target, 'Target expected');\n const data = target[MONKEY_PATCH_KEY_NAME];\n return typeof data === 'number' ? getLViewById(data) : data || null;\n}\nfunction readPatchedLView(target) {\n const value = readPatchedData(target);\n if (value) {\n return isLView(value) ? value : value.lView;\n }\n return null;\n}\nfunction isComponentInstance(instance) {\n return instance && instance.constructor && instance.constructor.ɵcmp;\n}\nfunction isDirectiveInstance(instance) {\n return instance && instance.constructor && instance.constructor.ɵdir;\n}\n/**\n * Locates the element within the given LView and returns the matching index\n */\nfunction findViaNativeElement(lView, target) {\n const tView = lView[TVIEW];\n for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {\n if (unwrapRNode(lView[i]) === target) {\n return i;\n }\n }\n return -1;\n}\n/**\n * Locates the next tNode (child, sibling or parent).\n */\nfunction traverseNextElement(tNode) {\n if (tNode.child) {\n return tNode.child;\n } else if (tNode.next) {\n return tNode.next;\n } else {\n // Let's take the following template:
text
\n // After checking the text node, we need to find the next parent that has a \"next\" TNode,\n // in this case the parent `div`, so that we can find the component.\n while (tNode.parent && !tNode.parent.next) {\n tNode = tNode.parent;\n }\n return tNode.parent && tNode.parent.next;\n }\n}\n/**\n * Locates the component within the given LView and returns the matching index\n */\nfunction findViaComponent(lView, componentInstance) {\n const componentIndices = lView[TVIEW].components;\n if (componentIndices) {\n for (let i = 0; i < componentIndices.length; i++) {\n const elementComponentIndex = componentIndices[i];\n const componentView = getComponentLViewByIndex(elementComponentIndex, lView);\n if (componentView[CONTEXT] === componentInstance) {\n return elementComponentIndex;\n }\n }\n } else {\n const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);\n const rootComponent = rootComponentView[CONTEXT];\n if (rootComponent === componentInstance) {\n // we are dealing with the root element here therefore we know that the\n // element is the very first element after the HEADER data in the lView\n return HEADER_OFFSET;\n }\n }\n return -1;\n}\n/**\n * Locates the directive within the given LView and returns the matching index\n */\nfunction findViaDirective(lView, directiveInstance) {\n // if a directive is monkey patched then it will (by default)\n // have a reference to the LView of the current view. The\n // element bound to the directive being search lives somewhere\n // in the view data. We loop through the nodes and check their\n // list of directives for the instance.\n let tNode = lView[TVIEW].firstChild;\n while (tNode) {\n const directiveIndexStart = tNode.directiveStart;\n const directiveIndexEnd = tNode.directiveEnd;\n for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {\n if (lView[i] === directiveInstance) {\n return tNode.index;\n }\n }\n tNode = traverseNextElement(tNode);\n }\n return -1;\n}\n/**\n * Returns a list of directives applied to a node at a specific index. The list includes\n * directives matched by selector and any host directives, but it excludes components.\n * Use `getComponentAtNodeIndex` to find the component applied to a node.\n *\n * @param nodeIndex The node index\n * @param lView The target view data\n */\nfunction getDirectivesAtNodeIndex(nodeIndex, lView) {\n const tNode = lView[TVIEW].data[nodeIndex];\n if (tNode.directiveStart === 0) return EMPTY_ARRAY;\n const results = [];\n for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {\n const directiveInstance = lView[i];\n if (!isComponentInstance(directiveInstance)) {\n results.push(directiveInstance);\n }\n }\n return results;\n}\nfunction getComponentAtNodeIndex(nodeIndex, lView) {\n const tNode = lView[TVIEW].data[nodeIndex];\n const {\n directiveStart,\n componentOffset\n } = tNode;\n return componentOffset > -1 ? lView[directiveStart + componentOffset] : null;\n}\n/**\n * Returns a map of local references (local reference name => element or directive instance) that\n * exist on a given element.\n */\nfunction discoverLocalRefs(lView, nodeIndex) {\n const tNode = lView[TVIEW].data[nodeIndex];\n if (tNode && tNode.localNames) {\n const result = {};\n let localIndex = tNode.index + 1;\n for (let i = 0; i < tNode.localNames.length; i += 2) {\n result[tNode.localNames[i]] = lView[localIndex];\n localIndex++;\n }\n return result;\n }\n return null;\n}\n\n/**\n * Retrieve the root view from any component or `LView` by walking the parent `LView` until\n * reaching the root `LView`.\n *\n * @param componentOrLView any component or `LView`\n */\nfunction getRootView(componentOrLView) {\n ngDevMode && assertDefined(componentOrLView, 'component');\n let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);\n while (lView && !(lView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {\n lView = getLViewParent(lView);\n }\n ngDevMode && assertLView(lView);\n return lView;\n}\n/**\n * Returns the context information associated with the application where the target is situated. It\n * does this by walking the parent views until it gets to the root view, then getting the context\n * off of that.\n *\n * @param viewOrComponent the `LView` or component to get the root context for.\n */\nfunction getRootContext(viewOrComponent) {\n const rootView = getRootView(viewOrComponent);\n ngDevMode && assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');\n return rootView[CONTEXT];\n}\n/**\n * Gets the first `LContainer` in the LView or `null` if none exists.\n */\nfunction getFirstLContainer(lView) {\n return getNearestLContainer(lView[CHILD_HEAD]);\n}\n/**\n * Gets the next `LContainer` that is a sibling of the given container.\n */\nfunction getNextLContainer(container) {\n return getNearestLContainer(container[NEXT]);\n}\nfunction getNearestLContainer(viewOrContainer) {\n while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {\n viewOrContainer = viewOrContainer[NEXT];\n }\n return viewOrContainer;\n}\n\n/**\n * Retrieves the component instance associated with a given DOM element.\n *\n * @usageNotes\n * Given the following DOM structure:\n *\n * ```html\n * \n *
\n * \n *
\n *
\n * ```\n *\n * Calling `getComponent` on `` will return the instance of `ChildComponent`\n * associated with this DOM element.\n *\n * Calling the function on `` will return the `MyApp` instance.\n *\n *\n * @param element DOM element from which the component should be retrieved.\n * @returns Component instance associated with the element or `null` if there\n * is no component associated with it.\n *\n * @publicApi\n * @globalApi ng\n */\nfunction getComponent$1(element) {\n ngDevMode && assertDomElement(element);\n const context = getLContext(element);\n if (context === null) return null;\n if (context.component === undefined) {\n const lView = context.lView;\n if (lView === null) {\n return null;\n }\n context.component = getComponentAtNodeIndex(context.nodeIndex, lView);\n }\n return context.component;\n}\n/**\n * If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded\n * view that the element is part of. Otherwise retrieves the instance of the component whose view\n * owns the element (in this case, the result is the same as calling `getOwningComponent`).\n *\n * @param element Element for which to get the surrounding component instance.\n * @returns Instance of the component that is around the element or null if the element isn't\n * inside any component.\n *\n * @publicApi\n * @globalApi ng\n */\nfunction getContext(element) {\n assertDomElement(element);\n const context = getLContext(element);\n const lView = context ? context.lView : null;\n return lView === null ? null : lView[CONTEXT];\n}\n/**\n * Retrieves the component instance whose view contains the DOM element.\n *\n * For example, if `` is used in the template of ``\n * (i.e. a `ViewChild` of ``), calling `getOwningComponent` on ``\n * would return ``.\n *\n * @param elementOrDir DOM element, component or directive instance\n * for which to retrieve the root components.\n * @returns Component instance whose view owns the DOM element or null if the element is not\n * part of a component view.\n *\n * @publicApi\n * @globalApi ng\n */\nfunction getOwningComponent(elementOrDir) {\n const context = getLContext(elementOrDir);\n let lView = context ? context.lView : null;\n if (lView === null) return null;\n let parent;\n while (lView[TVIEW].type === 2 /* TViewType.Embedded */ && (parent = getLViewParent(lView))) {\n lView = parent;\n }\n return lView[FLAGS] & 512 /* LViewFlags.IsRoot */ ? null : lView[CONTEXT];\n}\n/**\n * Retrieves all root components associated with a DOM element, directive or component instance.\n * Root components are those which have been bootstrapped by Angular.\n *\n * @param elementOrDir DOM element, component or directive instance\n * for which to retrieve the root components.\n * @returns Root components associated with the target object.\n *\n * @publicApi\n * @globalApi ng\n */\nfunction getRootComponents(elementOrDir) {\n const lView = readPatchedLView(elementOrDir);\n return lView !== null ? [getRootContext(lView)] : [];\n}\n/**\n * Retrieves an `Injector` associated with an element, component or directive instance.\n *\n * @param elementOrDir DOM element, component or directive instance for which to\n * retrieve the injector.\n * @returns Injector associated with the element, component or directive instance.\n *\n * @publicApi\n * @globalApi ng\n */\nfunction getInjector(elementOrDir) {\n const context = getLContext(elementOrDir);\n const lView = context ? context.lView : null;\n if (lView === null) return Injector.NULL;\n const tNode = lView[TVIEW].data[context.nodeIndex];\n return new NodeInjector(tNode, lView);\n}\n/**\n * Retrieve a set of injection tokens at a given DOM node.\n *\n * @param element Element for which the injection tokens should be retrieved.\n */\nfunction getInjectionTokens(element) {\n const context = getLContext(element);\n const lView = context ? context.lView : null;\n if (lView === null) return [];\n const tView = lView[TVIEW];\n const tNode = tView.data[context.nodeIndex];\n const providerTokens = [];\n const startIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;\n const endIndex = tNode.directiveEnd;\n for (let i = startIndex; i < endIndex; i++) {\n let value = tView.data[i];\n if (isDirectiveDefHack(value)) {\n // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a\n // design flaw. We should always store same type so that we can be monomorphic. The issue\n // is that for Components/Directives we store the def instead the type. The correct behavior\n // is that we should always be storing injectable type in this location.\n value = value.type;\n }\n providerTokens.push(value);\n }\n return providerTokens;\n}\n/**\n * Retrieves directive instances associated with a given DOM node. Does not include\n * component instances.\n *\n * @usageNotes\n * Given the following DOM structure:\n *\n * ```html\n * \n * \n * \n * \n * ```\n *\n * Calling `getDirectives` on `