@saasquatch/component-boilerplate 1.6.2 → 1.6.3-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/graphql/useParentQuery.d.ts +12 -0
- package/dist/hooks/useParentState.d.ts +12 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.modern.js +17 -17
- package/dist/index.modern.js.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -1
package/dist/index.modern.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.modern.js","sources":["../src/hooks/useHost.ts","../src/hooks/environment/useLocale.ts","../src/hooks/environment/useProgramId.ts","../src/hooks/environment/useUserIdentity.ts","../src/hooks/environment/index.ts","../node_modules/tslib/tslib.es6.js","../node_modules/graphql-tag/lib/index.js","../src/BatchedGraphQLClient.ts","../src/hooks/graphql/useGraphQLClient.ts","../src/hooks/graphql/useBaseQuery.ts","../src/hooks/graphql/useMutation.ts","../src/hooks/managedIdentity/useAuthenticateWithEmailAndPasswordMutation.ts","../src/hooks/managedIdentity/useRegisterWithEmailAndPasswordMutation.ts","../src/hooks/managedIdentity/useRegisterViaRegistrationFormMutation.ts","../src/hooks/managedIdentity/useChangePasswordMutation.ts","../src/hooks/managedIdentity/useResetPasswordMutation.ts","../src/hooks/managedIdentity/useVerifyPasswordResetCodeMutation.ts","../src/hooks/graphql/Refresh.ts","../src/hooks/useDeepEffect.ts","../src/hooks/graphql/useLazyQuery.ts","../src/hooks/managedIdentity/useManagedIdentitySessionQuery.ts","../src/hooks/managedIdentity/useVerifyEmailMutation.ts","../src/hooks/managedIdentity/useRequestPasswordResetEmailMutation.ts","../src/hooks/managedIdentity/useRequestVerificationEmailMutation.ts","../src/hooks/instantaccess/useAuthenticateManagedIdentityWithInstantAccess.ts","../src/hooks/useDeepMemo.ts","../src/hooks/useTick.ts","../src/hooks/graphql/useQuery.ts","../src/hooks/useNavigation.ts","../src/hooks/pagination/usePagination.ts","../src/hooks/pagination/usePaginatedQuery.ts","../src/hooks/useDebounce.ts","../src/hooks/useShareEvent.ts","../node_modules/ms/index.js","../node_modules/debug/src/common.js","../node_modules/debug/src/browser.js","../src/hooks/useLoadEvent.ts","../src/hooks/useForm.ts"],"sourcesContent":["const ref = { current: undefined };\n\nexport function useHost(): HTMLElement {\n if (ref.current === undefined) {\n throw new Error(\"no implementation of useHost provided\");\n }\n\n return ref.current();\n}\n\nexport function setImplementation(implementation: () => HTMLElement) {\n if (!implementation) {\n throw new Error(\"Must supply an implementation\");\n }\n\n if (typeof implementation !== \"function\") {\n throw new Error(\"implementation must be a function\");\n }\n\n ref.current = implementation;\n}","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport {\n LOCALE_CONTEXT_NAME,\n lazilyStartLocaleContext,\n} from \"@saasquatch/component-environment\";\nimport { useHost } from \"../useHost\";\n\nexport function useLocale(): string | undefined {\n lazilyStartLocaleContext();\n const host = useHost();\n return useDomContext<string>(host, LOCALE_CONTEXT_NAME);\n}\n","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport {\n PROGRAM_CONTEXT_NAME,\n lazilyStartProgramContext,\n} from \"@saasquatch/component-environment\";\nimport { useHost } from \"../useHost\";\n\nexport function useProgramId(): string | undefined {\n lazilyStartProgramContext();\n const host = useHost();\n return useDomContext<string>(host, PROGRAM_CONTEXT_NAME);\n}\n","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport { useHost } from \"../useHost\";\nimport {\n UserIdentity,\n USER_CONTEXT_NAME,\n lazilyStartUserContext,\n setUserIdentity,\n userIdentityFromJwt,\n isDemo,\n} from \"@saasquatch/component-environment\";\n\n/**\n * Gets the SessionData of the current user, or undefined if logged out\n */\nexport function useSessionData(): { [key: string]: any } | undefined {\n return useUserIdentity()?.managedIdentity?.sessionData;\n}\n\n/**\n * Gets the JWT of the current user, or undefined if logged out\n */\nexport function useToken(): string | undefined {\n return useUserIdentity()?.jwt;\n}\n\n/**\n * Get the IDs and JWT of the current user, or undefined if logged out\n */\nexport function useUserIdentity(): UserIdentity | undefined {\n lazilyStartUserContext();\n const host = useHost();\n const identity = useDomContext(host, USER_CONTEXT_NAME) as\n | UserIdentity\n | undefined;\n\n const validIdentity = userIdentityFromJwt(identity?.jwt);\n if (!isDemo() && identity && !validIdentity) {\n // Likely that the JWT has expired\n setUserIdentity(undefined);\n return undefined;\n }\n return identity;\n}\n","import {\n getTenantAlias,\n getAppDomain,\n getEngagementMedium,\n} from \"@saasquatch/component-environment\";\n\n// Aliases to function in component-environment to maintain a backwards-compatible API\nexport const useTenantAlias = getTenantAlias;\nexport const useAppDomain = getAppDomain;\nexport const useEngagementMedium = getEngagementMedium;\n\nexport {\n getEnvironmentSDK,\n setUserIdentity,\n setProgramId,\n isDemo,\n DecodedSquatchJWT,\n} from \"@saasquatch/component-environment\";\n\nexport * from \"./useLocale\";\nexport * from \"./useProgramId\";\nexport * from \"./useUserIdentity\";\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n var seenKeys = new Set();\n var definitions = [];\n ast.definitions.forEach(function (fragmentDefinition) {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n var sourceKeySet = fragmentSourceMap.get(fragmentName);\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n if (printFragmentWarnings) {\n console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n }\n }\n else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n sourceKeySet.add(sourceKey);\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n }\n else {\n definitions.push(fragmentDefinition);\n }\n });\n return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n var workSet = new Set(doc.definitions);\n workSet.forEach(function (node) {\n if (node.loc)\n delete node.loc;\n Object.keys(node).forEach(function (key) {\n var value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n var loc = doc.loc;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n return doc;\n}\nfunction parseDocument(source) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n var parsed = parse(source, {\n experimentalFragmentVariables: experimentalFragmentVariables\n });\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n }\n return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (typeof literals === 'string') {\n literals = [literals];\n }\n var result = literals[0];\n args.forEach(function (arg, i) {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n }\n else {\n result += arg;\n }\n result += literals[i + 1];\n });\n return parseDocument(result);\n}\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\nvar extras = {\n gql: gql,\n resetCaches: resetCaches,\n disableFragmentWarnings: disableFragmentWarnings,\n enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","import { Subject } from \"rxjs\";\nimport { bufferTime } from \"rxjs/operators\";\nimport { nanoid } from \"nanoid\";\nimport { ClientError, RequestDocument } from \"graphql-request/dist/types\";\nimport { GraphQLClient } from \"graphql-request\";\nimport { print, parse, DocumentNode } from \"graphql\";\n\nimport combineQuery, {\n CombinedQueryBuilder,\n NewCombinedQueryBuilder,\n} from \"graphql-combine-query\";\n\n/*************\n * constants *\n *************/\nconst MAX_REQUESTS = 10;\nconst REQUEST_INTERVAL = 200; //ms\n\nexport class BatchedGraphQLClient extends GraphQLClient {\n subject = new Subject();\n\n constructor(url: string, opts?: any) {\n super(url, opts);\n\n const unmergable = new Subject();\n const buffer = this.subject.pipe(\n bufferTime(REQUEST_INTERVAL, undefined, MAX_REQUESTS)\n );\n\n // look into replacing subscribe\n buffer.subscribe(async (queryAddedEvents: QueryAddedEvent[]) => {\n // no requests in the last REQUEST_INTERVAL ms\n if (!queryAddedEvents.length) {\n return;\n }\n // merge the requests\n const {\n mergedQuery,\n mergedVariables,\n mergedQueryAddedEvents,\n unmergedQueryAddedEvents,\n } = mergeQueryAddedEvents(queryAddedEvents);\n\n // push queries that failed to merge to a separate stream to be processed\n for (const unmergedQuery of unmergedQueryAddedEvents)\n unmergable.next(unmergedQuery);\n\n // If there are no merged queries, all were unmergeable and we can exit here\n if (!mergedQueryAddedEvents.length) {\n return;\n }\n\n try {\n // make the request\n const mergedQueryResult = await this.superRequest(\n mergedQuery,\n mergedVariables\n );\n //resolve the results\n resolveMergedQueryResult(mergedQueryResult, mergedQueryAddedEvents);\n } catch (e) {\n // So, there is possibly both data and errors here.\n if (e instanceof ClientError) {\n const { data, errors } = e.response;\n if (!data) {\n return rejectAllQueryAddedEventsWithError(\n mergedQueryAddedEvents,\n e\n );\n }\n const aliases = Object.keys(data);\n let eventsToResolve = [...mergedQueryAddedEvents];\n // reject all that errored:\n for (const error of errors) {\n let erroredEvent: QueryAddedEvent;\n // todo: this needs testing, is path going to work??\n error.path.find((key, index, path) => {\n if (aliases.includes(key)) {\n const erroredId = getIdFromAliasedField(key);\n const indexOfErroredEvent = eventsToResolve.findIndex(\n (event) => event.id === erroredId\n );\n if (indexOfErroredEvent === -1) return false;\n // remove from aliases\n aliases.splice(index, 1);\n // remove from events\n erroredEvent = eventsToResolve.splice(\n indexOfErroredEvent,\n 1\n )[0];\n // rebuild data\n const eventSpecificData = removeAliasesFromDataResult(\n e.response.data,\n erroredEvent\n );\n // fix path\n path[index] = removeAliasFromField(path[index], erroredId);\n const { query, variables } = erroredEvent;\n // rebuild error to be event specific\n const errorResponse = {\n ...e.response,\n errors: [error],\n data: eventSpecificData,\n path,\n };\n const newError = new ClientError(errorResponse, {\n query: typeof query !== \"string\" ? print(query) : query,\n variables,\n });\n rejectQueryAddedEventWithError(erroredEvent, newError);\n return true;\n }\n return false;\n });\n }\n // resolve the rest:\n resolveMergedQueryResult(data, eventsToResolve);\n } else rejectAllQueryAddedEventsWithError(mergedQueryAddedEvents, e);\n }\n });\n\n //process unmergable requests as they come in\n unmergable.subscribe(async (event: QueryAddedEvent) => {\n try {\n const { query, variables } = event;\n const result = await this.superRequest(query, variables);\n resolveSingleQueryResult(result, event);\n } catch (e) {\n rejectQueryAddedEventWithError(event, e);\n }\n });\n }\n\n superRequest<T>(query: RequestDocument, variables?: any) {\n return super.request<T>(query, variables);\n }\n\n request<T>(query, variables) {\n return new Promise<T>((resolve, reject) => {\n const queryAddedEvent: QueryAddedEvent = {\n query,\n variables,\n id: generateQueryAddedEventId(),\n resolve,\n reject,\n };\n this.subject.next(queryAddedEvent);\n });\n }\n}\n\n/*************\n * types *\n *************/\n\ninterface QueryAddedEvent {\n query: RequestDocument;\n variables: { [key: string]: unknown };\n id: string; // nanoid with '-'s removed\n resolve: (data: any) => void;\n reject: (err: any) => void;\n}\n\ninterface MergedQueryAddedEvents {\n mergedQuery?: RequestDocument;\n mergedVariables?: { [key: string]: unknown };\n mergedQueryAddedEvents: QueryAddedEvent[];\n unmergedQueryAddedEvents: QueryAddedEvent[];\n}\n\n/*************\n * utils *\n *************/\n// Remove dashes and underscores from alias\nconst generateQueryAddedEventId = () => nanoid().replace(/[-_]/g, \"\");\n\n// Numbers not allowed in graphQL alias, so ID must be added to the end\nconst aliasFieldOrVariableFn = (name, id) => `${name}_${id}`;\n\n// ID will always be at the end of the alias separated by a single \"_\"\nconst removeAliasFromField = (field: string, id: string) =>\n field.replace(`_${id}`, \"\");\n\nconst getIdFromAliasedField = (field: string): string => {\n const fieldArray = field.split(\"_\");\n return fieldArray[fieldArray.length - 1];\n};\n\nconst mergeQueryAddedEvents = (\n events: QueryAddedEvent[]\n): MergedQueryAddedEvents => {\n const mergedQueryAddedEvents = [];\n const unmergedQueryAddedEvents = [];\n const { document, variables } = events.reduce(\n (\n acc: NewCombinedQueryBuilder | CombinedQueryBuilder,\n curr: QueryAddedEvent\n ): NewCombinedQueryBuilder | CombinedQueryBuilder => {\n const { query, variables, id } = curr;\n try {\n const parsedQuery: DocumentNode =\n typeof query === \"string\" ? parse(query) : query;\n // if fragment exists, this request should be processed separately\n const fragmentDefinition = parsedQuery.definitions.find(\n (node) => node.kind === \"FragmentDefinition\"\n );\n // '@' is reserved for directives, and since both top level and nested directives are broken, we dont want any.\n const queryStr = typeof query === \"string\" ? query : print(query);\n const containsDirective = /@/.test(queryStr);\n\n if (fragmentDefinition || containsDirective) {\n unmergedQueryAddedEvents.push(curr);\n return acc;\n }\n\n const renameFn = (name) => aliasFieldOrVariableFn(name, id);\n // if this fails, event will be added to unmergedQueryAddedEvents\n acc = acc.addN(parsedQuery, [variables], renameFn, renameFn);\n mergedQueryAddedEvents.push(curr);\n return acc;\n } catch (e) {\n unmergedQueryAddedEvents.push(curr);\n return acc;\n }\n },\n combineQuery(\"BatchedQuery\")\n ) as CombinedQueryBuilder;\n\n const mergedQuery = document && print(document);\n const mergedVariables = variables;\n\n return {\n mergedQuery,\n mergedVariables,\n mergedQueryAddedEvents,\n unmergedQueryAddedEvents,\n };\n};\n\nconst removeAliasesFromDataResult = (\n queryResult: any,\n event: QueryAddedEvent\n) => {\n if (!queryResult) return queryResult;\n const aliases = Object.keys(queryResult);\n const { id } = event;\n return aliases.reduce((data, key) => {\n if (key.endsWith(id)) {\n data = {\n ...data,\n [removeAliasFromField(key, id)]: queryResult[key],\n };\n }\n return data;\n }, {});\n};\n\nconst resolveSingleQueryResult = (queryResult: any, event: QueryAddedEvent) => {\n const { resolve } = event;\n resolve(queryResult);\n};\n\nconst resolveMergedQueryResult = (\n mergedQueryResult: any,\n events: QueryAddedEvent[]\n): void => {\n for (const event of events) {\n //figure out what data we need\n const data = removeAliasesFromDataResult(mergedQueryResult, event);\n event.resolve(data);\n }\n};\n\nconst rejectQueryAddedEventWithError = (\n event: QueryAddedEvent,\n err: Error\n): void => {\n const { reject } = event;\n reject(err);\n};\n\nconst rejectAllQueryAddedEventsWithError = (\n events: QueryAddedEvent[],\n err: Error\n): void => {\n for (const event of events) {\n const { reject } = event;\n reject(err);\n }\n};\n","import memoize from \"fast-memoize\";\nimport { BatchedGraphQLClient } from \"../../BatchedGraphQLClient\";\nimport { useAppDomain, useTenantAlias, useToken } from \"../environment\";\nimport { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport { useHost } from \"../useHost\";\nimport { GraphQLClient } from \"graphql-request\";\n\nexport const GRAPHQL_CONTEXT = \"sq:graphql-client\";\n\nfunction createGraphQlClient(\n appDomain: string,\n tenantAlias: string,\n token?: string\n): GraphQLClient {\n const uri = appDomain + \"/api/v1/\" + tenantAlias + \"/graphql\";\n const headers = {\n Authorization: `Bearer ${token || \"\"}`,\n };\n const newClient = new BatchedGraphQLClient(uri, {\n headers,\n });\n return newClient;\n}\n\nexport const memoizedGraphQLClient = memoize(createGraphQlClient);\n\nfunction useGraphQLClient(): GraphQLClient {\n const token = useToken();\n const appDomain = useAppDomain();\n const tenantAlias = useTenantAlias();\n\n // Memoization is shared. One client per domain, tenant and token (or null)\n const localClient: GraphQLClient = memoizedGraphQLClient(\n appDomain,\n tenantAlias,\n token\n );\n const host = useHost();\n const clientFromContext = useDomContext<GraphQLClient>(\n host,\n GRAPHQL_CONTEXT,\n // Won't poll / re-attempt\n { attempts: 0 }\n );\n return clientFromContext ?? localClient;\n}\n\nexport default useGraphQLClient;\n","import {\n useCallback,\n useEffect,\n useReducer,\n useRef,\n} from \"@saasquatch/universal-hooks\";\nimport useGraphQLClient from \"./useGraphQLClient\";\nimport { RequestDocument } from \"graphql-request/dist/types\";\nimport { GraphQLClient } from \"graphql-request\";\n\nexport type GqlType = RequestDocument;\n\nexport interface BaseQueryData<T = unknown> {\n loading: boolean;\n data?: T;\n errors?: GraphQlRequestError<T>;\n}\n\nexport type QueryData<T> = BaseQueryData<T> & {\n refetch: (variables?: unknown) => Promise<T | Error>;\n};\n\n/**\n * Note: reverse-engineered from a returned error. May not capture all error types.\n */\n\nexport type GraphQlRequestError<T> = {\n response: {\n errors: [\n {\n message: string;\n locations: [{ line: number; column: number }];\n path: string[];\n extensions: {\n apiError: {\n message: string;\n statusCode: number;\n apiErrorCode: string;\n rsCode: string;\n };\n classification: string;\n // V managed identity extensions V\n message?: string;\n code?: string;\n };\n }\n ];\n data: Partial<T>;\n status: number;\n };\n request: {\n query: string;\n variables: { [key: string]: unknown };\n };\n message?: string;\n};\n\ntype Action<T> =\n | {\n type: \"loading\";\n }\n | {\n type: \"data\";\n payload?: T;\n }\n | {\n type: \"errors\";\n payload: GraphQlRequestError<T>;\n };\n\nfunction reducer<T>(\n // @ts-ignore = unused\n state: BaseQueryData<T>,\n action: Action<T>\n): BaseQueryData<T> {\n switch (action.type) {\n case \"loading\":\n return { data: undefined, errors: undefined, loading: true };\n case \"data\":\n return { data: action.payload, errors: undefined, loading: false };\n case \"errors\":\n return { data: undefined, errors: action.payload, loading: false };\n }\n}\n\nexport function useBaseQuery<T = any>(\n query: GqlType,\n initialState: BaseQueryData<T>\n): [\n BaseQueryData<T>,\n (variables: unknown, skipLoading?: boolean) => Promise<T | Error>\n] {\n const client: GraphQLClient = useGraphQLClient();\n const [state, dispatch] = useReducer<BaseQueryData<T>, Action<T>>(\n reducer,\n initialState\n );\n const update = useCallback(\n async function (variables: unknown, skipLoading = false) {\n if (!client) {\n const error = new Error(\"No GraphQL client found\");\n // Hook will return an error state when no client exists (used to be a loading state)\n dispatch({\n type: \"errors\",\n // @ts-expect-error -- Need to fix this\n payload: error,\n });\n return error;\n }\n try {\n // Skips showing a \"loading\" state before the data appears\n if (!skipLoading) dispatch({ type: \"loading\" });\n const res = await client.request<T>(query, variables);\n dispatch({ type: \"data\", payload: res });\n return res;\n } catch (error) {\n dispatch({ type: \"errors\", payload: error });\n return error;\n }\n },\n [client, query, dispatch]\n );\n\n return [state, update];\n}\n","import { BaseQueryData, GqlType, useBaseQuery } from \"./useBaseQuery\";\n\nconst initialMutationState: BaseQueryData = {\n loading: false,\n data: undefined,\n errors: undefined,\n} as const;\n\nexport function useMutation<T = any>(\n query: GqlType\n): [(e: unknown) => Promise<T | Error>, BaseQueryData<T>] {\n const [state, update] = useBaseQuery<T>(\n query,\n initialMutationState as BaseQueryData<T>\n );\n return [update, state];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst AuthenticateWithEmailAndPasswordMutation = gql`\n mutation AuthenticateWithEmailAndPassword(\n $email: String!\n $password: String!\n ) {\n authenticateManagedIdentityWithEmailAndPassword(\n authenticateManagedIdentityWithEmailAndPasswordInput: {\n email: $email\n password: $password\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface AuthenticateWithEmailAndPasswordResult {\n authenticateManagedIdentityWithEmailAndPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useAuthenticateWithEmailAndPasswordMutation(): [\n (variables: {\n email: string;\n password: string;\n }) => Promise<AuthenticateWithEmailAndPasswordResult | Error>,\n BaseQueryData<AuthenticateWithEmailAndPasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<AuthenticateWithEmailAndPasswordResult>(\n AuthenticateWithEmailAndPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n email: string;\n password: string;\n }) => {\n const result = await request(v);\n if (\n !(result instanceof Error) &&\n result.authenticateManagedIdentityWithEmailAndPassword\n ) {\n const jwt = result.authenticateManagedIdentityWithEmailAndPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.authenticateManagedIdentityWithEmailAndPassword.email,\n emailVerified:\n result.authenticateManagedIdentityWithEmailAndPassword\n .emailVerified,\n sessionData:\n result.authenticateManagedIdentityWithEmailAndPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RegisterWithEmailAndPasswordMutation = gql`\n mutation RegisterWithEmailAndPassword(\n $email: String!\n $password: String!\n $formData: RSJsonNode\n $redirectPath: String\n ) {\n registerManagedIdentityWithEmailAndPassword(\n registerManagedIdentityWithEmailAndPasswordInput: {\n email: $email\n password: $password\n formData: $formData\n redirectPath: $redirectPath\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface RegisterWithEmailAndPasswordResult {\n registerManagedIdentityWithEmailAndPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useRegisterWithEmailAndPasswordMutation(): [\n (variables: {\n email: string;\n password: string;\n formData?: Record<string, any>;\n }) => Promise<RegisterWithEmailAndPasswordResult | Error>,\n BaseQueryData<RegisterWithEmailAndPasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<RegisterWithEmailAndPasswordResult>(\n RegisterWithEmailAndPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n email: string;\n password: string;\n formData?: Record<string, any>;\n }) => {\n const result = await request(v);\n if (\n !(result instanceof Error) &&\n result.registerManagedIdentityWithEmailAndPassword\n ) {\n const jwt = result.registerManagedIdentityWithEmailAndPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.registerManagedIdentityWithEmailAndPassword.email,\n emailVerified:\n result.registerManagedIdentityWithEmailAndPassword.emailVerified,\n sessionData:\n result.registerManagedIdentityWithEmailAndPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect, useState } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport {\n setUserIdentity,\n DecodedSquatchJWT,\n} from \"@saasquatch/component-environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RegisterViaRegistrationFormMutation = gql`\n mutation RegisterViaRegistrationForm($key: String!, $formData: RSJsonNode!) {\n submitForm(formSubmissionInput: { key: $key, formData: $formData }) {\n results {\n ... on FormHandlerSubmissionResult {\n result\n formHandler {\n namespace\n }\n }\n ... on FormHandlerError {\n errorCode\n error\n errorType\n formHandler {\n name\n endpointUrl\n }\n }\n }\n }\n }\n`;\n\ntype RegistrationResult =\n | {\n success: true;\n message: string;\n data: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n }\n | {\n success: false;\n message: string;\n };\n\ninterface RegisterViaRegistrationFormResult {\n submitForm: {\n results: Array<{\n result: {\n results: Array<RegistrationResult>;\n };\n formHandler: {\n namespace: string;\n };\n }>;\n };\n}\ninterface RegistrationFormResponseData<T> extends BaseQueryData<T> {\n formError?: string;\n}\n\nexport function useRegisterViaRegistrationFormMutation(): [\n (variables: {\n key: string;\n formData: {\n email: string;\n password: string;\n redirectUrl?: string;\n [field: string]: any;\n };\n }) => Promise<RegisterViaRegistrationFormResult | Error>,\n RegistrationFormResponseData<RegisterViaRegistrationFormResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<RegisterViaRegistrationFormResult>(\n RegisterViaRegistrationFormMutation\n );\n const [formError, setFormError] = useState<string | null>(null);\n\n const requestAndSetUserIdentityOrFormError = async (v: {\n key: string;\n formData: {\n email: string;\n password: string;\n redirectUrl?: string;\n [field: string]: any;\n };\n }) => {\n setFormError(null);\n const result = await request(v);\n if (result instanceof Error) {\n return result;\n }\n const managedIdentityResponse:\n | undefined\n | RegisterViaRegistrationFormResult[\"submitForm\"][\"results\"][number] = result.submitForm?.results?.find(\n (result) => result?.formHandler?.namespace === \"identity\"\n );\n if (\n managedIdentityResponse &&\n managedIdentityResponse.result?.results?.length\n ) {\n const registrationResult = managedIdentityResponse.result.results[0];\n if (registrationResult.success) {\n // if success handle setUserIdentity\n const jwt = registrationResult.data.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: registrationResult.data.email,\n emailVerified: registrationResult.data.emailVerified,\n sessionData: registrationResult.data.sessionData,\n },\n });\n } else {\n // handle errors\n setFormError(registrationResult.message);\n }\n }\n return result;\n };\n\n return [\n requestAndSetUserIdentityOrFormError,\n { loading, data, errors, formError },\n ];\n}\n","import gql from \"graphql-tag\";\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst ChangePasswordMutation = gql`\n mutation ChangePassword($password: String!) {\n changeManagedIdentityPassword(\n changeManagedIdentityPasswordInput: { password: $password }\n ) {\n success\n }\n }\n`;\n\ninterface ChangePasswordResult {\n changeManagedIdentityPassword: {\n success: boolean;\n };\n}\n\nexport function useChangePasswordMutation(): [\n (variables: { password: string }) => Promise<ChangePasswordResult | Error>,\n BaseQueryData<ChangePasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<ChangePasswordResult>(ChangePasswordMutation);\n\n return [request, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst ResetPasswordMutation = gql`\n mutation ResetPassword($oobCode: String!, $password: String!) {\n resetManagedIdentityPassword(\n resetManagedIdentityPasswordInput: {\n password: $password\n oobCode: $oobCode\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface ResetPasswordResult {\n resetManagedIdentityPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useResetPasswordMutation(): [\n (variables: {\n oobCode: string;\n password: string;\n }) => Promise<ResetPasswordResult | Error>,\n BaseQueryData<ResetPasswordResult>\n] {\n const [request, { loading, data, errors }] = useMutation<ResetPasswordResult>(\n ResetPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n oobCode: string;\n password: string;\n }) => {\n const result = await request(v);\n if (!(result instanceof Error) && result.resetManagedIdentityPassword) {\n const jwt = result.resetManagedIdentityPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.resetManagedIdentityPassword.email,\n emailVerified: result.resetManagedIdentityPassword.emailVerified,\n sessionData: result.resetManagedIdentityPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst VerifyPasswordResetCodeMutation = gql`\n mutation VerifyPasswordResetCode($oobCode: String!) {\n verifyManagedIdentityPasswordResetCode(\n verifyManagedIdentityPasswordResetCodeInput: { oobCode: $oobCode }\n ) {\n success\n }\n }\n`;\n\ninterface VerifyPasswordResetCodeResult {\n verifyManagedIdentityPasswordResetCode: {\n success: boolean;\n };\n}\n\nexport function useVerifyPasswordResetCodeMutation(): [\n (variables: {\n oobCode: string;\n }) => Promise<VerifyPasswordResetCodeResult | Error>,\n BaseQueryData<VerifyPasswordResetCodeResult>\n] {\n return useMutation<VerifyPasswordResetCodeResult>(\n VerifyPasswordResetCodeMutation\n );\n}\n","import { useCallback } from \"@saasquatch/universal-hooks\";\nimport { useDeepCompareEffect } from \"../useDeepEffect\";\nimport { useHost } from \"../useHost\";\n\nexport const REFRESH_EVENT_NAME = \"sq:refresh\";\n\nexport function useRefreshDispatcher() {\n const host = useHost();\n\n const refresh = useCallback(() => {\n host.dispatchEvent(\n new CustomEvent(REFRESH_EVENT_NAME, {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n // Could add some \"scope\" for more granular refresh\n },\n })\n );\n }, [host]);\n\n return { refresh };\n}\n\nexport function useRefreshListener({\n skip = false,\n update,\n variables,\n}: {\n skip?: boolean;\n update: (variables: unknown, skipLoading?: boolean) => unknown;\n variables: unknown;\n}) {\n useDeepCompareEffect(() => {\n const listener = (e: CustomEvent) => {\n !skip && update(variables, true);\n };\n document.addEventListener(REFRESH_EVENT_NAME, listener);\n return () => document.removeEventListener(REFRESH_EVENT_NAME, listener);\n }, [variables, update, skip]);\n}\n","/*\n * Forked From: https://github.com/kentcdodds/use-deep-compare-effect/blob/main/src/index.ts\n *\n * The MIT License (MIT)\n * Copyright (c) 2020 Kent C. Dodds\n *\n */\n\nimport { useEffect, useRef, useMemo } from \"@saasquatch/universal-hooks\";\nimport { equal as deepEqual } from \"@wry/equality\";\n\ntype UseEffectParams = Parameters<typeof useEffect>;\ntype EffectCallback = UseEffectParams[0];\ntype DependencyList = UseEffectParams[1];\n// yes, I know it's void, but I like what this communicates about\n// the intent of these functions: It's just like useEffect\ntype UseEffectReturn = ReturnType<typeof useEffect>;\n\n\n/**\n * @param value the value to be memoized (usually a dependency list)\n * @returns a memoized version of the value as long as it remains deeply equal\n */\nexport function useDeepCompareMemoize<T>(value: T) {\n const ref = useRef<T>(value);\n const signalRef = useRef<number>(0);\n\n if (!deepEqual(value, ref.current)) {\n ref.current = value;\n signalRef.current += 1;\n }\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => ref.current, [signalRef.current]);\n}\n\nexport function useDeepCompareEffect(\n callback: EffectCallback,\n dependencies: DependencyList\n): UseEffectReturn {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useEffect(callback, useDeepCompareMemoize(dependencies));\n}\n\nexport default useDeepCompareEffect;\n","import { useRef, useCallback } from \"@saasquatch/universal-hooks\";\nimport { useRefreshListener } from \"./Refresh\";\nimport {\n BaseQueryData,\n GqlType,\n QueryData,\n useBaseQuery,\n} from \"./useBaseQuery\";\n\nconst initialLazyQueryState: BaseQueryData = {\n loading: false,\n data: undefined,\n errors: undefined,\n} as const;\n\nconst NOTLOADED = Symbol();\nexport function useLazyQuery<T = any>(\n query: GqlType\n): [(e: unknown) => Promise<T | Error>, QueryData<T>] {\n const [state, update] = useBaseQuery<T>(\n query,\n initialLazyQueryState as BaseQueryData<T>\n );\n\n const variablesRef = useRef<unknown>(NOTLOADED);\n // To preserve laziness, this query will not refresh if the query has not already been run at least once\n const skip = variablesRef.current === NOTLOADED;\n useRefreshListener({\n skip,\n update,\n variables: variablesRef.current,\n });\n\n // can override props when refetching for new pagination, offset, etc\n const refetch = useCallback(\n (variables) => {\n variablesRef.current = variables;\n return update(variables);\n },\n [update]\n );\n\n return [\n update,\n {\n ...state,\n refetch,\n },\n ];\n}\n","import gql from \"graphql-tag\";\n\nimport { QueryData } from \"../graphql/useBaseQuery\";\nimport { useUserIdentity, setUserIdentity } from \"../environment\";\nimport { useLazyQuery } from \"../graphql/useLazyQuery\";\n\nconst ManagedIdentitySessionQuery = gql`\n query ManagedIdentitySession {\n managedIdentitySession {\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface ManagedIdentitySessionResult {\n managedIdentitySession: {\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useManagedIdentitySessionQuery(): [\n () => Promise<ManagedIdentitySessionResult | Error>,\n QueryData<ManagedIdentitySessionResult>\n] {\n const userIdentity = useUserIdentity();\n const [request, { loading, data, errors, refetch }] =\n useLazyQuery<ManagedIdentitySessionResult>(ManagedIdentitySessionQuery);\n\n const updateUserIdentity = (result: ManagedIdentitySessionResult | Error) => {\n if (!(result instanceof Error) && result.managedIdentitySession) {\n setUserIdentity({\n ...userIdentity,\n managedIdentity: result.managedIdentitySession,\n });\n }\n };\n\n const requestAndSetUserIdentity = async () => {\n const result = await request({});\n updateUserIdentity(result);\n return result;\n };\n\n const refetchAndSetUserIdentity = async () => {\n const result = await refetch();\n updateUserIdentity(result);\n return result;\n };\n\n return [\n requestAndSetUserIdentity,\n { loading, data, errors, refetch: refetchAndSetUserIdentity },\n ];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\nimport { useManagedIdentitySessionQuery } from \"./useManagedIdentitySessionQuery\";\n\nconst VerifyEmailMutation = gql`\n mutation VerifyEmail($oobCode: String!) {\n verifyManagedIdentityEmail(\n verifyManagedIdentityEmailInput: { oobCode: $oobCode }\n ) {\n success\n }\n }\n`;\n\ninterface VerifyEmailResult {\n verifyManagedIdentityEmail: {\n success: boolean;\n };\n}\n\nexport function useVerifyEmailMutation(): [\n (e: { oobCode: string }) => Promise<VerifyEmailResult | Error>,\n BaseQueryData<VerifyEmailResult>\n] {\n const [refreshManagedIdentitySession] = useManagedIdentitySessionQuery();\n const [request, { loading, data, errors }] =\n useMutation<VerifyEmailResult>(VerifyEmailMutation);\n\n const requestAndRefreshManagedIdentitySession = async (e: {\n oobCode: string;\n }) => {\n const result = await request(e);\n if (\n !(result instanceof Error) &&\n result.verifyManagedIdentityEmail.success\n ) {\n await refreshManagedIdentitySession();\n }\n return result;\n };\n\n return [requestAndRefreshManagedIdentitySession, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RequestPasswordResetEmailMutation = gql`\n mutation RequestPasswordResetEmail(\n $email: String!\n $urlParams: RSJsonNode\n $redirectPath: String\n ) {\n requestManagedIdentityPasswordResetEmail(\n requestManagedIdentityPasswordResetEmailInput: {\n email: $email\n urlParams: $urlParams\n redirectPath: $redirectPath\n }\n ) {\n success\n }\n }\n`;\n\ninterface RequestPasswordResetEmailResult {\n requestManagedIdentityPasswordResetEmail: {\n success: boolean;\n };\n}\n\nexport function useRequestPasswordResetEmailMutation(): [\n (variables: {\n email: string;\n urlParams?: Record<string, any>;\n }) => Promise<RequestPasswordResetEmailResult | Error>,\n BaseQueryData<RequestPasswordResetEmailResult>\n] {\n return useMutation<RequestPasswordResetEmailResult>(\n RequestPasswordResetEmailMutation\n );\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RequestVerificationEmailMutation = gql`\n mutation RequestVerificationEmail(\n $email: String!\n $urlParams: RSJsonNode\n $redirectPath: String\n ) {\n requestManagedIdentityVerificationEmail(\n requestManagedIdentityVerificationEmailInput: {\n email: $email\n urlParams: $urlParams\n redirectPath: $redirectPath\n }\n ) {\n success\n }\n }\n`;\n\ninterface RequestVerificationEmailResult {\n requestManagedIdentityVerificationEmail: {\n success: boolean;\n };\n}\n\nexport function useRequestVerificationEmailMutation(): [\n (variables: {\n email: string;\n urlParams?: Record<string, any>;\n }) => Promise<RequestVerificationEmailResult | Error>,\n BaseQueryData<RequestVerificationEmailResult>\n] {\n return useMutation<RequestVerificationEmailResult>(\n RequestVerificationEmailMutation\n );\n}\n","import {\n getAppDomain,\n getEnvironment,\n getTenantAlias,\n setUserIdentity,\n} from \"@saasquatch/component-environment\";\nimport gql from \"graphql-tag\";\nimport { BaseQueryData, useBaseQuery } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\nimport { useProgramId } from \"../environment\";\n\ninterface AuthenticateManagedIdentityWithInstantAccessVariables {\n email: string;\n firstName: string;\n lastName: string;\n locale: string;\n countryCode: string;\n cookies: string;\n}\n\ninterface AuthenticateManagedIdentityWithInstantAccessResult {\n authenticateManagedIdentityWithInstantAccess: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nconst AuthenticateManagedIdentityWithInstantAccessMutation = gql`\n mutation authenticateManagedIdentityWithInstantAccess(\n $email: String!\n $firstName: String\n $lastName: String\n $locale: RSLocale\n $countryCode: RSCountryCode\n $cookies: String\n ) {\n authenticateManagedIdentityWithInstantAccess(\n authenticateManagedIdentityWithInstantAccessInput: {\n email: $email\n firstName: $firstName\n lastName: $lastName\n locale: $locale\n countryCode: $countryCode\n cookies: $cookies\n }\n ) {\n email\n emailVerified\n sessionData\n token\n }\n }\n`;\n\nconst CheckReferralFraudStatusQuery = `\n query checkReferralFraudStatus($programId: ID) {\n viewer {\n ... on User {\n id\n instantAccessRewards(filter: { programId_eq: $programId }) {\n data {\n id\n pendingReasons\n cancelledReason\n }\n }\n }\n }\n }\n`;\n\nasync function fetchFraud(programId: string, jwt: string) {\n try {\n const result = await fetch(\n `${getAppDomain()}/api/v1/${getTenantAlias()}/graphql`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${jwt}`,\n },\n body: JSON.stringify({\n query: CheckReferralFraudStatusQuery,\n variables: {\n programId,\n },\n }),\n }\n );\n\n if (!result.ok) {\n throw new Error(\"Failed to fetch locale\");\n }\n\n const json = await result.json();\n if (json.errors) {\n throw new Error(JSON.stringify(json.errors, null, 2));\n }\n\n const results = (json as any).data.viewer.instantAccessRewards?.data || [];\n if (results.some((r) => r.cancelledReason === \"SUSPECTED_FRAUD\"))\n return \"DENIED\";\n else if (results.some((r) => r.pendingReasons?.includes(\"SUSPECTED_FRAUD\")))\n return \"PENDING_REVIEW\";\n else return \"APPROVED\";\n } catch (e) {\n console.error(e);\n return undefined;\n }\n}\n\nexport function useAuthenticateManagedIdentityWithInstantAccess(): [\n (\n e: unknown\n ) => Promise<AuthenticateManagedIdentityWithInstantAccessResult | Error>,\n BaseQueryData<AuthenticateManagedIdentityWithInstantAccessResult>\n] {\n const programId = useProgramId();\n const env = getEnvironment();\n\n const [request, { loading, data, errors }] =\n useMutation<AuthenticateManagedIdentityWithInstantAccessResult>(\n AuthenticateManagedIdentityWithInstantAccessMutation\n );\n\n const requestAndSetUserIdentity = async (\n variables: AuthenticateManagedIdentityWithInstantAccessVariables\n ) => {\n const result = await request(variables);\n\n if (\n !(result instanceof Error) &&\n result.authenticateManagedIdentityWithInstantAccess\n ) {\n const fraudStatus = await fetchFraud(\n programId,\n result.authenticateManagedIdentityWithInstantAccess.token\n );\n\n if (fraudStatus === \"APPROVED\") {\n const jwt = result.authenticateManagedIdentityWithInstantAccess.token;\n const email = result.authenticateManagedIdentityWithInstantAccess.email;\n\n setUserIdentity({\n jwt,\n id: email,\n accountId: email,\n });\n\n // If in squatch-js, fire a sq:user-registered event\n if (env === \"SquatchJS2\") {\n const event = new CustomEvent(\"sq:user-registration\", {\n bubbles: true,\n detail: {\n userId: email,\n accountId: email,\n },\n });\n\n document.dispatchEvent(event);\n }\n } else {\n throw {\n name: \"fraud_error\",\n message: \"Referral flagged as fraud.\",\n };\n }\n }\n\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import { equal } from \"@wry/equality\";\nimport { useRef } from \"@saasquatch/universal-hooks\";\n\nexport function useDeepMemo<TKey, TValue>(\n memoFn: () => TValue,\n key: TKey\n): TValue {\n //@ts-ignore\n const ref = useRef<{ key: TKey; value: TValue }>();\n\n if (!ref.current || !equal(key, ref.current.key)) {\n ref.current = { key, value: memoFn() };\n }\n\n return ref.current.value;\n}\n","import { useReducer } from \"@saasquatch/universal-hooks\";\n\nexport function useTick(): readonly [number, () => unknown] {\n //@ts-expect-error -- bad typing on callback\n return useReducer<number, number, number>((x) => x + 1, 0);\n}\n","import { useDeepMemo } from \"../useDeepMemo\";\nimport { useTick } from \"../useTick\";\nimport { useRefreshListener } from \"./Refresh\";\nimport {\n BaseQueryData,\n GqlType,\n QueryData,\n useBaseQuery,\n} from \"./useBaseQuery\";\n\n// from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\nfunction deepFreeze(object) {\n // Retrieve the property names defined on object\n const propNames = Object.getOwnPropertyNames(object);\n\n // Freeze properties before freezing self\n\n for (const name of propNames) {\n const value = object[name];\n\n if (value && typeof value === \"object\") {\n deepFreeze(value);\n }\n }\n\n return Object.freeze(object);\n}\n\nexport const initialQueryState: BaseQueryData = {\n loading: true,\n data: undefined,\n errors: undefined,\n} as const;\n\nexport function useQuery<T = any>(\n query: GqlType,\n variables: unknown,\n skip?: boolean\n): QueryData<T> {\n const [state, update] = useBaseQuery<T>(\n query,\n initialQueryState as BaseQueryData<T>\n );\n\n const [tick, forceUpdate] = useTick();\n\n useDeepMemo(() => {\n !skip && update(variables);\n }, [query, variables, update, tick, skip]);\n\n useRefreshListener({ skip, update, variables });\n\n return deepFreeze({\n ...state,\n // can override props when refetching for new pagination, offset, etc\n refetch: forceUpdate,\n });\n}\n","import { useEffect } from \"@saasquatch/universal-hooks\";\nimport {\n history,\n HistoryEntry,\n LazyHistory,\n} from \"@saasquatch/component-environment\";\nimport { useTick } from \"./useTick\";\n\n/**\n * Returns the current location. Similar to `window.location` but works with SPA page changes and virtual pages in Squatch.js\n */\nexport function useCurrentPage(): HistoryEntry {\n const [, tick] = useTick();\n useEffect(() => {\n const cleanup = history.listen(() => {\n // re-render\n tick();\n });\n return cleanup;\n }, []);\n\n return history.location;\n}\n\nexport const navigation: LazyHistory = history;\n","import { useState } from \"@saasquatch/universal-hooks\";\n\nexport function usePagination(pageVars: { limit: number; offset: number }) {\n const [pageState, setPageState] = useState({\n limit: pageVars.limit,\n offset: pageVars.offset,\n });\n const { offset, limit } = pageState;\n\n const calcOffset = (limit: number, page: number) => limit * page;\n const calcPage = (offset: number, limit: number) =>\n Math.ceil(offset / limit) || 0;\n const calcPageCount = (totalCount: number, limit: number) =>\n Math.ceil(totalCount / limit) || 0;\n\n const setLimit = (newLimit: number) => {\n const newPage = calcPage(offset, newLimit);\n const newOffset = calcOffset(newLimit, newPage);\n setPageState({\n ...pageState,\n limit: newLimit,\n offset: newOffset,\n });\n };\n\n // page numbering starts at 0\n const setCurrentPage = (newPage: number) => {\n let newOffset = calcOffset(newPage, limit);\n setPageState((pageState) => ({\n ...pageState,\n offset: newOffset,\n }));\n };\n\n // there are no safety guards here for invalid inputs\n function calculatePagination(count: number, totalCount: number) {\n const currentPage = calcPage(offset, limit);\n const pageCount = calcPageCount(totalCount, limit);\n\n const rangeOnPage: string =\n count === 0\n ? \"0\"\n : count > 1\n ? `${offset + 1}-${offset + count}`\n : `${offset + 1}`;\n const pageProgress: string = `${rangeOnPage} of ${totalCount}`;\n\n return { currentPage, pageCount, rangeOnPage, pageProgress };\n }\n\n return {\n limit,\n setLimit,\n offset,\n setCurrentPage,\n calculatePagination,\n };\n}\n","import { useQuery } from \"../graphql/useQuery\";\nimport { usePagination } from \"./usePagination\";\n\nexport type Envelope<T = unknown> = {\n data: T[];\n totalCount?: number;\n};\n\nexport type PageVars = {\n offset: number;\n limit: number;\n};\n\n/**\n * dataPath MUST use the question mark operator when accessing fields.\n * If it doesn't then it will violate a Rule of Hooks\n */\nexport function usePaginatedQuery<\n TData,\n TVars extends { [key: string]: any } = {}\n>(\n query: any,\n dataPath: (data: any) => Envelope<TData>,\n pageVars: PageVars,\n extraVars: TVars = {} as TVars,\n skip: boolean = false,\n) {\n const {\n limit,\n offset,\n setLimit,\n setCurrentPage,\n calculatePagination,\n } = usePagination(pageVars);\n\n const variables = { limit, offset, ...extraVars };\n\n const { loading, errors, data, refetch } = useQuery(query, variables, skip);\n\n // this value needs to be accessed using the ? operator\n // react throws a hook error otherwise\n const envelope = dataPath(data);\n\n const { currentPage, pageCount, pageProgress } = calculatePagination(\n envelope?.data?.length || 0,\n envelope?.totalCount || 0\n );\n\n return {\n envelope,\n states: {\n errors,\n loading,\n limit,\n currentPage,\n pageCount,\n pageProgress,\n },\n callbacks: {\n refetch,\n setLimit,\n setCurrentPage,\n },\n };\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"@saasquatch/universal-hooks\";\nimport debounce from \"debounce\";\n\nfunction valueEquality<T>(left: T, right: T): boolean {\n return left === right;\n}\n\n/**\n * Provides a debounced value\n *\n * Forked from React version here: https://github.com/xnimorz/use-debounce\n *\n * @param value\n * @param delay\n * @param options\n */\nexport function useDebounce<T>(\n value: T,\n delay: number,\n options?: {\n maxWait?: number;\n leading?: boolean;\n trailing?: boolean;\n equalityFn?: (left: T, right: T) => boolean;\n }\n) {\n const eq = (options && options.equalityFn) || valueEquality;\n\n const [state, dispatch] = useState(value);\n const debounced = useDebouncedCallback(\n useCallback((value: T) => dispatch(value), []),\n delay,\n options\n );\n const previousValue = useRef(value);\n\n useEffect(() => {\n // We need to use this condition otherwise we will run debounce timer for the first render (including maxWait option)\n if (!eq(previousValue.current, value)) {\n debounced.callback(value);\n previousValue.current = value;\n }\n }, [value, debounced, eq]);\n\n return [\n state,\n {\n cancel: debounced.cancel,\n flush: debounced.flush,\n },\n ] as const;\n}\n\nexport interface CallOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\nexport interface ControlFunctions {\n cancel: () => void;\n flush: () => void;\n}\n\n/**\n * Subsequent calls to the debounced function `debounced.callback` return the result of the last func invocation.\n * Note, that if there are no previous invocations it's mean you will get undefined. You should check it in your code properly.\n */\nexport interface DebouncedState<T extends (...args: any[]) => ReturnType<T>>\n extends ControlFunctions {\n callback: (...args: Parameters<T>) => ReturnType<T>;\n}\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked, or until the next browser frame is drawn. The debounced function\n * comes with a `cancel` method to cancel delayed `func` invocations and a\n * `flush` method to immediately invoke them. Provide `options` to indicate\n * whether `func` should be invoked on the leading and/or trailing edge of the\n * `wait` timeout. The `func` is invoked with the last arguments provided to the\n * debounced function. Subsequent calls to the debounced function return the\n * result of the last `func` invocation.\n\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `debounce` and `throttle`.\n *\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0]\n * The number of milliseconds to delay\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n */\nexport function useDebouncedCallback<\n T extends (...args: any[]) => ReturnType<T>\n>(\n func: T,\n wait: number = 0,\n options: CallOptions = { leading: false }\n): DebouncedState<T> {\n const callback = useMemo(() => debounce(func, wait, options.leading), [\n func,\n wait,\n options.leading,\n ]);\n\n const { flush, clear } = callback;\n\n return {\n flush,\n cancel: clear,\n callback,\n };\n}\n","import { gql } from \"graphql-request\";\nimport {\n useEngagementMedium,\n useProgramId,\n useUserIdentity,\n} from \"../hooks/environment\";\nimport { useMutation } from \"./graphql/useMutation\";\n\nconst FIRE_EVENT = gql`\n mutation ($eventMeta: UserAnalyticsEvent!) {\n createUserAnalyticsEvent(eventMeta: $eventMeta)\n }\n`;\n\nexport function useShareEvent() {\n const engagementMedium = useEngagementMedium();\n const userIdentity = useUserIdentity();\n const program = useProgramId();\n const [dispatch] = useMutation(FIRE_EVENT);\n\n if (!userIdentity) {\n // Not logged in. No-op callback for tracking sharing.\n return () => {};\n }\n\n return (shareMedium: string) => {\n const variables = {\n eventMeta: {\n id: userIdentity.id,\n accountId: userIdentity.accountId,\n programId: program,\n type: \"USER_REFERRAL_PROGRAM_ENGAGEMENT_EVENT\",\n meta: {\n engagementMedium: engagementMedium,\n shareMedium,\n },\n },\n };\n dispatch(variables);\n };\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","import { UserIdentity } from \"@saasquatch/component-environment\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\nimport { equal as deepEqual } from \"@wry/equality\";\nimport debugFn from \"debug\";\nimport { ContextProvider } from \"dom-context\";\nimport { gql } from \"graphql-request\";\nimport {\n useEngagementMedium,\n useProgramId,\n useUserIdentity,\n} from \"./environment\";\nimport { useMutation } from \"./graphql/useMutation\";\nimport { useHost } from \"./useHost\";\n\nconst LOAD_EVENT_CONTEXT_NAME = \"sq:load-event\";\nexport const debug = debugFn(LOAD_EVENT_CONTEXT_NAME);\n\ndeclare global {\n interface Window {\n squatchLoadEvent?: ContextProvider<EventContext>;\n }\n}\n\ntype EventContext = {\n userIdentity?: UserIdentity;\n programId?: string;\n};\n\nconst FIRE_EVENT = gql`\n mutation loadEvent($eventMeta: UserAnalyticsEvent!) {\n createUserAnalyticsEvent(eventMeta: $eventMeta)\n }\n`;\n\nexport function lazilyStartLoadEventContext() {\n let globalProvider = window.squatchLoadEvent;\n\n if (!globalProvider) {\n debug(\"Creating load event provider\");\n\n globalProvider = new ContextProvider<EventContext>({\n element: document.documentElement,\n initialState: {\n userIdentity: undefined,\n programId: undefined,\n },\n contextName: LOAD_EVENT_CONTEXT_NAME,\n }).start();\n\n window.squatchLoadEvent = globalProvider;\n }\n\n return globalProvider;\n}\n\nexport function useLoadEvent() {\n const host = useHost();\n const globalProvider = lazilyStartLoadEventContext();\n\n const engagementMedium = useEngagementMedium();\n\n const userIdentity = useUserIdentity();\n\n const programId = useProgramId();\n\n const [dispatch] = useMutation(FIRE_EVENT);\n\n useEffect(() => {\n if (!userIdentity || !programId || !globalProvider?.context) return;\n\n if (\n // First time loading\n !globalProvider.context.userIdentity ||\n // User changed\n !deepEqual(userIdentity, globalProvider.context.userIdentity) ||\n // Different programId\n programId !== globalProvider.context.programId\n ) {\n const variables = {\n eventMeta: {\n programId,\n id: userIdentity.id,\n accountId: userIdentity.accountId,\n type: \"USER_REFERRAL_PROGRAM_LOADED_EVENT\",\n meta: {\n engagementMedium,\n },\n },\n };\n dispatch(variables);\n\n debug(\"Event sent\", { variables, globalProvider });\n\n globalProvider.context = { userIdentity, programId };\n }\n }, [userIdentity?.id, userIdentity?.accountId, programId]);\n}\n","import { useEffect, useReducer } from \"@saasquatch/universal-hooks\";\nimport { gql } from \"graphql-request\";\nimport debugFn from \"debug\";\nimport jsonpointer from \"jsonpointer\";\nimport { useMutation } from \"./graphql/useMutation\";\nimport { useLazyQuery } from \"./graphql/useLazyQuery\";\nimport { useDeepMemo } from \"./useDeepMemo\";\nexport const debug = debugFn(\"sq:useForm\");\n\nconst GET_FORM = gql`\n query ($key: String!) {\n form(key: $key) {\n schema\n initialData {\n initialData\n isEnabled\n isEnabledErrorMessage\n }\n }\n }\n`;\n\nconst SUBMIT_FORM = gql`\n mutation ($formSubmissionInput: FormSubmissionInput!) {\n submitForm(formSubmissionInput: $formSubmissionInput) {\n success\n results {\n ... on FormHandlerSubmissionResult {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n result\n }\n ... on FormHandlerError {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n errorType\n error\n errorCode\n }\n }\n }\n }\n`;\n\nconst VALIDATE_FORM = gql`\n query ($formValidationInput: FormValidationInput!) {\n validateForm(formValidationInput: $formValidationInput) {\n valid\n results {\n ... on FormHandlerValidationResult {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n result\n }\n ... on FormHandlerError {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n errorType\n error\n errorCode\n }\n }\n }\n }\n`;\n\ntype UseFormProps = {\n formKey: string;\n formRef: HTMLFormElement;\n /** Flag to submit the form automatically once validated */\n autoSubmit?: boolean;\n setInitialData?: (htmlForm?: HTMLFormElement, initialData?: unknown) => void;\n};\n\ntype FormState = {\n validating: boolean;\n valid: boolean;\n enabled: boolean;\n disabledMessage: string;\n error: string;\n formData: object;\n validationData: any;\n submitData: any;\n};\n\nexport function useForm(props: UseFormProps) {\n const { formKey, formRef, autoSubmit = false } = props;\n\n const [getForm, { data, loading: loadingForm }] = useLazyQuery(GET_FORM);\n const [submit, submitData] = useMutation(SUBMIT_FORM);\n const [validate, validationData] = useLazyQuery(VALIDATE_FORM);\n\n const initialState = {\n enabled: false,\n validating: false,\n valid: true,\n validationMessage: \"\",\n error: \"\",\n disabledMessage: \"\",\n formData: {},\n validationData,\n submitData,\n };\n\n const [formState, setFormState] = useReducer<FormState, Partial<FormState>>(\n (state, next) => ({\n ...state,\n ...next,\n }),\n initialState\n );\n\n const { enabled, disabledMessage, validating, valid, error, formData } =\n formState;\n\n useDeepMemo(() => {\n debug(\"submitData useEffect\", submitData);\n setFormState({ submitData });\n }, [submitData]);\n\n useDeepMemo(() => {\n debug(\"validationData useEffect\", validationData);\n setFormState({ validationData });\n }, [validationData]);\n\n // load initial data into form\n useEffect(() => {\n async function setInitialData(htmlForm, initialData) {\n const inputs = htmlForm.elements;\n\n const formContent = new FormData(htmlForm);\n\n debug({ htmlForm, formContent });\n formContent?.forEach((value, key) => {\n debug({ value, key, inputs });\n const input = inputs.namedItem(key) as HTMLInputElement;\n\n try {\n if (input.type == \"checkbox\") {\n input.checked = jsonpointer.get(initialData, key);\n } else {\n input.value = jsonpointer.get(initialData, key) || \"\";\n }\n } catch (error) {\n debug(\"no initialData found for key\", key);\n }\n });\n }\n function initialize() {\n setFormState({\n enabled: data?.form.initialData?.isEnabled,\n disabledMessage: data?.form?.initialData?.isEnabledErrorMessage,\n });\n const htmlForm = formRef;\n\n if (!htmlForm) return;\n\n const initialData = data?.form?.initialData?.initialData;\n\n props.setInitialData !== undefined\n ? props.setInitialData(htmlForm, initialData)\n : setInitialData(htmlForm, initialData);\n }\n if (!loadingForm && data) initialize();\n }, [loadingForm]);\n\n // submit if form data is valid\n useEffect(() => {\n if (!!formState.validationData) {\n setFormState({\n validating: false,\n valid: formState.validationData?.data?.validateForm?.valid || false,\n });\n\n if (autoSubmit && formState.validationData?.data?.validateForm?.valid) {\n submit({\n formSubmissionInput: { key: formKey, formData },\n });\n }\n }\n }, [formState.validationData?.data?.validateForm?.valid]);\n\n /**\n * Schema, network, and integration errors after submission to GraphQL\n */\n function getSubmissionErrors(): Array<SubmissionError> {\n if (!formState.submitData) return [];\n\n const submissionResults = formState.submitData.data?.submitForm.results;\n\n return (\n submissionResults?.map((error) => {\n // salesforce errors\n const messages = error.result?.results\n ?.flatMap((res) => !res.success && res.message)\n .filter((message) => message);\n\n // fatal errors\n const errors = error.result?.results\n ?.flatMap(\n (res) =>\n !res.success && {\n error: res.error,\n errorType: res.errorType,\n errorCode: res.errorCode,\n }\n )\n .filter(({ error }) => error);\n\n return {\n integration: error.formHandler?.integration?.name,\n formHandler: error.formHandler?.name,\n messages,\n errors,\n };\n }) || []\n );\n }\n\n /**\n * Schema validation based on return data from validateForm results\n */\n function getValidationErrors(): ValidationErrors {\n const validationErrors =\n validationData?.data?.validateForm?.results[0]?.result?.errors;\n\n /**\n * Provide a JSON path and receive any errors at that path\n */\n function getErrorAtPath(path: string) {\n return validationErrors?.filter((result) => {\n const instanceLocation = result.instanceLocation.substring(1);\n return instanceLocation === path;\n });\n }\n\n /**\n * Provide a JSON path and receive any errors at that path,\n * and any errors for nested paths\n */\n function getSubErrorsAtPath(path: string) {\n return validationErrors?.filter((result: ValidationError) => {\n const instanceLocation = result.instanceLocation.substring(1);\n return instanceLocation.startsWith(`${path}`);\n });\n }\n\n return {\n getErrorAtPath,\n getSubErrorsAtPath,\n hasSubErrors: (path) => getSubErrorsAtPath(path)?.length > 0,\n };\n }\n\n async function validateForm(formData) {\n await validate({\n formValidationInput: {\n key: formKey,\n formData,\n },\n });\n }\n\n async function submitForm(formData) {\n await submit({\n formSubmissionInput: {\n key: formKey,\n formData,\n },\n });\n }\n\n /**\n * Submit function for regular <form> submissions\n */\n async function handleSubmit(e: any) {\n e.preventDefault();\n\n setFormState({ validating: true });\n const form = e.target;\n debug(\"submit form\", form);\n const data = new FormData(form);\n\n let formData = {};\n\n //@ts-ignore\n for (var pair of data.entries()) {\n jsonpointer.set(formData, pair[0], pair[1]);\n }\n\n setFormState({ formData });\n\n await validateForm(formData);\n }\n\n return {\n states: {\n enabled,\n disabledMessage,\n loadingForm,\n validating,\n valid,\n error,\n validationData: formState.validationData,\n submitData: formState.submitData,\n },\n data: {\n formKey,\n schema: data?.form?.schema,\n },\n callbacks: {\n /** Retrieve schema and initial data if provided from backend */\n getForm,\n /** Validate and submit <form> element data */\n handleSubmit,\n /** Validates form data and submits form if autoSubmit flag is true */\n validateForm,\n /** Submits form data */\n submitForm,\n /** Set form state for custom validation errors and multi-page forms */\n setFormState,\n getValidationErrors,\n getSubmissionErrors,\n },\n };\n}\n\ninterface ValidationErrors {\n getErrorAtPath(path: string): ValidationError[];\n getSubErrorsAtPath(path: string): ValidationError[];\n // TODO: implement ajv-i18n for translatable errors\n // getHumanizedErrorAtPath(path: string): string;\n hasSubErrors(path: string): boolean;\n}\n\ntype ValidationError = {\n error: string;\n keywordLocation: string;\n instanceLocation: string;\n};\n\ntype SubmissionError = {\n formHandler: string;\n integration: string;\n messages: string[];\n};\n\nexport type UseFormViewProps = ReturnType<typeof useForm>;\n"],"names":["ref","current","undefined","useHost","Error","setImplementation","implementation","useLocale","lazilyStartLocaleContext","host","useDomContext","LOCALE_CONTEXT_NAME","useProgramId","lazilyStartProgramContext","PROGRAM_CONTEXT_NAME","useSessionData","useUserIdentity","_useUserIdentity","managedIdentity","_useUserIdentity$mana","sessionData","useToken","_useUserIdentity2","jwt","lazilyStartUserContext","identity","USER_CONTEXT_NAME","validIdentity","userIdentityFromJwt","isDemo","setUserIdentity","useTenantAlias","getTenantAlias","useAppDomain","getAppDomain","useEngagementMedium","getEngagementMedium","__assign","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","this","docCache","Map","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","normalize","string","replace","trim","parseDocument","source","ast","seenKeys","definitions","cacheKey","has","parsed","parse","kind","set","doc","workSet","Set","forEach","node","loc","keys","key","value","add","startToken","endToken","stripLoc","fragmentDefinition","fragmentName","name","sourceKey","body","substring","start","end","sourceKeySet","get","console","warn","push","gql","literals","args","_i","result","arg","gql_1","extras","resetCaches","clear","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","BatchedGraphQLClient","GraphQLClient","constructor","url","opts","super","Subject","unmergable","subject","pipe","bufferTime","subscribe","async","queryAddedEvents","mergedQuery","mergedVariables","mergedQueryAddedEvents","unmergedQueryAddedEvents","mergeQueryAddedEvents","unmergedQuery","next","mergedQueryResult","_this","superRequest","resolveMergedQueryResult","e","ClientError","data","errors","response","rejectAllQueryAddedEventsWithError","aliases","eventsToResolve","error","erroredEvent","path","find","index","includes","erroredId","getIdFromAliasedField","indexOfErroredEvent","findIndex","event","id","splice","eventSpecificData","removeAliasesFromDataResult","removeAliasFromField","query","variables","errorResponse","newError","print","rejectQueryAddedEventWithError","resolveSingleQueryResult","request","Promise","resolve","reject","queryAddedEvent","generateQueryAddedEventId","nanoid","field","fieldArray","split","events","document","reduce","acc","curr","parsedQuery","queryStr","containsDirective","test","renameFn","aliasFieldOrVariableFn","addN","combineQuery","queryResult","endsWith","[object Object]","err","GRAPHQL_CONTEXT","memoizedGraphQLClient","memoize","appDomain","tenantAlias","token","headers","Authorization","reducer","state","action","type","loading","payload","useBaseQuery","initialState","client","localClient","clientFromContext","attempts","useGraphQLClient","dispatch","useReducer","useCallback","skipLoading","res","initialMutationState","useMutation","update","AuthenticateWithEmailAndPasswordMutation","useAuthenticateWithEmailAndPasswordMutation","v","authenticateManagedIdentityWithEmailAndPassword","user","decode","accountId","email","emailVerified","RegisterWithEmailAndPasswordMutation","useRegisterWithEmailAndPasswordMutation","registerManagedIdentityWithEmailAndPassword","RegisterViaRegistrationFormMutation","useRegisterViaRegistrationFormMutation","formError","setFormError","useState","managedIdentityResponse","submitForm","_result$submitForm","results","_result$submitForm$re","formHandler","namespace","_managedIdentityRespo","_managedIdentityRespo2","registrationResult","success","message","ChangePasswordMutation","useChangePasswordMutation","ResetPasswordMutation","useResetPasswordMutation","resetManagedIdentityPassword","VerifyPasswordResetCodeMutation","useVerifyPasswordResetCodeMutation","useRefreshDispatcher","refresh","dispatchEvent","CustomEvent","bubbles","composed","cancelable","detail","useRefreshListener","skip","useEffect","listener","addEventListener","removeEventListener","useRef","signalRef","deepEqual","useMemo","useDeepCompareMemoize","initialLazyQueryState","NOTLOADED","Symbol","useLazyQuery","variablesRef","refetch","ManagedIdentitySessionQuery","useManagedIdentitySessionQuery","userIdentity","updateUserIdentity","managedIdentitySession","VerifyEmailMutation","useVerifyEmailMutation","refreshManagedIdentitySession","verifyManagedIdentityEmail","RequestPasswordResetEmailMutation","useRequestPasswordResetEmailMutation","RequestVerificationEmailMutation","useRequestVerificationEmailMutation","AuthenticateManagedIdentityWithInstantAccessMutation","useAuthenticateManagedIdentityWithInstantAccess","programId","env","getEnvironment","authenticateManagedIdentityWithInstantAccess","fetch","method","Content-Type","JSON","stringify","ok","json","viewer","instantAccessRewards","some","r","cancelledReason","pendingReasons","_r$pendingReasons","fetchFraud","userId","useDeepMemo","memoFn","equal","useTick","x","deepFreeze","object","propNames","getOwnPropertyNames","freeze","initialQueryState","useQuery","tick","forceUpdate","useCurrentPage","history","listen","location","navigation","usePagination","pageVars","pageState","setPageState","limit","offset","calcOffset","page","calcPage","Math","ceil","setLimit","newLimit","newPage","newOffset","setCurrentPage","calculatePagination","count","totalCount","currentPage","pageCount","calcPageCount","rangeOnPage","pageProgress","usePaginatedQuery","dataPath","extraVars","envelope","states","callbacks","valueEquality","left","right","useDebounce","delay","options","eq","equalityFn","debounced","useDebouncedCallback","previousValue","callback","cancel","flush","func","wait","leading","debounce","FIRE_EVENT","useShareEvent","engagementMedium","program","shareMedium","eventMeta","meta","m","h","d","val","str","String","match","exec","parseFloat","toLowerCase","isFinite","long","ms","msAbs","abs","plural","fmtLong","round","fmtShort","isPlural","exports","useColors","module","humanize","diff","c","color","lastC","namespaces","storage","setItem","removeItem","getItem","process","DEBUG","window","__nwjs","navigator","userAgent","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","RegExp","$1","localStorage","localstorage","warned","debug","log","createDebug","prevTime","enableOverride","enabled","self","Number","Date","prev","coerce","unshift","format","formatter","formatters","formatArgs","selectColor","extend","destroy","defineProperty","enumerable","configurable","init","delimiter","newDebug","toNamespace","regexp","toString","default","stack","disable","names","map","skips","join","enable","save","len","substr","require$$0","hash","charCodeAt","colors","load","j","debugFn","useLoadEvent","globalProvider","squatchLoadEvent","ContextProvider","element","contextName","lazilyStartLoadEventContext","context","GET_FORM","SUBMIT_FORM","VALIDATE_FORM","useForm","props","formKey","formRef","autoSubmit","getForm","loadingForm","submit","submitData","validate","validationData","validating","valid","validationMessage","disabledMessage","formData","formState","setFormState","validateForm","formValidationInput","form","initialData","_data$form$initialDat","isEnabled","_data$form","_data$form$initialDat2","isEnabledErrorMessage","htmlForm","_data$form2","_data$form2$initialDa","setInitialData","inputs","elements","formContent","FormData","input","namedItem","checked","jsonpointer","initialize","_formState$validation4","_formState$validation5","_formState$validation6","formSubmissionInput","_formState$validation7","_formState$validation8","_formState$validation9","schema","_data$form3","handleSubmit","preventDefault","target","pair","entries","getValidationErrors","validationErrors","_validationData$data","_validationData$data$","_validationData$data$2","_validationData$data$3","getSubErrorsAtPath","filter","instanceLocation","startsWith","getErrorAtPath","hasSubErrors","getSubmissionErrors","submissionResults","_formState$submitData","messages","_error$result","_error$result$results","flatMap","_error$result2","_error$result2$result","errorType","errorCode","integration","_error$formHandler","_error$formHandler$in","_error$formHandler2"],"mappings":"ynCAAA,MAAMA,EAAM,CAAEC,aAASC,YAEPC,IACd,QAAoBD,IAAhBF,EAAIC,QACN,U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AAK5U,sBAEtB,MAAM0a,WAAW1a,EAAM1C,kBAANqd,EAAcxU,gBAAdyU,EACbC,QAASlW,IAASA,EAAI+B,SAAW/B,EAAIgC,SACtCuT,OAAQvT,GAAYA,GAGjBhH,WAASK,EAAM1C,kBAANwd,EAAc3U,gBAAd4U,EACXF,QACClW,IACEA,EAAI+B,SAAW,CACd1G,MAAO2E,EAAI3E,MACXgb,UAAWrW,EAAIqW,UACfC,UAAWtW,EAAIsW,YAGpBf,OAAO,EAAGla,MAAAA,KAAYA,GAEzB,MAAO,CACLkb,qBAAalb,EAAMqG,uBAAN8U,EAAmBD,oBAAnBE,EAAgC7e,KAC7C8J,qBAAarG,EAAMqG,oBAANgV,EAAmB9e,KAChCme,SAAAA,EACA/a,OAAAA,OAEE"}
|
|
1
|
+
{"version":3,"file":"index.modern.js","sources":["../src/hooks/useHost.ts","../src/hooks/environment/useLocale.ts","../src/hooks/environment/useProgramId.ts","../src/hooks/environment/useUserIdentity.ts","../src/hooks/environment/index.ts","../node_modules/tslib/tslib.es6.js","../node_modules/graphql-tag/lib/index.js","../src/BatchedGraphQLClient.ts","../src/hooks/graphql/useGraphQLClient.ts","../src/hooks/graphql/useBaseQuery.ts","../src/hooks/graphql/useMutation.ts","../src/hooks/managedIdentity/useAuthenticateWithEmailAndPasswordMutation.ts","../src/hooks/managedIdentity/useRegisterWithEmailAndPasswordMutation.ts","../src/hooks/managedIdentity/useRegisterViaRegistrationFormMutation.ts","../src/hooks/managedIdentity/useChangePasswordMutation.ts","../src/hooks/managedIdentity/useResetPasswordMutation.ts","../src/hooks/managedIdentity/useVerifyPasswordResetCodeMutation.ts","../src/hooks/graphql/Refresh.ts","../src/hooks/useDeepEffect.ts","../src/hooks/graphql/useLazyQuery.ts","../src/hooks/managedIdentity/useManagedIdentitySessionQuery.ts","../src/hooks/managedIdentity/useVerifyEmailMutation.ts","../src/hooks/managedIdentity/useRequestPasswordResetEmailMutation.ts","../src/hooks/managedIdentity/useRequestVerificationEmailMutation.ts","../src/hooks/instantaccess/useAuthenticateManagedIdentityWithInstantAccess.ts","../src/hooks/useDeepMemo.ts","../src/hooks/useTick.ts","../src/hooks/graphql/useQuery.ts","../node_modules/lit-html/lib/template.js","../node_modules/lit-html/lib/template-result.js","../node_modules/lit-html/lib/parts.js","../node_modules/lit-html/lit-html.js","../node_modules/haunted/lib/interface.js","../node_modules/haunted/lib/symbols.js","../node_modules/haunted/lib/scheduler.js","../node_modules/haunted/lib/hook.js","../node_modules/haunted/lib/create-effect.js","../node_modules/haunted/lib/use-effect.js","../node_modules/haunted/lib/use-context.js","../node_modules/haunted/lib/use-memo.js","../node_modules/haunted/lib/use-layout-effect.js","../node_modules/haunted/lib/use-state.js","../node_modules/haunted/lib/use-reducer.js","../node_modules/ms/index.js","../node_modules/debug/src/common.js","../node_modules/debug/src/browser.js","../node_modules/@saasquatch/stencil-hooks/build/stencil-hooks.module.js","../node_modules/@stencil/core/internal/client/index.js","../src/hooks/useParentState.ts","../src/hooks/graphql/useParentQuery.ts","../src/hooks/useNavigation.ts","../src/hooks/pagination/usePagination.ts","../src/hooks/pagination/usePaginatedQuery.ts","../src/hooks/useDebounce.ts","../src/hooks/useShareEvent.ts","../src/hooks/useLoadEvent.ts","../src/hooks/useForm.ts"],"sourcesContent":["const ref = { current: undefined };\n\nexport function useHost(): HTMLElement {\n if (ref.current === undefined) {\n throw new Error(\"no implementation of useHost provided\");\n }\n\n return ref.current();\n}\n\nexport function setImplementation(implementation: () => HTMLElement) {\n if (!implementation) {\n throw new Error(\"Must supply an implementation\");\n }\n\n if (typeof implementation !== \"function\") {\n throw new Error(\"implementation must be a function\");\n }\n\n ref.current = implementation;\n}","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport {\n LOCALE_CONTEXT_NAME,\n lazilyStartLocaleContext,\n} from \"@saasquatch/component-environment\";\nimport { useHost } from \"../useHost\";\n\nexport function useLocale(): string | undefined {\n lazilyStartLocaleContext();\n const host = useHost();\n return useDomContext<string>(host, LOCALE_CONTEXT_NAME);\n}\n","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport {\n PROGRAM_CONTEXT_NAME,\n lazilyStartProgramContext,\n} from \"@saasquatch/component-environment\";\nimport { useHost } from \"../useHost\";\n\nexport function useProgramId(): string | undefined {\n lazilyStartProgramContext();\n const host = useHost();\n return useDomContext<string>(host, PROGRAM_CONTEXT_NAME);\n}\n","import { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport { useHost } from \"../useHost\";\nimport {\n UserIdentity,\n USER_CONTEXT_NAME,\n lazilyStartUserContext,\n setUserIdentity,\n userIdentityFromJwt,\n isDemo,\n} from \"@saasquatch/component-environment\";\n\n/**\n * Gets the SessionData of the current user, or undefined if logged out\n */\nexport function useSessionData(): { [key: string]: any } | undefined {\n return useUserIdentity()?.managedIdentity?.sessionData;\n}\n\n/**\n * Gets the JWT of the current user, or undefined if logged out\n */\nexport function useToken(): string | undefined {\n return useUserIdentity()?.jwt;\n}\n\n/**\n * Get the IDs and JWT of the current user, or undefined if logged out\n */\nexport function useUserIdentity(): UserIdentity | undefined {\n lazilyStartUserContext();\n const host = useHost();\n const identity = useDomContext(host, USER_CONTEXT_NAME) as\n | UserIdentity\n | undefined;\n\n const validIdentity = userIdentityFromJwt(identity?.jwt);\n if (!isDemo() && identity && !validIdentity) {\n // Likely that the JWT has expired\n setUserIdentity(undefined);\n return undefined;\n }\n return identity;\n}\n","import {\n getTenantAlias,\n getAppDomain,\n getEngagementMedium,\n} from \"@saasquatch/component-environment\";\n\n// Aliases to function in component-environment to maintain a backwards-compatible API\nexport const useTenantAlias = getTenantAlias;\nexport const useAppDomain = getAppDomain;\nexport const useEngagementMedium = getEngagementMedium;\n\nexport {\n getEnvironmentSDK,\n setUserIdentity,\n setProgramId,\n isDemo,\n DecodedSquatchJWT,\n} from \"@saasquatch/component-environment\";\n\nexport * from \"./useLocale\";\nexport * from \"./useProgramId\";\nexport * from \"./useUserIdentity\";\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n var seenKeys = new Set();\n var definitions = [];\n ast.definitions.forEach(function (fragmentDefinition) {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n var sourceKeySet = fragmentSourceMap.get(fragmentName);\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n if (printFragmentWarnings) {\n console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n }\n }\n else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n sourceKeySet.add(sourceKey);\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n }\n else {\n definitions.push(fragmentDefinition);\n }\n });\n return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n var workSet = new Set(doc.definitions);\n workSet.forEach(function (node) {\n if (node.loc)\n delete node.loc;\n Object.keys(node).forEach(function (key) {\n var value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n var loc = doc.loc;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n return doc;\n}\nfunction parseDocument(source) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n var parsed = parse(source, {\n experimentalFragmentVariables: experimentalFragmentVariables\n });\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n }\n return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (typeof literals === 'string') {\n literals = [literals];\n }\n var result = literals[0];\n args.forEach(function (arg, i) {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n }\n else {\n result += arg;\n }\n result += literals[i + 1];\n });\n return parseDocument(result);\n}\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\nvar extras = {\n gql: gql,\n resetCaches: resetCaches,\n disableFragmentWarnings: disableFragmentWarnings,\n enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","import { Subject } from \"rxjs\";\nimport { bufferTime } from \"rxjs/operators\";\nimport { nanoid } from \"nanoid\";\nimport { ClientError, RequestDocument } from \"graphql-request/dist/types\";\nimport { GraphQLClient } from \"graphql-request\";\nimport { print, parse, DocumentNode } from \"graphql\";\n\nimport combineQuery, {\n CombinedQueryBuilder,\n NewCombinedQueryBuilder,\n} from \"graphql-combine-query\";\n\n/*************\n * constants *\n *************/\nconst MAX_REQUESTS = 10;\nconst REQUEST_INTERVAL = 200; //ms\n\nexport class BatchedGraphQLClient extends GraphQLClient {\n subject = new Subject();\n\n constructor(url: string, opts?: any) {\n super(url, opts);\n\n const unmergable = new Subject();\n const buffer = this.subject.pipe(\n bufferTime(REQUEST_INTERVAL, undefined, MAX_REQUESTS)\n );\n\n // look into replacing subscribe\n buffer.subscribe(async (queryAddedEvents: QueryAddedEvent[]) => {\n // no requests in the last REQUEST_INTERVAL ms\n if (!queryAddedEvents.length) {\n return;\n }\n // merge the requests\n const {\n mergedQuery,\n mergedVariables,\n mergedQueryAddedEvents,\n unmergedQueryAddedEvents,\n } = mergeQueryAddedEvents(queryAddedEvents);\n\n // push queries that failed to merge to a separate stream to be processed\n for (const unmergedQuery of unmergedQueryAddedEvents)\n unmergable.next(unmergedQuery);\n\n // If there are no merged queries, all were unmergeable and we can exit here\n if (!mergedQueryAddedEvents.length) {\n return;\n }\n\n try {\n // make the request\n const mergedQueryResult = await this.superRequest(\n mergedQuery,\n mergedVariables\n );\n //resolve the results\n resolveMergedQueryResult(mergedQueryResult, mergedQueryAddedEvents);\n } catch (e) {\n // So, there is possibly both data and errors here.\n if (e instanceof ClientError) {\n const { data, errors } = e.response;\n if (!data) {\n return rejectAllQueryAddedEventsWithError(\n mergedQueryAddedEvents,\n e\n );\n }\n const aliases = Object.keys(data);\n let eventsToResolve = [...mergedQueryAddedEvents];\n // reject all that errored:\n for (const error of errors) {\n let erroredEvent: QueryAddedEvent;\n // todo: this needs testing, is path going to work??\n error.path.find((key, index, path) => {\n if (aliases.includes(key)) {\n const erroredId = getIdFromAliasedField(key);\n const indexOfErroredEvent = eventsToResolve.findIndex(\n (event) => event.id === erroredId\n );\n if (indexOfErroredEvent === -1) return false;\n // remove from aliases\n aliases.splice(index, 1);\n // remove from events\n erroredEvent = eventsToResolve.splice(\n indexOfErroredEvent,\n 1\n )[0];\n // rebuild data\n const eventSpecificData = removeAliasesFromDataResult(\n e.response.data,\n erroredEvent\n );\n // fix path\n path[index] = removeAliasFromField(path[index], erroredId);\n const { query, variables } = erroredEvent;\n // rebuild error to be event specific\n const errorResponse = {\n ...e.response,\n errors: [error],\n data: eventSpecificData,\n path,\n };\n const newError = new ClientError(errorResponse, {\n query: typeof query !== \"string\" ? print(query) : query,\n variables,\n });\n rejectQueryAddedEventWithError(erroredEvent, newError);\n return true;\n }\n return false;\n });\n }\n // resolve the rest:\n resolveMergedQueryResult(data, eventsToResolve);\n } else rejectAllQueryAddedEventsWithError(mergedQueryAddedEvents, e);\n }\n });\n\n //process unmergable requests as they come in\n unmergable.subscribe(async (event: QueryAddedEvent) => {\n try {\n const { query, variables } = event;\n const result = await this.superRequest(query, variables);\n resolveSingleQueryResult(result, event);\n } catch (e) {\n rejectQueryAddedEventWithError(event, e);\n }\n });\n }\n\n superRequest<T>(query: RequestDocument, variables?: any) {\n return super.request<T>(query, variables);\n }\n\n request<T>(query, variables) {\n return new Promise<T>((resolve, reject) => {\n const queryAddedEvent: QueryAddedEvent = {\n query,\n variables,\n id: generateQueryAddedEventId(),\n resolve,\n reject,\n };\n this.subject.next(queryAddedEvent);\n });\n }\n}\n\n/*************\n * types *\n *************/\n\ninterface QueryAddedEvent {\n query: RequestDocument;\n variables: { [key: string]: unknown };\n id: string; // nanoid with '-'s removed\n resolve: (data: any) => void;\n reject: (err: any) => void;\n}\n\ninterface MergedQueryAddedEvents {\n mergedQuery?: RequestDocument;\n mergedVariables?: { [key: string]: unknown };\n mergedQueryAddedEvents: QueryAddedEvent[];\n unmergedQueryAddedEvents: QueryAddedEvent[];\n}\n\n/*************\n * utils *\n *************/\n// Remove dashes and underscores from alias\nconst generateQueryAddedEventId = () => nanoid().replace(/[-_]/g, \"\");\n\n// Numbers not allowed in graphQL alias, so ID must be added to the end\nconst aliasFieldOrVariableFn = (name, id) => `${name}_${id}`;\n\n// ID will always be at the end of the alias separated by a single \"_\"\nconst removeAliasFromField = (field: string, id: string) =>\n field.replace(`_${id}`, \"\");\n\nconst getIdFromAliasedField = (field: string): string => {\n const fieldArray = field.split(\"_\");\n return fieldArray[fieldArray.length - 1];\n};\n\nconst mergeQueryAddedEvents = (\n events: QueryAddedEvent[]\n): MergedQueryAddedEvents => {\n const mergedQueryAddedEvents = [];\n const unmergedQueryAddedEvents = [];\n const { document, variables } = events.reduce(\n (\n acc: NewCombinedQueryBuilder | CombinedQueryBuilder,\n curr: QueryAddedEvent\n ): NewCombinedQueryBuilder | CombinedQueryBuilder => {\n const { query, variables, id } = curr;\n try {\n const parsedQuery: DocumentNode =\n typeof query === \"string\" ? parse(query) : query;\n // if fragment exists, this request should be processed separately\n const fragmentDefinition = parsedQuery.definitions.find(\n (node) => node.kind === \"FragmentDefinition\"\n );\n // '@' is reserved for directives, and since both top level and nested directives are broken, we dont want any.\n const queryStr = typeof query === \"string\" ? query : print(query);\n const containsDirective = /@/.test(queryStr);\n\n if (fragmentDefinition || containsDirective) {\n unmergedQueryAddedEvents.push(curr);\n return acc;\n }\n\n const renameFn = (name) => aliasFieldOrVariableFn(name, id);\n // if this fails, event will be added to unmergedQueryAddedEvents\n acc = acc.addN(parsedQuery, [variables], renameFn, renameFn);\n mergedQueryAddedEvents.push(curr);\n return acc;\n } catch (e) {\n unmergedQueryAddedEvents.push(curr);\n return acc;\n }\n },\n combineQuery(\"BatchedQuery\")\n ) as CombinedQueryBuilder;\n\n const mergedQuery = document && print(document);\n const mergedVariables = variables;\n\n return {\n mergedQuery,\n mergedVariables,\n mergedQueryAddedEvents,\n unmergedQueryAddedEvents,\n };\n};\n\nconst removeAliasesFromDataResult = (\n queryResult: any,\n event: QueryAddedEvent\n) => {\n if (!queryResult) return queryResult;\n const aliases = Object.keys(queryResult);\n const { id } = event;\n return aliases.reduce((data, key) => {\n if (key.endsWith(id)) {\n data = {\n ...data,\n [removeAliasFromField(key, id)]: queryResult[key],\n };\n }\n return data;\n }, {});\n};\n\nconst resolveSingleQueryResult = (queryResult: any, event: QueryAddedEvent) => {\n const { resolve } = event;\n resolve(queryResult);\n};\n\nconst resolveMergedQueryResult = (\n mergedQueryResult: any,\n events: QueryAddedEvent[]\n): void => {\n for (const event of events) {\n //figure out what data we need\n const data = removeAliasesFromDataResult(mergedQueryResult, event);\n event.resolve(data);\n }\n};\n\nconst rejectQueryAddedEventWithError = (\n event: QueryAddedEvent,\n err: Error\n): void => {\n const { reject } = event;\n reject(err);\n};\n\nconst rejectAllQueryAddedEventsWithError = (\n events: QueryAddedEvent[],\n err: Error\n): void => {\n for (const event of events) {\n const { reject } = event;\n reject(err);\n }\n};\n","import memoize from \"fast-memoize\";\nimport { BatchedGraphQLClient } from \"../../BatchedGraphQLClient\";\nimport { useAppDomain, useTenantAlias, useToken } from \"../environment\";\nimport { useDomContext } from \"@saasquatch/dom-context-hooks\";\nimport { useHost } from \"../useHost\";\nimport { GraphQLClient } from \"graphql-request\";\n\nexport const GRAPHQL_CONTEXT = \"sq:graphql-client\";\n\nfunction createGraphQlClient(\n appDomain: string,\n tenantAlias: string,\n token?: string\n): GraphQLClient {\n const uri = appDomain + \"/api/v1/\" + tenantAlias + \"/graphql\";\n const headers = {\n Authorization: `Bearer ${token || \"\"}`,\n };\n const newClient = new BatchedGraphQLClient(uri, {\n headers,\n });\n return newClient;\n}\n\nexport const memoizedGraphQLClient = memoize(createGraphQlClient);\n\nfunction useGraphQLClient(): GraphQLClient {\n const token = useToken();\n const appDomain = useAppDomain();\n const tenantAlias = useTenantAlias();\n\n // Memoization is shared. One client per domain, tenant and token (or null)\n const localClient: GraphQLClient = memoizedGraphQLClient(\n appDomain,\n tenantAlias,\n token\n );\n const host = useHost();\n const clientFromContext = useDomContext<GraphQLClient>(\n host,\n GRAPHQL_CONTEXT,\n // Won't poll / re-attempt\n { attempts: 0 }\n );\n return clientFromContext ?? localClient;\n}\n\nexport default useGraphQLClient;\n","import {\n useCallback,\n useEffect,\n useReducer,\n useRef,\n} from \"@saasquatch/universal-hooks\";\nimport useGraphQLClient from \"./useGraphQLClient\";\nimport { RequestDocument } from \"graphql-request/dist/types\";\nimport { GraphQLClient } from \"graphql-request\";\n\nexport type GqlType = RequestDocument;\n\nexport interface BaseQueryData<T = unknown> {\n loading: boolean;\n data?: T;\n errors?: GraphQlRequestError<T>;\n}\n\nexport type QueryData<T> = BaseQueryData<T> & {\n refetch: (variables?: unknown) => Promise<T | Error>;\n};\n\n/**\n * Note: reverse-engineered from a returned error. May not capture all error types.\n */\n\nexport type GraphQlRequestError<T> = {\n response: {\n errors: [\n {\n message: string;\n locations: [{ line: number; column: number }];\n path: string[];\n extensions: {\n apiError: {\n message: string;\n statusCode: number;\n apiErrorCode: string;\n rsCode: string;\n };\n classification: string;\n // V managed identity extensions V\n message?: string;\n code?: string;\n };\n }\n ];\n data: Partial<T>;\n status: number;\n };\n request: {\n query: string;\n variables: { [key: string]: unknown };\n };\n message?: string;\n};\n\ntype Action<T> =\n | {\n type: \"loading\";\n }\n | {\n type: \"data\";\n payload?: T;\n }\n | {\n type: \"errors\";\n payload: GraphQlRequestError<T>;\n };\n\nfunction reducer<T>(\n // @ts-ignore = unused\n state: BaseQueryData<T>,\n action: Action<T>\n): BaseQueryData<T> {\n switch (action.type) {\n case \"loading\":\n return { data: undefined, errors: undefined, loading: true };\n case \"data\":\n return { data: action.payload, errors: undefined, loading: false };\n case \"errors\":\n return { data: undefined, errors: action.payload, loading: false };\n }\n}\n\nexport function useBaseQuery<T = any>(\n query: GqlType,\n initialState: BaseQueryData<T>\n): [\n BaseQueryData<T>,\n (variables: unknown, skipLoading?: boolean) => Promise<T | Error>\n] {\n const client: GraphQLClient = useGraphQLClient();\n const [state, dispatch] = useReducer<BaseQueryData<T>, Action<T>>(\n reducer,\n initialState\n );\n const update = useCallback(\n async function (variables: unknown, skipLoading = false) {\n if (!client) {\n const error = new Error(\"No GraphQL client found\");\n // Hook will return an error state when no client exists (used to be a loading state)\n dispatch({\n type: \"errors\",\n // @ts-expect-error -- Need to fix this\n payload: error,\n });\n return error;\n }\n try {\n // Skips showing a \"loading\" state before the data appears\n if (!skipLoading) dispatch({ type: \"loading\" });\n const res = await client.request<T>(query, variables);\n dispatch({ type: \"data\", payload: res });\n return res;\n } catch (error) {\n dispatch({ type: \"errors\", payload: error });\n return error;\n }\n },\n [client, query, dispatch]\n );\n\n return [state, update];\n}\n","import { BaseQueryData, GqlType, useBaseQuery } from \"./useBaseQuery\";\n\nconst initialMutationState: BaseQueryData = {\n loading: false,\n data: undefined,\n errors: undefined,\n} as const;\n\nexport function useMutation<T = any>(\n query: GqlType\n): [(e: unknown) => Promise<T | Error>, BaseQueryData<T>] {\n const [state, update] = useBaseQuery<T>(\n query,\n initialMutationState as BaseQueryData<T>\n );\n return [update, state];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst AuthenticateWithEmailAndPasswordMutation = gql`\n mutation AuthenticateWithEmailAndPassword(\n $email: String!\n $password: String!\n ) {\n authenticateManagedIdentityWithEmailAndPassword(\n authenticateManagedIdentityWithEmailAndPasswordInput: {\n email: $email\n password: $password\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface AuthenticateWithEmailAndPasswordResult {\n authenticateManagedIdentityWithEmailAndPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useAuthenticateWithEmailAndPasswordMutation(): [\n (variables: {\n email: string;\n password: string;\n }) => Promise<AuthenticateWithEmailAndPasswordResult | Error>,\n BaseQueryData<AuthenticateWithEmailAndPasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<AuthenticateWithEmailAndPasswordResult>(\n AuthenticateWithEmailAndPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n email: string;\n password: string;\n }) => {\n const result = await request(v);\n if (\n !(result instanceof Error) &&\n result.authenticateManagedIdentityWithEmailAndPassword\n ) {\n const jwt = result.authenticateManagedIdentityWithEmailAndPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.authenticateManagedIdentityWithEmailAndPassword.email,\n emailVerified:\n result.authenticateManagedIdentityWithEmailAndPassword\n .emailVerified,\n sessionData:\n result.authenticateManagedIdentityWithEmailAndPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RegisterWithEmailAndPasswordMutation = gql`\n mutation RegisterWithEmailAndPassword(\n $email: String!\n $password: String!\n $formData: RSJsonNode\n $redirectPath: String\n ) {\n registerManagedIdentityWithEmailAndPassword(\n registerManagedIdentityWithEmailAndPasswordInput: {\n email: $email\n password: $password\n formData: $formData\n redirectPath: $redirectPath\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface RegisterWithEmailAndPasswordResult {\n registerManagedIdentityWithEmailAndPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useRegisterWithEmailAndPasswordMutation(): [\n (variables: {\n email: string;\n password: string;\n formData?: Record<string, any>;\n }) => Promise<RegisterWithEmailAndPasswordResult | Error>,\n BaseQueryData<RegisterWithEmailAndPasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<RegisterWithEmailAndPasswordResult>(\n RegisterWithEmailAndPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n email: string;\n password: string;\n formData?: Record<string, any>;\n }) => {\n const result = await request(v);\n if (\n !(result instanceof Error) &&\n result.registerManagedIdentityWithEmailAndPassword\n ) {\n const jwt = result.registerManagedIdentityWithEmailAndPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.registerManagedIdentityWithEmailAndPassword.email,\n emailVerified:\n result.registerManagedIdentityWithEmailAndPassword.emailVerified,\n sessionData:\n result.registerManagedIdentityWithEmailAndPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect, useState } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport {\n setUserIdentity,\n DecodedSquatchJWT,\n} from \"@saasquatch/component-environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RegisterViaRegistrationFormMutation = gql`\n mutation RegisterViaRegistrationForm($key: String!, $formData: RSJsonNode!) {\n submitForm(formSubmissionInput: { key: $key, formData: $formData }) {\n results {\n ... on FormHandlerSubmissionResult {\n result\n formHandler {\n namespace\n }\n }\n ... on FormHandlerError {\n errorCode\n error\n errorType\n formHandler {\n name\n endpointUrl\n }\n }\n }\n }\n }\n`;\n\ntype RegistrationResult =\n | {\n success: true;\n message: string;\n data: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n }\n | {\n success: false;\n message: string;\n };\n\ninterface RegisterViaRegistrationFormResult {\n submitForm: {\n results: Array<{\n result: {\n results: Array<RegistrationResult>;\n };\n formHandler: {\n namespace: string;\n };\n }>;\n };\n}\ninterface RegistrationFormResponseData<T> extends BaseQueryData<T> {\n formError?: string;\n}\n\nexport function useRegisterViaRegistrationFormMutation(): [\n (variables: {\n key: string;\n formData: {\n email: string;\n password: string;\n redirectUrl?: string;\n [field: string]: any;\n };\n }) => Promise<RegisterViaRegistrationFormResult | Error>,\n RegistrationFormResponseData<RegisterViaRegistrationFormResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<RegisterViaRegistrationFormResult>(\n RegisterViaRegistrationFormMutation\n );\n const [formError, setFormError] = useState<string | null>(null);\n\n const requestAndSetUserIdentityOrFormError = async (v: {\n key: string;\n formData: {\n email: string;\n password: string;\n redirectUrl?: string;\n [field: string]: any;\n };\n }) => {\n setFormError(null);\n const result = await request(v);\n if (result instanceof Error) {\n return result;\n }\n const managedIdentityResponse:\n | undefined\n | RegisterViaRegistrationFormResult[\"submitForm\"][\"results\"][number] = result.submitForm?.results?.find(\n (result) => result?.formHandler?.namespace === \"identity\"\n );\n if (\n managedIdentityResponse &&\n managedIdentityResponse.result?.results?.length\n ) {\n const registrationResult = managedIdentityResponse.result.results[0];\n if (registrationResult.success) {\n // if success handle setUserIdentity\n const jwt = registrationResult.data.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: registrationResult.data.email,\n emailVerified: registrationResult.data.emailVerified,\n sessionData: registrationResult.data.sessionData,\n },\n });\n } else {\n // handle errors\n setFormError(registrationResult.message);\n }\n }\n return result;\n };\n\n return [\n requestAndSetUserIdentityOrFormError,\n { loading, data, errors, formError },\n ];\n}\n","import gql from \"graphql-tag\";\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst ChangePasswordMutation = gql`\n mutation ChangePassword($password: String!) {\n changeManagedIdentityPassword(\n changeManagedIdentityPasswordInput: { password: $password }\n ) {\n success\n }\n }\n`;\n\ninterface ChangePasswordResult {\n changeManagedIdentityPassword: {\n success: boolean;\n };\n}\n\nexport function useChangePasswordMutation(): [\n (variables: { password: string }) => Promise<ChangePasswordResult | Error>,\n BaseQueryData<ChangePasswordResult>\n] {\n const [request, { loading, data, errors }] =\n useMutation<ChangePasswordResult>(ChangePasswordMutation);\n\n return [request, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\nimport decode from \"jwt-decode\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { setUserIdentity, DecodedSquatchJWT } from \"../environment\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst ResetPasswordMutation = gql`\n mutation ResetPassword($oobCode: String!, $password: String!) {\n resetManagedIdentityPassword(\n resetManagedIdentityPasswordInput: {\n password: $password\n oobCode: $oobCode\n }\n ) {\n token\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface ResetPasswordResult {\n resetManagedIdentityPassword: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useResetPasswordMutation(): [\n (variables: {\n oobCode: string;\n password: string;\n }) => Promise<ResetPasswordResult | Error>,\n BaseQueryData<ResetPasswordResult>\n] {\n const [request, { loading, data, errors }] = useMutation<ResetPasswordResult>(\n ResetPasswordMutation\n );\n\n const requestAndSetUserIdentity = async (v: {\n oobCode: string;\n password: string;\n }) => {\n const result = await request(v);\n if (!(result instanceof Error) && result.resetManagedIdentityPassword) {\n const jwt = result.resetManagedIdentityPassword.token;\n const { user } = decode<DecodedSquatchJWT>(jwt);\n setUserIdentity({\n jwt,\n id: user.id,\n accountId: user.accountId,\n managedIdentity: {\n email: result.resetManagedIdentityPassword.email,\n emailVerified: result.resetManagedIdentityPassword.emailVerified,\n sessionData: result.resetManagedIdentityPassword.sessionData,\n },\n });\n }\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst VerifyPasswordResetCodeMutation = gql`\n mutation VerifyPasswordResetCode($oobCode: String!) {\n verifyManagedIdentityPasswordResetCode(\n verifyManagedIdentityPasswordResetCodeInput: { oobCode: $oobCode }\n ) {\n success\n }\n }\n`;\n\ninterface VerifyPasswordResetCodeResult {\n verifyManagedIdentityPasswordResetCode: {\n success: boolean;\n };\n}\n\nexport function useVerifyPasswordResetCodeMutation(): [\n (variables: {\n oobCode: string;\n }) => Promise<VerifyPasswordResetCodeResult | Error>,\n BaseQueryData<VerifyPasswordResetCodeResult>\n] {\n return useMutation<VerifyPasswordResetCodeResult>(\n VerifyPasswordResetCodeMutation\n );\n}\n","import { useCallback } from \"@saasquatch/universal-hooks\";\nimport { useDeepCompareEffect } from \"../useDeepEffect\";\nimport { useHost } from \"../useHost\";\n\nexport const REFRESH_EVENT_NAME = \"sq:refresh\";\n\nexport function useRefreshDispatcher() {\n const host = useHost();\n\n const refresh = useCallback(() => {\n host.dispatchEvent(\n new CustomEvent(REFRESH_EVENT_NAME, {\n bubbles: true,\n composed: true,\n cancelable: true,\n detail: {\n // Could add some \"scope\" for more granular refresh\n },\n })\n );\n }, [host]);\n\n return { refresh };\n}\n\nexport function useRefreshListener({\n skip = false,\n update,\n variables,\n}: {\n skip?: boolean;\n update: (variables: unknown, skipLoading?: boolean) => unknown;\n variables: unknown;\n}) {\n useDeepCompareEffect(() => {\n const listener = (e: CustomEvent) => {\n !skip && update(variables, true);\n };\n document.addEventListener(REFRESH_EVENT_NAME, listener);\n return () => document.removeEventListener(REFRESH_EVENT_NAME, listener);\n }, [variables, update, skip]);\n}\n","/*\n * Forked From: https://github.com/kentcdodds/use-deep-compare-effect/blob/main/src/index.ts\n *\n * The MIT License (MIT)\n * Copyright (c) 2020 Kent C. Dodds\n *\n */\n\nimport { useEffect, useRef, useMemo } from \"@saasquatch/universal-hooks\";\nimport { equal as deepEqual } from \"@wry/equality\";\n\ntype UseEffectParams = Parameters<typeof useEffect>;\ntype EffectCallback = UseEffectParams[0];\ntype DependencyList = UseEffectParams[1];\n// yes, I know it's void, but I like what this communicates about\n// the intent of these functions: It's just like useEffect\ntype UseEffectReturn = ReturnType<typeof useEffect>;\n\n\n/**\n * @param value the value to be memoized (usually a dependency list)\n * @returns a memoized version of the value as long as it remains deeply equal\n */\nexport function useDeepCompareMemoize<T>(value: T) {\n const ref = useRef<T>(value);\n const signalRef = useRef<number>(0);\n\n if (!deepEqual(value, ref.current)) {\n ref.current = value;\n signalRef.current += 1;\n }\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => ref.current, [signalRef.current]);\n}\n\nexport function useDeepCompareEffect(\n callback: EffectCallback,\n dependencies: DependencyList\n): UseEffectReturn {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useEffect(callback, useDeepCompareMemoize(dependencies));\n}\n\nexport default useDeepCompareEffect;\n","import { useRef, useCallback } from \"@saasquatch/universal-hooks\";\nimport { useRefreshListener } from \"./Refresh\";\nimport {\n BaseQueryData,\n GqlType,\n QueryData,\n useBaseQuery,\n} from \"./useBaseQuery\";\n\nconst initialLazyQueryState: BaseQueryData = {\n loading: false,\n data: undefined,\n errors: undefined,\n} as const;\n\nconst NOTLOADED = Symbol();\nexport function useLazyQuery<T = any>(\n query: GqlType\n): [(e: unknown) => Promise<T | Error>, QueryData<T>] {\n const [state, update] = useBaseQuery<T>(\n query,\n initialLazyQueryState as BaseQueryData<T>\n );\n\n const variablesRef = useRef<unknown>(NOTLOADED);\n // To preserve laziness, this query will not refresh if the query has not already been run at least once\n const skip = variablesRef.current === NOTLOADED;\n useRefreshListener({\n skip,\n update,\n variables: variablesRef.current,\n });\n\n // can override props when refetching for new pagination, offset, etc\n const refetch = useCallback(\n (variables) => {\n variablesRef.current = variables;\n return update(variables);\n },\n [update]\n );\n\n return [\n update,\n {\n ...state,\n refetch,\n },\n ];\n}\n","import gql from \"graphql-tag\";\n\nimport { QueryData } from \"../graphql/useBaseQuery\";\nimport { useUserIdentity, setUserIdentity } from \"../environment\";\nimport { useLazyQuery } from \"../graphql/useLazyQuery\";\n\nconst ManagedIdentitySessionQuery = gql`\n query ManagedIdentitySession {\n managedIdentitySession {\n email\n emailVerified\n sessionData\n }\n }\n`;\n\ninterface ManagedIdentitySessionResult {\n managedIdentitySession: {\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nexport function useManagedIdentitySessionQuery(): [\n () => Promise<ManagedIdentitySessionResult | Error>,\n QueryData<ManagedIdentitySessionResult>\n] {\n const userIdentity = useUserIdentity();\n const [request, { loading, data, errors, refetch }] =\n useLazyQuery<ManagedIdentitySessionResult>(ManagedIdentitySessionQuery);\n\n const updateUserIdentity = (result: ManagedIdentitySessionResult | Error) => {\n if (!(result instanceof Error) && result.managedIdentitySession) {\n setUserIdentity({\n ...userIdentity,\n managedIdentity: result.managedIdentitySession,\n });\n }\n };\n\n const requestAndSetUserIdentity = async () => {\n const result = await request({});\n updateUserIdentity(result);\n return result;\n };\n\n const refetchAndSetUserIdentity = async () => {\n const result = await refetch();\n updateUserIdentity(result);\n return result;\n };\n\n return [\n requestAndSetUserIdentity,\n { loading, data, errors, refetch: refetchAndSetUserIdentity },\n ];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\nimport { useManagedIdentitySessionQuery } from \"./useManagedIdentitySessionQuery\";\n\nconst VerifyEmailMutation = gql`\n mutation VerifyEmail($oobCode: String!) {\n verifyManagedIdentityEmail(\n verifyManagedIdentityEmailInput: { oobCode: $oobCode }\n ) {\n success\n }\n }\n`;\n\ninterface VerifyEmailResult {\n verifyManagedIdentityEmail: {\n success: boolean;\n };\n}\n\nexport function useVerifyEmailMutation(): [\n (e: { oobCode: string }) => Promise<VerifyEmailResult | Error>,\n BaseQueryData<VerifyEmailResult>\n] {\n const [refreshManagedIdentitySession] = useManagedIdentitySessionQuery();\n const [request, { loading, data, errors }] =\n useMutation<VerifyEmailResult>(VerifyEmailMutation);\n\n const requestAndRefreshManagedIdentitySession = async (e: {\n oobCode: string;\n }) => {\n const result = await request(e);\n if (\n !(result instanceof Error) &&\n result.verifyManagedIdentityEmail.success\n ) {\n await refreshManagedIdentitySession();\n }\n return result;\n };\n\n return [requestAndRefreshManagedIdentitySession, { loading, data, errors }];\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RequestPasswordResetEmailMutation = gql`\n mutation RequestPasswordResetEmail(\n $email: String!\n $urlParams: RSJsonNode\n $redirectPath: String\n ) {\n requestManagedIdentityPasswordResetEmail(\n requestManagedIdentityPasswordResetEmailInput: {\n email: $email\n urlParams: $urlParams\n redirectPath: $redirectPath\n }\n ) {\n success\n }\n }\n`;\n\ninterface RequestPasswordResetEmailResult {\n requestManagedIdentityPasswordResetEmail: {\n success: boolean;\n };\n}\n\nexport function useRequestPasswordResetEmailMutation(): [\n (variables: {\n email: string;\n urlParams?: Record<string, any>;\n }) => Promise<RequestPasswordResetEmailResult | Error>,\n BaseQueryData<RequestPasswordResetEmailResult>\n] {\n return useMutation<RequestPasswordResetEmailResult>(\n RequestPasswordResetEmailMutation\n );\n}\n","import gql from \"graphql-tag\";\n\nimport { BaseQueryData } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\n\nconst RequestVerificationEmailMutation = gql`\n mutation RequestVerificationEmail(\n $email: String!\n $urlParams: RSJsonNode\n $redirectPath: String\n ) {\n requestManagedIdentityVerificationEmail(\n requestManagedIdentityVerificationEmailInput: {\n email: $email\n urlParams: $urlParams\n redirectPath: $redirectPath\n }\n ) {\n success\n }\n }\n`;\n\ninterface RequestVerificationEmailResult {\n requestManagedIdentityVerificationEmail: {\n success: boolean;\n };\n}\n\nexport function useRequestVerificationEmailMutation(): [\n (variables: {\n email: string;\n urlParams?: Record<string, any>;\n }) => Promise<RequestVerificationEmailResult | Error>,\n BaseQueryData<RequestVerificationEmailResult>\n] {\n return useMutation<RequestVerificationEmailResult>(\n RequestVerificationEmailMutation\n );\n}\n","import {\n getAppDomain,\n getEnvironment,\n getTenantAlias,\n setUserIdentity,\n} from \"@saasquatch/component-environment\";\nimport gql from \"graphql-tag\";\nimport { BaseQueryData, useBaseQuery } from \"../graphql/useBaseQuery\";\nimport { useMutation } from \"../graphql/useMutation\";\nimport { useProgramId } from \"../environment\";\n\ninterface AuthenticateManagedIdentityWithInstantAccessVariables {\n email: string;\n firstName: string;\n lastName: string;\n locale: string;\n countryCode: string;\n cookies: string;\n}\n\ninterface AuthenticateManagedIdentityWithInstantAccessResult {\n authenticateManagedIdentityWithInstantAccess: {\n token: string;\n email: string;\n emailVerified: boolean;\n sessionData: Record<string, any>;\n };\n}\n\nconst AuthenticateManagedIdentityWithInstantAccessMutation = gql`\n mutation authenticateManagedIdentityWithInstantAccess(\n $email: String!\n $firstName: String\n $lastName: String\n $locale: RSLocale\n $countryCode: RSCountryCode\n $cookies: String\n ) {\n authenticateManagedIdentityWithInstantAccess(\n authenticateManagedIdentityWithInstantAccessInput: {\n email: $email\n firstName: $firstName\n lastName: $lastName\n locale: $locale\n countryCode: $countryCode\n cookies: $cookies\n }\n ) {\n email\n emailVerified\n sessionData\n token\n }\n }\n`;\n\nconst CheckReferralFraudStatusQuery = `\n query checkReferralFraudStatus($programId: ID) {\n viewer {\n ... on User {\n id\n instantAccessRewards(filter: { programId_eq: $programId }) {\n data {\n id\n pendingReasons\n cancelledReason\n }\n }\n }\n }\n }\n`;\n\nasync function fetchFraud(programId: string, jwt: string) {\n try {\n const result = await fetch(\n `${getAppDomain()}/api/v1/${getTenantAlias()}/graphql`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${jwt}`,\n },\n body: JSON.stringify({\n query: CheckReferralFraudStatusQuery,\n variables: {\n programId,\n },\n }),\n }\n );\n\n if (!result.ok) {\n throw new Error(\"Failed to fetch locale\");\n }\n\n const json = await result.json();\n if (json.errors) {\n throw new Error(JSON.stringify(json.errors, null, 2));\n }\n\n const results = (json as any).data.viewer.instantAccessRewards?.data || [];\n if (results.some((r) => r.cancelledReason === \"SUSPECTED_FRAUD\"))\n return \"DENIED\";\n else if (results.some((r) => r.pendingReasons?.includes(\"SUSPECTED_FRAUD\")))\n return \"PENDING_REVIEW\";\n else return \"APPROVED\";\n } catch (e) {\n console.error(e);\n return undefined;\n }\n}\n\nexport function useAuthenticateManagedIdentityWithInstantAccess(): [\n (\n e: unknown\n ) => Promise<AuthenticateManagedIdentityWithInstantAccessResult | Error>,\n BaseQueryData<AuthenticateManagedIdentityWithInstantAccessResult>\n] {\n const programId = useProgramId();\n const env = getEnvironment();\n\n const [request, { loading, data, errors }] =\n useMutation<AuthenticateManagedIdentityWithInstantAccessResult>(\n AuthenticateManagedIdentityWithInstantAccessMutation\n );\n\n const requestAndSetUserIdentity = async (\n variables: AuthenticateManagedIdentityWithInstantAccessVariables\n ) => {\n const result = await request(variables);\n\n if (\n !(result instanceof Error) &&\n result.authenticateManagedIdentityWithInstantAccess\n ) {\n const fraudStatus = await fetchFraud(\n programId,\n result.authenticateManagedIdentityWithInstantAccess.token\n );\n\n if (fraudStatus === \"APPROVED\") {\n const jwt = result.authenticateManagedIdentityWithInstantAccess.token;\n const email = result.authenticateManagedIdentityWithInstantAccess.email;\n\n setUserIdentity({\n jwt,\n id: email,\n accountId: email,\n });\n\n // If in squatch-js, fire a sq:user-registered event\n if (env === \"SquatchJS2\") {\n const event = new CustomEvent(\"sq:user-registration\", {\n bubbles: true,\n detail: {\n userId: email,\n accountId: email,\n },\n });\n\n document.dispatchEvent(event);\n }\n } else {\n throw {\n name: \"fraud_error\",\n message: \"Referral flagged as fraud.\",\n };\n }\n }\n\n return result;\n };\n\n return [requestAndSetUserIdentity, { loading, data, errors }];\n}\n","import { equal } from \"@wry/equality\";\nimport { useRef } from \"@saasquatch/universal-hooks\";\n\nexport function useDeepMemo<TKey, TValue>(\n memoFn: () => TValue,\n key: TKey\n): TValue {\n //@ts-ignore\n const ref = useRef<{ key: TKey; value: TValue }>();\n\n if (!ref.current || !equal(key, ref.current.key)) {\n ref.current = { key, value: memoFn() };\n }\n\n return ref.current.value;\n}\n","import { useReducer } from \"@saasquatch/universal-hooks\";\n\nexport function useTick(): readonly [number, () => unknown] {\n //@ts-expect-error -- bad typing on callback\n return useReducer<number, number, number>((x) => x + 1, 0);\n}\n","import { useDeepMemo } from \"../useDeepMemo\";\nimport { useTick } from \"../useTick\";\nimport { useRefreshListener } from \"./Refresh\";\nimport {\n BaseQueryData,\n GqlType,\n QueryData,\n useBaseQuery,\n} from \"./useBaseQuery\";\n\n// from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\nfunction deepFreeze(object) {\n // Retrieve the property names defined on object\n const propNames = Object.getOwnPropertyNames(object);\n\n // Freeze properties before freezing self\n\n for (const name of propNames) {\n const value = object[name];\n\n if (value && typeof value === \"object\") {\n deepFreeze(value);\n }\n }\n\n return Object.freeze(object);\n}\n\nexport const initialQueryState: BaseQueryData = {\n loading: true,\n data: undefined,\n errors: undefined,\n} as const;\n\nexport function useQuery<T = any>(\n query: GqlType,\n variables: unknown,\n skip?: boolean\n): QueryData<T> {\n const [state, update] = useBaseQuery<T>(\n query,\n initialQueryState as BaseQueryData<T>\n );\n\n const [tick, forceUpdate] = useTick();\n\n useDeepMemo(() => {\n !skip && update(variables);\n }, [query, variables, update, tick, skip]);\n\n useRefreshListener({ skip, update, variables });\n\n return deepFreeze({\n ...state,\n // can override props when refetching for new pagination, offset, etc\n refetch: forceUpdate,\n });\n}\n","/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\n/**\n * An expression marker with embedded unique key to avoid collision with\n * possible text in templates.\n */\nexport const marker = `{{lit-${String(Math.random()).slice(2)}}}`;\n/**\n * An expression marker used text-positions, multi-binding attributes, and\n * attributes with markup-like text values.\n */\nexport const nodeMarker = `<!--${marker}-->`;\nexport const markerRegex = new RegExp(`${marker}|${nodeMarker}`);\n/**\n * Suffix appended to all bound attribute names.\n */\nexport const boundAttributeSuffix = '$lit$';\n/**\n * An updatable Template that tracks the location of dynamic parts.\n */\nexport class Template {\n constructor(result, element) {\n this.parts = [];\n this.element = element;\n const nodesToRemove = [];\n const stack = [];\n // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null\n const walker = document.createTreeWalker(element.content, 133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */, null, false);\n // Keeps track of the last index associated with a part. We try to delete\n // unnecessary nodes, but we never want to associate two different parts\n // to the same index. They must have a constant node between.\n let lastPartIndex = 0;\n let index = -1;\n let partIndex = 0;\n const { strings, values: { length } } = result;\n while (partIndex < length) {\n const node = walker.nextNode();\n if (node === null) {\n // We've exhausted the content inside a nested template element.\n // Because we still have parts (the outer for-loop), we know:\n // - There is a template in the stack\n // - The walker will find a nextNode outside the template\n walker.currentNode = stack.pop();\n continue;\n }\n index++;\n if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {\n if (node.hasAttributes()) {\n const attributes = node.attributes;\n const { length } = attributes;\n // Per\n // https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap,\n // attributes are not guaranteed to be returned in document order.\n // In particular, Edge/IE can return them out of order, so we cannot\n // assume a correspondence between part index and attribute index.\n let count = 0;\n for (let i = 0; i < length; i++) {\n if (endsWith(attributes[i].name, boundAttributeSuffix)) {\n count++;\n }\n }\n while (count-- > 0) {\n // Get the template literal section leading up to the first\n // expression in this attribute\n const stringForPart = strings[partIndex];\n // Find the attribute name\n const name = lastAttributeNameRegex.exec(stringForPart)[2];\n // Find the corresponding attribute\n // All bound attributes have had a suffix added in\n // TemplateResult#getHTML to opt out of special attribute\n // handling. To look up the attribute value we also need to add\n // the suffix.\n const attributeLookupName = name.toLowerCase() + boundAttributeSuffix;\n const attributeValue = node.getAttribute(attributeLookupName);\n node.removeAttribute(attributeLookupName);\n const statics = attributeValue.split(markerRegex);\n this.parts.push({ type: 'attribute', index, name, strings: statics });\n partIndex += statics.length - 1;\n }\n }\n if (node.tagName === 'TEMPLATE') {\n stack.push(node);\n walker.currentNode = node.content;\n }\n }\n else if (node.nodeType === 3 /* Node.TEXT_NODE */) {\n const data = node.data;\n if (data.indexOf(marker) >= 0) {\n const parent = node.parentNode;\n const strings = data.split(markerRegex);\n const lastIndex = strings.length - 1;\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for node parts\n for (let i = 0; i < lastIndex; i++) {\n let insert;\n let s = strings[i];\n if (s === '') {\n insert = createMarker();\n }\n else {\n const match = lastAttributeNameRegex.exec(s);\n if (match !== null && endsWith(match[2], boundAttributeSuffix)) {\n s = s.slice(0, match.index) + match[1] +\n match[2].slice(0, -boundAttributeSuffix.length) + match[3];\n }\n insert = document.createTextNode(s);\n }\n parent.insertBefore(insert, node);\n this.parts.push({ type: 'node', index: ++index });\n }\n // If there's no text, we must insert a comment to mark our place.\n // Else, we can trust it will stick around after cloning.\n if (strings[lastIndex] === '') {\n parent.insertBefore(createMarker(), node);\n nodesToRemove.push(node);\n }\n else {\n node.data = strings[lastIndex];\n }\n // We have a part for each match found\n partIndex += lastIndex;\n }\n }\n else if (node.nodeType === 8 /* Node.COMMENT_NODE */) {\n if (node.data === marker) {\n const parent = node.parentNode;\n // Add a new marker node to be the startNode of the Part if any of\n // the following are true:\n // * We don't have a previousSibling\n // * The previousSibling is already the start of a previous part\n if (node.previousSibling === null || index === lastPartIndex) {\n index++;\n parent.insertBefore(createMarker(), node);\n }\n lastPartIndex = index;\n this.parts.push({ type: 'node', index });\n // If we don't have a nextSibling, keep this node so we have an end.\n // Else, we can remove it to save future costs.\n if (node.nextSibling === null) {\n node.data = '';\n }\n else {\n nodesToRemove.push(node);\n index--;\n }\n partIndex++;\n }\n else {\n let i = -1;\n while ((i = node.data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n // TODO (justinfagnani): consider whether it's even worth it to\n // make bindings in comments work\n this.parts.push({ type: 'node', index: -1 });\n partIndex++;\n }\n }\n }\n }\n // Remove text binding nodes after the walk to not disturb the TreeWalker\n for (const n of nodesToRemove) {\n n.parentNode.removeChild(n);\n }\n }\n}\nconst endsWith = (str, suffix) => {\n const index = str.length - suffix.length;\n return index >= 0 && str.slice(index) === suffix;\n};\nexport const isTemplatePartActive = (part) => part.index !== -1;\n// Allows `document.createComment('')` to be renamed for a\n// small manual size-savings.\nexport const createMarker = () => document.createComment('');\n/**\n * This regex extracts the attribute name preceding an attribute-position\n * expression. It does this by matching the syntax allowed for attributes\n * against the string literal directly preceding the expression, assuming that\n * the expression is in an attribute-value position.\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\x09\\x0a\\x0c\\x0d\" are HTML space characters:\n * https://www.w3.org/TR/html5/infrastructure.html#space-characters\n *\n * \"\\0-\\x1F\\x7F-\\x9F\" are Unicode control characters, which includes every\n * space character except \" \".\n *\n * So an attribute is:\n * * The name: any character except a control character, space character, ('),\n * (\"), \">\", \"=\", or \"/\"\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nexport const lastAttributeNameRegex = \n// eslint-disable-next-line no-control-regex\n/([ \\x09\\x0a\\x0c\\x0d])([^\\0-\\x1F\\x7F-\\x9F \"'>=/]+)([ \\x09\\x0a\\x0c\\x0d]*=[ \\x09\\x0a\\x0c\\x0d]*(?:[^ \\x09\\x0a\\x0c\\x0d\"'`<>=]*|\"[^\"]*|'[^']*))$/;\n//# sourceMappingURL=template.js.map","/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\n/**\n * @module lit-html\n */\nimport { reparentNodes } from './dom.js';\nimport { boundAttributeSuffix, lastAttributeNameRegex, marker, nodeMarker } from './template.js';\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = window.trustedTypes &&\n trustedTypes.createPolicy('lit-html', { createHTML: (s) => s });\nconst commentMarker = ` ${marker} `;\n/**\n * The return type of `html`, which holds a Template and the values from\n * interpolated expressions.\n */\nexport class TemplateResult {\n constructor(strings, values, type, processor) {\n this.strings = strings;\n this.values = values;\n this.type = type;\n this.processor = processor;\n }\n /**\n * Returns a string of HTML used to create a `<template>` element.\n */\n getHTML() {\n const l = this.strings.length - 1;\n let html = '';\n let isCommentBinding = false;\n for (let i = 0; i < l; i++) {\n const s = this.strings[i];\n // For each binding we want to determine the kind of marker to insert\n // into the template source before it's parsed by the browser's HTML\n // parser. The marker type is based on whether the expression is in an\n // attribute, text, or comment position.\n // * For node-position bindings we insert a comment with the marker\n // sentinel as its text content, like <!--{{lit-guid}}-->.\n // * For attribute bindings we insert just the marker sentinel for the\n // first binding, so that we support unquoted attribute bindings.\n // Subsequent bindings can use a comment marker because multi-binding\n // attributes must be quoted.\n // * For comment bindings we insert just the marker sentinel so we don't\n // close the comment.\n //\n // The following code scans the template source, but is *not* an HTML\n // parser. We don't need to track the tree structure of the HTML, only\n // whether a binding is inside a comment, and if not, if it appears to be\n // the first binding in an attribute.\n const commentOpen = s.lastIndexOf('<!--');\n // We're in comment position if we have a comment open with no following\n // comment close. Because <-- can appear in an attribute value there can\n // be false positives.\n isCommentBinding = (commentOpen > -1 || isCommentBinding) &&\n s.indexOf('-->', commentOpen + 1) === -1;\n // Check to see if we have an attribute-like sequence preceding the\n // expression. This can match \"name=value\" like structures in text,\n // comments, and attribute values, so there can be false-positives.\n const attributeMatch = lastAttributeNameRegex.exec(s);\n if (attributeMatch === null) {\n // We're only in this branch if we don't have a attribute-like\n // preceding sequence. For comments, this guards against unusual\n // attribute values like <div foo=\"<!--${'bar'}\">. Cases like\n // <!-- foo=${'bar'}--> are handled correctly in the attribute branch\n // below.\n html += s + (isCommentBinding ? commentMarker : nodeMarker);\n }\n else {\n // For attributes we use just a marker sentinel, and also append a\n // $lit$ suffix to the name to opt-out of attribute-specific parsing\n // that IE and Edge do for style and certain SVG attributes.\n html += s.substr(0, attributeMatch.index) + attributeMatch[1] +\n attributeMatch[2] + boundAttributeSuffix + attributeMatch[3] +\n marker;\n }\n }\n html += this.strings[l];\n return html;\n }\n getTemplateElement() {\n const template = document.createElement('template');\n let value = this.getHTML();\n if (policy !== undefined) {\n // this is secure because `this.strings` is a TemplateStringsArray.\n // TODO: validate this when\n // https://github.com/tc39/proposal-array-is-template-object is\n // implemented.\n value = policy.createHTML(value);\n }\n template.innerHTML = value;\n return template;\n }\n}\n/**\n * A TemplateResult for SVG fragments.\n *\n * This class wraps HTML in an `<svg>` tag in order to parse its contents in the\n * SVG namespace, then modifies the template to remove the `<svg>` tag so that\n * clones only container the original fragment.\n */\nexport class SVGTemplateResult extends TemplateResult {\n getHTML() {\n return `<svg>${super.getHTML()}</svg>`;\n }\n getTemplateElement() {\n const template = super.getTemplateElement();\n const content = template.content;\n const svgElement = content.firstChild;\n content.removeChild(svgElement);\n reparentNodes(content, svgElement.firstChild);\n return template;\n }\n}\n//# sourceMappingURL=template-result.js.map","/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\nimport { isDirective } from './directive.js';\nimport { removeNodes } from './dom.js';\nimport { noChange, nothing } from './part.js';\nimport { TemplateInstance } from './template-instance.js';\nimport { TemplateResult } from './template-result.js';\nimport { createMarker } from './template.js';\nexport const isPrimitive = (value) => {\n return (value === null ||\n !(typeof value === 'object' || typeof value === 'function'));\n};\nexport const isIterable = (value) => {\n return Array.isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n !!(value && value[Symbol.iterator]);\n};\n/**\n * Writes attribute values to the DOM for a group of AttributeParts bound to a\n * single attribute. The value is only set once even if there are multiple parts\n * for an attribute.\n */\nexport class AttributeCommitter {\n constructor(element, name, strings) {\n this.dirty = true;\n this.element = element;\n this.name = name;\n this.strings = strings;\n this.parts = [];\n for (let i = 0; i < strings.length - 1; i++) {\n this.parts[i] = this._createPart();\n }\n }\n /**\n * Creates a single part. Override this to create a differnt type of part.\n */\n _createPart() {\n return new AttributePart(this);\n }\n _getValue() {\n const strings = this.strings;\n const l = strings.length - 1;\n const parts = this.parts;\n // If we're assigning an attribute via syntax like:\n // attr=\"${foo}\" or attr=${foo}\n // but not\n // attr=\"${foo} ${bar}\" or attr=\"${foo} baz\"\n // then we don't want to coerce the attribute value into one long\n // string. Instead we want to just return the value itself directly,\n // so that sanitizeDOMValue can get the actual value rather than\n // String(value)\n // The exception is if v is an array, in which case we do want to smash\n // it together into a string without calling String() on the array.\n //\n // This also allows trusted values (when using TrustedTypes) being\n // assigned to DOM sinks without being stringified in the process.\n if (l === 1 && strings[0] === '' && strings[1] === '') {\n const v = parts[0].value;\n if (typeof v === 'symbol') {\n return String(v);\n }\n if (typeof v === 'string' || !isIterable(v)) {\n return v;\n }\n }\n let text = '';\n for (let i = 0; i < l; i++) {\n text += strings[i];\n const part = parts[i];\n if (part !== undefined) {\n const v = part.value;\n if (isPrimitive(v) || !isIterable(v)) {\n text += typeof v === 'string' ? v : String(v);\n }\n else {\n for (const t of v) {\n text += typeof t === 'string' ? t : String(t);\n }\n }\n }\n }\n text += strings[l];\n return text;\n }\n commit() {\n if (this.dirty) {\n this.dirty = false;\n this.element.setAttribute(this.name, this._getValue());\n }\n }\n}\n/**\n * A Part that controls all or part of an attribute value.\n */\nexport class AttributePart {\n constructor(committer) {\n this.value = undefined;\n this.committer = committer;\n }\n setValue(value) {\n if (value !== noChange && (!isPrimitive(value) || value !== this.value)) {\n this.value = value;\n // If the value is a not a directive, dirty the committer so that it'll\n // call setAttribute. If the value is a directive, it'll dirty the\n // committer if it calls setValue().\n if (!isDirective(value)) {\n this.committer.dirty = true;\n }\n }\n }\n commit() {\n while (isDirective(this.value)) {\n const directive = this.value;\n this.value = noChange;\n directive(this);\n }\n if (this.value === noChange) {\n return;\n }\n this.committer.commit();\n }\n}\n/**\n * A Part that controls a location within a Node tree. Like a Range, NodePart\n * has start and end locations and can set and update the Nodes between those\n * locations.\n *\n * NodeParts support several value types: primitives, Nodes, TemplateResults,\n * as well as arrays and iterables of those types.\n */\nexport class NodePart {\n constructor(options) {\n this.value = undefined;\n this.__pendingValue = undefined;\n this.options = options;\n }\n /**\n * Appends this part into a container.\n *\n * This part must be empty, as its contents are not automatically moved.\n */\n appendInto(container) {\n this.startNode = container.appendChild(createMarker());\n this.endNode = container.appendChild(createMarker());\n }\n /**\n * Inserts this part after the `ref` node (between `ref` and `ref`'s next\n * sibling). Both `ref` and its next sibling must be static, unchanging nodes\n * such as those that appear in a literal section of a template.\n *\n * This part must be empty, as its contents are not automatically moved.\n */\n insertAfterNode(ref) {\n this.startNode = ref;\n this.endNode = ref.nextSibling;\n }\n /**\n * Appends this part into a parent part.\n *\n * This part must be empty, as its contents are not automatically moved.\n */\n appendIntoPart(part) {\n part.__insert(this.startNode = createMarker());\n part.__insert(this.endNode = createMarker());\n }\n /**\n * Inserts this part after the `ref` part.\n *\n * This part must be empty, as its contents are not automatically moved.\n */\n insertAfterPart(ref) {\n ref.__insert(this.startNode = createMarker());\n this.endNode = ref.endNode;\n ref.endNode = this.startNode;\n }\n setValue(value) {\n this.__pendingValue = value;\n }\n commit() {\n if (this.startNode.parentNode === null) {\n return;\n }\n while (isDirective(this.__pendingValue)) {\n const directive = this.__pendingValue;\n this.__pendingValue = noChange;\n directive(this);\n }\n const value = this.__pendingValue;\n if (value === noChange) {\n return;\n }\n if (isPrimitive(value)) {\n if (value !== this.value) {\n this.__commitText(value);\n }\n }\n else if (value instanceof TemplateResult) {\n this.__commitTemplateResult(value);\n }\n else if (value instanceof Node) {\n this.__commitNode(value);\n }\n else if (isIterable(value)) {\n this.__commitIterable(value);\n }\n else if (value === nothing) {\n this.value = nothing;\n this.clear();\n }\n else {\n // Fallback, will render the string representation\n this.__commitText(value);\n }\n }\n __insert(node) {\n this.endNode.parentNode.insertBefore(node, this.endNode);\n }\n __commitNode(value) {\n if (this.value === value) {\n return;\n }\n this.clear();\n this.__insert(value);\n this.value = value;\n }\n __commitText(value) {\n const node = this.startNode.nextSibling;\n value = value == null ? '' : value;\n // If `value` isn't already a string, we explicitly convert it here in case\n // it can't be implicitly converted - i.e. it's a symbol.\n const valueAsString = typeof value === 'string' ? value : String(value);\n if (node === this.endNode.previousSibling &&\n node.nodeType === 3 /* Node.TEXT_NODE */) {\n // If we only have a single text node between the markers, we can just\n // set its value, rather than replacing it.\n // TODO(justinfagnani): Can we just check if this.value is primitive?\n node.data = valueAsString;\n }\n else {\n this.__commitNode(document.createTextNode(valueAsString));\n }\n this.value = value;\n }\n __commitTemplateResult(value) {\n const template = this.options.templateFactory(value);\n if (this.value instanceof TemplateInstance &&\n this.value.template === template) {\n this.value.update(value.values);\n }\n else {\n // Make sure we propagate the template processor from the TemplateResult\n // so that we use its syntax extension, etc. The template factory comes\n // from the render function options so that it can control template\n // caching and preprocessing.\n const instance = new TemplateInstance(template, value.processor, this.options);\n const fragment = instance._clone();\n instance.update(value.values);\n this.__commitNode(fragment);\n this.value = instance;\n }\n }\n __commitIterable(value) {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n // If _value is an array, then the previous render was of an\n // iterable and _value will contain the NodeParts from the previous\n // render. If _value is not an array, clear this part and make a new\n // array for NodeParts.\n if (!Array.isArray(this.value)) {\n this.value = [];\n this.clear();\n }\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this.value;\n let partIndex = 0;\n let itemPart;\n for (const item of value) {\n // Try to reuse an existing part\n itemPart = itemParts[partIndex];\n // If no existing part, create a new one\n if (itemPart === undefined) {\n itemPart = new NodePart(this.options);\n itemParts.push(itemPart);\n if (partIndex === 0) {\n itemPart.appendIntoPart(this);\n }\n else {\n itemPart.insertAfterPart(itemParts[partIndex - 1]);\n }\n }\n itemPart.setValue(item);\n itemPart.commit();\n partIndex++;\n }\n if (partIndex < itemParts.length) {\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n this.clear(itemPart && itemPart.endNode);\n }\n }\n clear(startNode = this.startNode) {\n removeNodes(this.startNode.parentNode, startNode.nextSibling, this.endNode);\n }\n}\n/**\n * Implements a boolean attribute, roughly as defined in the HTML\n * specification.\n *\n * If the value is truthy, then the attribute is present with a value of\n * ''. If the value is falsey, the attribute is removed.\n */\nexport class BooleanAttributePart {\n constructor(element, name, strings) {\n this.value = undefined;\n this.__pendingValue = undefined;\n if (strings.length !== 2 || strings[0] !== '' || strings[1] !== '') {\n throw new Error('Boolean attributes can only contain a single expression');\n }\n this.element = element;\n this.name = name;\n this.strings = strings;\n }\n setValue(value) {\n this.__pendingValue = value;\n }\n commit() {\n while (isDirective(this.__pendingValue)) {\n const directive = this.__pendingValue;\n this.__pendingValue = noChange;\n directive(this);\n }\n if (this.__pendingValue === noChange) {\n return;\n }\n const value = !!this.__pendingValue;\n if (this.value !== value) {\n if (value) {\n this.element.setAttribute(this.name, '');\n }\n else {\n this.element.removeAttribute(this.name);\n }\n this.value = value;\n }\n this.__pendingValue = noChange;\n }\n}\n/**\n * Sets attribute values for PropertyParts, so that the value is only set once\n * even if there are multiple parts for a property.\n *\n * If an expression controls the whole property value, then the value is simply\n * assigned to the property under control. If there are string literals or\n * multiple expressions, then the strings are expressions are interpolated into\n * a string first.\n */\nexport class PropertyCommitter extends AttributeCommitter {\n constructor(element, name, strings) {\n super(element, name, strings);\n this.single =\n (strings.length === 2 && strings[0] === '' && strings[1] === '');\n }\n _createPart() {\n return new PropertyPart(this);\n }\n _getValue() {\n if (this.single) {\n return this.parts[0].value;\n }\n return super._getValue();\n }\n commit() {\n if (this.dirty) {\n this.dirty = false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.element[this.name] = this._getValue();\n }\n }\n}\nexport class PropertyPart extends AttributePart {\n}\n// Detect event listener options support. If the `capture` property is read\n// from the options object, then options are supported. If not, then the third\n// argument to add/removeEventListener is interpreted as the boolean capture\n// value so we should only pass the `capture` property.\nlet eventOptionsSupported = false;\n// Wrap into an IIFE because MS Edge <= v41 does not support having try/catch\n// blocks right into the body of a module\n(() => {\n try {\n const options = {\n get capture() {\n eventOptionsSupported = true;\n return false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n window.addEventListener('test', options, options);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n window.removeEventListener('test', options, options);\n }\n catch (_e) {\n // event options not supported\n }\n})();\nexport class EventPart {\n constructor(element, eventName, eventContext) {\n this.value = undefined;\n this.__pendingValue = undefined;\n this.element = element;\n this.eventName = eventName;\n this.eventContext = eventContext;\n this.__boundHandleEvent = (e) => this.handleEvent(e);\n }\n setValue(value) {\n this.__pendingValue = value;\n }\n commit() {\n while (isDirective(this.__pendingValue)) {\n const directive = this.__pendingValue;\n this.__pendingValue = noChange;\n directive(this);\n }\n if (this.__pendingValue === noChange) {\n return;\n }\n const newListener = this.__pendingValue;\n const oldListener = this.value;\n const shouldRemoveListener = newListener == null ||\n oldListener != null &&\n (newListener.capture !== oldListener.capture ||\n newListener.once !== oldListener.once ||\n newListener.passive !== oldListener.passive);\n const shouldAddListener = newListener != null && (oldListener == null || shouldRemoveListener);\n if (shouldRemoveListener) {\n this.element.removeEventListener(this.eventName, this.__boundHandleEvent, this.__options);\n }\n if (shouldAddListener) {\n this.__options = getOptions(newListener);\n this.element.addEventListener(this.eventName, this.__boundHandleEvent, this.__options);\n }\n this.value = newListener;\n this.__pendingValue = noChange;\n }\n handleEvent(event) {\n if (typeof this.value === 'function') {\n this.value.call(this.eventContext || this.element, event);\n }\n else {\n this.value.handleEvent(event);\n }\n }\n}\n// We copy options because of the inconsistent behavior of browsers when reading\n// the third argument of add/removeEventListener. IE11 doesn't support options\n// at all. Chrome 41 only reads `capture` if the argument is an object.\nconst getOptions = (o) => o &&\n (eventOptionsSupported ?\n { capture: o.capture, passive: o.passive, once: o.once } :\n o.capture);\n//# sourceMappingURL=parts.js.map","/**\n * @license\n * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.\n * This code may only be used under the BSD style license found at\n * http://polymer.github.io/LICENSE.txt\n * The complete set of authors may be found at\n * http://polymer.github.io/AUTHORS.txt\n * The complete set of contributors may be found at\n * http://polymer.github.io/CONTRIBUTORS.txt\n * Code distributed by Google as part of the polymer project is also\n * subject to an additional IP rights grant found at\n * http://polymer.github.io/PATENTS.txt\n */\n/**\n *\n * Main lit-html module.\n *\n * Main exports:\n *\n * - [[html]]\n * - [[svg]]\n * - [[render]]\n *\n * @packageDocumentation\n */\n/**\n * Do not remove this comment; it keeps typedoc from misplacing the module\n * docs.\n */\nimport { defaultTemplateProcessor } from './lib/default-template-processor.js';\nimport { SVGTemplateResult, TemplateResult } from './lib/template-result.js';\nexport { DefaultTemplateProcessor, defaultTemplateProcessor } from './lib/default-template-processor.js';\nexport { directive, isDirective } from './lib/directive.js';\n// TODO(justinfagnani): remove line when we get NodePart moving methods\nexport { removeNodes, reparentNodes } from './lib/dom.js';\nexport { noChange, nothing } from './lib/part.js';\nexport { AttributeCommitter, AttributePart, BooleanAttributePart, EventPart, isIterable, isPrimitive, NodePart, PropertyCommitter, PropertyPart } from './lib/parts.js';\nexport { parts, render } from './lib/render.js';\nexport { templateCaches, templateFactory } from './lib/template-factory.js';\nexport { TemplateInstance } from './lib/template-instance.js';\nexport { SVGTemplateResult, TemplateResult } from './lib/template-result.js';\nexport { createMarker, isTemplatePartActive, Template } from './lib/template.js';\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n// TODO(justinfagnani): inject version number at build time\nif (typeof window !== 'undefined') {\n (window['litHtmlVersions'] || (window['litHtmlVersions'] = [])).push('1.4.1');\n}\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n */\nexport const html = (strings, ...values) => new TemplateResult(strings, values, 'html', defaultTemplateProcessor);\n/**\n * Interprets a template literal as an SVG template that can efficiently\n * render to and update a container.\n */\nexport const svg = (strings, ...values) => new SVGTemplateResult(strings, values, 'svg', defaultTemplateProcessor);\n//# sourceMappingURL=lit-html.js.map","let current;\nlet currentId = 0;\nfunction setCurrent(state) {\n current = state;\n}\nfunction clear() {\n current = null;\n currentId = 0;\n}\nfunction notify() {\n return currentId++;\n}\nexport { clear, current, setCurrent, notify };\n","const phaseSymbol = Symbol('haunted.phase');\nconst hookSymbol = Symbol('haunted.hook');\nconst updateSymbol = Symbol('haunted.update');\nconst commitSymbol = Symbol('haunted.commit');\nconst effectsSymbol = Symbol('haunted.effects');\nconst layoutEffectsSymbol = Symbol('haunted.layoutEffects');\nconst contextEvent = 'haunted.context';\nexport { phaseSymbol, hookSymbol, updateSymbol, commitSymbol, effectsSymbol, layoutEffectsSymbol, contextEvent, };\n","import { State } from './state';\nimport { commitSymbol, phaseSymbol, updateSymbol, effectsSymbol, layoutEffectsSymbol } from './symbols';\nconst defer = Promise.resolve().then.bind(Promise.resolve());\nfunction runner() {\n let tasks = [];\n let id;\n function runTasks() {\n id = null;\n let t = tasks;\n tasks = [];\n for (var i = 0, len = t.length; i < len; i++) {\n t[i]();\n }\n }\n return function (task) {\n tasks.push(task);\n if (id == null) {\n id = defer(runTasks);\n }\n };\n}\nconst read = runner();\nconst write = runner();\nclass BaseScheduler {\n constructor(renderer, host) {\n this.renderer = renderer;\n this.host = host;\n this.state = new State(this.update.bind(this), host);\n this[phaseSymbol] = null;\n this._updateQueued = false;\n }\n update() {\n if (this._updateQueued)\n return;\n read(() => {\n let result = this.handlePhase(updateSymbol);\n write(() => {\n this.handlePhase(commitSymbol, result);\n write(() => {\n this.handlePhase(effectsSymbol);\n });\n });\n this._updateQueued = false;\n });\n this._updateQueued = true;\n }\n handlePhase(phase, arg) {\n this[phaseSymbol] = phase;\n switch (phase) {\n case commitSymbol:\n this.commit(arg);\n this.runEffects(layoutEffectsSymbol);\n return;\n case updateSymbol: return this.render();\n case effectsSymbol: return this.runEffects(effectsSymbol);\n }\n this[phaseSymbol] = null;\n }\n render() {\n return this.state.run(() => this.renderer.call(this.host, this.host));\n }\n runEffects(phase) {\n this.state._runEffects(phase);\n }\n teardown() {\n this.state.teardown();\n }\n}\nexport { BaseScheduler };\n","import { current, notify } from './interface';\nimport { hookSymbol } from './symbols';\nclass Hook {\n constructor(id, state) {\n this.id = id;\n this.state = state;\n }\n}\nfunction use(Hook, ...args) {\n let id = notify();\n let hooks = current[hookSymbol];\n let hook = hooks.get(id);\n if (!hook) {\n hook = new Hook(id, current, ...args);\n hooks.set(id, hook);\n }\n return hook.update(...args);\n}\nfunction hook(Hook) {\n return use.bind(null, Hook);\n}\nexport { hook, Hook };\n","import { Hook, hook } from './hook';\nfunction createEffect(setEffects) {\n return hook(class extends Hook {\n constructor(id, state, ignored1, ignored2) {\n super(id, state);\n setEffects(state, this);\n }\n update(callback, values) {\n this.callback = callback;\n this.values = values;\n }\n call() {\n if (!this.values || this.hasChanged()) {\n this.run();\n }\n this.lastValues = this.values;\n }\n run() {\n this.teardown();\n this._teardown = this.callback.call(this.state);\n }\n teardown() {\n if (typeof this._teardown === 'function') {\n this._teardown();\n }\n }\n hasChanged() {\n return !this.lastValues || this.values.some((value, i) => this.lastValues[i] !== value);\n }\n });\n}\nexport { createEffect };\n","import { effectsSymbol } from './symbols';\nimport { createEffect } from './create-effect';\nfunction setEffects(state, cb) {\n state[effectsSymbol].push(cb);\n}\nconst useEffect = createEffect(setEffects);\nexport { setEffects, useEffect };\n","import { hook, Hook } from './hook';\nimport { contextEvent } from './symbols';\nimport { setEffects } from './use-effect';\nconst useContext = hook(class extends Hook {\n constructor(id, state, _) {\n super(id, state);\n this._updater = this._updater.bind(this);\n this._ranEffect = false;\n this._unsubscribe = null;\n setEffects(state, this);\n }\n update(Context) {\n if (this.state.virtual) {\n throw new Error('can\\'t be used with virtual components');\n }\n if (this.Context !== Context) {\n this._subscribe(Context);\n this.Context = Context;\n }\n return this.value;\n }\n call() {\n if (!this._ranEffect) {\n this._ranEffect = true;\n if (this._unsubscribe)\n this._unsubscribe();\n this._subscribe(this.Context);\n this.state.update();\n }\n }\n _updater(value) {\n this.value = value;\n this.state.update();\n }\n _subscribe(Context) {\n const detail = { Context, callback: this._updater };\n this.state.host.dispatchEvent(new CustomEvent(contextEvent, {\n detail,\n bubbles: true,\n cancelable: true,\n composed: true,\n }));\n const { unsubscribe = null, value } = detail;\n this.value = unsubscribe ? value : Context.defaultValue;\n this._unsubscribe = unsubscribe;\n }\n teardown() {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n }\n});\nexport { useContext };\n","import { hook, Hook } from './hook';\nconst useMemo = hook(class extends Hook {\n constructor(id, state, fn, values) {\n super(id, state);\n this.value = fn();\n this.values = values;\n }\n update(fn, values) {\n if (this.hasChanged(values)) {\n this.values = values;\n this.value = fn();\n }\n return this.value;\n }\n hasChanged(values = []) {\n return values.some((value, i) => this.values[i] !== value);\n }\n});\nexport { useMemo };\n","import { layoutEffectsSymbol } from './symbols';\nimport { createEffect } from './create-effect';\nfunction setLayoutEffects(state, cb) {\n state[layoutEffectsSymbol].push(cb);\n}\nconst useLayoutEffect = createEffect(setLayoutEffects);\nexport { useLayoutEffect };\n","import { hook, Hook } from './hook';\nconst useState = hook(class extends Hook {\n constructor(id, state, initialValue) {\n super(id, state);\n this.updater = this.updater.bind(this);\n if (typeof initialValue === 'function') {\n initialValue = initialValue();\n }\n this.makeArgs(initialValue);\n }\n update() {\n return this.args;\n }\n updater(value) {\n if (typeof value === 'function') {\n const updaterFn = value;\n const [previousValue] = this.args;\n value = updaterFn(previousValue);\n }\n this.makeArgs(value);\n this.state.update();\n }\n makeArgs(value) {\n this.args = Object.freeze([value, this.updater]);\n }\n});\n;\nexport { useState };\n","import { hook, Hook } from './hook';\nconst useReducer = hook(class extends Hook {\n constructor(id, state, _, initialState, init) {\n super(id, state);\n this.dispatch = this.dispatch.bind(this);\n this.currentState = init !== undefined ? init(initialState) : initialState;\n }\n update(reducer) {\n this.reducer = reducer;\n return [this.currentState, this.dispatch];\n }\n dispatch(action) {\n this.currentState = this.reducer(this.currentState, action);\n this.state.update();\n }\n});\nexport { useReducer };\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","import{State as e}from\"haunted\";export{Hook,State,hook,useCallback,useEffect,useLayoutEffect,useMemo,useReducer,useRef,useState}from\"haunted\";import{getRenderingRef as t,getElement as n,forceUpdate as o}from\"@stencil/core\";import r from\"debug\";import{createContext as u,useDomContext as c,useDomContextState as a}from\"@saasquatch/dom-context-hooks\";function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}).apply(this,arguments)}function f(e,t){return i({},u(e,t),{useContext:function(t){return d(e,t)},useContextState:function(n){return m(e,n||t)}})}function s(){return t()}function l(){var e=s();return n(e)}function d(e,t){void 0===t&&(t={});var n=l();return c(n,e,t)}function m(e,t){var n=l();return a(n,e,t)}var p=r(\"stencil-hook\");function h(t){var r,u=n(t),c=(r=!1,new e(function(){p(\"Queue update on element\",u),r||(r=!0,Promise.resolve().then(function(){p(\"Forced update on element\",u),r=!1,o(u)}))},u)),a=t.disconnectedCallback;if(!a)throw new Error(\"Stencil hooks requires `disconnectedCallback` to be defined (even if it's empty). This is because of how the Stencil compiler works internally\");t.disconnectedCallback=function(){c.teardown(),v(a)};var i=t.connectedCallback;t.connectedCallback=function(){c.update(),v(i)};var f=t.render.bind(t);t.render=function(){var e=c.run(f);return c.runEffects(),e}}function v(e){\"function\"==typeof e&&e()}export{f as createContext,s as useComponent,d as useDomContext,m as useDomContextState,l as useHost,h as withHooks};\n//# sourceMappingURL=stencil-hooks.module.js.map\n","let scopeId;\nlet contentRef;\nlet hostTagName;\nlet customError;\nlet i = 0;\nlet useNativeShadowDom = false;\nlet checkSlotFallbackVisibility = false;\nlet checkSlotRelocate = false;\nlet isSvgMode = false;\nlet renderingRef = null;\nlet queueCongestion = 0;\nlet queuePending = false;\n/*\n Stencil Client Platform v2.5.2 | MIT Licensed | https://stenciljs.com\n */\nimport { BUILD, NAMESPACE } from '@stencil/core/internal/app-data';\nconst win = typeof window !== 'undefined' ? window : {};\nconst CSS = BUILD.cssVarShim ? win.CSS : null;\nconst doc = win.document || { head: {} };\nconst H = (win.HTMLElement || class {\n});\nconst plt = {\n $flags$: 0,\n $resourcesUrl$: '',\n jmp: h => h(),\n raf: h => requestAnimationFrame(h),\n ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),\n rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),\n ce: (eventName, opts) => new CustomEvent(eventName, opts),\n};\nconst supportsShadow = BUILD.shadowDomShim && BUILD.shadowDom ? /*@__PURE__*/ (() => (doc.head.attachShadow + '').indexOf('[native') > -1)() : true;\nconst supportsListenerOptions = /*@__PURE__*/ (() => {\n let supportsListenerOptions = false;\n try {\n doc.addEventListener('e', null, Object.defineProperty({}, 'passive', {\n get() {\n supportsListenerOptions = true;\n },\n }));\n }\n catch (e) { }\n return supportsListenerOptions;\n})();\nconst promiseResolve = (v) => Promise.resolve(v);\nconst supportsConstructibleStylesheets = BUILD.constructableCSS\n ? /*@__PURE__*/ (() => {\n try {\n new CSSStyleSheet();\n return typeof (new CSSStyleSheet()).replace === 'function';\n }\n catch (e) { }\n return false;\n })()\n : false;\nconst Context = {};\nconst addHostEventListeners = (elm, hostRef, listeners, attachParentListeners) => {\n if (BUILD.hostListener && listeners) {\n // this is called immediately within the element's constructor\n // initialize our event listeners on the host element\n // we do this now so that we can listen to events that may\n // have fired even before the instance is ready\n if (BUILD.hostListenerTargetParent) {\n // this component may have event listeners that should be attached to the parent\n if (attachParentListeners) {\n // this is being ran from within the connectedCallback\n // which is important so that we know the host element actually has a parent element\n // filter out the listeners to only have the ones that ARE being attached to the parent\n listeners = listeners.filter(([flags]) => flags & 32 /* TargetParent */);\n }\n else {\n // this is being ran from within the component constructor\n // everything BUT the parent element listeners should be attached at this time\n // filter out the listeners that are NOT being attached to the parent\n listeners = listeners.filter(([flags]) => !(flags & 32 /* TargetParent */));\n }\n }\n listeners.map(([flags, name, method]) => {\n const target = BUILD.hostListenerTarget ? getHostListenerTarget(elm, flags) : elm;\n const handler = hostListenerProxy(hostRef, method);\n const opts = hostListenerOpts(flags);\n plt.ael(target, name, handler, opts);\n (hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts));\n });\n }\n};\nconst hostListenerProxy = (hostRef, methodName) => (ev) => {\n try {\n if (BUILD.lazyLoad) {\n if (hostRef.$flags$ & 256 /* isListenReady */) {\n // instance is ready, let's call it's member method for this event\n hostRef.$lazyInstance$[methodName](ev);\n }\n else {\n (hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]);\n }\n }\n else {\n hostRef.$hostElement$[methodName](ev);\n }\n }\n catch (e) {\n consoleError(e);\n }\n};\nconst getHostListenerTarget = (elm, flags) => {\n if (BUILD.hostListenerTargetDocument && flags & 4 /* TargetDocument */)\n return doc;\n if (BUILD.hostListenerTargetWindow && flags & 8 /* TargetWindow */)\n return win;\n if (BUILD.hostListenerTargetBody && flags & 16 /* TargetBody */)\n return doc.body;\n if (BUILD.hostListenerTargetParent && flags & 32 /* TargetParent */)\n return elm.parentElement;\n return elm;\n};\n// prettier-ignore\nconst hostListenerOpts = (flags) => supportsListenerOptions\n ? ({\n passive: (flags & 1 /* Passive */) !== 0,\n capture: (flags & 2 /* Capture */) !== 0,\n })\n : (flags & 2 /* Capture */) !== 0;\nconst CONTENT_REF_ID = 'r';\nconst ORG_LOCATION_ID = 'o';\nconst SLOT_NODE_ID = 's';\nconst TEXT_NODE_ID = 't';\nconst HYDRATE_ID = 's-id';\nconst HYDRATED_STYLE_ID = 'sty-id';\nconst HYDRATE_CHILD_ID = 'c-id';\nconst HYDRATED_CSS = '{visibility:hidden}.hydrated{visibility:inherit}';\nconst XLINK_NS = 'http://www.w3.org/1999/xlink';\nconst createTime = (fnName, tagName = '') => {\n if (BUILD.profile && performance.mark) {\n const key = `st:${fnName}:${tagName}:${i++}`;\n // Start\n performance.mark(key);\n // End\n return () => performance.measure(`[Stencil] ${fnName}() <${tagName}>`, key);\n }\n else {\n return () => {\n return;\n };\n }\n};\nconst uniqueTime = (key, measureText) => {\n if (BUILD.profile && performance.mark) {\n if (performance.getEntriesByName(key).length === 0) {\n performance.mark(key);\n }\n return () => {\n if (performance.getEntriesByName(measureText).length === 0) {\n performance.measure(measureText, key);\n }\n };\n }\n else {\n return () => {\n return;\n };\n }\n};\nconst inspect = (ref) => {\n const hostRef = getHostRef(ref);\n if (!hostRef) {\n return undefined;\n }\n const flags = hostRef.$flags$;\n const hostElement = hostRef.$hostElement$;\n return {\n renderCount: hostRef.$renderCount$,\n flags: {\n hasRendered: !!(flags & 2 /* hasRendered */),\n hasConnected: !!(flags & 1 /* hasConnected */),\n isWaitingForChildren: !!(flags & 4 /* isWaitingForChildren */),\n isConstructingInstance: !!(flags & 8 /* isConstructingInstance */),\n isQueuedForUpdate: !!(flags & 16 /* isQueuedForUpdate */),\n hasInitializedComponent: !!(flags & 32 /* hasInitializedComponent */),\n hasLoadedComponent: !!(flags & 64 /* hasLoadedComponent */),\n isWatchReady: !!(flags & 128 /* isWatchReady */),\n isListenReady: !!(flags & 256 /* isListenReady */),\n needsRerender: !!(flags & 512 /* needsRerender */),\n },\n instanceValues: hostRef.$instanceValues$,\n ancestorComponent: hostRef.$ancestorComponent$,\n hostElement,\n lazyInstance: hostRef.$lazyInstance$,\n vnode: hostRef.$vnode$,\n modeName: hostRef.$modeName$,\n onReadyPromise: hostRef.$onReadyPromise$,\n onReadyResolve: hostRef.$onReadyResolve$,\n onInstancePromise: hostRef.$onInstancePromise$,\n onInstanceResolve: hostRef.$onInstanceResolve$,\n onRenderResolve: hostRef.$onRenderResolve$,\n queuedListeners: hostRef.$queuedListeners$,\n rmListeners: hostRef.$rmListeners$,\n ['s-id']: hostElement['s-id'],\n ['s-cr']: hostElement['s-cr'],\n ['s-lr']: hostElement['s-lr'],\n ['s-p']: hostElement['s-p'],\n ['s-rc']: hostElement['s-rc'],\n ['s-sc']: hostElement['s-sc'],\n };\n};\nconst installDevTools = () => {\n if (BUILD.devTools) {\n const stencil = (win.stencil = win.stencil || {});\n const originalInspect = stencil.inspect;\n stencil.inspect = (ref) => {\n let result = inspect(ref);\n if (!result && typeof originalInspect === 'function') {\n result = originalInspect(ref);\n }\n return result;\n };\n }\n};\nconst rootAppliedStyles = new WeakMap();\nconst registerStyle = (scopeId, cssText, allowCS) => {\n let style = styles.get(scopeId);\n if (supportsConstructibleStylesheets && allowCS) {\n style = (style || new CSSStyleSheet());\n style.replace(cssText);\n }\n else {\n style = cssText;\n }\n styles.set(scopeId, style);\n};\nconst addStyle = (styleContainerNode, cmpMeta, mode, hostElm) => {\n let scopeId = getScopeId(cmpMeta, mode);\n let style = styles.get(scopeId);\n if (!BUILD.attachStyles) {\n return scopeId;\n }\n // if an element is NOT connected then getRootNode() will return the wrong root node\n // so the fallback is to always use the document for the root node in those cases\n styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : doc;\n if (style) {\n if (typeof style === 'string') {\n styleContainerNode = styleContainerNode.head || styleContainerNode;\n let appliedStyles = rootAppliedStyles.get(styleContainerNode);\n let styleElm;\n if (!appliedStyles) {\n rootAppliedStyles.set(styleContainerNode, (appliedStyles = new Set()));\n }\n if (!appliedStyles.has(scopeId)) {\n if (BUILD.hydrateClientSide && styleContainerNode.host && (styleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}=\"${scopeId}\"]`))) {\n // This is only happening on native shadow-dom, do not needs CSS var shim\n styleElm.innerHTML = style;\n }\n else {\n if (BUILD.cssVarShim && plt.$cssShim$) {\n styleElm = plt.$cssShim$.createHostStyle(hostElm, scopeId, style, !!(cmpMeta.$flags$ & 10 /* needsScopedEncapsulation */));\n const newScopeId = styleElm['s-sc'];\n if (newScopeId) {\n scopeId = newScopeId;\n // we don't want to add this styleID to the appliedStyles Set\n // since the cssVarShim might need to apply several different\n // stylesheets for the same component\n appliedStyles = null;\n }\n }\n else {\n styleElm = doc.createElement('style');\n styleElm.innerHTML = style;\n }\n if (BUILD.hydrateServerSide || BUILD.hotModuleReplacement) {\n styleElm.setAttribute(HYDRATED_STYLE_ID, scopeId);\n }\n styleContainerNode.insertBefore(styleElm, styleContainerNode.querySelector('link'));\n }\n if (appliedStyles) {\n appliedStyles.add(scopeId);\n }\n }\n }\n else if (BUILD.constructableCSS && !styleContainerNode.adoptedStyleSheets.includes(style)) {\n styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, style];\n }\n }\n return scopeId;\n};\nconst attachStyles = (hostRef) => {\n const cmpMeta = hostRef.$cmpMeta$;\n const elm = hostRef.$hostElement$;\n const flags = cmpMeta.$flags$;\n const endAttachStyles = createTime('attachStyles', cmpMeta.$tagName$);\n const scopeId = addStyle(BUILD.shadowDom && supportsShadow && elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(), cmpMeta, hostRef.$modeName$, elm);\n if ((BUILD.shadowDom || BUILD.scoped) && BUILD.cssAnnotations && flags & 10 /* needsScopedEncapsulation */) {\n // only required when we're NOT using native shadow dom (slot)\n // or this browser doesn't support native shadow dom\n // and this host element was NOT created with SSR\n // let's pick out the inner content for slot projection\n // create a node to represent where the original\n // content was first placed, which is useful later on\n // DOM WRITE!!\n elm['s-sc'] = scopeId;\n elm.classList.add(scopeId + '-h');\n if (BUILD.scoped && flags & 2 /* scopedCssEncapsulation */) {\n elm.classList.add(scopeId + '-s');\n }\n }\n endAttachStyles();\n};\nconst getScopeId = (cmp, mode) => 'sc-' + (BUILD.mode && mode && cmp.$flags$ & 32 /* hasMode */ ? cmp.$tagName$ + '-' + mode : cmp.$tagName$);\nconst convertScopedToShadow = (css) => css.replace(/\\/\\*!@([^\\/]+)\\*\\/[^\\{]+\\{/g, '$1{');\n// Private\nconst computeMode = (elm) => modeResolutionChain.map(h => h(elm)).find(m => !!m);\n// Public\nconst setMode = (handler) => modeResolutionChain.push(handler);\nconst getMode = (ref) => getHostRef(ref).$modeName$;\n/**\n * Default style mode id\n */\n/**\n * Reusable empty obj/array\n * Don't add values to these!!\n */\nconst EMPTY_OBJ = {};\n/**\n * Namespaces\n */\nconst SVG_NS = 'http://www.w3.org/2000/svg';\nconst HTML_NS = 'http://www.w3.org/1999/xhtml';\nconst isDef = (v) => v != null;\nconst isComplexType = (o) => {\n // https://jsperf.com/typeof-fn-object/5\n o = typeof o;\n return o === 'object' || o === 'function';\n};\n/**\n * Production h() function based on Preact by\n * Jason Miller (@developit)\n * Licensed under the MIT License\n * https://github.com/developit/preact/blob/master/LICENSE\n *\n * Modified for Stencil's compiler and vdom\n */\n// const stack: any[] = [];\n// export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, child?: d.ChildType): d.VNode;\n// export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, ...children: d.ChildType[]): d.VNode;\nconst h = (nodeName, vnodeData, ...children) => {\n let child = null;\n let key = null;\n let slotName = null;\n let simple = false;\n let lastSimple = false;\n let vNodeChildren = [];\n const walk = (c) => {\n for (let i = 0; i < c.length; i++) {\n child = c[i];\n if (Array.isArray(child)) {\n walk(child);\n }\n else if (child != null && typeof child !== 'boolean') {\n if ((simple = typeof nodeName !== 'function' && !isComplexType(child))) {\n child = String(child);\n }\n else if (BUILD.isDev && typeof nodeName !== 'function' && child.$flags$ === undefined) {\n consoleDevError(`vNode passed as children has unexpected type.\nMake sure it's using the correct h() function.\nEmpty objects can also be the cause, look for JSX comments that became objects.`);\n }\n if (simple && lastSimple) {\n // If the previous child was simple (string), we merge both\n vNodeChildren[vNodeChildren.length - 1].$text$ += child;\n }\n else {\n // Append a new vNode, if it's text, we create a text vNode\n vNodeChildren.push(simple ? newVNode(null, child) : child);\n }\n lastSimple = simple;\n }\n }\n };\n walk(children);\n if (vnodeData) {\n if (BUILD.isDev && nodeName === 'input') {\n validateInputProperties(vnodeData);\n }\n // normalize class / classname attributes\n if (BUILD.vdomKey && vnodeData.key) {\n key = vnodeData.key;\n }\n if (BUILD.slotRelocation && vnodeData.name) {\n slotName = vnodeData.name;\n }\n if (BUILD.vdomClass) {\n const classData = vnodeData.className || vnodeData.class;\n if (classData) {\n vnodeData.class =\n typeof classData !== 'object'\n ? classData\n : Object.keys(classData)\n .filter(k => classData[k])\n .join(' ');\n }\n }\n }\n if (BUILD.isDev && vNodeChildren.some(isHost)) {\n consoleDevError(`The <Host> must be the single root component. Make sure:\n- You are NOT using hostData() and <Host> in the same component.\n- <Host> is used once, and it's the single root component of the render() function.`);\n }\n if (BUILD.vdomFunctional && typeof nodeName === 'function') {\n // nodeName is a functional component\n return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils);\n }\n const vnode = newVNode(nodeName, null);\n vnode.$attrs$ = vnodeData;\n if (vNodeChildren.length > 0) {\n vnode.$children$ = vNodeChildren;\n }\n if (BUILD.vdomKey) {\n vnode.$key$ = key;\n }\n if (BUILD.slotRelocation) {\n vnode.$name$ = slotName;\n }\n return vnode;\n};\nconst newVNode = (tag, text) => {\n const vnode = {\n $flags$: 0,\n $tag$: tag,\n $text$: text,\n $elm$: null,\n $children$: null,\n };\n if (BUILD.vdomAttribute) {\n vnode.$attrs$ = null;\n }\n if (BUILD.vdomKey) {\n vnode.$key$ = null;\n }\n if (BUILD.slotRelocation) {\n vnode.$name$ = null;\n }\n return vnode;\n};\nconst Host = {};\nconst isHost = (node) => node && node.$tag$ === Host;\nconst vdomFnUtils = {\n forEach: (children, cb) => children.map(convertToPublic).forEach(cb),\n map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate),\n};\nconst convertToPublic = (node) => ({\n vattrs: node.$attrs$,\n vchildren: node.$children$,\n vkey: node.$key$,\n vname: node.$name$,\n vtag: node.$tag$,\n vtext: node.$text$,\n});\nconst convertToPrivate = (node) => {\n if (typeof node.vtag === 'function') {\n const vnodeData = Object.assign({}, node.vattrs);\n if (node.vkey) {\n vnodeData.key = node.vkey;\n }\n if (node.vname) {\n vnodeData.name = node.vname;\n }\n return h(node.vtag, vnodeData, ...(node.vchildren || []));\n }\n const vnode = newVNode(node.vtag, node.vtext);\n vnode.$attrs$ = node.vattrs;\n vnode.$children$ = node.vchildren;\n vnode.$key$ = node.vkey;\n vnode.$name$ = node.vname;\n return vnode;\n};\nconst validateInputProperties = (vnodeData) => {\n const props = Object.keys(vnodeData);\n const typeIndex = props.indexOf('type');\n const minIndex = props.indexOf('min');\n const maxIndex = props.indexOf('max');\n const stepIndex = props.indexOf('min');\n const value = props.indexOf('value');\n if (value === -1) {\n return;\n }\n if (value < typeIndex || value < minIndex || value < maxIndex || value < stepIndex) {\n consoleDevWarn(`The \"value\" prop of <input> should be set after \"min\", \"max\", \"type\" and \"step\"`);\n }\n};\n/**\n * Production setAccessor() function based on Preact by\n * Jason Miller (@developit)\n * Licensed under the MIT License\n * https://github.com/developit/preact/blob/master/LICENSE\n *\n * Modified for Stencil's compiler and vdom\n */\nconst setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags) => {\n if (oldValue !== newValue) {\n let isProp = isMemberInElement(elm, memberName);\n let ln = memberName.toLowerCase();\n if (BUILD.vdomClass && memberName === 'class') {\n const classList = elm.classList;\n const oldClasses = parseClassList(oldValue);\n const newClasses = parseClassList(newValue);\n classList.remove(...oldClasses.filter(c => c && !newClasses.includes(c)));\n classList.add(...newClasses.filter(c => c && !oldClasses.includes(c)));\n }\n else if (BUILD.vdomStyle && memberName === 'style') {\n // update style attribute, css properties and values\n if (BUILD.updatable) {\n for (const prop in oldValue) {\n if (!newValue || newValue[prop] == null) {\n if (!BUILD.hydrateServerSide && prop.includes('-')) {\n elm.style.removeProperty(prop);\n }\n else {\n elm.style[prop] = '';\n }\n }\n }\n }\n for (const prop in newValue) {\n if (!oldValue || newValue[prop] !== oldValue[prop]) {\n if (!BUILD.hydrateServerSide && prop.includes('-')) {\n elm.style.setProperty(prop, newValue[prop]);\n }\n else {\n elm.style[prop] = newValue[prop];\n }\n }\n }\n }\n else if (BUILD.vdomKey && memberName === 'key')\n ;\n else if (BUILD.vdomRef && memberName === 'ref') {\n // minifier will clean this up\n if (newValue) {\n newValue(elm);\n }\n }\n else if (BUILD.vdomListener && (BUILD.lazyLoad ? !isProp : !elm.__lookupSetter__(memberName)) && memberName[0] === 'o' && memberName[1] === 'n') {\n // Event Handlers\n // so if the member name starts with \"on\" and the 3rd characters is\n // a capital letter, and it's not already a member on the element,\n // then we're assuming it's an event listener\n if (memberName[2] === '-') {\n // on- prefixed events\n // allows to be explicit about the dom event to listen without any magic\n // under the hood:\n // <my-cmp on-click> // listens for \"click\"\n // <my-cmp on-Click> // listens for \"Click\"\n // <my-cmp on-ionChange> // listens for \"ionChange\"\n // <my-cmp on-EVENTS> // listens for \"EVENTS\"\n memberName = memberName.slice(3);\n }\n else if (isMemberInElement(win, ln)) {\n // standard event\n // the JSX attribute could have been \"onMouseOver\" and the\n // member name \"onmouseover\" is on the window's prototype\n // so let's add the listener \"mouseover\", which is all lowercased\n memberName = ln.slice(2);\n }\n else {\n // custom event\n // the JSX attribute could have been \"onMyCustomEvent\"\n // so let's trim off the \"on\" prefix and lowercase the first character\n // and add the listener \"myCustomEvent\"\n // except for the first character, we keep the event name case\n memberName = ln[2] + memberName.slice(3);\n }\n if (oldValue) {\n plt.rel(elm, memberName, oldValue, false);\n }\n if (newValue) {\n plt.ael(elm, memberName, newValue, false);\n }\n }\n else if (BUILD.vdomPropOrAttr) {\n // Set property if it exists and it's not a SVG\n const isComplex = isComplexType(newValue);\n if ((isProp || (isComplex && newValue !== null)) && !isSvg) {\n try {\n if (!elm.tagName.includes('-')) {\n let n = newValue == null ? '' : newValue;\n // Workaround for Safari, moving the <input> caret when re-assigning the same valued\n if (memberName === 'list') {\n isProp = false;\n // tslint:disable-next-line: triple-equals\n }\n else if (oldValue == null || elm[memberName] != n) {\n elm[memberName] = n;\n }\n }\n else {\n elm[memberName] = newValue;\n }\n }\n catch (e) { }\n }\n /**\n * Need to manually update attribute if:\n * - memberName is not an attribute\n * - if we are rendering the host element in order to reflect attribute\n * - if it's a SVG, since properties might not work in <svg>\n * - if the newValue is null/undefined or 'false'.\n */\n let xlink = false;\n if (BUILD.vdomXlink) {\n if (ln !== (ln = ln.replace(/^xlink\\:?/, ''))) {\n memberName = ln;\n xlink = true;\n }\n }\n if (newValue == null || newValue === false) {\n if (newValue !== false || elm.getAttribute(memberName) === '') {\n if (BUILD.vdomXlink && xlink) {\n elm.removeAttributeNS(XLINK_NS, memberName);\n }\n else {\n elm.removeAttribute(memberName);\n }\n }\n }\n else if ((!isProp || flags & 4 /* isHost */ || isSvg) && !isComplex) {\n newValue = newValue === true ? '' : newValue;\n if (BUILD.vdomXlink && xlink) {\n elm.setAttributeNS(XLINK_NS, memberName, newValue);\n }\n else {\n elm.setAttribute(memberName, newValue);\n }\n }\n }\n }\n};\nconst parseClassListRegex = /\\s/;\nconst parseClassList = (value) => (!value ? [] : value.split(parseClassListRegex));\nconst updateElement = (oldVnode, newVnode, isSvgMode, memberName) => {\n // if the element passed in is a shadow root, which is a document fragment\n // then we want to be adding attrs/props to the shadow root's \"host\" element\n // if it's not a shadow root, then we add attrs/props to the same element\n const elm = newVnode.$elm$.nodeType === 11 /* DocumentFragment */ && newVnode.$elm$.host ? newVnode.$elm$.host : newVnode.$elm$;\n const oldVnodeAttrs = (oldVnode && oldVnode.$attrs$) || EMPTY_OBJ;\n const newVnodeAttrs = newVnode.$attrs$ || EMPTY_OBJ;\n if (BUILD.updatable) {\n // remove attributes no longer present on the vnode by setting them to undefined\n for (memberName in oldVnodeAttrs) {\n if (!(memberName in newVnodeAttrs)) {\n setAccessor(elm, memberName, oldVnodeAttrs[memberName], undefined, isSvgMode, newVnode.$flags$);\n }\n }\n }\n // add new & update changed attributes\n for (memberName in newVnodeAttrs) {\n setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode, newVnode.$flags$);\n }\n};\nconst createElm = (oldParentVNode, newParentVNode, childIndex, parentElm) => {\n // tslint:disable-next-line: prefer-const\n let newVNode = newParentVNode.$children$[childIndex];\n let i = 0;\n let elm;\n let childNode;\n let oldVNode;\n if (BUILD.slotRelocation && !useNativeShadowDom) {\n // remember for later we need to check to relocate nodes\n checkSlotRelocate = true;\n if (newVNode.$tag$ === 'slot') {\n if (scopeId) {\n // scoped css needs to add its scoped id to the parent element\n parentElm.classList.add(scopeId + '-s');\n }\n newVNode.$flags$ |= newVNode.$children$\n ? // slot element has fallback content\n 2 /* isSlotFallback */\n : // slot element does not have fallback content\n 1 /* isSlotReference */;\n }\n }\n if (BUILD.isDev && newVNode.$elm$) {\n consoleDevError(`The JSX ${newVNode.$text$ !== null ? `\"${newVNode.$text$}\" text` : `\"${newVNode.$tag$}\" element`} node should not be shared within the same renderer. The renderer caches element lookups in order to improve performance. However, a side effect from this is that the exact same JSX node should not be reused. For more information please see https://stenciljs.com/docs/templating-jsx#avoid-shared-jsx-nodes`);\n }\n if (BUILD.vdomText && newVNode.$text$ !== null) {\n // create text node\n elm = newVNode.$elm$ = doc.createTextNode(newVNode.$text$);\n }\n else if (BUILD.slotRelocation && newVNode.$flags$ & 1 /* isSlotReference */) {\n // create a slot reference node\n elm = newVNode.$elm$ = BUILD.isDebug || BUILD.hydrateServerSide ? slotReferenceDebugNode(newVNode) : doc.createTextNode('');\n }\n else {\n if (BUILD.svg && !isSvgMode) {\n isSvgMode = newVNode.$tag$ === 'svg';\n }\n // create element\n elm = newVNode.$elm$ = (BUILD.svg\n ? doc.createElementNS(isSvgMode ? SVG_NS : HTML_NS, BUILD.slotRelocation && newVNode.$flags$ & 2 /* isSlotFallback */ ? 'slot-fb' : newVNode.$tag$)\n : doc.createElement(BUILD.slotRelocation && newVNode.$flags$ & 2 /* isSlotFallback */ ? 'slot-fb' : newVNode.$tag$));\n if (BUILD.svg && isSvgMode && newVNode.$tag$ === 'foreignObject') {\n isSvgMode = false;\n }\n // add css classes, attrs, props, listeners, etc.\n if (BUILD.vdomAttribute) {\n updateElement(null, newVNode, isSvgMode);\n }\n if ((BUILD.shadowDom || BUILD.scoped) && isDef(scopeId) && elm['s-si'] !== scopeId) {\n // if there is a scopeId and this is the initial render\n // then let's add the scopeId as a css class\n elm.classList.add((elm['s-si'] = scopeId));\n }\n if (newVNode.$children$) {\n for (i = 0; i < newVNode.$children$.length; ++i) {\n // create the node\n childNode = createElm(oldParentVNode, newVNode, i, elm);\n // return node could have been null\n if (childNode) {\n // append our new node\n elm.appendChild(childNode);\n }\n }\n }\n if (BUILD.svg) {\n if (newVNode.$tag$ === 'svg') {\n // Only reset the SVG context when we're exiting <svg> element\n isSvgMode = false;\n }\n else if (elm.tagName === 'foreignObject') {\n // Reenter SVG context when we're exiting <foreignObject> element\n isSvgMode = true;\n }\n }\n }\n if (BUILD.slotRelocation) {\n elm['s-hn'] = hostTagName;\n if (newVNode.$flags$ & (2 /* isSlotFallback */ | 1 /* isSlotReference */)) {\n // remember the content reference comment\n elm['s-sr'] = true;\n // remember the content reference comment\n elm['s-cr'] = contentRef;\n // remember the slot name, or empty string for default slot\n elm['s-sn'] = newVNode.$name$ || '';\n // check if we've got an old vnode for this slot\n oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];\n if (oldVNode && oldVNode.$tag$ === newVNode.$tag$ && oldParentVNode.$elm$) {\n // we've got an old slot vnode and the wrapper is being replaced\n // so let's move the old slot content back to it's original location\n putBackInOriginalLocation(oldParentVNode.$elm$, false);\n }\n }\n }\n return elm;\n};\nconst putBackInOriginalLocation = (parentElm, recursive) => {\n plt.$flags$ |= 1 /* isTmpDisconnected */;\n const oldSlotChildNodes = parentElm.childNodes;\n for (let i = oldSlotChildNodes.length - 1; i >= 0; i--) {\n const childNode = oldSlotChildNodes[i];\n if (childNode['s-hn'] !== hostTagName && childNode['s-ol']) {\n // // this child node in the old element is from another component\n // // remove this node from the old slot's parent\n // childNode.remove();\n // and relocate it back to it's original location\n parentReferenceNode(childNode).insertBefore(childNode, referenceNode(childNode));\n // remove the old original location comment entirely\n // later on the patch function will know what to do\n // and move this to the correct spot in need be\n childNode['s-ol'].remove();\n childNode['s-ol'] = undefined;\n checkSlotRelocate = true;\n }\n if (recursive) {\n putBackInOriginalLocation(childNode, recursive);\n }\n }\n plt.$flags$ &= ~1 /* isTmpDisconnected */;\n};\nconst addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {\n let containerElm = ((BUILD.slotRelocation && parentElm['s-cr'] && parentElm['s-cr'].parentNode) || parentElm);\n let childNode;\n if (BUILD.shadowDom && containerElm.shadowRoot && containerElm.tagName === hostTagName) {\n containerElm = containerElm.shadowRoot;\n }\n for (; startIdx <= endIdx; ++startIdx) {\n if (vnodes[startIdx]) {\n childNode = createElm(null, parentVNode, startIdx, parentElm);\n if (childNode) {\n vnodes[startIdx].$elm$ = childNode;\n containerElm.insertBefore(childNode, BUILD.slotRelocation ? referenceNode(before) : before);\n }\n }\n }\n};\nconst removeVnodes = (vnodes, startIdx, endIdx, vnode, elm) => {\n for (; startIdx <= endIdx; ++startIdx) {\n if ((vnode = vnodes[startIdx])) {\n elm = vnode.$elm$;\n callNodeRefs(vnode);\n if (BUILD.slotRelocation) {\n // we're removing this element\n // so it's possible we need to show slot fallback content now\n checkSlotFallbackVisibility = true;\n if (elm['s-ol']) {\n // remove the original location comment\n elm['s-ol'].remove();\n }\n else {\n // it's possible that child nodes of the node\n // that's being removed are slot nodes\n putBackInOriginalLocation(elm, true);\n }\n }\n // remove the vnode's element from the dom\n elm.remove();\n }\n }\n};\nconst updateChildren = (parentElm, oldCh, newVNode, newCh) => {\n let oldStartIdx = 0;\n let newStartIdx = 0;\n let idxInOld = 0;\n let i = 0;\n let oldEndIdx = oldCh.length - 1;\n let oldStartVnode = oldCh[0];\n let oldEndVnode = oldCh[oldEndIdx];\n let newEndIdx = newCh.length - 1;\n let newStartVnode = newCh[0];\n let newEndVnode = newCh[newEndIdx];\n let node;\n let elmToMove;\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (oldStartVnode == null) {\n // Vnode might have been moved left\n oldStartVnode = oldCh[++oldStartIdx];\n }\n else if (oldEndVnode == null) {\n oldEndVnode = oldCh[--oldEndIdx];\n }\n else if (newStartVnode == null) {\n newStartVnode = newCh[++newStartIdx];\n }\n else if (newEndVnode == null) {\n newEndVnode = newCh[--newEndIdx];\n }\n else if (isSameVnode(oldStartVnode, newStartVnode)) {\n patch(oldStartVnode, newStartVnode);\n oldStartVnode = oldCh[++oldStartIdx];\n newStartVnode = newCh[++newStartIdx];\n }\n else if (isSameVnode(oldEndVnode, newEndVnode)) {\n patch(oldEndVnode, newEndVnode);\n oldEndVnode = oldCh[--oldEndIdx];\n newEndVnode = newCh[--newEndIdx];\n }\n else if (isSameVnode(oldStartVnode, newEndVnode)) {\n // Vnode moved right\n if (BUILD.slotRelocation && (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot')) {\n putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);\n }\n patch(oldStartVnode, newEndVnode);\n parentElm.insertBefore(oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);\n oldStartVnode = oldCh[++oldStartIdx];\n newEndVnode = newCh[--newEndIdx];\n }\n else if (isSameVnode(oldEndVnode, newStartVnode)) {\n // Vnode moved left\n if (BUILD.slotRelocation && (oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot')) {\n putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false);\n }\n patch(oldEndVnode, newStartVnode);\n parentElm.insertBefore(oldEndVnode.$elm$, oldStartVnode.$elm$);\n oldEndVnode = oldCh[--oldEndIdx];\n newStartVnode = newCh[++newStartIdx];\n }\n else {\n // createKeyToOldIdx\n idxInOld = -1;\n if (BUILD.vdomKey) {\n for (i = oldStartIdx; i <= oldEndIdx; ++i) {\n if (oldCh[i] && oldCh[i].$key$ !== null && oldCh[i].$key$ === newStartVnode.$key$) {\n idxInOld = i;\n break;\n }\n }\n }\n if (BUILD.vdomKey && idxInOld >= 0) {\n elmToMove = oldCh[idxInOld];\n if (elmToMove.$tag$ !== newStartVnode.$tag$) {\n node = createElm(oldCh && oldCh[newStartIdx], newVNode, idxInOld, parentElm);\n }\n else {\n patch(elmToMove, newStartVnode);\n oldCh[idxInOld] = undefined;\n node = elmToMove.$elm$;\n }\n newStartVnode = newCh[++newStartIdx];\n }\n else {\n // new element\n node = createElm(oldCh && oldCh[newStartIdx], newVNode, newStartIdx, parentElm);\n newStartVnode = newCh[++newStartIdx];\n }\n if (node) {\n if (BUILD.slotRelocation) {\n parentReferenceNode(oldStartVnode.$elm$).insertBefore(node, referenceNode(oldStartVnode.$elm$));\n }\n else {\n oldStartVnode.$elm$.parentNode.insertBefore(node, oldStartVnode.$elm$);\n }\n }\n }\n }\n if (oldStartIdx > oldEndIdx) {\n addVnodes(parentElm, newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$, newVNode, newCh, newStartIdx, newEndIdx);\n }\n else if (BUILD.updatable && newStartIdx > newEndIdx) {\n removeVnodes(oldCh, oldStartIdx, oldEndIdx);\n }\n};\nconst isSameVnode = (vnode1, vnode2) => {\n // compare if two vnode to see if they're \"technically\" the same\n // need to have the same element tag, and same key to be the same\n if (vnode1.$tag$ === vnode2.$tag$) {\n if (BUILD.slotRelocation && vnode1.$tag$ === 'slot') {\n return vnode1.$name$ === vnode2.$name$;\n }\n if (BUILD.vdomKey) {\n return vnode1.$key$ === vnode2.$key$;\n }\n return true;\n }\n return false;\n};\nconst referenceNode = (node) => {\n // this node was relocated to a new location in the dom\n // because of some other component's slot\n // but we still have an html comment in place of where\n // it's original location was according to it's original vdom\n return (node && node['s-ol']) || node;\n};\nconst parentReferenceNode = (node) => (node['s-ol'] ? node['s-ol'] : node).parentNode;\nconst patch = (oldVNode, newVNode) => {\n const elm = (newVNode.$elm$ = oldVNode.$elm$);\n const oldChildren = oldVNode.$children$;\n const newChildren = newVNode.$children$;\n const tag = newVNode.$tag$;\n const text = newVNode.$text$;\n let defaultHolder;\n if (!BUILD.vdomText || text === null) {\n if (BUILD.svg) {\n // test if we're rendering an svg element, or still rendering nodes inside of one\n // only add this to the when the compiler sees we're using an svg somewhere\n isSvgMode = tag === 'svg' ? true : tag === 'foreignObject' ? false : isSvgMode;\n }\n // element node\n if (BUILD.vdomAttribute || BUILD.reflect) {\n if (BUILD.slot && tag === 'slot')\n ;\n else {\n // either this is the first render of an element OR it's an update\n // AND we already know it's possible it could have changed\n // this updates the element's css classes, attrs, props, listeners, etc.\n updateElement(oldVNode, newVNode, isSvgMode);\n }\n }\n if (BUILD.updatable && oldChildren !== null && newChildren !== null) {\n // looks like there's child vnodes for both the old and new vnodes\n updateChildren(elm, oldChildren, newVNode, newChildren);\n }\n else if (newChildren !== null) {\n // no old child vnodes, but there are new child vnodes to add\n if (BUILD.updatable && BUILD.vdomText && oldVNode.$text$ !== null) {\n // the old vnode was text, so be sure to clear it out\n elm.textContent = '';\n }\n // add the new vnode children\n addVnodes(elm, null, newVNode, newChildren, 0, newChildren.length - 1);\n }\n else if (BUILD.updatable && oldChildren !== null) {\n // no new child vnodes, but there are old child vnodes to remove\n removeVnodes(oldChildren, 0, oldChildren.length - 1);\n }\n if (BUILD.svg && isSvgMode && tag === 'svg') {\n isSvgMode = false;\n }\n }\n else if (BUILD.vdomText && BUILD.slotRelocation && (defaultHolder = elm['s-cr'])) {\n // this element has slotted content\n defaultHolder.parentNode.textContent = text;\n }\n else if (BUILD.vdomText && oldVNode.$text$ !== text) {\n // update the text content for the text only vnode\n // and also only if the text is different than before\n elm.data = text;\n }\n};\nconst updateFallbackSlotVisibility = (elm) => {\n // tslint:disable-next-line: prefer-const\n let childNodes = elm.childNodes;\n let childNode;\n let i;\n let ilen;\n let j;\n let slotNameAttr;\n let nodeType;\n for (i = 0, ilen = childNodes.length; i < ilen; i++) {\n childNode = childNodes[i];\n if (childNode.nodeType === 1 /* ElementNode */) {\n if (childNode['s-sr']) {\n // this is a slot fallback node\n // get the slot name for this slot reference node\n slotNameAttr = childNode['s-sn'];\n // by default always show a fallback slot node\n // then hide it if there are other slots in the light dom\n childNode.hidden = false;\n for (j = 0; j < ilen; j++) {\n nodeType = childNodes[j].nodeType;\n if (childNodes[j]['s-hn'] !== childNode['s-hn'] || slotNameAttr !== '') {\n // this sibling node is from a different component OR is a named fallback slot node\n if (nodeType === 1 /* ElementNode */ && slotNameAttr === childNodes[j].getAttribute('slot')) {\n childNode.hidden = true;\n break;\n }\n }\n else {\n // this is a default fallback slot node\n // any element or text node (with content)\n // should hide the default fallback slot node\n if (nodeType === 1 /* ElementNode */ ||\n (nodeType === 3 /* TextNode */ && childNodes[j].textContent.trim() !== '')) {\n childNode.hidden = true;\n break;\n }\n }\n }\n }\n // keep drilling down\n updateFallbackSlotVisibility(childNode);\n }\n }\n};\nconst relocateNodes = [];\nconst relocateSlotContent = (elm) => {\n // tslint:disable-next-line: prefer-const\n let childNode;\n let node;\n let hostContentNodes;\n let slotNameAttr;\n let relocateNodeData;\n let j;\n let i = 0;\n let childNodes = elm.childNodes;\n let ilen = childNodes.length;\n for (; i < ilen; i++) {\n childNode = childNodes[i];\n if (childNode['s-sr'] && (node = childNode['s-cr']) && node.parentNode) {\n // first got the content reference comment node\n // then we got it's parent, which is where all the host content is in now\n hostContentNodes = node.parentNode.childNodes;\n slotNameAttr = childNode['s-sn'];\n for (j = hostContentNodes.length - 1; j >= 0; j--) {\n node = hostContentNodes[j];\n if (!node['s-cn'] && !node['s-nr'] && node['s-hn'] !== childNode['s-hn']) {\n // let's do some relocating to its new home\n // but never relocate a content reference node\n // that is suppose to always represent the original content location\n if (isNodeLocatedInSlot(node, slotNameAttr)) {\n // it's possible we've already decided to relocate this node\n relocateNodeData = relocateNodes.find(r => r.$nodeToRelocate$ === node);\n // made some changes to slots\n // let's make sure we also double check\n // fallbacks are correctly hidden or shown\n checkSlotFallbackVisibility = true;\n node['s-sn'] = node['s-sn'] || slotNameAttr;\n if (relocateNodeData) {\n // previously we never found a slot home for this node\n // but turns out we did, so let's remember it now\n relocateNodeData.$slotRefNode$ = childNode;\n }\n else {\n // add to our list of nodes to relocate\n relocateNodes.push({\n $slotRefNode$: childNode,\n $nodeToRelocate$: node,\n });\n }\n if (node['s-sr']) {\n relocateNodes.map(relocateNode => {\n if (isNodeLocatedInSlot(relocateNode.$nodeToRelocate$, node['s-sn'])) {\n relocateNodeData = relocateNodes.find(r => r.$nodeToRelocate$ === node);\n if (relocateNodeData && !relocateNode.$slotRefNode$) {\n relocateNode.$slotRefNode$ = relocateNodeData.$slotRefNode$;\n }\n }\n });\n }\n }\n else if (!relocateNodes.some(r => r.$nodeToRelocate$ === node)) {\n // so far this element does not have a slot home, not setting slotRefNode on purpose\n // if we never find a home for this element then we'll need to hide it\n relocateNodes.push({\n $nodeToRelocate$: node,\n });\n }\n }\n }\n }\n if (childNode.nodeType === 1 /* ElementNode */) {\n relocateSlotContent(childNode);\n }\n }\n};\nconst isNodeLocatedInSlot = (nodeToRelocate, slotNameAttr) => {\n if (nodeToRelocate.nodeType === 1 /* ElementNode */) {\n if (nodeToRelocate.getAttribute('slot') === null && slotNameAttr === '') {\n return true;\n }\n if (nodeToRelocate.getAttribute('slot') === slotNameAttr) {\n return true;\n }\n return false;\n }\n if (nodeToRelocate['s-sn'] === slotNameAttr) {\n return true;\n }\n return slotNameAttr === '';\n};\nconst callNodeRefs = (vNode) => {\n if (BUILD.vdomRef) {\n vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null);\n vNode.$children$ && vNode.$children$.map(callNodeRefs);\n }\n};\nconst renderVdom = (hostRef, renderFnResults) => {\n const hostElm = hostRef.$hostElement$;\n const cmpMeta = hostRef.$cmpMeta$;\n const oldVNode = hostRef.$vnode$ || newVNode(null, null);\n const rootVnode = isHost(renderFnResults) ? renderFnResults : h(null, null, renderFnResults);\n hostTagName = hostElm.tagName;\n // <Host> runtime check\n if (BUILD.isDev && Array.isArray(renderFnResults) && renderFnResults.some(isHost)) {\n throw new Error(`The <Host> must be the single root component.\nLooks like the render() function of \"${hostTagName.toLowerCase()}\" is returning an array that contains the <Host>.\n\nThe render() function should look like this instead:\n\nrender() {\n // Do not return an array\n return (\n <Host>{content}</Host>\n );\n}\n `);\n }\n if (BUILD.reflect && cmpMeta.$attrsToReflect$) {\n rootVnode.$attrs$ = rootVnode.$attrs$ || {};\n cmpMeta.$attrsToReflect$.map(([propName, attribute]) => (rootVnode.$attrs$[attribute] = hostElm[propName]));\n }\n rootVnode.$tag$ = null;\n rootVnode.$flags$ |= 4 /* isHost */;\n hostRef.$vnode$ = rootVnode;\n rootVnode.$elm$ = oldVNode.$elm$ = (BUILD.shadowDom ? hostElm.shadowRoot || hostElm : hostElm);\n if (BUILD.scoped || BUILD.shadowDom) {\n scopeId = hostElm['s-sc'];\n }\n if (BUILD.slotRelocation) {\n contentRef = hostElm['s-cr'];\n useNativeShadowDom = supportsShadow && (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) !== 0;\n // always reset\n checkSlotFallbackVisibility = false;\n }\n // synchronous patch\n patch(oldVNode, rootVnode);\n if (BUILD.slotRelocation) {\n // while we're moving nodes around existing nodes, temporarily disable\n // the disconnectCallback from working\n plt.$flags$ |= 1 /* isTmpDisconnected */;\n if (checkSlotRelocate) {\n relocateSlotContent(rootVnode.$elm$);\n let relocateData;\n let nodeToRelocate;\n let orgLocationNode;\n let parentNodeRef;\n let insertBeforeNode;\n let refNode;\n let i = 0;\n for (; i < relocateNodes.length; i++) {\n relocateData = relocateNodes[i];\n nodeToRelocate = relocateData.$nodeToRelocate$;\n if (!nodeToRelocate['s-ol']) {\n // add a reference node marking this node's original location\n // keep a reference to this node for later lookups\n orgLocationNode = BUILD.isDebug || BUILD.hydrateServerSide ? originalLocationDebugNode(nodeToRelocate) : doc.createTextNode('');\n orgLocationNode['s-nr'] = nodeToRelocate;\n nodeToRelocate.parentNode.insertBefore((nodeToRelocate['s-ol'] = orgLocationNode), nodeToRelocate);\n }\n }\n for (i = 0; i < relocateNodes.length; i++) {\n relocateData = relocateNodes[i];\n nodeToRelocate = relocateData.$nodeToRelocate$;\n if (relocateData.$slotRefNode$) {\n // by default we're just going to insert it directly\n // after the slot reference node\n parentNodeRef = relocateData.$slotRefNode$.parentNode;\n insertBeforeNode = relocateData.$slotRefNode$.nextSibling;\n orgLocationNode = nodeToRelocate['s-ol'];\n while ((orgLocationNode = orgLocationNode.previousSibling)) {\n refNode = orgLocationNode['s-nr'];\n if (refNode && refNode['s-sn'] === nodeToRelocate['s-sn'] && parentNodeRef === refNode.parentNode) {\n refNode = refNode.nextSibling;\n if (!refNode || !refNode['s-nr']) {\n insertBeforeNode = refNode;\n break;\n }\n }\n }\n if ((!insertBeforeNode && parentNodeRef !== nodeToRelocate.parentNode) || nodeToRelocate.nextSibling !== insertBeforeNode) {\n // we've checked that it's worth while to relocate\n // since that the node to relocate\n // has a different next sibling or parent relocated\n if (nodeToRelocate !== insertBeforeNode) {\n if (!nodeToRelocate['s-hn'] && nodeToRelocate['s-ol']) {\n // probably a component in the index.html that doesn't have it's hostname set\n nodeToRelocate['s-hn'] = nodeToRelocate['s-ol'].parentNode.nodeName;\n }\n // add it back to the dom but in its new home\n parentNodeRef.insertBefore(nodeToRelocate, insertBeforeNode);\n }\n }\n }\n else {\n // this node doesn't have a slot home to go to, so let's hide it\n if (nodeToRelocate.nodeType === 1 /* ElementNode */) {\n nodeToRelocate.hidden = true;\n }\n }\n }\n }\n if (checkSlotFallbackVisibility) {\n updateFallbackSlotVisibility(rootVnode.$elm$);\n }\n // done moving nodes around\n // allow the disconnect callback to work again\n plt.$flags$ &= ~1 /* isTmpDisconnected */;\n // always reset\n relocateNodes.length = 0;\n }\n};\n// slot comment debug nodes only created with the `--debug` flag\n// otherwise these nodes are text nodes w/out content\nconst slotReferenceDebugNode = (slotVNode) => doc.createComment(`<slot${slotVNode.$name$ ? ' name=\"' + slotVNode.$name$ + '\"' : ''}> (host=${hostTagName.toLowerCase()})`);\nconst originalLocationDebugNode = (nodeToRelocate) => doc.createComment(`org-location for ` + (nodeToRelocate.localName ? `<${nodeToRelocate.localName}> (host=${nodeToRelocate['s-hn']})` : `[${nodeToRelocate.textContent}]`));\nconst getElement = (ref) => (BUILD.lazyLoad ? getHostRef(ref).$hostElement$ : ref);\nconst createEvent = (ref, name, flags) => {\n const elm = getElement(ref);\n return {\n emit: (detail) => {\n if (BUILD.isDev && !elm.isConnected) {\n consoleDevWarn(`The \"${name}\" event was emitted, but the dispatcher node is no longer connected to the dom.`);\n }\n return emitEvent(elm, name, {\n bubbles: !!(flags & 4 /* Bubbles */),\n composed: !!(flags & 2 /* Composed */),\n cancelable: !!(flags & 1 /* Cancellable */),\n detail,\n });\n },\n };\n};\nconst emitEvent = (elm, name, opts) => {\n const ev = plt.ce(name, opts);\n elm.dispatchEvent(ev);\n return ev;\n};\nconst attachToAncestor = (hostRef, ancestorComponent) => {\n if (BUILD.asyncLoading && ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent['s-p']) {\n ancestorComponent['s-p'].push(new Promise(r => (hostRef.$onRenderResolve$ = r)));\n }\n};\nconst scheduleUpdate = (hostRef, isInitialLoad) => {\n if (BUILD.taskQueue && BUILD.updatable) {\n hostRef.$flags$ |= 16 /* isQueuedForUpdate */;\n }\n if (BUILD.asyncLoading && hostRef.$flags$ & 4 /* isWaitingForChildren */) {\n hostRef.$flags$ |= 512 /* needsRerender */;\n return;\n }\n attachToAncestor(hostRef, hostRef.$ancestorComponent$);\n // there is no ancestor component or the ancestor component\n // has already fired off its lifecycle update then\n // fire off the initial update\n const dispatch = () => dispatchHooks(hostRef, isInitialLoad);\n return BUILD.taskQueue ? writeTask(dispatch) : dispatch();\n};\nconst dispatchHooks = (hostRef, isInitialLoad) => {\n const elm = hostRef.$hostElement$;\n const endSchedule = createTime('scheduleUpdate', hostRef.$cmpMeta$.$tagName$);\n const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;\n let promise;\n if (isInitialLoad) {\n if (BUILD.lazyLoad && BUILD.hostListener) {\n hostRef.$flags$ |= 256 /* isListenReady */;\n if (hostRef.$queuedListeners$) {\n hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event));\n hostRef.$queuedListeners$ = null;\n }\n }\n emitLifecycleEvent(elm, 'componentWillLoad');\n if (BUILD.cmpWillLoad) {\n promise = safeCall(instance, 'componentWillLoad');\n }\n }\n else {\n emitLifecycleEvent(elm, 'componentWillUpdate');\n if (BUILD.cmpWillUpdate) {\n promise = safeCall(instance, 'componentWillUpdate');\n }\n }\n emitLifecycleEvent(elm, 'componentWillRender');\n if (BUILD.cmpWillRender) {\n promise = then(promise, () => safeCall(instance, 'componentWillRender'));\n }\n endSchedule();\n return then(promise, () => updateComponent(hostRef, instance, isInitialLoad));\n};\nconst updateComponent = async (hostRef, instance, isInitialLoad) => {\n // updateComponent\n const elm = hostRef.$hostElement$;\n const endUpdate = createTime('update', hostRef.$cmpMeta$.$tagName$);\n const rc = elm['s-rc'];\n if (BUILD.style && isInitialLoad) {\n // DOM WRITE!\n attachStyles(hostRef);\n }\n const endRender = createTime('render', hostRef.$cmpMeta$.$tagName$);\n if (BUILD.isDev) {\n hostRef.$flags$ |= 1024 /* devOnRender */;\n }\n if (BUILD.hydrateServerSide) {\n await callRender(hostRef, instance, elm);\n }\n else {\n callRender(hostRef, instance, elm);\n }\n if (BUILD.cssVarShim && plt.$cssShim$) {\n plt.$cssShim$.updateHost(elm);\n }\n if (BUILD.isDev) {\n hostRef.$renderCount$++;\n hostRef.$flags$ &= ~1024 /* devOnRender */;\n }\n if (BUILD.hydrateServerSide) {\n try {\n // manually connected child components during server-side hydrate\n serverSideConnected(elm);\n if (isInitialLoad) {\n // using only during server-side hydrate\n if (hostRef.$cmpMeta$.$flags$ & 1 /* shadowDomEncapsulation */) {\n elm['s-en'] = '';\n }\n else if (hostRef.$cmpMeta$.$flags$ & 2 /* scopedCssEncapsulation */) {\n elm['s-en'] = 'c';\n }\n }\n }\n catch (e) {\n consoleError(e, elm);\n }\n }\n if (BUILD.asyncLoading && rc) {\n // ok, so turns out there are some child host elements\n // waiting on this parent element to load\n // let's fire off all update callbacks waiting\n rc.map(cb => cb());\n elm['s-rc'] = undefined;\n }\n endRender();\n endUpdate();\n if (BUILD.asyncLoading) {\n const childrenPromises = elm['s-p'];\n const postUpdate = () => postUpdateComponent(hostRef);\n if (childrenPromises.length === 0) {\n postUpdate();\n }\n else {\n Promise.all(childrenPromises).then(postUpdate);\n hostRef.$flags$ |= 4 /* isWaitingForChildren */;\n childrenPromises.length = 0;\n }\n }\n else {\n postUpdateComponent(hostRef);\n }\n};\nconst callRender = (hostRef, instance, elm) => {\n // in order for bundlers to correctly treeshake the BUILD object\n // we need to ensure BUILD is not deoptimized within a try/catch\n // https://rollupjs.org/guide/en/#treeshake tryCatchDeoptimization\n const allRenderFn = BUILD.allRenderFn ? true : false;\n const lazyLoad = BUILD.lazyLoad ? true : false;\n const taskQueue = BUILD.taskQueue ? true : false;\n const updatable = BUILD.updatable ? true : false;\n try {\n renderingRef = instance;\n instance = allRenderFn ? instance.render() : instance.render && instance.render();\n if (updatable && taskQueue) {\n hostRef.$flags$ &= ~16 /* isQueuedForUpdate */;\n }\n if (updatable || lazyLoad) {\n hostRef.$flags$ |= 2 /* hasRendered */;\n }\n if (BUILD.hasRenderFn || BUILD.reflect) {\n if (BUILD.vdomRender || BUILD.reflect) {\n // looks like we've got child nodes to render into this host element\n // or we need to update the css class/attrs on the host element\n // DOM WRITE!\n if (BUILD.hydrateServerSide) {\n return Promise.resolve(instance).then(value => renderVdom(hostRef, value));\n }\n else {\n renderVdom(hostRef, instance);\n }\n }\n else {\n elm.textContent = instance;\n }\n }\n }\n catch (e) {\n consoleError(e, hostRef.$hostElement$);\n }\n renderingRef = null;\n return null;\n};\nconst getRenderingRef = () => renderingRef;\nconst postUpdateComponent = (hostRef) => {\n const tagName = hostRef.$cmpMeta$.$tagName$;\n const elm = hostRef.$hostElement$;\n const endPostUpdate = createTime('postUpdate', tagName);\n const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;\n const ancestorComponent = hostRef.$ancestorComponent$;\n if (BUILD.cmpDidRender) {\n if (BUILD.isDev) {\n hostRef.$flags$ |= 1024 /* devOnRender */;\n }\n safeCall(instance, 'componentDidRender');\n if (BUILD.isDev) {\n hostRef.$flags$ &= ~1024 /* devOnRender */;\n }\n }\n emitLifecycleEvent(elm, 'componentDidRender');\n if (!(hostRef.$flags$ & 64 /* hasLoadedComponent */)) {\n hostRef.$flags$ |= 64 /* hasLoadedComponent */;\n if (BUILD.asyncLoading && BUILD.cssAnnotations) {\n // DOM WRITE!\n addHydratedFlag(elm);\n }\n if (BUILD.cmpDidLoad) {\n if (BUILD.isDev) {\n hostRef.$flags$ |= 2048 /* devOnDidLoad */;\n }\n safeCall(instance, 'componentDidLoad');\n if (BUILD.isDev) {\n hostRef.$flags$ &= ~2048 /* devOnDidLoad */;\n }\n }\n emitLifecycleEvent(elm, 'componentDidLoad');\n endPostUpdate();\n if (BUILD.asyncLoading) {\n hostRef.$onReadyResolve$(elm);\n if (!ancestorComponent) {\n appDidLoad(tagName);\n }\n }\n }\n else {\n if (BUILD.cmpDidUpdate) {\n // we've already loaded this component\n // fire off the user's componentDidUpdate method (if one was provided)\n // componentDidUpdate runs AFTER render() has been called\n // and all child components have finished updating\n if (BUILD.isDev) {\n hostRef.$flags$ |= 1024 /* devOnRender */;\n }\n safeCall(instance, 'componentDidUpdate');\n if (BUILD.isDev) {\n hostRef.$flags$ &= ~1024 /* devOnRender */;\n }\n }\n emitLifecycleEvent(elm, 'componentDidUpdate');\n endPostUpdate();\n }\n if (BUILD.hotModuleReplacement) {\n elm['s-hmr-load'] && elm['s-hmr-load']();\n }\n if (BUILD.method && BUILD.lazyLoad) {\n hostRef.$onInstanceResolve$(elm);\n }\n // load events fire from bottom to top\n // the deepest elements load first then bubbles up\n if (BUILD.asyncLoading) {\n if (hostRef.$onRenderResolve$) {\n hostRef.$onRenderResolve$();\n hostRef.$onRenderResolve$ = undefined;\n }\n if (hostRef.$flags$ & 512 /* needsRerender */) {\n nextTick(() => scheduleUpdate(hostRef, false));\n }\n hostRef.$flags$ &= ~(4 /* isWaitingForChildren */ | 512 /* needsRerender */);\n }\n // ( •_•)\n // ( •_•)>⌐■-■\n // (⌐■_■)\n};\nconst forceUpdate = (ref) => {\n if (BUILD.updatable) {\n const hostRef = getHostRef(ref);\n const isConnected = hostRef.$hostElement$.isConnected;\n if (isConnected && (hostRef.$flags$ & (2 /* hasRendered */ | 16 /* isQueuedForUpdate */)) === 2 /* hasRendered */) {\n scheduleUpdate(hostRef, false);\n }\n // Returns \"true\" when the forced update was successfully scheduled\n return isConnected;\n }\n return false;\n};\nconst appDidLoad = (who) => {\n // on appload\n // we have finish the first big initial render\n if (BUILD.cssAnnotations) {\n addHydratedFlag(doc.documentElement);\n }\n if (BUILD.asyncQueue) {\n plt.$flags$ |= 2 /* appLoaded */;\n }\n nextTick(() => emitEvent(win, 'appload', { detail: { namespace: NAMESPACE } }));\n if (BUILD.profile && performance.measure) {\n performance.measure(`[Stencil] ${NAMESPACE} initial load (by ${who})`, 'st:app:start');\n }\n};\nconst safeCall = (instance, method, arg) => {\n if (instance && instance[method]) {\n try {\n return instance[method](arg);\n }\n catch (e) {\n consoleError(e);\n }\n }\n return undefined;\n};\nconst then = (promise, thenFn) => {\n return promise && promise.then ? promise.then(thenFn) : thenFn();\n};\nconst emitLifecycleEvent = (elm, lifecycleName) => {\n if (BUILD.lifecycleDOMEvents) {\n emitEvent(elm, 'stencil_' + lifecycleName, {\n bubbles: true,\n composed: true,\n detail: {\n namespace: NAMESPACE,\n },\n });\n }\n};\nconst addHydratedFlag = (elm) => (BUILD.hydratedClass ? elm.classList.add('hydrated') : BUILD.hydratedAttribute ? elm.setAttribute('hydrated', '') : undefined);\nconst serverSideConnected = (elm) => {\n const children = elm.children;\n if (children != null) {\n for (let i = 0, ii = children.length; i < ii; i++) {\n const childElm = children[i];\n if (typeof childElm.connectedCallback === 'function') {\n childElm.connectedCallback();\n }\n serverSideConnected(childElm);\n }\n }\n};\nconst initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {\n const endHydrate = createTime('hydrateClient', tagName);\n const shadowRoot = hostElm.shadowRoot;\n const childRenderNodes = [];\n const slotNodes = [];\n const shadowRootNodes = BUILD.shadowDom && shadowRoot ? [] : null;\n const vnode = (hostRef.$vnode$ = newVNode(tagName, null));\n if (!plt.$orgLocNodes$) {\n initializeDocumentHydrate(doc.body, (plt.$orgLocNodes$ = new Map()));\n }\n hostElm[HYDRATE_ID] = hostId;\n hostElm.removeAttribute(HYDRATE_ID);\n clientHydrate(vnode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, hostElm, hostId);\n childRenderNodes.map(c => {\n const orgLocationId = c.$hostId$ + '.' + c.$nodeId$;\n const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId);\n const node = c.$elm$;\n if (orgLocationNode && supportsShadow && orgLocationNode['s-en'] === '') {\n orgLocationNode.parentNode.insertBefore(node, orgLocationNode.nextSibling);\n }\n if (!shadowRoot) {\n node['s-hn'] = tagName;\n if (orgLocationNode) {\n node['s-ol'] = orgLocationNode;\n node['s-ol']['s-nr'] = node;\n }\n }\n plt.$orgLocNodes$.delete(orgLocationId);\n });\n if (BUILD.shadowDom && shadowRoot) {\n shadowRootNodes.map(shadowRootNode => {\n if (shadowRootNode) {\n shadowRoot.appendChild(shadowRootNode);\n }\n });\n }\n endHydrate();\n};\nconst clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node, hostId) => {\n let childNodeType;\n let childIdSplt;\n let childVNode;\n let i;\n if (node.nodeType === 1 /* ElementNode */) {\n childNodeType = node.getAttribute(HYDRATE_CHILD_ID);\n if (childNodeType) {\n // got the node data from the element's attribute\n // `${hostId}.${nodeId}.${depth}.${index}`\n childIdSplt = childNodeType.split('.');\n if (childIdSplt[0] === hostId || childIdSplt[0] === '0') {\n childVNode = {\n $flags$: 0,\n $hostId$: childIdSplt[0],\n $nodeId$: childIdSplt[1],\n $depth$: childIdSplt[2],\n $index$: childIdSplt[3],\n $tag$: node.tagName.toLowerCase(),\n $elm$: node,\n $attrs$: null,\n $children$: null,\n $key$: null,\n $name$: null,\n $text$: null,\n };\n childRenderNodes.push(childVNode);\n node.removeAttribute(HYDRATE_CHILD_ID);\n // this is a new child vnode\n // so ensure its parent vnode has the vchildren array\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n // add our child vnode to a specific index of the vnode's children\n parentVNode.$children$[childVNode.$index$] = childVNode;\n // this is now the new parent vnode for all the next child checks\n parentVNode = childVNode;\n if (shadowRootNodes && childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n }\n // recursively drill down, end to start so we can remove nodes\n for (i = node.childNodes.length - 1; i >= 0; i--) {\n clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.childNodes[i], hostId);\n }\n if (node.shadowRoot) {\n // keep drilling down through the shadow root nodes\n for (i = node.shadowRoot.childNodes.length - 1; i >= 0; i--) {\n clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.shadowRoot.childNodes[i], hostId);\n }\n }\n }\n else if (node.nodeType === 8 /* CommentNode */) {\n // `${COMMENT_TYPE}.${hostId}.${nodeId}.${depth}.${index}`\n childIdSplt = node.nodeValue.split('.');\n if (childIdSplt[1] === hostId || childIdSplt[1] === '0') {\n // comment node for either the host id or a 0 host id\n childNodeType = childIdSplt[0];\n childVNode = {\n $flags$: 0,\n $hostId$: childIdSplt[1],\n $nodeId$: childIdSplt[2],\n $depth$: childIdSplt[3],\n $index$: childIdSplt[4],\n $elm$: node,\n $attrs$: null,\n $children$: null,\n $key$: null,\n $name$: null,\n $tag$: null,\n $text$: null,\n };\n if (childNodeType === TEXT_NODE_ID) {\n childVNode.$elm$ = node.nextSibling;\n if (childVNode.$elm$ && childVNode.$elm$.nodeType === 3 /* TextNode */) {\n childVNode.$text$ = childVNode.$elm$.textContent;\n childRenderNodes.push(childVNode);\n // remove the text comment since it's no longer needed\n node.remove();\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n parentVNode.$children$[childVNode.$index$] = childVNode;\n if (shadowRootNodes && childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n }\n else if (childVNode.$hostId$ === hostId) {\n // this comment node is specifcally for this host id\n if (childNodeType === SLOT_NODE_ID) {\n // `${SLOT_NODE_ID}.${hostId}.${nodeId}.${depth}.${index}.${slotName}`;\n childVNode.$tag$ = 'slot';\n if (childIdSplt[5]) {\n node['s-sn'] = childVNode.$name$ = childIdSplt[5];\n }\n else {\n node['s-sn'] = '';\n }\n node['s-sr'] = true;\n if (BUILD.shadowDom && shadowRootNodes) {\n // browser support shadowRoot and this is a shadow dom component\n // create an actual slot element\n childVNode.$elm$ = doc.createElement(childVNode.$tag$);\n if (childVNode.$name$) {\n // add the slot name attribute\n childVNode.$elm$.setAttribute('name', childVNode.$name$);\n }\n // insert the new slot element before the slot comment\n node.parentNode.insertBefore(childVNode.$elm$, node);\n // remove the slot comment since it's not needed for shadow\n node.remove();\n if (childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n slotNodes.push(childVNode);\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n parentVNode.$children$[childVNode.$index$] = childVNode;\n }\n else if (childNodeType === CONTENT_REF_ID) {\n // `${CONTENT_REF_ID}.${hostId}`;\n if (BUILD.shadowDom && shadowRootNodes) {\n // remove the content ref comment since it's not needed for shadow\n node.remove();\n }\n else if (BUILD.slotRelocation) {\n hostElm['s-cr'] = node;\n node['s-cn'] = true;\n }\n }\n }\n }\n }\n else if (parentVNode && parentVNode.$tag$ === 'style') {\n const vnode = newVNode(null, node.textContent);\n vnode.$elm$ = node;\n vnode.$index$ = '0';\n parentVNode.$children$ = [vnode];\n }\n};\nconst initializeDocumentHydrate = (node, orgLocNodes) => {\n if (node.nodeType === 1 /* ElementNode */) {\n let i = 0;\n for (; i < node.childNodes.length; i++) {\n initializeDocumentHydrate(node.childNodes[i], orgLocNodes);\n }\n if (node.shadowRoot) {\n for (i = 0; i < node.shadowRoot.childNodes.length; i++) {\n initializeDocumentHydrate(node.shadowRoot.childNodes[i], orgLocNodes);\n }\n }\n }\n else if (node.nodeType === 8 /* CommentNode */) {\n const childIdSplt = node.nodeValue.split('.');\n if (childIdSplt[0] === ORG_LOCATION_ID) {\n orgLocNodes.set(childIdSplt[1] + '.' + childIdSplt[2], node);\n node.nodeValue = '';\n // useful to know if the original location is\n // the root light-dom of a shadow dom component\n node['s-en'] = childIdSplt[3];\n }\n }\n};\nconst parsePropertyValue = (propValue, propType) => {\n // ensure this value is of the correct prop type\n if (propValue != null && !isComplexType(propValue)) {\n if (BUILD.propBoolean && propType & 4 /* Boolean */) {\n // per the HTML spec, any string value means it is a boolean true value\n // but we'll cheat here and say that the string \"false\" is the boolean false\n return propValue === 'false' ? false : propValue === '' || !!propValue;\n }\n if (BUILD.propNumber && propType & 2 /* Number */) {\n // force it to be a number\n return parseFloat(propValue);\n }\n if (BUILD.propString && propType & 1 /* String */) {\n // could have been passed as a number or boolean\n // but we still want it as a string\n return String(propValue);\n }\n // redundant return here for better minification\n return propValue;\n }\n // not sure exactly what type we want\n // so no need to change to a different type\n return propValue;\n};\nconst getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName);\nconst setValue = (ref, propName, newVal, cmpMeta) => {\n // check our new property value against our internal value\n const hostRef = getHostRef(ref);\n const elm = BUILD.lazyLoad ? hostRef.$hostElement$ : ref;\n const oldVal = hostRef.$instanceValues$.get(propName);\n const flags = hostRef.$flags$;\n const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;\n newVal = parsePropertyValue(newVal, cmpMeta.$members$[propName][0]);\n if ((!BUILD.lazyLoad || !(flags & 8 /* isConstructingInstance */) || oldVal === undefined) && newVal !== oldVal) {\n // gadzooks! the property's value has changed!!\n // set our new value!\n hostRef.$instanceValues$.set(propName, newVal);\n if (BUILD.isDev) {\n if (hostRef.$flags$ & 1024 /* devOnRender */) {\n consoleDevWarn(`The state/prop \"${propName}\" changed during rendering. This can potentially lead to infinite-loops and other bugs.`, '\\nElement', elm, '\\nNew value', newVal, '\\nOld value', oldVal);\n }\n else if (hostRef.$flags$ & 2048 /* devOnDidLoad */) {\n consoleDevWarn(`The state/prop \"${propName}\" changed during \"componentDidLoad()\", this triggers extra re-renders, try to setup on \"componentWillLoad()\"`, '\\nElement', elm, '\\nNew value', newVal, '\\nOld value', oldVal);\n }\n }\n if (!BUILD.lazyLoad || instance) {\n // get an array of method names of watch functions to call\n if (BUILD.watchCallback && cmpMeta.$watchers$ && flags & 128 /* isWatchReady */) {\n const watchMethods = cmpMeta.$watchers$[propName];\n if (watchMethods) {\n // this instance is watching for when this property changed\n watchMethods.map(watchMethodName => {\n try {\n // fire off each of the watch methods that are watching this property\n instance[watchMethodName](newVal, oldVal, propName);\n }\n catch (e) {\n consoleError(e, elm);\n }\n });\n }\n }\n if (BUILD.updatable && (flags & (2 /* hasRendered */ | 16 /* isQueuedForUpdate */)) === 2 /* hasRendered */) {\n if (BUILD.cmpShouldUpdate && instance.componentShouldUpdate) {\n if (instance.componentShouldUpdate(newVal, oldVal, propName) === false) {\n return;\n }\n }\n // looks like this value actually changed, so we've got work to do!\n // but only if we've already rendered, otherwise just chill out\n // queue that we need to do an update, but don't worry about queuing\n // up millions cuz this function ensures it only runs once\n scheduleUpdate(hostRef, false);\n }\n }\n }\n};\nconst proxyComponent = (Cstr, cmpMeta, flags) => {\n if (BUILD.member && cmpMeta.$members$) {\n if (BUILD.watchCallback && Cstr.watchers) {\n cmpMeta.$watchers$ = Cstr.watchers;\n }\n // It's better to have a const than two Object.entries()\n const members = Object.entries(cmpMeta.$members$);\n const prototype = Cstr.prototype;\n members.map(([memberName, [memberFlags]]) => {\n if ((BUILD.prop || BUILD.state) && (memberFlags & 31 /* Prop */ || ((!BUILD.lazyLoad || flags & 2 /* proxyState */) && memberFlags & 32 /* State */))) {\n // proxyComponent - prop\n Object.defineProperty(prototype, memberName, {\n get() {\n // proxyComponent, get value\n return getValue(this, memberName);\n },\n set(newValue) {\n // only during dev time\n if (BUILD.isDev) {\n const ref = getHostRef(this);\n if (\n // we are proxying the instance (not element)\n (flags & 1 /* isElementConstructor */) === 0 &&\n // the element is not constructing\n (ref.$flags$ & 8 /* isConstructingInstance */) === 0 &&\n // the member is a prop\n (memberFlags & 31 /* Prop */) !== 0 &&\n // the member is not mutable\n (memberFlags & 1024 /* Mutable */) === 0) {\n consoleDevWarn(`@Prop() \"${memberName}\" on <${cmpMeta.$tagName$}> is immutable but was modified from within the component.\\nMore information: https://stenciljs.com/docs/properties#prop-mutability`);\n }\n }\n // proxyComponent, set value\n setValue(this, memberName, newValue, cmpMeta);\n },\n configurable: true,\n enumerable: true,\n });\n }\n else if (BUILD.lazyLoad && BUILD.method && flags & 1 /* isElementConstructor */ && memberFlags & 64 /* Method */) {\n // proxyComponent - method\n Object.defineProperty(prototype, memberName, {\n value(...args) {\n const ref = getHostRef(this);\n return ref.$onInstancePromise$.then(() => ref.$lazyInstance$[memberName](...args));\n },\n });\n }\n });\n if (BUILD.observeAttribute && (!BUILD.lazyLoad || flags & 1 /* isElementConstructor */)) {\n const attrNameToPropName = new Map();\n prototype.attributeChangedCallback = function (attrName, _oldValue, newValue) {\n plt.jmp(() => {\n const propName = attrNameToPropName.get(attrName);\n this[propName] = newValue === null && typeof this[propName] === 'boolean' ? false : newValue;\n });\n };\n // create an array of attributes to observe\n // and also create a map of html attribute name to js property name\n Cstr.observedAttributes = members\n .filter(([_, m]) => m[0] & 15 /* HasAttribute */) // filter to only keep props that should match attributes\n .map(([propName, m]) => {\n const attrName = m[1] || propName;\n attrNameToPropName.set(attrName, propName);\n if (BUILD.reflect && m[0] & 512 /* ReflectAttr */) {\n cmpMeta.$attrsToReflect$.push([propName, attrName]);\n }\n return attrName;\n });\n }\n }\n return Cstr;\n};\nconst initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId, Cstr) => {\n // initializeComponent\n if ((BUILD.lazyLoad || BUILD.hydrateServerSide || BUILD.style) && (hostRef.$flags$ & 32 /* hasInitializedComponent */) === 0) {\n if (BUILD.lazyLoad || BUILD.hydrateClientSide) {\n // we haven't initialized this element yet\n hostRef.$flags$ |= 32 /* hasInitializedComponent */;\n // lazy loaded components\n // request the component's implementation to be\n // wired up with the host element\n Cstr = loadModule(cmpMeta, hostRef, hmrVersionId);\n if (Cstr.then) {\n // Await creates a micro-task avoid if possible\n const endLoad = uniqueTime(`st:load:${cmpMeta.$tagName$}:${hostRef.$modeName$}`, `[Stencil] Load module for <${cmpMeta.$tagName$}>`);\n Cstr = await Cstr;\n endLoad();\n }\n if ((BUILD.isDev || BUILD.isDebug) && !Cstr) {\n throw new Error(`Constructor for \"${cmpMeta.$tagName$}#${hostRef.$modeName$}\" was not found`);\n }\n if (BUILD.member && !Cstr.isProxied) {\n // we'eve never proxied this Constructor before\n // let's add the getters/setters to its prototype before\n // the first time we create an instance of the implementation\n if (BUILD.watchCallback) {\n cmpMeta.$watchers$ = Cstr.watchers;\n }\n proxyComponent(Cstr, cmpMeta, 2 /* proxyState */);\n Cstr.isProxied = true;\n }\n const endNewInstance = createTime('createInstance', cmpMeta.$tagName$);\n // ok, time to construct the instance\n // but let's keep track of when we start and stop\n // so that the getters/setters don't incorrectly step on data\n if (BUILD.member) {\n hostRef.$flags$ |= 8 /* isConstructingInstance */;\n }\n // construct the lazy-loaded component implementation\n // passing the hostRef is very important during\n // construction in order to directly wire together the\n // host element and the lazy-loaded instance\n try {\n new Cstr(hostRef);\n }\n catch (e) {\n consoleError(e);\n }\n if (BUILD.member) {\n hostRef.$flags$ &= ~8 /* isConstructingInstance */;\n }\n if (BUILD.watchCallback) {\n hostRef.$flags$ |= 128 /* isWatchReady */;\n }\n endNewInstance();\n fireConnectedCallback(hostRef.$lazyInstance$);\n }\n else {\n // sync constructor component\n Cstr = elm.constructor;\n hostRef.$flags$ |= 128 /* isWatchReady */ | 32 /* hasInitializedComponent */;\n }\n if (BUILD.style && Cstr.style) {\n // this component has styles but we haven't registered them yet\n let style = Cstr.style;\n if (BUILD.mode && typeof style !== 'string') {\n style = style[(hostRef.$modeName$ = computeMode(elm))];\n if (BUILD.hydrateServerSide && hostRef.$modeName$) {\n elm.setAttribute('s-mode', hostRef.$modeName$);\n }\n }\n const scopeId = getScopeId(cmpMeta, hostRef.$modeName$);\n if (!styles.has(scopeId)) {\n const endRegisterStyles = createTime('registerStyles', cmpMeta.$tagName$);\n if (!BUILD.hydrateServerSide && BUILD.shadowDom && BUILD.shadowDomShim && cmpMeta.$flags$ & 8 /* needsShadowDomShim */) {\n style = await import('./shadow-css.js').then(m => m.scopeCss(style, scopeId, false));\n }\n registerStyle(scopeId, style, !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */));\n endRegisterStyles();\n }\n }\n }\n // we've successfully created a lazy instance\n const ancestorComponent = hostRef.$ancestorComponent$;\n const schedule = () => scheduleUpdate(hostRef, true);\n if (BUILD.asyncLoading && ancestorComponent && ancestorComponent['s-rc']) {\n // this is the intial load and this component it has an ancestor component\n // but the ancestor component has NOT fired its will update lifecycle yet\n // so let's just cool our jets and wait for the ancestor to continue first\n // this will get fired off when the ancestor component\n // finally gets around to rendering its lazy self\n // fire off the initial update\n ancestorComponent['s-rc'].push(schedule);\n }\n else {\n schedule();\n }\n};\nconst fireConnectedCallback = (instance) => {\n if (BUILD.lazyLoad && BUILD.connectedCallback) {\n safeCall(instance, 'connectedCallback');\n }\n};\nconst connectedCallback = (elm) => {\n if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {\n const hostRef = getHostRef(elm);\n const cmpMeta = hostRef.$cmpMeta$;\n const endConnected = createTime('connectedCallback', cmpMeta.$tagName$);\n if (BUILD.hostListenerTargetParent) {\n // only run if we have listeners being attached to a parent\n addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, true);\n }\n if (!(hostRef.$flags$ & 1 /* hasConnected */)) {\n // first time this component has connected\n hostRef.$flags$ |= 1 /* hasConnected */;\n let hostId;\n if (BUILD.hydrateClientSide) {\n hostId = elm.getAttribute(HYDRATE_ID);\n if (hostId) {\n if (BUILD.shadowDom && supportsShadow && cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {\n const scopeId = BUILD.mode ? addStyle(elm.shadowRoot, cmpMeta, elm.getAttribute('s-mode')) : addStyle(elm.shadowRoot, cmpMeta);\n elm.classList.remove(scopeId + '-h', scopeId + '-s');\n }\n initializeClientHydrate(elm, cmpMeta.$tagName$, hostId, hostRef);\n }\n }\n if (BUILD.slotRelocation && !hostId) {\n // initUpdate\n // if the slot polyfill is required we'll need to put some nodes\n // in here to act as original content anchors as we move nodes around\n // host element has been connected to the DOM\n if (BUILD.hydrateServerSide || ((BUILD.slot || BUILD.shadowDom) && cmpMeta.$flags$ & (4 /* hasSlotRelocation */ | 8 /* needsShadowDomShim */))) {\n setContentReference(elm);\n }\n }\n if (BUILD.asyncLoading) {\n // find the first ancestor component (if there is one) and register\n // this component as one of the actively loading child components for its ancestor\n let ancestorComponent = elm;\n while ((ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host)) {\n // climb up the ancestors looking for the first\n // component that hasn't finished its lifecycle update yet\n if ((BUILD.hydrateClientSide && ancestorComponent.nodeType === 1 /* ElementNode */ && ancestorComponent.hasAttribute('s-id') && ancestorComponent['s-p']) ||\n ancestorComponent['s-p']) {\n // we found this components first ancestor component\n // keep a reference to this component's ancestor component\n attachToAncestor(hostRef, (hostRef.$ancestorComponent$ = ancestorComponent));\n break;\n }\n }\n }\n // Lazy properties\n // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties\n if (BUILD.prop && BUILD.lazyLoad && !BUILD.hydrateServerSide && cmpMeta.$members$) {\n Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {\n if (memberFlags & 31 /* Prop */ && elm.hasOwnProperty(memberName)) {\n const value = elm[memberName];\n delete elm[memberName];\n elm[memberName] = value;\n }\n });\n }\n if (BUILD.initializeNextTick) {\n // connectedCallback, taskQueue, initialLoad\n // angular sets attribute AFTER connectCallback\n // https://github.com/angular/angular/issues/18909\n // https://github.com/angular/angular/issues/19940\n nextTick(() => initializeComponent(elm, hostRef, cmpMeta));\n }\n else {\n initializeComponent(elm, hostRef, cmpMeta);\n }\n }\n else {\n // not the first time this has connected\n // reattach any event listeners to the host\n // since they would have been removed when disconnected\n addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, false);\n // fire off connectedCallback() on component instance\n fireConnectedCallback(hostRef.$lazyInstance$);\n }\n endConnected();\n }\n};\nconst setContentReference = (elm) => {\n // only required when we're NOT using native shadow dom (slot)\n // or this browser doesn't support native shadow dom\n // and this host element was NOT created with SSR\n // let's pick out the inner content for slot projection\n // create a node to represent where the original\n // content was first placed, which is useful later on\n const contentRefElm = (elm['s-cr'] = doc.createComment(BUILD.isDebug ? `content-ref (host=${elm.localName})` : ''));\n contentRefElm['s-cn'] = true;\n elm.insertBefore(contentRefElm, elm.firstChild);\n};\nconst disconnectedCallback = (elm) => {\n if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {\n const hostRef = getHostRef(elm);\n const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;\n if (BUILD.hostListener) {\n if (hostRef.$rmListeners$) {\n hostRef.$rmListeners$.map(rmListener => rmListener());\n hostRef.$rmListeners$ = undefined;\n }\n }\n // clear CSS var-shim tracking\n if (BUILD.cssVarShim && plt.$cssShim$) {\n plt.$cssShim$.removeHost(elm);\n }\n if (BUILD.lazyLoad && BUILD.disconnectedCallback) {\n safeCall(instance, 'disconnectedCallback');\n }\n if (BUILD.cmpDidUnload) {\n safeCall(instance, 'componentDidUnload');\n }\n }\n};\nconst defineCustomElement = (Cstr, compactMeta) => {\n customElements.define(compactMeta[1], proxyCustomElement(Cstr, compactMeta));\n};\nconst proxyCustomElement = (Cstr, compactMeta) => {\n const cmpMeta = {\n $flags$: compactMeta[0],\n $tagName$: compactMeta[1],\n };\n if (BUILD.member) {\n cmpMeta.$members$ = compactMeta[2];\n }\n if (BUILD.hostListener) {\n cmpMeta.$listeners$ = compactMeta[3];\n }\n if (BUILD.watchCallback) {\n cmpMeta.$watchers$ = Cstr.$watchers$;\n }\n if (BUILD.reflect) {\n cmpMeta.$attrsToReflect$ = [];\n }\n if (BUILD.shadowDom && !supportsShadow && cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {\n cmpMeta.$flags$ |= 8 /* needsShadowDomShim */;\n }\n const originalConnectedCallback = Cstr.prototype.connectedCallback;\n const originalDisconnectedCallback = Cstr.prototype.disconnectedCallback;\n Object.assign(Cstr.prototype, {\n __registerHost() {\n registerHost(this, cmpMeta);\n },\n connectedCallback() {\n connectedCallback(this);\n if (BUILD.connectedCallback && originalConnectedCallback) {\n originalConnectedCallback.call(this);\n }\n },\n disconnectedCallback() {\n disconnectedCallback(this);\n if (BUILD.disconnectedCallback && originalDisconnectedCallback) {\n originalDisconnectedCallback.call(this);\n }\n },\n });\n Cstr.is = cmpMeta.$tagName$;\n return proxyComponent(Cstr, cmpMeta, 1 /* isElementConstructor */ | 2 /* proxyState */);\n};\nconst forceModeUpdate = (elm) => {\n if (BUILD.style && BUILD.mode && !BUILD.lazyLoad) {\n const mode = computeMode(elm);\n const hostRef = getHostRef(elm);\n if (hostRef.$modeName$ !== mode) {\n const cmpMeta = hostRef.$cmpMeta$;\n const oldScopeId = elm['s-sc'];\n const scopeId = getScopeId(cmpMeta, mode);\n const style = elm.constructor.style[mode];\n const flags = cmpMeta.$flags$;\n if (style) {\n if (!styles.has(scopeId)) {\n registerStyle(scopeId, style, !!(flags & 1 /* shadowDomEncapsulation */));\n }\n hostRef.$modeName$ = mode;\n elm.classList.remove(oldScopeId + '-h', oldScopeId + '-s');\n attachStyles(hostRef);\n forceUpdate(elm);\n }\n }\n }\n};\nconst attachShadow = (el) => {\n if (supportsShadow) {\n el.attachShadow({ mode: 'open' });\n }\n else {\n el.shadowRoot = el;\n }\n};\nconst hmrStart = (elm, cmpMeta, hmrVersionId) => {\n // ¯\\_(ツ)_/¯\n const hostRef = getHostRef(elm);\n // reset state flags to only have been connected\n hostRef.$flags$ = 1 /* hasConnected */;\n // TODO\n // detatch any event listeners that may have been added\n // because we're not passing an exact event name it'll\n // remove all of this element's event, which is good\n // create a callback for when this component finishes hmr\n elm['s-hmr-load'] = () => {\n // finished hmr for this element\n delete elm['s-hmr-load'];\n };\n // re-initialize the component\n initializeComponent(elm, hostRef, cmpMeta, hmrVersionId);\n};\nconst patchCloneNode = (HostElementPrototype) => {\n const orgCloneNode = HostElementPrototype.cloneNode;\n HostElementPrototype.cloneNode = function (deep) {\n const srcNode = this;\n const isShadowDom = BUILD.shadowDom ? srcNode.shadowRoot && supportsShadow : false;\n const clonedNode = orgCloneNode.call(srcNode, isShadowDom ? deep : false);\n if (BUILD.slot && !isShadowDom && deep) {\n let i = 0;\n let slotted, nonStencilNode;\n let stencilPrivates = ['s-id', 's-cr', 's-lr', 's-rc', 's-sc', 's-p', 's-cn', 's-sr', 's-sn', 's-hn', 's-ol', 's-nr', 's-si'];\n for (; i < srcNode.childNodes.length; i++) {\n slotted = srcNode.childNodes[i]['s-nr'];\n nonStencilNode = stencilPrivates.every((privateField) => !srcNode.childNodes[i][privateField]);\n if (slotted) {\n if (BUILD.appendChildSlotFix && clonedNode.__appendChild) {\n clonedNode.__appendChild(slotted.cloneNode(true));\n }\n else {\n clonedNode.appendChild(slotted.cloneNode(true));\n }\n }\n if (nonStencilNode) {\n clonedNode.appendChild(srcNode.childNodes[i].cloneNode(true));\n }\n }\n }\n return clonedNode;\n };\n};\nconst patchSlotAppendChild = (HostElementPrototype) => {\n HostElementPrototype.__appendChild = HostElementPrototype.appendChild;\n HostElementPrototype.appendChild = function (newChild) {\n const slotName = (newChild['s-sn'] = getSlotName(newChild));\n const slotNode = getHostSlotNode(this.childNodes, slotName);\n if (slotNode) {\n const slotChildNodes = getHostSlotChildNodes(slotNode, slotName);\n const appendAfter = slotChildNodes[slotChildNodes.length - 1];\n return appendAfter.parentNode.insertBefore(newChild, appendAfter.nextSibling);\n }\n return this.__appendChild(newChild);\n };\n};\nconst patchChildSlotNodes = (elm, cmpMeta) => {\n class FakeNodeList extends Array {\n item(n) {\n return this[n];\n }\n }\n if (cmpMeta.$flags$ & 8 /* needsShadowDomShim */) {\n const childNodesFn = elm.__lookupGetter__('childNodes');\n Object.defineProperty(elm, 'children', {\n get() {\n return this.childNodes.map((n) => n.nodeType === 1);\n },\n });\n Object.defineProperty(elm, 'childElementCount', {\n get() {\n return elm.children.length;\n },\n });\n Object.defineProperty(elm, 'childNodes', {\n get() {\n const childNodes = childNodesFn.call(this);\n if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0 && getHostRef(this).$flags$ & 2 /* hasRendered */) {\n const result = new FakeNodeList();\n for (let i = 0; i < childNodes.length; i++) {\n const slot = childNodes[i]['s-nr'];\n if (slot) {\n result.push(slot);\n }\n }\n return result;\n }\n return FakeNodeList.from(childNodes);\n },\n });\n }\n};\nconst getSlotName = (node) => node['s-sn'] || (node.nodeType === 1 && node.getAttribute('slot')) || '';\nconst getHostSlotNode = (childNodes, slotName) => {\n let i = 0;\n let childNode;\n for (; i < childNodes.length; i++) {\n childNode = childNodes[i];\n if (childNode['s-sr'] && childNode['s-sn'] === slotName) {\n return childNode;\n }\n childNode = getHostSlotNode(childNode.childNodes, slotName);\n if (childNode) {\n return childNode;\n }\n }\n return null;\n};\nconst getHostSlotChildNodes = (n, slotName) => {\n const childNodes = [n];\n while ((n = n.nextSibling) && n['s-sn'] === slotName) {\n childNodes.push(n);\n }\n return childNodes;\n};\nconst bootstrapLazy = (lazyBundles, options = {}) => {\n if (BUILD.profile && performance.mark) {\n performance.mark('st:app:start');\n }\n installDevTools();\n const endBootstrap = createTime('bootstrapLazy');\n const cmpTags = [];\n const exclude = options.exclude || [];\n const customElements = win.customElements;\n const head = doc.head;\n const metaCharset = /*@__PURE__*/ head.querySelector('meta[charset]');\n const visibilityStyle = /*@__PURE__*/ doc.createElement('style');\n const deferredConnectedCallbacks = [];\n const styles = /*@__PURE__*/ doc.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);\n let appLoadFallback;\n let isBootstrapping = true;\n let i = 0;\n Object.assign(plt, options);\n plt.$resourcesUrl$ = new URL(options.resourcesUrl || './', doc.baseURI).href;\n if (BUILD.asyncQueue) {\n if (options.syncQueue) {\n plt.$flags$ |= 4 /* queueSync */;\n }\n }\n if (BUILD.hydrateClientSide) {\n // If the app is already hydrated there is not point to disable the\n // async queue. This will improve the first input delay\n plt.$flags$ |= 2 /* appLoaded */;\n }\n if (BUILD.hydrateClientSide && BUILD.shadowDom) {\n for (; i < styles.length; i++) {\n registerStyle(styles[i].getAttribute(HYDRATED_STYLE_ID), convertScopedToShadow(styles[i].innerHTML), true);\n }\n }\n lazyBundles.map(lazyBundle => lazyBundle[1].map(compactMeta => {\n const cmpMeta = {\n $flags$: compactMeta[0],\n $tagName$: compactMeta[1],\n $members$: compactMeta[2],\n $listeners$: compactMeta[3],\n };\n if (BUILD.member) {\n cmpMeta.$members$ = compactMeta[2];\n }\n if (BUILD.hostListener) {\n cmpMeta.$listeners$ = compactMeta[3];\n }\n if (BUILD.reflect) {\n cmpMeta.$attrsToReflect$ = [];\n }\n if (BUILD.watchCallback) {\n cmpMeta.$watchers$ = {};\n }\n if (BUILD.shadowDom && !supportsShadow && cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {\n cmpMeta.$flags$ |= 8 /* needsShadowDomShim */;\n }\n const tagName = BUILD.transformTagName && options.transformTagName ? options.transformTagName(cmpMeta.$tagName$) : cmpMeta.$tagName$;\n const HostElement = class extends HTMLElement {\n // StencilLazyHost\n constructor(self) {\n // @ts-ignore\n super(self);\n self = this;\n registerHost(self, cmpMeta);\n if (BUILD.shadowDom && cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {\n // this component is using shadow dom\n // and this browser supports shadow dom\n // add the read-only property \"shadowRoot\" to the host element\n // adding the shadow root build conditionals to minimize runtime\n if (supportsShadow) {\n if (BUILD.shadowDelegatesFocus) {\n self.attachShadow({\n mode: 'open',\n delegatesFocus: !!(cmpMeta.$flags$ & 16 /* shadowDelegatesFocus */),\n });\n }\n else {\n self.attachShadow({ mode: 'open' });\n }\n }\n else if (!BUILD.hydrateServerSide && !('shadowRoot' in self)) {\n self.shadowRoot = self;\n }\n }\n if (BUILD.slotChildNodesFix) {\n patchChildSlotNodes(self, cmpMeta);\n }\n }\n connectedCallback() {\n if (appLoadFallback) {\n clearTimeout(appLoadFallback);\n appLoadFallback = null;\n }\n if (isBootstrapping) {\n // connectedCallback will be processed once all components have been registered\n deferredConnectedCallbacks.push(this);\n }\n else {\n plt.jmp(() => connectedCallback(this));\n }\n }\n disconnectedCallback() {\n plt.jmp(() => disconnectedCallback(this));\n }\n componentOnReady() {\n return getHostRef(this).$onReadyPromise$;\n }\n };\n if (BUILD.cloneNodeFix) {\n patchCloneNode(HostElement.prototype);\n }\n if (BUILD.appendChildSlotFix) {\n patchSlotAppendChild(HostElement.prototype);\n }\n if (BUILD.hotModuleReplacement) {\n HostElement.prototype['s-hmr'] = function (hmrVersionId) {\n hmrStart(this, cmpMeta, hmrVersionId);\n };\n }\n cmpMeta.$lazyBundleId$ = lazyBundle[0];\n if (!exclude.includes(tagName) && !customElements.get(tagName)) {\n cmpTags.push(tagName);\n customElements.define(tagName, proxyComponent(HostElement, cmpMeta, 1 /* isElementConstructor */));\n }\n }));\n if (BUILD.hydratedClass || BUILD.hydratedAttribute) {\n visibilityStyle.innerHTML = cmpTags + HYDRATED_CSS;\n visibilityStyle.setAttribute('data-styles', '');\n head.insertBefore(visibilityStyle, metaCharset ? metaCharset.nextSibling : head.firstChild);\n }\n // Process deferred connectedCallbacks now all components have been registered\n isBootstrapping = false;\n if (deferredConnectedCallbacks.length) {\n deferredConnectedCallbacks.map(host => host.connectedCallback());\n }\n else {\n if (BUILD.profile) {\n plt.jmp(() => (appLoadFallback = setTimeout(appDidLoad, 30, 'timeout')));\n }\n else {\n plt.jmp(() => (appLoadFallback = setTimeout(appDidLoad, 30)));\n }\n }\n // Fallback appLoad event\n endBootstrap();\n};\nconst getAssetPath = (path) => {\n const assetUrl = new URL(path, plt.$resourcesUrl$);\n return assetUrl.origin !== win.location.origin ? assetUrl.href : assetUrl.pathname;\n};\nconst setAssetPath = (path) => (plt.$resourcesUrl$ = path);\nconst getConnect = (_ref, tagName) => {\n const componentOnReady = () => {\n let elm = doc.querySelector(tagName);\n if (!elm) {\n elm = doc.createElement(tagName);\n doc.body.appendChild(elm);\n }\n return typeof elm.componentOnReady === 'function' ? elm.componentOnReady() : Promise.resolve(elm);\n };\n const create = (...args) => {\n return componentOnReady().then(el => el.create(...args));\n };\n return {\n create,\n componentOnReady,\n };\n};\nconst getContext = (_elm, context) => {\n if (context in Context) {\n return Context[context];\n }\n else if (context === 'window') {\n return win;\n }\n else if (context === 'document') {\n return doc;\n }\n else if (context === 'isServer' || context === 'isPrerender') {\n return BUILD.hydrateServerSide ? true : false;\n }\n else if (context === 'isClient') {\n return BUILD.hydrateServerSide ? false : true;\n }\n else if (context === 'resourcesUrl' || context === 'publicPath') {\n return getAssetPath('.');\n }\n else if (context === 'queue') {\n return {\n write: writeTask,\n read: readTask,\n tick: {\n then(cb) {\n return nextTick(cb);\n },\n },\n };\n }\n return undefined;\n};\nconst insertVdomAnnotations = (doc, staticComponents) => {\n if (doc != null) {\n const docData = {\n hostIds: 0,\n rootLevelIds: 0,\n staticComponents: new Set(staticComponents),\n };\n const orgLocationNodes = [];\n parseVNodeAnnotations(doc, doc.body, docData, orgLocationNodes);\n orgLocationNodes.forEach(orgLocationNode => {\n if (orgLocationNode != null) {\n const nodeRef = orgLocationNode['s-nr'];\n let hostId = nodeRef['s-host-id'];\n let nodeId = nodeRef['s-node-id'];\n let childId = `${hostId}.${nodeId}`;\n if (hostId == null) {\n hostId = 0;\n docData.rootLevelIds++;\n nodeId = docData.rootLevelIds;\n childId = `${hostId}.${nodeId}`;\n if (nodeRef.nodeType === 1 /* ElementNode */) {\n nodeRef.setAttribute(HYDRATE_CHILD_ID, childId);\n }\n else if (nodeRef.nodeType === 3 /* TextNode */) {\n if (hostId === 0) {\n const textContent = nodeRef.nodeValue.trim();\n if (textContent === '') {\n // useless whitespace node at the document root\n orgLocationNode.remove();\n return;\n }\n }\n const commentBeforeTextNode = doc.createComment(childId);\n commentBeforeTextNode.nodeValue = `${TEXT_NODE_ID}.${childId}`;\n nodeRef.parentNode.insertBefore(commentBeforeTextNode, nodeRef);\n }\n }\n let orgLocationNodeId = `${ORG_LOCATION_ID}.${childId}`;\n const orgLocationParentNode = orgLocationNode.parentElement;\n if (orgLocationParentNode) {\n if (orgLocationParentNode['s-en'] === '') {\n // ending with a \".\" means that the parent element\n // of this node's original location is a SHADOW dom element\n // and this node is apart of the root level light dom\n orgLocationNodeId += `.`;\n }\n else if (orgLocationParentNode['s-en'] === 'c') {\n // ending with a \".c\" means that the parent element\n // of this node's original location is a SCOPED element\n // and this node is apart of the root level light dom\n orgLocationNodeId += `.c`;\n }\n }\n orgLocationNode.nodeValue = orgLocationNodeId;\n }\n });\n }\n};\nconst parseVNodeAnnotations = (doc, node, docData, orgLocationNodes) => {\n if (node == null) {\n return;\n }\n if (node['s-nr'] != null) {\n orgLocationNodes.push(node);\n }\n if (node.nodeType === 1 /* ElementNode */) {\n node.childNodes.forEach(childNode => {\n const hostRef = getHostRef(childNode);\n if (hostRef != null && !docData.staticComponents.has(childNode.nodeName.toLowerCase())) {\n const cmpData = {\n nodeIds: 0,\n };\n insertVNodeAnnotations(doc, childNode, hostRef.$vnode$, docData, cmpData);\n }\n parseVNodeAnnotations(doc, childNode, docData, orgLocationNodes);\n });\n }\n};\nconst insertVNodeAnnotations = (doc, hostElm, vnode, docData, cmpData) => {\n if (vnode != null) {\n const hostId = ++docData.hostIds;\n hostElm.setAttribute(HYDRATE_ID, hostId);\n if (hostElm['s-cr'] != null) {\n hostElm['s-cr'].nodeValue = `${CONTENT_REF_ID}.${hostId}`;\n }\n if (vnode.$children$ != null) {\n const depth = 0;\n vnode.$children$.forEach((vnodeChild, index) => {\n insertChildVNodeAnnotations(doc, vnodeChild, cmpData, hostId, depth, index);\n });\n }\n if (hostElm && vnode && vnode.$elm$ && !hostElm.hasAttribute('c-id')) {\n const parent = hostElm.parentElement;\n if (parent && parent.childNodes) {\n const parentChildNodes = Array.from(parent.childNodes);\n const comment = parentChildNodes.find(node => node.nodeType === 8 /* CommentNode */ && node['s-sr']);\n if (comment) {\n const index = parentChildNodes.indexOf(hostElm) - 1;\n vnode.$elm$.setAttribute(HYDRATE_CHILD_ID, `${comment['s-host-id']}.${comment['s-node-id']}.0.${index}`);\n }\n }\n }\n }\n};\nconst insertChildVNodeAnnotations = (doc, vnodeChild, cmpData, hostId, depth, index) => {\n const childElm = vnodeChild.$elm$;\n if (childElm == null) {\n return;\n }\n const nodeId = cmpData.nodeIds++;\n const childId = `${hostId}.${nodeId}.${depth}.${index}`;\n childElm['s-host-id'] = hostId;\n childElm['s-node-id'] = nodeId;\n if (childElm.nodeType === 1 /* ElementNode */) {\n childElm.setAttribute(HYDRATE_CHILD_ID, childId);\n }\n else if (childElm.nodeType === 3 /* TextNode */) {\n const parentNode = childElm.parentNode;\n const nodeName = parentNode.nodeName;\n if (nodeName !== 'STYLE' && nodeName !== 'SCRIPT') {\n const textNodeId = `${TEXT_NODE_ID}.${childId}`;\n const commentBeforeTextNode = doc.createComment(textNodeId);\n parentNode.insertBefore(commentBeforeTextNode, childElm);\n }\n }\n else if (childElm.nodeType === 8 /* CommentNode */) {\n if (childElm['s-sr']) {\n const slotName = childElm['s-sn'] || '';\n const slotNodeId = `${SLOT_NODE_ID}.${childId}.${slotName}`;\n childElm.nodeValue = slotNodeId;\n }\n }\n if (vnodeChild.$children$ != null) {\n const childDepth = depth + 1;\n vnodeChild.$children$.forEach((vnode, index) => {\n insertChildVNodeAnnotations(doc, vnode, cmpData, hostId, childDepth, index);\n });\n }\n};\nconst setPlatformOptions = (opts) => Object.assign(plt, opts);\nconst Fragment = (_, children) => children;\nconst hostRefs = new WeakMap();\nconst getHostRef = (ref) => hostRefs.get(ref);\nconst registerInstance = (lazyInstance, hostRef) => hostRefs.set((hostRef.$lazyInstance$ = lazyInstance), hostRef);\nconst registerHost = (elm, cmpMeta) => {\n const hostRef = {\n $flags$: 0,\n $hostElement$: elm,\n $cmpMeta$: cmpMeta,\n $instanceValues$: new Map(),\n };\n if (BUILD.isDev) {\n hostRef.$renderCount$ = 0;\n }\n if (BUILD.method && BUILD.lazyLoad) {\n hostRef.$onInstancePromise$ = new Promise(r => (hostRef.$onInstanceResolve$ = r));\n }\n if (BUILD.asyncLoading) {\n hostRef.$onReadyPromise$ = new Promise(r => (hostRef.$onReadyResolve$ = r));\n elm['s-p'] = [];\n elm['s-rc'] = [];\n }\n addHostEventListeners(elm, hostRef, cmpMeta.$listeners$, false);\n return hostRefs.set(elm, hostRef);\n};\nconst isMemberInElement = (elm, memberName) => memberName in elm;\nconst consoleError = (e, el) => (customError || console.error)(e, el);\nconst STENCIL_DEV_MODE = BUILD.isTesting\n ? ['STENCIL:'] // E2E testing\n : ['%cstencil', 'color: white;background:#4c47ff;font-weight: bold; font-size:10px; padding:2px 6px; border-radius: 5px'];\nconst consoleDevError = (...m) => console.error(...STENCIL_DEV_MODE, ...m);\nconst consoleDevWarn = (...m) => console.warn(...STENCIL_DEV_MODE, ...m);\nconst consoleDevInfo = (...m) => console.info(...STENCIL_DEV_MODE, ...m);\nconst setErrorHandler = (handler) => customError = handler;\nconst cmpModules = /*@__PURE__*/ new Map();\nconst loadModule = (cmpMeta, hostRef, hmrVersionId) => {\n // loadModuleImport\n const exportName = cmpMeta.$tagName$.replace(/-/g, '_');\n const bundleId = cmpMeta.$lazyBundleId$;\n if (BUILD.isDev && typeof bundleId !== 'string') {\n consoleDevError(`Trying to lazily load component <${cmpMeta.$tagName$}> with style mode \"${hostRef.$modeName$}\", but it does not exist.`);\n return undefined;\n }\n const module = !BUILD.hotModuleReplacement ? cmpModules.get(bundleId) : false;\n if (module) {\n return module[exportName];\n }\n return import(\n /* webpackInclude: /\\.entry\\.js$/ */\n /* webpackExclude: /\\.system\\.entry\\.js$/ */\n /* webpackMode: \"lazy\" */\n `./${bundleId}.entry.js${BUILD.hotModuleReplacement && hmrVersionId ? '?s-hmr=' + hmrVersionId : ''}`).then(importedModule => {\n if (!BUILD.hotModuleReplacement) {\n cmpModules.set(bundleId, importedModule);\n }\n return importedModule[exportName];\n }, consoleError);\n};\nconst styles = new Map();\nconst modeResolutionChain = [];\nconst queueDomReads = [];\nconst queueDomWrites = [];\nconst queueDomWritesLow = [];\nconst queueTask = (queue, write) => (cb) => {\n queue.push(cb);\n if (!queuePending) {\n queuePending = true;\n if (write && plt.$flags$ & 4 /* queueSync */) {\n nextTick(flush);\n }\n else {\n plt.raf(flush);\n }\n }\n};\nconst consume = (queue) => {\n for (let i = 0; i < queue.length; i++) {\n try {\n queue[i](performance.now());\n }\n catch (e) {\n consoleError(e);\n }\n }\n queue.length = 0;\n};\nconst consumeTimeout = (queue, timeout) => {\n let i = 0;\n let ts = 0;\n while (i < queue.length && (ts = performance.now()) < timeout) {\n try {\n queue[i++](ts);\n }\n catch (e) {\n consoleError(e);\n }\n }\n if (i === queue.length) {\n queue.length = 0;\n }\n else if (i !== 0) {\n queue.splice(0, i);\n }\n};\nconst flush = () => {\n if (BUILD.asyncQueue) {\n queueCongestion++;\n }\n // always force a bunch of medium callbacks to run, but still have\n // a throttle on how many can run in a certain time\n // DOM READS!!!\n consume(queueDomReads);\n // DOM WRITES!!!\n if (BUILD.asyncQueue) {\n const timeout = (plt.$flags$ & 6 /* queueMask */) === 2 /* appLoaded */ ? performance.now() + 14 * Math.ceil(queueCongestion * (1.0 / 10.0)) : Infinity;\n consumeTimeout(queueDomWrites, timeout);\n consumeTimeout(queueDomWritesLow, timeout);\n if (queueDomWrites.length > 0) {\n queueDomWritesLow.push(...queueDomWrites);\n queueDomWrites.length = 0;\n }\n if ((queuePending = queueDomReads.length + queueDomWrites.length + queueDomWritesLow.length > 0)) {\n // still more to do yet, but we've run out of time\n // let's let this thing cool off and try again in the next tick\n plt.raf(flush);\n }\n else {\n queueCongestion = 0;\n }\n }\n else {\n consume(queueDomWrites);\n if ((queuePending = queueDomReads.length > 0)) {\n // still more to do yet, but we've run out of time\n // let's let this thing cool off and try again in the next tick\n plt.raf(flush);\n }\n }\n};\nconst nextTick = /*@__PURE__*/ (cb) => promiseResolve().then(cb);\nconst readTask = /*@__PURE__*/ queueTask(queueDomReads, false);\nconst writeTask = /*@__PURE__*/ queueTask(queueDomWrites, true);\nconst Build = {\n isDev: BUILD.isDev ? true : false,\n isBrowser: true,\n isServer: false,\n isTesting: BUILD.isTesting ? true : false,\n};\nexport { BUILD, Env, NAMESPACE } from '@stencil/core/internal/app-data';\nexport { Build, CSS, Context, Fragment, H, H as HTMLElement, Host, STENCIL_DEV_MODE, addHostEventListeners, attachShadow, bootstrapLazy, cmpModules, connectedCallback, consoleDevError, consoleDevInfo, consoleDevWarn, consoleError, createEvent, defineCustomElement, disconnectedCallback, doc, forceModeUpdate, forceUpdate, getAssetPath, getConnect, getContext, getElement, getHostRef, getMode, getRenderingRef, getValue, h, insertVdomAnnotations, isMemberInElement, loadModule, modeResolutionChain, nextTick, parsePropertyValue, plt, postUpdateComponent, promiseResolve, proxyComponent, proxyCustomElement, readTask, registerHost, registerInstance, renderVdom, setAssetPath, setErrorHandler, setMode, setPlatformOptions, setValue, styles, supportsConstructibleStylesheets, supportsListenerOptions, supportsShadow, win, writeTask };\n","import { useDomContextState } from \"@saasquatch/dom-context-hooks\";\nimport { useDomContext } from \"@saasquatch/stencil-hooks\";\nimport { useHost } from \"./useHost\";\n\nexport type StateType<T> = [value?: T, setValue?: (value: T) => void];\n\ntype ParentStateProps<T> = {\n namespace: string;\n initialValue?: T;\n};\n\nexport function useParentState<T>(props: ParentStateProps<T>): StateType<T> {\n const host = useHost();\n const [value, setValue] = useDomContextState<T>(\n host,\n getContextValueName(props.namespace),\n props.initialValue as T\n );\n\n useDomContextState<StateType<T>>(host, getContextName(props.namespace), [\n value,\n setValue,\n ]);\n\n return [value, setValue];\n}\n\nexport function useParent<T>(namespace: string): StateType<T | undefined> {\n const parent = useDomContext<StateType<T | undefined>>(\n getContextName(namespace)\n );\n\n const parentValue = useDomContext<T | undefined>(\n getContextValueName(namespace)\n );\n\n if (!parent) return [undefined, undefined];\n return [parentValue, parent[1]];\n}\n\nexport function useSetParent<T>(\n namespace: string\n): (value: T) => void | undefined {\n const parent = useDomContext<StateType<T | undefined>>(\n getContextName(namespace)\n );\n if (!parent) return undefined;\n return parent[1];\n}\n\nexport function useParentValue<T>(namespace: string): T | undefined {\n const parentValue = useDomContext<T | undefined>(\n getContextValueName(namespace)\n );\n\n if (!parentValue) undefined;\n return parentValue;\n}\n\nexport function getContextValueName(namespace: string) {\n return namespace + \"-value\";\n}\n\nexport function getContextName(namespace: string) {\n return namespace + \"-state\";\n}\n","import { useDomContextState } from \"@saasquatch/dom-context-hooks\";\nimport { useDomContext } from \"@saasquatch/stencil-hooks\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\nimport { deepEqual } from \"fast-equals\";\nimport { getContextValueName } from \"../useParentState\";\nimport { useHost } from \"../useHost\";\nimport { useQuery } from \"./useQuery\";\nimport { QueryData } from \"./useBaseQuery\";\n\ntype ParentQueryProps = {\n namespace: string;\n query?: string;\n variables?: { [key: string]: unknown };\n skip?: boolean;\n};\n\nexport function useParentQuery<T>(props: ParentQueryProps): QueryData<T> {\n const host = useHost();\n const query = useQuery(props.query, props.variables || {}, props.skip);\n\n const [value, setValue] = useDomContextState<QueryData<any>>(\n host,\n getContextValueName(props.namespace),\n query\n );\n\n useEffect(() => {\n if (deepEqual(query, value)) return;\n setValue(query);\n }, [query, value]);\n\n return query;\n}\n\nexport function useParentQueryValue<T>(namespace: string): QueryData<T> {\n const parentValue = useDomContext<QueryData<T> | undefined>(\n getContextValueName(namespace)\n );\n\n if (!parentValue)\n return {\n data: null,\n loading: true,\n refetch: () => console.warn(\"component still loading\"),\n } as QueryData<T>;\n return parentValue;\n}\n","import { useEffect } from \"@saasquatch/universal-hooks\";\nimport {\n history,\n HistoryEntry,\n LazyHistory,\n} from \"@saasquatch/component-environment\";\nimport { useTick } from \"./useTick\";\n\n/**\n * Returns the current location. Similar to `window.location` but works with SPA page changes and virtual pages in Squatch.js\n */\nexport function useCurrentPage(): HistoryEntry {\n const [, tick] = useTick();\n useEffect(() => {\n const cleanup = history.listen(() => {\n // re-render\n tick();\n });\n return cleanup;\n }, []);\n\n return history.location;\n}\n\nexport const navigation: LazyHistory = history;\n","import { useState } from \"@saasquatch/universal-hooks\";\n\nexport function usePagination(pageVars: { limit: number; offset: number }) {\n const [pageState, setPageState] = useState({\n limit: pageVars.limit,\n offset: pageVars.offset,\n });\n const { offset, limit } = pageState;\n\n const calcOffset = (limit: number, page: number) => limit * page;\n const calcPage = (offset: number, limit: number) =>\n Math.ceil(offset / limit) || 0;\n const calcPageCount = (totalCount: number, limit: number) =>\n Math.ceil(totalCount / limit) || 0;\n\n const setLimit = (newLimit: number) => {\n const newPage = calcPage(offset, newLimit);\n const newOffset = calcOffset(newLimit, newPage);\n setPageState({\n ...pageState,\n limit: newLimit,\n offset: newOffset,\n });\n };\n\n // page numbering starts at 0\n const setCurrentPage = (newPage: number) => {\n let newOffset = calcOffset(newPage, limit);\n setPageState((pageState) => ({\n ...pageState,\n offset: newOffset,\n }));\n };\n\n // there are no safety guards here for invalid inputs\n function calculatePagination(count: number, totalCount: number) {\n const currentPage = calcPage(offset, limit);\n const pageCount = calcPageCount(totalCount, limit);\n\n const rangeOnPage: string =\n count === 0\n ? \"0\"\n : count > 1\n ? `${offset + 1}-${offset + count}`\n : `${offset + 1}`;\n const pageProgress: string = `${rangeOnPage} of ${totalCount}`;\n\n return { currentPage, pageCount, rangeOnPage, pageProgress };\n }\n\n return {\n limit,\n setLimit,\n offset,\n setCurrentPage,\n calculatePagination,\n };\n}\n","import { useQuery } from \"../graphql/useQuery\";\nimport { usePagination } from \"./usePagination\";\n\nexport type Envelope<T = unknown> = {\n data: T[];\n totalCount?: number;\n};\n\nexport type PageVars = {\n offset: number;\n limit: number;\n};\n\n/**\n * dataPath MUST use the question mark operator when accessing fields.\n * If it doesn't then it will violate a Rule of Hooks\n */\nexport function usePaginatedQuery<\n TData,\n TVars extends { [key: string]: any } = {}\n>(\n query: any,\n dataPath: (data: any) => Envelope<TData>,\n pageVars: PageVars,\n extraVars: TVars = {} as TVars,\n skip: boolean = false,\n) {\n const {\n limit,\n offset,\n setLimit,\n setCurrentPage,\n calculatePagination,\n } = usePagination(pageVars);\n\n const variables = { limit, offset, ...extraVars };\n\n const { loading, errors, data, refetch } = useQuery(query, variables, skip);\n\n // this value needs to be accessed using the ? operator\n // react throws a hook error otherwise\n const envelope = dataPath(data);\n\n const { currentPage, pageCount, pageProgress } = calculatePagination(\n envelope?.data?.length || 0,\n envelope?.totalCount || 0\n );\n\n return {\n envelope,\n states: {\n errors,\n loading,\n limit,\n currentPage,\n pageCount,\n pageProgress,\n },\n callbacks: {\n refetch,\n setLimit,\n setCurrentPage,\n },\n };\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"@saasquatch/universal-hooks\";\nimport debounce from \"debounce\";\n\nfunction valueEquality<T>(left: T, right: T): boolean {\n return left === right;\n}\n\n/**\n * Provides a debounced value\n *\n * Forked from React version here: https://github.com/xnimorz/use-debounce\n *\n * @param value\n * @param delay\n * @param options\n */\nexport function useDebounce<T>(\n value: T,\n delay: number,\n options?: {\n maxWait?: number;\n leading?: boolean;\n trailing?: boolean;\n equalityFn?: (left: T, right: T) => boolean;\n }\n) {\n const eq = (options && options.equalityFn) || valueEquality;\n\n const [state, dispatch] = useState(value);\n const debounced = useDebouncedCallback(\n useCallback((value: T) => dispatch(value), []),\n delay,\n options\n );\n const previousValue = useRef(value);\n\n useEffect(() => {\n // We need to use this condition otherwise we will run debounce timer for the first render (including maxWait option)\n if (!eq(previousValue.current, value)) {\n debounced.callback(value);\n previousValue.current = value;\n }\n }, [value, debounced, eq]);\n\n return [\n state,\n {\n cancel: debounced.cancel,\n flush: debounced.flush,\n },\n ] as const;\n}\n\nexport interface CallOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\nexport interface ControlFunctions {\n cancel: () => void;\n flush: () => void;\n}\n\n/**\n * Subsequent calls to the debounced function `debounced.callback` return the result of the last func invocation.\n * Note, that if there are no previous invocations it's mean you will get undefined. You should check it in your code properly.\n */\nexport interface DebouncedState<T extends (...args: any[]) => ReturnType<T>>\n extends ControlFunctions {\n callback: (...args: Parameters<T>) => ReturnType<T>;\n}\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked, or until the next browser frame is drawn. The debounced function\n * comes with a `cancel` method to cancel delayed `func` invocations and a\n * `flush` method to immediately invoke them. Provide `options` to indicate\n * whether `func` should be invoked on the leading and/or trailing edge of the\n * `wait` timeout. The `func` is invoked with the last arguments provided to the\n * debounced function. Subsequent calls to the debounced function return the\n * result of the last `func` invocation.\n\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `debounce` and `throttle`.\n *\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0]\n * The number of milliseconds to delay\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n */\nexport function useDebouncedCallback<\n T extends (...args: any[]) => ReturnType<T>\n>(\n func: T,\n wait: number = 0,\n options: CallOptions = { leading: false }\n): DebouncedState<T> {\n const callback = useMemo(() => debounce(func, wait, options.leading), [\n func,\n wait,\n options.leading,\n ]);\n\n const { flush, clear } = callback;\n\n return {\n flush,\n cancel: clear,\n callback,\n };\n}\n","import { gql } from \"graphql-request\";\nimport {\n useEngagementMedium,\n useProgramId,\n useUserIdentity,\n} from \"../hooks/environment\";\nimport { useMutation } from \"./graphql/useMutation\";\n\nconst FIRE_EVENT = gql`\n mutation ($eventMeta: UserAnalyticsEvent!) {\n createUserAnalyticsEvent(eventMeta: $eventMeta)\n }\n`;\n\nexport function useShareEvent() {\n const engagementMedium = useEngagementMedium();\n const userIdentity = useUserIdentity();\n const program = useProgramId();\n const [dispatch] = useMutation(FIRE_EVENT);\n\n if (!userIdentity) {\n // Not logged in. No-op callback for tracking sharing.\n return () => {};\n }\n\n return (shareMedium: string) => {\n const variables = {\n eventMeta: {\n id: userIdentity.id,\n accountId: userIdentity.accountId,\n programId: program,\n type: \"USER_REFERRAL_PROGRAM_ENGAGEMENT_EVENT\",\n meta: {\n engagementMedium: engagementMedium,\n shareMedium,\n },\n },\n };\n dispatch(variables);\n };\n}\n","import { UserIdentity } from \"@saasquatch/component-environment\";\nimport { useEffect } from \"@saasquatch/universal-hooks\";\nimport { equal as deepEqual } from \"@wry/equality\";\nimport debugFn from \"debug\";\nimport { ContextProvider } from \"dom-context\";\nimport { gql } from \"graphql-request\";\nimport {\n useEngagementMedium,\n useProgramId,\n useUserIdentity,\n} from \"./environment\";\nimport { useMutation } from \"./graphql/useMutation\";\nimport { useHost } from \"./useHost\";\n\nconst LOAD_EVENT_CONTEXT_NAME = \"sq:load-event\";\nexport const debug = debugFn(LOAD_EVENT_CONTEXT_NAME);\n\ndeclare global {\n interface Window {\n squatchLoadEvent?: ContextProvider<EventContext>;\n }\n}\n\ntype EventContext = {\n userIdentity?: UserIdentity;\n programId?: string;\n};\n\nconst FIRE_EVENT = gql`\n mutation loadEvent($eventMeta: UserAnalyticsEvent!) {\n createUserAnalyticsEvent(eventMeta: $eventMeta)\n }\n`;\n\nexport function lazilyStartLoadEventContext() {\n let globalProvider = window.squatchLoadEvent;\n\n if (!globalProvider) {\n debug(\"Creating load event provider\");\n\n globalProvider = new ContextProvider<EventContext>({\n element: document.documentElement,\n initialState: {\n userIdentity: undefined,\n programId: undefined,\n },\n contextName: LOAD_EVENT_CONTEXT_NAME,\n }).start();\n\n window.squatchLoadEvent = globalProvider;\n }\n\n return globalProvider;\n}\n\nexport function useLoadEvent() {\n const host = useHost();\n const globalProvider = lazilyStartLoadEventContext();\n\n const engagementMedium = useEngagementMedium();\n\n const userIdentity = useUserIdentity();\n\n const programId = useProgramId();\n\n const [dispatch] = useMutation(FIRE_EVENT);\n\n useEffect(() => {\n if (!userIdentity || !programId || !globalProvider?.context) return;\n\n if (\n // First time loading\n !globalProvider.context.userIdentity ||\n // User changed\n !deepEqual(userIdentity, globalProvider.context.userIdentity) ||\n // Different programId\n programId !== globalProvider.context.programId\n ) {\n const variables = {\n eventMeta: {\n programId,\n id: userIdentity.id,\n accountId: userIdentity.accountId,\n type: \"USER_REFERRAL_PROGRAM_LOADED_EVENT\",\n meta: {\n engagementMedium,\n },\n },\n };\n dispatch(variables);\n\n debug(\"Event sent\", { variables, globalProvider });\n\n globalProvider.context = { userIdentity, programId };\n }\n }, [userIdentity?.id, userIdentity?.accountId, programId]);\n}\n","import { useEffect, useReducer } from \"@saasquatch/universal-hooks\";\nimport { gql } from \"graphql-request\";\nimport debugFn from \"debug\";\nimport jsonpointer from \"jsonpointer\";\nimport { useMutation } from \"./graphql/useMutation\";\nimport { useLazyQuery } from \"./graphql/useLazyQuery\";\nimport { useDeepMemo } from \"./useDeepMemo\";\nexport const debug = debugFn(\"sq:useForm\");\n\nconst GET_FORM = gql`\n query ($key: String!) {\n form(key: $key) {\n schema\n initialData {\n initialData\n isEnabled\n isEnabledErrorMessage\n }\n }\n }\n`;\n\nconst SUBMIT_FORM = gql`\n mutation ($formSubmissionInput: FormSubmissionInput!) {\n submitForm(formSubmissionInput: $formSubmissionInput) {\n success\n results {\n ... on FormHandlerSubmissionResult {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n result\n }\n ... on FormHandlerError {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n errorType\n error\n errorCode\n }\n }\n }\n }\n`;\n\nconst VALIDATE_FORM = gql`\n query ($formValidationInput: FormValidationInput!) {\n validateForm(formValidationInput: $formValidationInput) {\n valid\n results {\n ... on FormHandlerValidationResult {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n result\n }\n ... on FormHandlerError {\n formHandler {\n name\n endpointUrl\n integration {\n name\n }\n }\n errorType\n error\n errorCode\n }\n }\n }\n }\n`;\n\ntype UseFormProps = {\n formKey: string;\n formRef: HTMLFormElement;\n /** Flag to submit the form automatically once validated */\n autoSubmit?: boolean;\n setInitialData?: (htmlForm?: HTMLFormElement, initialData?: unknown) => void;\n};\n\ntype FormState = {\n validating: boolean;\n valid: boolean;\n enabled: boolean;\n disabledMessage: string;\n error: string;\n formData: object;\n validationData: any;\n submitData: any;\n};\n\nexport function useForm(props: UseFormProps) {\n const { formKey, formRef, autoSubmit = false } = props;\n\n const [getForm, { data, loading: loadingForm }] = useLazyQuery(GET_FORM);\n const [submit, submitData] = useMutation(SUBMIT_FORM);\n const [validate, validationData] = useLazyQuery(VALIDATE_FORM);\n\n const initialState = {\n enabled: false,\n validating: false,\n valid: true,\n validationMessage: \"\",\n error: \"\",\n disabledMessage: \"\",\n formData: {},\n validationData,\n submitData,\n };\n\n const [formState, setFormState] = useReducer<FormState, Partial<FormState>>(\n (state, next) => ({\n ...state,\n ...next,\n }),\n initialState\n );\n\n const { enabled, disabledMessage, validating, valid, error, formData } =\n formState;\n\n useDeepMemo(() => {\n debug(\"submitData useEffect\", submitData);\n setFormState({ submitData });\n }, [submitData]);\n\n useDeepMemo(() => {\n debug(\"validationData useEffect\", validationData);\n setFormState({ validationData });\n }, [validationData]);\n\n // load initial data into form\n useEffect(() => {\n async function setInitialData(htmlForm, initialData) {\n const inputs = htmlForm.elements;\n\n const formContent = new FormData(htmlForm);\n\n debug({ htmlForm, formContent });\n formContent?.forEach((value, key) => {\n debug({ value, key, inputs });\n const input = inputs.namedItem(key) as HTMLInputElement;\n\n try {\n if (input.type == \"checkbox\") {\n input.checked = jsonpointer.get(initialData, key);\n } else {\n input.value = jsonpointer.get(initialData, key) || \"\";\n }\n } catch (error) {\n debug(\"no initialData found for key\", key);\n }\n });\n }\n function initialize() {\n setFormState({\n enabled: data?.form.initialData?.isEnabled,\n disabledMessage: data?.form?.initialData?.isEnabledErrorMessage,\n });\n const htmlForm = formRef;\n\n if (!htmlForm) return;\n\n const initialData = data?.form?.initialData?.initialData;\n\n props.setInitialData !== undefined\n ? props.setInitialData(htmlForm, initialData)\n : setInitialData(htmlForm, initialData);\n }\n if (!loadingForm && data) initialize();\n }, [loadingForm]);\n\n // submit if form data is valid\n useEffect(() => {\n if (!!formState.validationData) {\n setFormState({\n validating: false,\n valid: formState.validationData?.data?.validateForm?.valid || false,\n });\n\n if (autoSubmit && formState.validationData?.data?.validateForm?.valid) {\n submit({\n formSubmissionInput: { key: formKey, formData },\n });\n }\n }\n }, [formState.validationData?.data?.validateForm?.valid]);\n\n /**\n * Schema, network, and integration errors after submission to GraphQL\n */\n function getSubmissionErrors(): Array<SubmissionError> {\n if (!formState.submitData) return [];\n\n const submissionResults = formState.submitData.data?.submitForm.results;\n\n return (\n submissionResults?.map((error) => {\n // salesforce errors\n const messages = error.result?.results\n ?.flatMap((res) => !res.success && res.message)\n .filter((message) => message);\n\n // fatal errors\n const errors = error.result?.results\n ?.flatMap(\n (res) =>\n !res.success && {\n error: res.error,\n errorType: res.errorType,\n errorCode: res.errorCode,\n }\n )\n .filter(({ error }) => error);\n\n return {\n integration: error.formHandler?.integration?.name,\n formHandler: error.formHandler?.name,\n messages,\n errors,\n };\n }) || []\n );\n }\n\n /**\n * Schema validation based on return data from validateForm results\n */\n function getValidationErrors(): ValidationErrors {\n const validationErrors =\n validationData?.data?.validateForm?.results[0]?.result?.errors;\n\n /**\n * Provide a JSON path and receive any errors at that path\n */\n function getErrorAtPath(path: string) {\n return validationErrors?.filter((result) => {\n const instanceLocation = result.instanceLocation.substring(1);\n return instanceLocation === path;\n });\n }\n\n /**\n * Provide a JSON path and receive any errors at that path,\n * and any errors for nested paths\n */\n function getSubErrorsAtPath(path: string) {\n return validationErrors?.filter((result: ValidationError) => {\n const instanceLocation = result.instanceLocation.substring(1);\n return instanceLocation.startsWith(`${path}`);\n });\n }\n\n return {\n getErrorAtPath,\n getSubErrorsAtPath,\n hasSubErrors: (path) => getSubErrorsAtPath(path)?.length > 0,\n };\n }\n\n async function validateForm(formData) {\n await validate({\n formValidationInput: {\n key: formKey,\n formData,\n },\n });\n }\n\n async function submitForm(formData) {\n await submit({\n formSubmissionInput: {\n key: formKey,\n formData,\n },\n });\n }\n\n /**\n * Submit function for regular <form> submissions\n */\n async function handleSubmit(e: any) {\n e.preventDefault();\n\n setFormState({ validating: true });\n const form = e.target;\n debug(\"submit form\", form);\n const data = new FormData(form);\n\n let formData = {};\n\n //@ts-ignore\n for (var pair of data.entries()) {\n jsonpointer.set(formData, pair[0], pair[1]);\n }\n\n setFormState({ formData });\n\n await validateForm(formData);\n }\n\n return {\n states: {\n enabled,\n disabledMessage,\n loadingForm,\n validating,\n valid,\n error,\n validationData: formState.validationData,\n submitData: formState.submitData,\n },\n data: {\n formKey,\n schema: data?.form?.schema,\n },\n callbacks: {\n /** Retrieve schema and initial data if provided from backend */\n getForm,\n /** Validate and submit <form> element data */\n handleSubmit,\n /** Validates form data and submits form if autoSubmit flag is true */\n validateForm,\n /** Submits form data */\n submitForm,\n /** Set form state for custom validation errors and multi-page forms */\n setFormState,\n getValidationErrors,\n getSubmissionErrors,\n },\n };\n}\n\ninterface ValidationErrors {\n getErrorAtPath(path: string): ValidationError[];\n getSubErrorsAtPath(path: string): ValidationError[];\n // TODO: implement ajv-i18n for translatable errors\n // getHumanizedErrorAtPath(path: string): string;\n hasSubErrors(path: string): boolean;\n}\n\ntype ValidationError = {\n error: string;\n keywordLocation: string;\n instanceLocation: string;\n};\n\ntype SubmissionError = {\n formHandler: string;\n integration: string;\n messages: string[];\n};\n\nexport type UseFormViewProps = ReturnType<typeof useForm>;\n"],"names":["ref","current","undefined","useHost","Error","setImplementation","implementation","useLocale","lazilyStartLocaleContext","host","useDomContext","LOCALE_CONTEXT_NAME","useProgramId","lazilyStartProgramContext","PROGRAM_CONTEXT_NAME","useSessionData","useUserIdentity","_useUserIdentity","managedIdentity","_useUserIdentity$mana","sessionData","useToken","_useUserIdentity2","jwt","lazilyStartUserContext","identity","USER_CONTEXT_NAME","validIdentity","userIdentityFromJwt","isDemo","setUserIdentity","useTenantAlias","getTenantAlias","useAppDomain","getAppDomain","useEngagementMedium","getEngagementMedium","__assign","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","this","docCache","Map","fragmentSourceMap","printFragmentWarnings","experimentalFragmentVariables","normalize","string","replace","trim","parseDocument","source","ast","seenKeys","definitions","cacheKey","has","parsed","parse","kind","set","doc","workSet","Set","forEach","node","loc","keys","key","value","add","startToken","endToken","stripLoc","fragmentDefinition","fragmentName","name","sourceKey","body","substring","start","end","sourceKeySet","get","console","warn","push","gql","literals","args","_i","result","arg","gql_1","extras","resetCaches","clear","disableFragmentWarnings","enableExperimentalFragmentVariables","disableExperimentalFragmentVariables","BatchedGraphQLClient","GraphQLClient","constructor","url","opts","super","Subject","unmergable","subject","pipe","bufferTime","subscribe","async","queryAddedEvents","mergedQuery","mergedVariables","mergedQueryAddedEvents","unmergedQueryAddedEvents","mergeQueryAddedEvents","unmergedQuery","next","mergedQueryResult","_this","superRequest","resolveMergedQueryResult","e","ClientError","data","errors","response","rejectAllQueryAddedEventsWithError","aliases","eventsToResolve","error","erroredEvent","path","find","index","includes","erroredId","getIdFromAliasedField","indexOfErroredEvent","findIndex","event","id","splice","eventSpecificData","removeAliasesFromDataResult","removeAliasFromField","query","variables","errorResponse","newError","print","rejectQueryAddedEventWithError","resolveSingleQueryResult","request","Promise","resolve","reject","queryAddedEvent","generateQueryAddedEventId","nanoid","field","fieldArray","split","events","document","reduce","acc","curr","parsedQuery","queryStr","containsDirective","test","renameFn","aliasFieldOrVariableFn","addN","combineQuery","queryResult","endsWith","[object Object]","err","GRAPHQL_CONTEXT","memoizedGraphQLClient","memoize","appDomain","tenantAlias","token","headers","Authorization","reducer","state","action","type","loading","payload","useBaseQuery","initialState","client","localClient","clientFromContext","attempts","useGraphQLClient","dispatch","useReducer","useCallback","skipLoading","res","initialMutationState","useMutation","update","AuthenticateWithEmailAndPasswordMutation","useAuthenticateWithEmailAndPasswordMutation","v","authenticateManagedIdentityWithEmailAndPassword","user","decode","accountId","email","emailVerified","RegisterWithEmailAndPasswordMutation","useRegisterWithEmailAndPasswordMutation","registerManagedIdentityWithEmailAndPassword","RegisterViaRegistrationFormMutation","useRegisterViaRegistrationFormMutation","formError","setFormError","useState","managedIdentityResponse","submitForm","_result$submitForm","results","_result$submitForm$re","formHandler","namespace","_managedIdentityRespo","_managedIdentityRespo2","registrationResult","success","message","ChangePasswordMutation","useChangePasswordMutation","ResetPasswordMutation","useResetPasswordMutation","resetManagedIdentityPassword","VerifyPasswordResetCodeMutation","useVerifyPasswordResetCodeMutation","useRefreshDispatcher","refresh","dispatchEvent","CustomEvent","bubbles","composed","cancelable","detail","useRefreshListener","skip","useEffect","listener","addEventListener","removeEventListener","useRef","signalRef","deepEqual","useMemo","useDeepCompareMemoize","initialLazyQueryState","NOTLOADED","Symbol","useLazyQuery","variablesRef","refetch","ManagedIdentitySessionQuery","useManagedIdentitySessionQuery","userIdentity","updateUserIdentity","managedIdentitySession","VerifyEmailMutation","useVerifyEmailMutation","refreshManagedIdentitySession","verifyManagedIdentityEmail","RequestPasswordResetEmailMutation","useRequestPasswordResetEmailMutation","RequestVerificationEmailMutation","useRequestVerificationEmailMutation","AuthenticateManagedIdentityWithInstantAccessMutation","useAuthenticateManagedIdentityWithInstantAccess","programId","env","getEnvironment","authenticateManagedIdentityWithInstantAccess","fetch","method","Content-Type","JSON","stringify","ok","json","viewer","instantAccessRewards","some","r","cancelledReason","pendingReasons","_r$pendingReasons","fetchFraud","userId","useDeepMemo","memoFn","equal","useTick","x","deepFreeze","object","propNames","getOwnPropertyNames","freeze","initialQueryState","useQuery","tick","forceUpdate","String","Math","random","slice","window","trustedTypes","createPolicy","createHTML","eventOptionsSupported","options","capture","_e","currentId","hookSymbol","effectsSymbol","layoutEffectsSymbol","then","bind","Hook","use","hooks","hook","createEffect","setEffects","ignored1","ignored2","callback","values","hasChanged","run","lastValues","teardown","_teardown","cb","_","_updater","_ranEffect","_unsubscribe","Context","virtual","_subscribe","unsubscribe","defaultValue","fn","initialValue","updater","makeArgs","updaterFn","previousValue","init","currentState","m","h","d","val","str","match","exec","parseFloat","toLowerCase","isFinite","long","ms","msAbs","abs","plural","fmtLong","round","fmtShort","isPlural","exports","useColors","module","humanize","diff","c","color","lastC","namespaces","storage","setItem","removeItem","getItem","process","DEBUG","__nwjs","navigator","userAgent","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","RegExp","$1","localStorage","localstorage","warned","debug","log","createDebug","prevTime","enableOverride","enabled","self","Number","Date","prev","coerce","unshift","format","formatter","formatters","formatArgs","selectColor","extend","destroy","defineProperty","enumerable","configurable","delimiter","newDebug","toNamespace","regexp","toString","default","stack","disable","names","map","skips","join","enable","save","len","substr","require$$0","hash","charCodeAt","colors","load","j","useParentState","props","setValue","useDomContextState","getContextValueName","getContextName","useParent","parent","parentValue","useSetParent","useParentValue","useParentQuery","useParentQueryValue","useCurrentPage","history","listen","location","navigation","usePagination","pageVars","pageState","setPageState","limit","offset","calcOffset","page","calcPage","ceil","setLimit","newLimit","newPage","newOffset","setCurrentPage","calculatePagination","count","totalCount","currentPage","pageCount","calcPageCount","rangeOnPage","pageProgress","usePaginatedQuery","dataPath","extraVars","envelope","states","callbacks","valueEquality","left","right","useDebounce","delay","eq","equalityFn","debounced","useDebouncedCallback","cancel","flush","func","wait","leading","debounce","FIRE_EVENT","useShareEvent","engagementMedium","program","shareMedium","eventMeta","meta","debugFn","useLoadEvent","globalProvider","squatchLoadEvent","ContextProvider","element","contextName","lazilyStartLoadEventContext","context","GET_FORM","SUBMIT_FORM","VALIDATE_FORM","useForm","formKey","formRef","autoSubmit","getForm","loadingForm","submit","submitData","validate","validationData","validating","valid","validationMessage","disabledMessage","formData","formState","setFormState","validateForm","formValidationInput","form","initialData","_data$form$initialDat","isEnabled","_data$form","_data$form$initialDat2","isEnabledErrorMessage","htmlForm","_data$form2","_data$form2$initialDa","setInitialData","inputs","elements","formContent","FormData","input","namedItem","checked","jsonpointer","initialize","_formState$validation4","_formState$validation5","_formState$validation6","formSubmissionInput","_formState$validation7","_formState$validation8","_formState$validation9","schema","_data$form3","handleSubmit","preventDefault","target","pair","entries","getValidationErrors","validationErrors","_validationData$data","_validationData$data$","_validationData$data$2","_validationData$data$3","getSubErrorsAtPath","filter","instanceLocation","startsWith","getErrorAtPath","hasSubErrors","getSubmissionErrors","submissionResults","_formState$submitData","messages","_error$result","_error$result$results","flatMap","_error$result2","_error$result2$result","errorType","errorCode","integration","_error$formHandler","_error$formHandler$in","_error$formHandler2"],"mappings":"yrCAAA,MAAMA,EAAM,CAAEC,aAASC,YAEPC,IACd,QAAoBD,IAAhBF,EAAIC,QACN,UAAUG,MAAM,yCAGlB,OAAOJ,EAAIC,mBAGGI,EAAkBC,GAChC,IAAKA,EACH,UAAUF,MAAM,iCAGlB,GAA8B,mBAAnBE,EACT,UAAUF,MAAM,qCAGlBJ,EAAIC,QAAUK,WCZAC,IACdC,IACA,MAAMC,EAAON,IACb,OAAOO,EAAsBD,EAAME,YCHrBC,IACdC,IACA,MAAMJ,EAAON,IACb,OAAOO,EAAsBD,EAAMK,YCIrBC,YACd,gBAAOC,eAAAC,EAAmBC,wBAAnBC,EAAoCC,qBAM7BC,UACd,gBAAOL,YAAAM,EAAmBC,aAMZP,IACdQ,IACA,MAAMf,EAAON,IACPsB,EAAWf,EAAcD,EAAMiB,GAI/BC,EAAgBC,QAAoBH,SAAAA,EAAUF,KACpD,GAAKM,MAAYJ,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