{"version":3,"sources":["@webhare/env/src/envbackend.ts","@webhare/env/src/init-browser.ts","@webhare/frontend/src/init.ts","@webhare/tsrun/src/polyfills.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","@webhare/env/src/navigation.ts","@webhare/std/src/quacks.ts","@webhare/std/src/finmath.ts","@webhare/std/src/money.ts","@webhare/std/src/strings.ts","@webhare/std/src/collections.ts","@webhare/std/src/localmutex.ts","mod::system/js/dompack/src/events.ts","@webhare/dompack/src/busy.ts","@webhare/dompack/src/tree.ts","mod::system/js/dompack/src/tree.ts","mod::system/js/dompack/src/components.ts","@webhare/dompack/src/storage.ts","@webhare/dompack/src/browser.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::companyos/webdesigns/pages/frontend/login-background.ts","mod::companyos/webdesigns/pages/frontend/login.ts","mod::companyos/webdesigns/pages/frontend/arrays.ts","node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js","@webhare/js-api-tools/src/stacktracing.ts","@webhare/rpc/src/rpc.ts","@webhare/auth/src/shared.ts","@webhare/frontend/src/auth.ts","@webhare/frontend/src/gtm.ts","@webhare/frontend/src/frontend.ts","mod::companyos/webdesigns/companyos/frontend/composables/useRpc.ts","mod::companyos/webdesigns/pages/frontend/apps.ts","mod::companyos/webdesigns/companyos/frontend/lib/theme.ts","mod::companyos/webdesigns/pages/frontend/theme.ts","mod::companyos/webdesigns/pages/frontend/account.ts","mod::companyos/node_modules/@lit/reactive-element/src/css-tag.ts","mod::companyos/node_modules/@lit/reactive-element/src/reactive-element.ts","mod::companyos/node_modules/lit-html/src/lit-html.ts","mod::companyos/node_modules/lit-element/src/lit-element.ts","mod::companyos/webdesigns/pages/frontend/unsaved.ts","mod::companyos/webdesigns/pages/frontend/sections.ts","mod::companyos/webdesigns/companyos/frontend/lib/context-menu.ts","mod::companyos/webdesigns/companyos/frontend/lib/list.ts","mod::companyos/node_modules/lit-html/src/directives/if-defined.ts","mod::companyos/webdesigns/companyos/frontend/components/icons/icon-data.ts","mod::companyos/webdesigns/pages/frontend/screen/icon.ts","mod::companyos/webdesigns/pages/frontend/screen/list.ts","mod::companyos/webdesigns/pages/frontend/screen/dialog.ts","mod::companyos/webdesigns/companyos/frontend/lib/tabs.ts","mod::companyos/webdesigns/pages/frontend/screen/tabs.ts","mod::companyos/webdesigns/companyos/frontend/lib/toasts.ts","mod::companyos/webdesigns/pages/frontend/screen/toast.ts","mod::companyos/webdesigns/companyos/frontend/lib/loading.ts","mod::companyos/webdesigns/companyos/frontend/lib/form-validation.ts","mod::companyos/webdesigns/pages/frontend/screen/controllers.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-loading-model.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-lock-model.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-person-model.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-access-model.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-table-model.ts","mod::looping_os/webdesigns/loopingos/frontend/components/ip-access/ip-mask-model.ts","mod::looping_os/webdesigns/loopingos/frontend/ip-access/ip-access-controller.ts","mod::looping_os/webdesigns/loopingos/frontend/ip-access/ip-confirmations.ts","mod::looping_os/webdesigns/loopingos/frontend/ip-access/ip-history.ts","mod::looping_os/webdesigns/loopingos/frontend/ip-access/ip-mask-dialog.ts","mod::looping_os/webdesigns/loopingos/frontend/ip-access/ip-access.ts","mod::looping_os/webdesigns/loopingos/frontend/frontend.ts","/entrypoint.js"],"sourcesContent":["//We implement the backend version of getWHDebugFlags so bridge can access us without going through a recursive dep\n\nimport type { DTAPStage } from \"./concepts\";\n\n/// List global polyfills currently active. This may be needed to align TypeScript hosts configuration\nexport const globalPolyfills: string[] = [];\n\n/// An object with string keys and typed values\nexport interface WellKnownFlags {\n  /** Log RPcs */\n  rpc?: boolean;\n  /** Log web traffic */\n  wrq?: boolean;\n  /** Autoprofile */\n  apr?: boolean;\n  /** IPC */\n  ipc?: boolean;\n  /** async */\n  async?: boolean;\n}\nexport type DebugFlags = WellKnownFlags & { [key: string]: boolean | undefined };\n\nexport type DebugConfig = {\n  tags: readonly string[];\n  outputsession: string;\n  context: string;\n};\n\nconst settingschangedcallbacks = new Array<() => void>;\n\n/* Global debug flags are set by `wh debug`, local flags are prefilled by environment variables.\n   Edits to the debug flags will be applied to the local flags (unless setDebugFlagsOverrideCB returns\n   override records).\n*/\nconst globalDebugFlags: DebugFlags = {}, localDebugFlags: DebugFlags = {};\n\n/** Returns the flag override records. The first record is examined first, then the second, etc. */\nlet debugFlagsOverridesCB: undefined | (() => DebugFlags[]);\n\n/** Override the debug flag override getter. */\nexport function setDebugFlagsOverrideCB(cb: undefined | (() => DebugFlags[])) {\n  debugFlagsOverridesCB = cb;\n}\n\n/* Proxy handler for the published debug flags. Uses the override records (with the first record\n   examined first, then the second, etc.) to override the flags from baseDebugFlags. Setting to `true` sets\n   the flag, `false` disables it and setting to `undefined` has the same effect as deleting the property in the\n   current top record (exposing any value from a lower record, like the debug settings from `wh debug`).\n*/\nclass DebugFlagsProxyHandler implements ProxyHandler<DebugFlags> {\n  private getRecordList(): DebugFlags[] {\n    return [...debugFlagsOverridesCB?.() ?? [], localDebugFlags, globalDebugFlags];\n  }\n\n  get(target: DebugFlags, p: string) {\n    for (const record of this.getRecordList())\n      if (p in record && typeof record[p] !== \"undefined\")\n        return record[p];\n    return undefined;\n  }\n  has(target: DebugFlags, p: string): boolean {\n    return this.get(target, p) !== undefined;\n  }\n  ownKeys(target: DebugFlags): Array<string | symbol> {\n    const keys = new Array<string | symbol>;\n    for (const record of this.getRecordList())\n      for (const key of Reflect.ownKeys(record))\n        if (typeof key === \"string\" && record[key] !== undefined && !keys.includes(key))\n          keys.push(key);\n    return keys;\n  }\n  set(target: DebugFlags, p: string, newValue: boolean | undefined): boolean {\n    const toModify = this.getRecordList()[0];\n    if (typeof newValue === \"boolean\")\n      toModify[p] = newValue;\n    else\n      delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  deleteProperty(target: DebugFlags, p: string): boolean {\n    const toModify = this.getRecordList()[0];\n    delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  getOwnPropertyDescriptor(target: DebugFlags, p: string): PropertyDescriptor | undefined {\n    const value = this.get(target, p);\n    return value !== undefined ? { enumerable: true, value, configurable: true } : undefined;\n  }\n}\n\nexport const debugFlags = new Proxy<DebugFlags>({\n  [Symbol.for('nodejs.util.inspect.custom')]: formatForConsoleLogs\n}, new DebugFlagsProxyHandler());\n\nfunction formatForConsoleLogs() {\n  return `DebugFlags [${[...Object.keys(debugFlags)].filter(key => debugFlags[key]).join(\", \")}]`;\n}\n\nfunction runSettingsCallbacks() {\n  for (const cb of [...settingschangedcallbacks]) {\n    try {\n      cb();\n    } catch (e) {\n      console.error(\"Error invoking settings change callback\", cb?.name, e);\n      //ignore, debugFlags can change due to external updates so they're basically signal handlers and there's no real point in crashing whatever was really running\n    }\n  }\n}\n\n/** Update the debugconfig as present in the system configuration record\n    @param settings - debugconfig cell of the system configuration record\n*/\nexport function updateDebugConfig(settings: DebugConfig | null) {\n  const oldenabledflags = Object.keys(globalDebugFlags).sort();\n  const newenabledflags = settings?.tags ? [...settings.tags].sort() : [];\n\n  if (oldenabledflags.join(\",\") !== newenabledflags.join(\",\")) {\n    for (const flag of newenabledflags)\n      globalDebugFlags[flag] = true;\n    for (const flag of oldenabledflags)\n      if (!newenabledflags.includes(flag))\n        delete globalDebugFlags[flag];\n\n    runSettingsCallbacks();\n  }\n  if (debugFlags.async && Error.stackTraceLimit < 100)\n    Error.stackTraceLimit = 100;\n}\n\nexport function registerDebugConfigChangedCallback(cb: () => void) {\n  settingschangedcallbacks.push(cb);\n}\n\n/** DTAP stage set for this WebHare */\nlet dtapStage: DTAPStage = \"production\";\n\n/** @deprecated We now recommend checking dtapStage against production/acceptance Explicitly */\nlet isLive: boolean = dtapStage === \"production\" || dtapStage === \"acceptance\";\n\n/** The backend base URL. Used for eg. autoconfiguring JSON/RPC */\nlet backendBase = \"\";\n\n//deprecated variants\n/** @deprecated For WH5.4 and up use 'dtapStage' */\nlet dtapstage: DTAPStage = dtapStage;\n/** @deprecated For WH5.4 and up compare 'dtapStage' for production or acceptance */\nlet islive: boolean = isLive;\n\nexport function initEnv(setDtapStage: DTAPStage, setBackendBase: string) {\n  dtapStage = setDtapStage;\n  isLive = dtapStage === \"production\" || dtapStage === \"acceptance\";\n  backendBase = setBackendBase;\n\n  dtapstage = dtapStage;\n  islive = isLive;\n}\n\nexport { dtapStage, isLive, backendBase };\nexport { dtapstage, islive }; //deprecated variants\n","\n//Note that @webhare/env does not invoke this API itself. In WebHare @webhare/frontend/src/init uses this to initialize\nexport function getBrowserDebugFlags(varname: string): string[] {\n  const flags = [];\n  const urldebugvar = new URL(location.href).searchParams.get(varname);\n  if (urldebugvar)\n    flags.push(...urldebugvar.split(','));\n\n  //not importing getCookie to solve some import ordering issues\n  if (typeof document !== \"undefined\") { //'document' is undefined in a worker but assetpacks compiled for a ServiceWorker will also load us\n    const debugcookie = document.cookie.match(`(?:^|;)\\\\s*${varname}=([^;]*)`); //TODO escape varname\n    if (debugcookie) {\n      const debugcookievalue = decodeURIComponent(debugcookie[1]);\n      if (debugcookievalue)\n        flags.push(... (debugcookievalue.split('.').filter(flag => !flag.startsWith('sig='))));\n    }\n  }\n\n  return flags;\n}\n","/* frontend-config parses the wh-config object in the browser and mocks any missing data. @webhare/env does not actually expose this config, @webhare/frontend does\n   The frontend configuration is built in the SiteResponse's 'frontendConfig' member */\n\nimport type { DTAPStage } from \"@webhare/env/src/concepts\";\nimport { debugFlags, initEnv } from \"@webhare/env/src/envbackend\";\nimport { getBrowserDebugFlags } from \"@webhare/env/src/init-browser\";\nimport type { FrontendDataTypes } from \"@webhare/frontend\";\n\n\n/** The format of the <script id=\"wh-config\"> object  */\nexport interface WHConfigScriptData {\n  ///Plugins may add keys at this level\n  [key: string]: unknown;\n\n  //NOTE: existing frontend code doesn't expect site/obj to ever be null. not sure if 'object' provides the best interface or whether we need some sort of 'unknown but an existing object'\n  /** Page (targetobject) specific settings */\n  obj: { [key: string]: unknown };\n  /** Site specific settings */\n  site: { [key: string]: unknown };\n\n  /** Numeric server version number (eg 5.02.24 = 50224)\n   *  @deprecated Interpreting numbers (or version strings) is dangerous. Feature flags/testing or limiting your entire module to compatible versions is safer\n  */\n  server: number;\n  /** Root URL of this site */\n  siteRoot: string;\n  /** @deprecated Use `document.documentElement.lang` instead */\n  locale: never;\n}\n\n//names fields can still have when not yet republished\nexport interface WHConfigScriptData_OldPublishFields {\n  islive: boolean;\n  dtapstage: DTAPStage;\n  siteroot: string;\n}\n\n//fallback names with deprecation warnings\nexport interface WHConfigScriptData_LegacyFields {\n  /** @deprecated Use dtapStage in WH5.4+ */\n  islive: boolean;\n  /** @deprecated Use `dtapStage` from \"\\@webhare/env\"; in WH5.4+ */\n  dtapstage: DTAPStage;\n  /** @deprecated Use `getSiteRoot` from \"\\@webhare/frontend\"; in WH5.7+ */\n  siteroot: string;\n}\n\ntype Configured = Partial<WHConfigScriptData & WHConfigScriptData_OldPublishFields & { dtapStage?: DTAPStage }>;\nlet config: Configured | undefined;\nlet siteroot;\nlet dtapStage: DTAPStage = \"production\";\n\n//if document is undefined, we're serverside or in a worker\nconst whconfigel = typeof document !== \"undefined\" ? document.querySelector('script#wh-config') : null;\nif (whconfigel?.textContent) {\n  config = JSON.parse(whconfigel.textContent) as Configured;\n\n  //Fallbacks for pages last published with WH5.3 *and* pages published from HareScript which still emit lowercase props\n  siteroot = config.siteRoot ?? config.siteroot;\n  dtapStage = config.dtapstage ?? config.dtapStage ?? dtapStage;\n}\n\ninitEnv(dtapStage, '/');\n\nif (typeof location !== \"undefined\")\n  for (const flag of getBrowserDebugFlags('wh-debug'))\n    debugFlags[flag] = true;\n\n\n/** @deprecated frontendConfig has been deprecated. Switch to the getFrontendData system */\n// Make sure we have obj/site as some sort of object, to prevent crashes on naive 'if ($wh.config.obj.x)' tests'\nexport const frontendConfig = {\n  server: 0,\n  ...config,\n  obj: config?.obj || {},\n  site: config?.site || {},\n  siteRoot: siteroot,\n  //deprecated variables:\n  dtapstage: dtapStage,\n  islive: ([\"production\", \"acceptance\"]).includes(dtapStage!),\n  siteroot\n} as WHConfigScriptData & WHConfigScriptData_LegacyFields; //in a future version we can either obsolete or even drop '& WHConfigScriptData_LegacyFields' and validation will fail without breaking existing JS code\n\n\n//NOTE: These APIs need to live in init.ts so eg gtm.ts can access us without triggering a CSS reset through frontend.ts. When frontend.ts stops auto-resetting we might move it back\n\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options: { allowMissing: true }): FrontendDataTypes[Type] | null;\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options?: { allowMissing: boolean }): FrontendDataTypes[Type];\n\n/** Get data exported by the response\n * @typeParam Type - The type of data to get\n * @param dataObject - The data object of data to get\n * @param allowMissing - If true, return null if the data object is missing. Otherwise throw an error\n * @example\n```\n  declare module \"@webhare/frontend\" {\n    interface FrontendDataTypes {\n      \"mymodule:type\": {\n        test: number;\n      };\n    }\n  }\n\n  const data = getFrontendData(\"mymodule:type\");\n```\n*/\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(dataObject: Type, { allowMissing = false } = {}): FrontendDataTypes[Type] | null {\n  const retval = config?.[dataObject] as FrontendDataTypes[Type];\n  if (!retval)\n    if (allowMissing)\n      return null;\n    else\n      throw new Error(`Missing frontend data object: ${dataObject}`);\n\n  return retval;\n}\n\n/** Get the current site root\n *\n * @returns The site root URL (ending with a slash)\n*/\nexport function getSiteRoot() { //now an API to improve treeshaking\n  return frontendConfig.siteRoot;\n}\n","// Set up dispose symbols - https://github.com/evanw/esbuild/pull/3192 \"you'll need to polyfill Symbol.dispose if it's not present before you use it.\n\n//@ts-ignore -- It's marked readonly\nSymbol.dispose ||= Symbol.for('Symbol.dispose');\n//@ts-ignore -- It's marked readonly\nSymbol.asyncDispose ||= Symbol.for('Symbol.asyncDispose');\n\n// Set up promise resolvers (ES2024)\nPromise.withResolvers ||= function <T>(): PromiseWithResolvers<T> {\n  let resolve: (value: T | PromiseLike<T>) => void;\n  let reject: (reason: Error) => void;\n  const promise = new Promise<T>((_resolve, _reject) => { resolve = _resolve; reject = _reject; });\n  // @ts-ignore `resolve` and `reject` are assigned synchronously, which isn't picked up by the TypeScript compiler (see\n  // https://github.com/Microsoft/TypeScript/issues/30053)\n  return { promise, resolve, reject };\n};\n\n// Polyfills for https://caniuse.com/?search=groupby - needed until we can assume safari 17.4 as global baseline\nif (!Map.groupBy)\n  Map.groupBy = function <Item, Key>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Map<Key, Item[]> {\n    const retval = new Map<Key, Item[]>;\n    let idx = 0;\n    for (const item of items) {\n      const key = callbackfn(item, idx++);\n      let list = retval.get(key);\n      if (!list)\n        retval.set(key, list = []);\n      list.push(item);\n    }\n    return retval;\n  };\n\nif (!Object.groupBy)\n  Object.groupBy = function <Item, Key extends string | number | symbol>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Partial<Record<Key, Item[]>> {\n    return Object.fromEntries(Map.groupBy(items, callbackfn).entries()) as Partial<Record<Key, Item[]>>;\n  };\n","/* eslint-disable @typescript-eslint/array-type */\n/* eslint-disable @typescript-eslint/no-loop-func */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-this-alias */\n\n/* Iterator polyfills (https://caniuse.com/?search=iterator) - stage 4 ES but not in all browsers yet\n   Based on https://github.com/alkihis/iterator-polyfill/tree/master but we removed all the AsyncIterator\n   stuff as that's still stage 2 AND not implemented in TypeScript (as of 5.6)\n\n   We're ignoring a few linting/any issues as we really don't care to maintain this much\n   Fixed an issue with .some - reported as https://github.com/alkihis/iterator-polyfill/issues/6\n*/\n\n(function () {\n  // polyfill already applied / proposal implemented\n  if ('Iterator' in globalThis) {\n    return;\n  }\n\n  // Polyfill for Iterator\n  const IteratorPrototype = {};\n\n  const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());\n  const OriginalIteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);\n\n  Object.setPrototypeOf(OriginalIteratorPrototype, IteratorPrototype);\n\n  Object.defineProperties(IteratorPrototype, {\n    [Symbol.iterator]: {\n      value() {\n        return this;\n      }\n    },\n    map: {\n      *value<T, R>(callback: (value: T) => R): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = callback(value.value);\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    filter: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          if (callback(real_value)) {\n            next_value = yield real_value;\n            value = it.next(next_value);\n          } else {\n            value = it.next(next_value);\n          }\n        }\n\n        return value.value;\n      },\n    },\n    find: {\n      value<T>(callback: (value: boolean) => T) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return real_value;\n\n          value = it.next();\n        }\n      }\n    },\n    every: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!callback(real_value))\n            return false;\n\n          value = it.next();\n        }\n\n        return true;\n      }\n    },\n    some: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value)) {\n            it.return();\n            return true;\n          }\n\n          value = it.next();\n        }\n\n        return false;\n      }\n    },\n    toArray: {\n      value(max_count = Infinity) {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max_count <= 0)\n            return values;\n\n          values.push(real_value);\n\n          if (max_count !== Infinity)\n            max_count--;\n\n          value = it.next();\n        }\n\n        return values;\n      }\n    },\n    take: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining <= 0)\n            return;\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n          remaining--;\n        }\n\n        return value.value;\n      },\n    },\n    drop: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining > 0) {\n            value = it.next(next_value);\n            remaining--;\n            continue;\n          }\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    asIndexedPairs: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let index = 0;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const next_value = yield [index, real_value];\n          value = it.next(next_value);\n          index++;\n        }\n\n        return value.value;\n      }\n    },\n    flatMap: {\n      *value<T, R extends object>(mapper: (value: T) => IterableIterator<R> | R): Generator<any, any, any> {\n        if (typeof mapper !== 'function') {\n          throw new TypeError('Mapper must be a function.');\n        }\n\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const mapped = mapper(real_value);\n\n          if (Symbol.iterator in mapped) {\n            // @ts-ignore -- copied from original\n            next_value = yield* mapped[Symbol.iterator]();\n          } else {\n            next_value = yield mapped;\n          }\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    reduce: {\n      value<T, V>(reducer: (acc: V, value: T) => V, initial_value?: V) {\n        let acc = initial_value;\n\n        const it = this;\n        if (acc === undefined) {\n          acc = it.next().value;\n        }\n\n        let value = it.next();\n        while (!value.done) {\n          const real_value = value.value;\n\n          acc = reducer(acc!, real_value);\n\n          value = it.next();\n        }\n\n        return acc;\n      }\n    },\n    forEach: {\n      value<T>(callback: (value: T) => any) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          callback(real_value);\n\n          value = it.next();\n        }\n      }\n    },\n    [Symbol.toStringTag]: {\n      value: 'IteratorPrototype'\n    },\n\n    /* OUTSIDE PROPOSAL */\n    count: {\n      value() {\n        let count = 0;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          count++;\n          value = it.next();\n        }\n\n        return count;\n      },\n    },\n    join: {\n      value(string: string) {\n        let final = '';\n        let first = true;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (first) {\n            first = false;\n            final += real_value;\n          } else {\n            final += string + real_value;\n          }\n\n          value = it.next();\n        }\n\n        return final;\n      }\n    },\n    chain: {\n      *value<I>(...iterables: IterableIterator<I>[]) {\n        yield* this;\n\n        for (const it of iterables) {\n          yield* it;\n        }\n      }\n    },\n    zip: {\n      *value<T, O>(...others: IterableIterator<O>[]): Iterator<(T | O)[]> {\n        const it_array = [this, ...others].map((e: any) => Symbol.iterator in e ? e[Symbol.iterator]() : e as Iterator<T | O>);\n        let values = it_array.map(e => e.next());\n        let next_value: any;\n\n        while (values.every(e => !e.done)) {\n          next_value = yield values.map(e => e.value);\n          values = it_array.map(e => e.next(next_value));\n        }\n      },\n    },\n    takeWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    dropWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n        let finished = false;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!finished && callback(real_value)) {\n            value = it.next(next_value);\n            continue;\n          }\n\n          finished = true;\n          next_value = yield real_value;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    fuse: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (real_value !== undefined && real_value !== null)\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    partition: {\n      value<T>(callback: (value: T) => boolean) {\n        const partition1 = [], partition2 = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            partition1.push(real_value);\n          else\n            partition2.push(real_value);\n\n          value = it.next();\n        }\n\n        return [partition1, partition2];\n      },\n    },\n    findIndex: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let i = 0;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return i;\n\n          value = it.next();\n          i++;\n        }\n\n        return -1;\n      }\n    },\n    max: {\n      value() {\n        let max = -Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max < real_value)\n            max = real_value;\n\n          value = it.next();\n        }\n\n        return max;\n      },\n    },\n    min: {\n      value() {\n        let min = Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (min > real_value)\n            min = real_value;\n\n          value = it.next();\n        }\n\n        return min;\n      },\n    },\n    cycle: {\n      *value(): Generator<any, any, any> {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n          values.push(real_value);\n\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        while (true) {\n          yield* values;\n        }\n      },\n    },\n  });\n\n  //iterator.from from https://github.com/rauschma/iterator-helpers-polyfill/\n\n  function isObject(value: unknown) {\n    if (value === null) return false;\n    const t = typeof value;\n    return t === 'object' || t === 'function';\n  }\n\n  function GetIteratorFlattenable<T>(obj: Record<symbol, any>): T {\n    if (!isObject(obj)) {\n      throw new TypeError();\n    }\n    const method = obj[Symbol.iterator];\n    let iterator = undefined;\n    if (typeof method !== 'function') {\n      iterator = obj;\n    } else {\n      iterator = method.call(obj);\n    }\n    if (!isObject(iterator)) {\n      throw new TypeError();\n    }\n    return iterator;\n  }\n\n  if (!('Iterator' in globalThis)) {\n    const Iterator = function Iterator() { };\n\n    Iterator.prototype = IteratorPrototype;\n\n    // @ts-expect-error We're still missing From in this poyfill\n    (globalThis).Iterator = Iterator;\n  }\n\n\n  //----- Static method -----\n  // Must be done after Iterator.prototype was set up,\n  // so that `extends Iterator` works below\n\n  class WrappedIterator<T, TReturn = any, TNext = undefined> extends Iterator<T, TReturn, TNext> {\n    #iterator;\n    constructor(iterator: Iterator<T, TReturn, TNext>) {\n      super();\n      this.#iterator = iterator;\n    }\n    override next(...args: [] | [TNext]): any {\n      return this.#iterator.next(...args);\n    }\n    // `async` helps with line (*)\n    override return(value?: TReturn | PromiseLike<TReturn>): any {\n      const returnMethod = this.#iterator.return;\n      if (returnMethod === undefined) {\n        return { done: true, value: value as any }; // (*)\n      }\n      return returnMethod.call(this.#iterator);\n    }\n  }\n\n  function Iterator_from<T>(value: any) {\n    const iterator = GetIteratorFlattenable<Iterator<T>>(value);\n    if (iterator instanceof Iterator) {\n      return iterator;\n    }\n    // `iterator´ does not support the new API – wrap it so that it does\n    return new WrappedIterator(iterator);\n  }\n\n  Object.defineProperty(\n    Iterator, 'from',\n    {\n      writable: true,\n      enumerable: false,\n      configurable: true,\n      value: Iterator_from,\n    }\n  );\n})();\n","type FormValueList = Array<{ name: string; value: string }>;\n\n/** A navigation instruction encapsulates the next step that a client has to take in eg. a login, payment or wizard flow.\n * Use navigateTo to execute a navigation in a browser\n*/\n\nexport type NavigateInstruction =\n  {\n    type: \"redirect\";\n    url: string;\n  } | {\n    type: \"form\";\n    form: {\n      action: string;\n      vars: FormValueList;\n      method?: \"POST\";\n    };\n  } | {\n    type: \"reload\";\n  } | {\n    type: \"postmessage\";\n    message: unknown;\n    target?: \"parent\" | \"opener\";\n  } | {\n    type: \"close\";\n  };\n\nfunction submitForm(action: string, values: FormValueList, method = \"POST\") {\n  const form = document.createElement(\"form\");\n  form.method = method;\n  form.action = action;\n  form.append(...values.map(item => {\n    const input = document.createElement(\"input\");\n    input.type = \"hidden\";\n    input.name = item.name;\n    input.value = item.value;\n    return input;\n  }));\n  document.body.appendChild(form);\n  form.submit();\n}\n\n/** Navigate to a specific URL (may be hookable by other scripts)\n* @param navigation - Target URL or NavigateInstruction\n*/\nexport function navigateTo(navigation: string | NavigateInstruction) {\n  if (typeof window === \"undefined\")\n    throw new Error(`navigateTo() is not available in this environment`);\n\n  if (typeof navigation === \"string\")\n    navigation = { type: \"redirect\", url: navigation };\n\n  switch (navigation.type) {\n    case \"redirect\":\n      {\n        location.href = navigation.url;\n      } break;\n\n    case \"form\":\n      {\n        submitForm(navigation.form.action, navigation.form.vars, navigation.form.method);\n      } break;\n\n    case \"reload\":\n      {\n        window.location.reload();\n      } break;\n\n    case \"postmessage\":\n      {\n        if (!navigation.target || navigation.target === \"parent\")\n          window.parent.postMessage(navigation.message, \"*\");\n        else if (navigation.target === \"opener\") {\n          window.opener.postMessage(navigation.message, \"*\");\n          window.close();\n        } else\n          throw Error(\"Unknown postmessage target '\" + navigation.target + \"' received\");\n      } break;\n\n    case \"close\":\n      {\n        window.close();\n      } break;\n\n    default:\n      throw new Error(`Unknown navigation type '${(navigation as { type: string }).type}'`);\n  }\n}\n","//TODO can we replace ourselves with nodejs util.types in a pure NodeJS environment?\n\nimport type { Temporal } from \"temporal-polyfill\";\nimport type { Money } from \"./money\";\n\nexport function getWHType(obj: unknown): string | null { //not exporting this directly as we hope JS comes up with better solutions for instanceOf not being compatible with realms/reloading\n  // Ideally we'd use symbol but it breaks tree shaking in esbuild, so this is our workaround. Reported as https://github.com/evanw/esbuild/issues/3940\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Can't cleanly type this it seems and it's low level anyway\n  return (obj as any)?.constructor?.[\"__ $whTypeSymbol\"] ?? null;\n}\n\nfunction isCrossRealm(value: unknown): value is object {\n  return Boolean(value // it's not null\n    && typeof value === \"object\" //and it's an object\n    && !(value instanceof Object)); //and it's not an instance of our Object\n}\n\n/** Test whether a value looks like an instance of Money */\nexport function isMoney(value: unknown): value is Money {\n  return getWHType(value) === \"Money\";\n}\n\n/** Test whether a value looks like an instance of Temporal.Instant */\nexport function isTemporalInstant(value: unknown): value is Temporal.Instant {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.Instant');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDateTime */\nexport function isTemporalPlainDateTime(value: unknown): value is Temporal.PlainDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDateTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDate */\nexport function isTemporalPlainDate(value: unknown): value is Temporal.PlainDate {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDate');\n}\n\n/** Test whether a value looks like an instance of Temporal.ZonedDateTime */\nexport function isTemporalZonedDateTime(value: unknown): value is Temporal.ZonedDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.ZonedDateTime');\n}\n\n/** Test whether a value looks like an instance of Date (assumes no subclasses) */\nexport function isDate(value: unknown): value is Date {\n  return value instanceof Date || (isCrossRealm(value) && value.constructor.name === \"Date\");\n}\n\n/** Test whether a value appears to implement the Blob interface */\nexport function isBlob(value: unknown): value is Blob {\n  return value instanceof Blob || Boolean(value && typeof value === \"object\" && \"size\" in value && \"type\" in value && \"slice\" in value && typeof value.slice === \"function\" && \"stream\" in value && typeof value.stream === \"function\");\n}\n\n/** Test whether a value appears to implement the File interface */\nexport function isFile(value: unknown): value is File {\n  return isBlob(value) && \"name\" in value;\n}\n\n/** Check if the object is probably an Error object. Can't use 'instanceof Error' as an Error might come from a different frame */\nexport function isError(e: unknown): e is Error {\n  return e instanceof Error || (isCrossRealm(e) && \"name\" in e && \"stack\" in e && \"message\" in e);\n}\n\n/** Check if the object looks like a promise */\nexport function isPromise<T>(e: unknown): e is Promise<T> {\n  return Boolean(e && typeof (e as Promise<unknown>).then === \"function\" && typeof (e as Promise<unknown>).catch === \"function\");\n}\n\n/** Check the type of a value, return its JS or STD type\n * @param value - The value to check\n * @returns The type of the value. If the value is an object but recognized as any of Money, Date, Blob, Temporal.Instant/PlainDate/PlainDateTime, that type is returned.\n */\nexport function stdTypeOf(value: unknown): \"string\" | \"number\" | \"boolean\" | \"null\" | \"symbol\" | \"bigint\" | \"function\" | \"object\" | \"undefined\" | \"Date\" | \"Money\" | \"Array\" | \"Instant\" | \"PlainDate\" | \"PlainDateTime\" | \"ZonedDateTime\" | \"File\" | \"Blob\" {\n  const t = typeof value;\n  if (t === \"object\") {\n    if (!value)\n      return \"null\";\n    if (Array.isArray(value))\n      return \"Array\";\n    if (isMoney(value))\n      return \"Money\";\n    if (isBlob(value))\n      return isFile(value) ? \"File\" : \"Blob\";\n    if (isDate(value))\n      return \"Date\";\n    if (isTemporalInstant(value))\n      return \"Instant\";\n    if (isTemporalPlainDate(value))\n      return \"PlainDate\";\n    if (isTemporalPlainDateTime(value))\n      return \"PlainDateTime\";\n    if (isTemporalZonedDateTime(value))\n      return \"ZonedDateTime\";\n  }\n  return t;\n}\n","/* A math library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nexport type FinmathInput = string | number;\n\nexport type RoundMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\n\nexport interface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\n//a 'price' is a string of the form \"nnn[.NNNN]\"\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let num, decimals;\n  ({ num, decimals } = stripUnneededDecimals(amount.num, amount.decimals));\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substr(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substr(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  // insert decimal point if needed\n  if (decimals)\n    astext = astext.substr(0, astext.length - decimals) + decimalpoint + astext.substr(-decimals);\n\n  // add sign if needed\n  astext = (isnegative ? \"-\" : \"\") + astext;\n  return astext;\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: FinmathInput): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\n/** Convert split number into a string\n*/\nfunction joinPrice(parts: SplitNumber): string {\n  return toText(parts, '.', 0);\n}\n\nfunction adjustDecimals(amount: SplitNumber, requiredecimals: number) {\n  const toadd = requiredecimals - amount.decimals;\n  if (toadd <= 0)\n    return;\n\n  let multiplier = 1;\n  for (let idx = 0; idx < toadd; ++idx)\n    multiplier *= 10;\n\n  if (!Number.isSafeInteger(amount.num * multiplier))\n    throw new Error(\"adjustDecimals would overflow the safe value range\");\n\n  amount.num *= multiplier;\n  amount.decimals += toadd;\n}\n\n/** Returns if a price string is valid\n*/\nexport function isValidPrice(money: string) {\n  if (typeof money !== 'string' || !money.match(/[0-9]+(\\.[0-9]{0,5})?$/))\n    return false;\n  return true;\n}\n\nfunction __add(lhs: SplitNumber, rhs: SplitNumber) {\n  //equalize # of decimals, and then it's a simple addition\n  const requiredecimals = Math.max(lhs.decimals, rhs.decimals);\n  adjustDecimals(lhs, requiredecimals);\n  adjustDecimals(rhs, requiredecimals);\n  return { num: lhs.num + rhs.num, decimals: requiredecimals };\n}\n\n/** Adds two numbers together\n*/\nexport function add(amount1: FinmathInput, amount2: FinmathInput): string {\n  return joinPrice(__add(splitValue(amount1), splitValue(amount2)));\n}\n\n/** Subtracts a number from another number\n*/\nexport function subtract(amount: FinmathInput, tosubtract: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(tosubtract);\n  rhs.num = -rhs.num;\n  return joinPrice(__add(lhs, rhs));\n}\n\nfunction __multiply(lhs: SplitNumber, rhs: SplitNumber) {\n  //ADDME the naive 'add decimals, multiple nums' approach gets you out of the safe range real fast. needs tests\n  return { num: lhs.num * rhs.num, decimals: lhs.decimals + rhs.decimals };\n}\n\n/** Multiplies two numbers together\n*/\nexport function multiply(amount1: FinmathInput, amount2: FinmathInput): string {\n  const lhs = splitValue(amount1), rhs = splitValue(amount2);\n  return joinPrice(__multiply(lhs, rhs));\n}\n\n/** Compares two numbers\n    @param amount1 - Left hand value\n    @param amount2 - Right hand value\n    @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n*/\nexport function cmp(amount1: FinmathInput, amount2: FinmathInput) {\n  const diff = __add(splitValue(amount1), __multiply(splitValue(amount2), { num: -1, decimals: 0 }));\n  return diff.num < 0 ? -1 : diff.num === 0 ? 0 : 1;\n}\n\n/** Returns a percentage of an amount\n    @param amount - Original amount\n    @param perc - Percentage of the amount to return\n    @returns Percentage of the amount\n*/\nexport function getPercentageOfAmount(amount: FinmathInput, perc: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(perc);\n  const result = __multiply(lhs, rhs);\n  result.decimals += 2;\n  return joinPrice(normalize(result));\n}\n\nfunction normalize(amount: SplitNumber) {\n  while (amount.decimals && (amount.num % 10) === 0) {\n    amount.num /= 10;\n    --amount.decimals;\n  }\n  return amount;\n}\n\n/// format a price amount. extend # of decimals to specified # if not enough\nexport function formatPrice(money: FinmathInput, decimalpoint: string, decimals: number) {\n  return toText(splitValue(money), decimalpoint, decimals);\n}\n\n/** Rounds integer to multiple, exposed for testing only\n*/\nexport function __roundIntegerToMultiple(value: number, roundunit: number, mode: RoundMode) {\n  switch (mode) {\n    case \"none\":\n      {\n        // no rounding\n      } break;\n    case \"toward-zero\":\n      {\n        value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"down\":\n      {\n        if (value > 0)\n          value = Math.trunc(value / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"half-toward-zero\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-down\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    default:\n      {\n        throw new Error(`Unknown rounding mode ${mode}`);\n      }\n  }\n  return value;\n}\n\n/** Rounds a value to a multiple of a unit, with a specific rounding mode\n    @param value - Value to round\n    @param unit - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n    @param mode - Rounding mode. Possible values:\n      <ul>\n        <li>none: No rounding</li>\n        <li>toward-zero: Round toward zero</li>\n        <li>down: Round toward negative infity</li>\n        <li>up: Round toward positive infity</li>\n        <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n        <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n        <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n      </ul>\n    @returns The rounded value\n*/\nexport function roundToMultiple(value: FinmathInput, unit: FinmathInput, mode: RoundMode) {\n  const split_value = splitValue(value);\n  const split_unit = splitValue(unit);\n\n  const requiredecimals = Math.max(split_value.decimals, split_unit.decimals);\n  adjustDecimals(split_value, requiredecimals);\n  adjustDecimals(split_unit, requiredecimals);\n\n  const result = { num: __roundIntegerToMultiple(split_value.num, split_unit.num, mode), decimals: split_value.decimals };\n  return joinPrice(result);\n}\n\n/** Returns the minimum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The lowest value among amount and amounts\n*/\nexport function min(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) > 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns the maximum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The highest value among amount and amounts\n*/\nexport function max(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) < 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns a power of 10\n    @param exp - Integer power, must be 0 or bigger\n    @returns Requested power of 10\n*/\nfunction getNonNegativePowerOf10(exp: number) {\n  let retval = 1, running_exp = 10;\n  while (exp) {\n    if (exp & 1)\n      retval *= running_exp;\n    running_exp *= running_exp;\n    exp = exp >> 1;\n  }\n  return retval;\n}\n\n/** Divides two values, with 5 decimals of precision\n    @param value - Value To divide\n    @param divisor - Divisor\n    @returns Divided value, with 5 decimals of precision\n*/\nexport function divide(value: FinmathInput, divisor: FinmathInput) {\n  const lhs = splitValue(value), rhs = splitValue(divisor);\n  const mul10exp = lhs.decimals - rhs.decimals - 5;\n  const mulfactor = mul10exp < 0 ? getNonNegativePowerOf10(-mul10exp) : 1;\n  const roundunit = mul10exp > 0 ? getNonNegativePowerOf10(mul10exp) : 1;\n  return joinPrice({ num: __roundIntegerToMultiple(mulfactor * lhs.num / rhs.num, roundunit, \"half-toward-infinity\"), decimals: 5 });\n}\n\nexport function moneyDivide(value: FinmathInput, divisor: FinmathInput) { //divide was added in 5.0. remove this old name eventually\n  return divide(value, divisor);\n}\n\n/** Test whether two values have a specific relation\n    @param lhs - Left hand value\n    @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n    @param rhs - Right hand value\n    @returns TRUE if the relation holds\n    @example\n      console.log(finmath.test(1, '\\<', 2)); // prints 'true'\n*/\nexport function test(lhs: FinmathInput, relation: \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\", rhs: FinmathInput) {\n  const compareresult = cmp(lhs, rhs);\n  switch (relation) {\n    case '<': return compareresult < 0;\n    case '<=': return compareresult <= 0;\n    case '==': return compareresult === 0;\n    case '!=': return compareresult !== 0;\n    case '>': return compareresult > 0;\n    case '>=': return compareresult >= 0;\n  }\n  throw Error(`Cannot test for unknown relation '${relation}'`);\n}\n","/* A Money type library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   We haven't decideded yet what range Money should support. To keep our options open and keep HS compatbility for now\n   we will fix ourselves to 5 digits (HS compat) and not allow values bigger than 900_000_000 (2**53 / 100000 'number' compatbiility clamped to a more readable number)\n\n  Users should not rely on JS Money keeping this smaller range in the future. Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nimport * as finmath from \"./finmath\"; //TODO absorb into us as soon as noone externally depends on finmath anymore\nimport { isMoney } from \"./quacks\";\n\nexport type MoneyRoundingMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\nexport type MoneyTestTypes = \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\";\n\ntype MoneyParameter = Money | string;\n\ninterface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\nexport interface MoneyFormatOptions {\n  //thousand separator. defaults to \"\"\n  thousandsSeparator?: string;\n  //decimal separator. defaults to \".\"\n  decimalSeparator?: string;\n  //minimum # of decimals. defaults to 2\n  minDecimals?: number;\n}\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: MoneyParameter): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number, thousandpoint: string) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let { num, decimals } = stripUnneededDecimals(amount.num, amount.decimals);\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substring(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substring(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  let beforepoint = astext.substring(0, astext.length - decimals);\n  const afterpoint = astext.substring(astext.length - decimals);\n\n  // Add thouands points if neeed\n  if (thousandpoint)\n    beforepoint = beforepoint.replaceAll(/\\B(?=(\\d{3})+(?!\\d))/g, thousandpoint);\n\n  return (isnegative ? \"-\" : \"\") + beforepoint + (afterpoint.length ? decimalpoint + afterpoint : \"\");\n}\n\n/** A decimal based JS money type*/\nexport class Money {\n  /** finmath-compatible value */\n  readonly value: string;\n  private static \"__ $whTypeSymbol\" = \"Money\";\n\n  constructor(value: MoneyParameter = \"0\") {\n    this.value = Money.parseParameter(value);\n\n    const intvalue = parseInt(this.value);\n    //We need the number to be in the safe range even after adding 5 decimals\n    if (intvalue <= (Number.MIN_SAFE_INTEGER / 100000) || intvalue >= (Number.MAX_SAFE_INTEGER / 100000))\n      throw new TypeError(`Money value '${value}' is out of range`);\n  }\n\n  private static parseParameter(param: MoneyParameter): string {\n    if (typeof param === \"string\")\n      return toText(splitValue(param), \".\", 0, \"\");\n    if (Money.isMoney(param))\n      return (param as unknown as { value: string }).value;\n\n    throw new TypeError(`Money cannot be constructed out of a value of type ${typeof param}`);\n  }\n\n  static isMoney(value: unknown): value is Money {\n    return isMoney(value);\n  }\n\n  static fromNumber(value: number): Money {\n    return new Money(String(value));\n  }\n\n  /** Adds numbers together\n  */\n  static add(left: MoneyParameter, ...right: MoneyParameter[]): Money {\n    let sum = Money.parseParameter(left);\n    for (const item of right)\n      sum = finmath.add(sum, Money.parseParameter(item));\n    return new Money(sum);\n  }\n\n  /** Subtracts a number from another number\n  */\n  static subtract(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.subtract(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Rounds a value to a multiple of a unit, with a specific rounding mode\n      @param amount - Value to round\n      @param roundto - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n      @param mode - Rounding mode. Possible values:<br>\n        <ul>\n          <li>none: No rounding</li>\n          <li>toward-zero: Round toward zero</li>\n          <li>down: Round toward negative infity</li>\n          <li>up: Round toward positive infity</li>\n          <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n          <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n          <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n        </ul>\n      @returns The rounded value\n  */\n  static roundToMultiple(amount: MoneyParameter, roundto: MoneyParameter, mode: MoneyRoundingMode): Money {\n    return new Money(finmath.roundToMultiple(Money.parseParameter(amount), Money.parseParameter(roundto), mode));\n  }\n\n  /** Compares two numbers\n      @param lhs - Left hand value\n      @param rhs - Right hand value\n      @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n  */\n  static cmp(lhs: MoneyParameter, rhs: MoneyParameter): -1 | 0 | 1 {\n    return finmath.cmp(Money.parseParameter(lhs), Money.parseParameter(rhs));\n  }\n\n  /** Test whether two values have a specific relation\n      @param lhs - Left hand value\n      @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n      @param rhs - Right hand value\n      @returns TRUE if the relation holds\n      @example\n        console.log(Money.check(1, '\\<', 2)); // prints 'true'\n  */\n  static check(lhs: MoneyParameter, relation: MoneyTestTypes, rhs: MoneyParameter): boolean {\n    return finmath.test(Money.parseParameter(lhs), relation, Money.parseParameter(rhs));\n  }\n\n  /** Multiplies two numbers together\n  */\n  static multiply(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.multiply(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Returns a percentage of an amount\n      @param amount - Original amount\n      @param percentage - Percentage of the amount to return\n      @returns Percentage of the amount\n  */\n  static getPercentage(amount: MoneyParameter, percentage: MoneyParameter): Money {\n    return new Money(finmath.getPercentageOfAmount(Money.parseParameter(amount), Money.parseParameter(percentage)));\n  }\n\n  /** Divides two values, (currently with up to 5 decimals of precision)\n      @param numerator - Value to divide\n      @param divisor - Divisor\n      @returns Divided value\n  */\n  static divide(numerator: MoneyParameter, divisor: MoneyParameter): Money {\n    return new Money(finmath.divide(Money.parseParameter(numerator), Money.parseParameter(divisor)));\n  }\n  /** Returns the minimum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The lowest value among amount and amounts\n  */\n  static min(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.min(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n\n  }\n\n  /** Returns the maximum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The highest value among amount and amounts\n  */\n  static max(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.max(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n  }\n\n  /** format a price amount. extend # of decimals to specified # if not enough */\n  format(format?: MoneyFormatOptions): string {\n    return toText(splitValue(this.value),\n      format?.decimalSeparator ?? \".\",\n      format?.minDecimals ?? 2,\n      format?.thousandsSeparator ?? \"\");\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n\n  toNumber(): number {\n    return parseFloat(this.value);\n  }\n}\n","import { stdTypeOf } from \"./quacks\";\nimport { Money } from \"./money\";\n\nexport type WildcardTypes = \"?*\";\n\n/** Encode string for use in a regexp\n * @param text - Text to encode\n * @param options - Options for encoding\n * @param options.wildcards - Type of wildcards to encode (defaults to none)\n * @returns Encoded for safe use in a RegExp\n*/\nexport function escapeRegExp(text: string, options?: { wildcards?: WildcardTypes }): string {\n  let mask = text.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); // $& means the whole matched string\n  if (options?.wildcards === \"?*\") {\n    mask = mask.replaceAll(\"\\\\*\", \".*\");\n    mask = mask.replaceAll(\"\\\\?\", \".\");\n  }\n  return mask;\n}\n\n/** Create a regular expression from one or more wildcard masks\n * @param masks - One or more masks with '?' and/or '*' wildcards\n * @returns Regular expression string\n*/\nexport function regExpFromWildcards(masks: string | string[], options?: { wildcards?: WildcardTypes; caseInsensitive?: boolean }): RegExp {\n  if (Array.isArray(masks) && masks.length === 0)\n    throw new Error(\"Empty mask list\");\n\n  const code = Array.isArray(masks)\n    ? `^(${masks.map(mask => escapeRegExp(mask, { wildcards: options?.wildcards || \"?*\" })).join('|')})$`\n    : `^${escapeRegExp(masks, { wildcards: options?.wildcards || \"?*\" })}$`;\n  return new RegExp(code, options?.caseInsensitive ? \"i\" : undefined);\n}\n\nfunction isHTMLUnrepresentableChar(curch: number) {\n  return (curch < 32 && curch !== 9 && curch !== 10 && curch !== 13)\n    || (curch >= 128 && curch <= 159);\n}\n\nfunction encodeEntities(str: string, html: boolean) {\n  let s = \"\";\n  for (const char of str) {\n    const curch = char.codePointAt(0);\n    if (curch === undefined || isHTMLUnrepresentableChar(curch))\n      continue;\n    if (curch >= 32 && curch < 128 && curch !== 38 && curch !== 60 && curch !== 62 && (html || curch !== 34 && curch !== 39)) {\n      s += String.fromCodePoint(curch);\n      continue;\n    }\n\n    switch (curch) {\n      case 10:\n        {\n          if (html) {\n            s += \"<br>\";\n            continue;\n          }\n          break;\n        }\n      case 13:\n        {\n          if (html)\n            continue;\n          break;\n        }\n      case 34:\n        {\n          s += \"&quot;\";\n          continue;\n        }\n      case 38:\n        {\n          s += \"&amp;\";\n          continue;\n        }\n      case 39:\n        {\n          s += \"&apos;\";\n          continue;\n        }\n      case 60:\n        {\n          s += \"&lt;\";\n          continue;\n        }\n      case 62:\n        {\n          s += \"&gt;\";\n          continue;\n        }\n    }\n\n    s += \"&#\" + curch + \";\";\n  }\n  return s;\n}\n\nfunction decodeEntities(str: string, html: boolean) {\n  if (html)\n    str = str.replace(/<br *\\/?>/g, \"\\n\");\n\n  str = str.replace(/&#(\\d+);/g, (_, dec) => String.fromCharCode(dec))\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&quot;/g, '\"')\n    .replace(/&apos;/g, \"'\")\n    .replace(/&amp;/g, \"&\");\n\n  return str;\n}\n\nexport type StringEncodings = \"base64url\" | \"attribute\" | \"html\";\n\nexport function encodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return btoa(str).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n  if (encoding === \"attribute\")\n    return encodeEntities(str, false);\n  if (encoding === \"html\")\n    return encodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\nexport function decodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return atob(str.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n  if (encoding === \"attribute\")\n    return decodeEntities(str, false);\n  if (encoding === \"html\")\n    return decodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\ntype JSONReplacerArgument = ((this: unknown, key: string, value: unknown) => unknown) | undefined;\n\nexport interface StringifyOptions {\n  replacer?: JSONReplacerArgument;\n  space?: string | number;\n  stable?: boolean;\n  ///Encode with types (preserve Money, Date, BigInt). Needs std.parseTyped\n  typed?: boolean;\n  ///What to target: string (like JSON.stringify), script (escapes '/') or attribute (escapes '/' and applies attribute encoding)\n  target?: \"string\" | \"script\" | \"attribute\";\n}\n\n/** Improved JSON encoder\n * @param arg - Object to encode\n * @param options - Encoding options\n*/\nexport function stringify(arg: unknown, options?: StringifyOptions) {\n  const usereplacer: JSONReplacerArgument = options?.stable || options?.typed ? (function (this: unknown, key: string, value: unknown) {\n    if (options.typed) {\n      const origvalue = (this as Record<string, unknown>)[key]; //We can't use 'value' as .toJSON() will already have been invoked\n      const type = stdTypeOf(origvalue);\n      switch (type) {\n        case \"function\":\n          throw new Error(`Cannot stringify property '${key}' of type \"${type}'`);\n        case \"Date\":\n          value = { \"$stdType\": \"Date\", date: (origvalue as Date).toISOString() };\n          break;\n        case \"Money\":\n        case \"bigint\":\n        case \"Instant\":\n        case \"PlainDate\":\n        case \"PlainDateTime\":\n        case \"ZonedDateTime\":\n          value = { \"$stdType\": type, [type.toLowerCase()]: (origvalue as { toString: () => string }).toString() };\n          break;\n        case \"object\":\n          if (\"$stdType\" in (origvalue as { \"$stdType\": string }))\n            throw new Error(`Cannot encode objects with already embedded '$stdType's`);\n        //fallthrough\n      }\n    }\n    if (options.stable && value && typeof value === \"object\" && !Array.isArray(value))\n      value = Object.fromEntries(Object.entries(value).sort((lhs, rhs) => lhs < rhs ? -1 : lhs === rhs ? 0 : 1));\n    if (options.replacer)\n      value = options.replacer.call(this, key, value);\n    return value;\n  }) : options?.replacer ?? undefined;\n\n  let result = JSON.stringify(arg, usereplacer, options?.space);\n  if (options?.target && [\"script\", \"attribute\"].includes(options.target)) {\n    result = result.replaceAll(\"/\", \"\\\\/\");\n    if (options.target === \"attribute\")\n      result = encodeEntities(result, false);\n  }\n  return result;\n}\n\n/** Decode JSON with types (Generated using stringify with typed:true ) */\nexport function parseTyped(input: string) {\n  return JSON.parse(input, (key, value) => {\n    switch (value?.[\"$stdType\"]) {\n      case \"Money\":\n        return new Money(value.money);\n      case \"Date\":\n        return new Date(value.date);\n      case \"bigint\":\n      case \"BigInt\": //pre wh5.7 spelling\n        return BigInt(value.bigint as string);\n      case \"Instant\":\n      case \"PlainDate\":\n      case \"PlainDateTime\":\n      case \"ZonedDateTime\":\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        if (!(globalThis as any).Temporal)\n          throw new Error(`Temporal is not available in this environment, cannot deserialize value of type Temporal.${value[\"$stdType\"]}. Load eg. @webhare/deps/temporal-polyfill to use Temporal types in browsers`);\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        return (globalThis as any).Temporal[value[\"$stdType\"]].from(value[value[\"$stdType\"].toLowerCase()]);\n      case undefined:\n        return value;\n      default:\n        throw new Error(`Unrecognized type '${value[\"$stdType\"]}'`);\n    }\n  });\n}\n\n/** Generate a slug from a (suggested) (file)name\n * @param text - Text to convert\n * @param options - Options for slugification\n * @param options.separator - Separator to use between words (defaults to '-')\n * @param options.keep - Set of characters to keep in addition to a-z0-9\n * @returns Slugified text or null if we couldn't generate anything reeadable\n */\nexport function slugify(text: string, { separator = \"-\", keep = \"\" }: {\n  separator?: string;\n  keep?: string;\n} = {}): string | null {\n  //This function mixes HS getSafeName with a few more modern approaches\n  const keepclass = `[^a-z0-9${escapeRegExp(keep)}]`;\n  text = text\n    .normalize('NFD')                   // split an accented letter in the base letter and the acent\n    // eslint-disable-next-line no-control-regex\n    .replaceAll(/[\\u0000-\\u001F]/g, '')\n    .replaceAll(/[\\u0300-\\u036f]/g, '')   // remove all previously split accents\n    .replaceAll(/ß/g, 'ss')               // german ss\n    .toLowerCase()\n    .replace(new RegExp(`^${keepclass}+`), \"\") //replace bad characters at the start\n    .replace(new RegExp(`${keepclass}+$`), \"\") //.. and end\n    .replaceAll(new RegExp(`${keepclass}+`, \"g\"), separator); // replace all non alphanumeric/space with a single dash\n\n  return text || null; //we return 'null' on purpose so callers realize we won't necessarily give them a string!\n}\n\n/** Check if an email address is valid in modern times (an emailcheck much closer to what a browser would do, with additional sanity checks. No attempt to allow all legacy styles supported by the RFCs but 99.9%+ sure to be an error if seen submitted in a form\n    @returns True if the email address appears to be a well-formed email address to a non-greybeard\n*/\nexport function isValidEmail(email: string): boolean {\n  if (email.length > 254) //TODO count bytes instead of characters\n    return false;\n\n  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*(?:\\.[a-zA-Z0-9-]{2,})$/.test(email);\n}\n\n/** Joins a path to a URL, eliminating any double slash (similar to NodeJS path.join)\n * @param baseurl - URL to join to\n * @param path - Path to join. May not contain '.' or '..' segments in the path\n * @returns Joined URL, with a single slash between both parts\n*/\nexport function joinURL(baseurl: string, path: string) {\n  const pathtoks = path.match(/([^?#]*)(.*)/)!; //this will always return something\n  if (pathtoks[1].match(/(\\/\\/)|:/))\n    throw new Error(`Invalid path to merge with: ${path}`);\n  //look for any . or .. path segments\n  if ((\"/\" + path + \"/\").match(/\\/\\.\\.?\\//))\n    throw new Error(`Invalid path to merge with: ${path}`);\n\n  if (baseurl.endsWith(\"/\"))\n    baseurl = baseurl.substring(0, baseurl.length - 1);\n  return baseurl + (path.startsWith(\"/\") ? path : \"/\" + path);\n}\n\nfunction unpackUrl(inUrl: string) {\n  const retval = {\n    inUrl,\n    scheme: \"\",\n    schemeSpecificPart: \"\",\n    user: \"\",\n    password: \"\",\n    host: \"\",\n    port: 0,\n    urlPathSlash: false,\n    urlPath: \"\",\n    secure: false,\n    specifiedPort: false,\n    isDefaultPort: false,\n    origin: \"\",\n  };\n  let missingSlash = false;\n  const firstColon = inUrl.indexOf(\":\");\n  if (firstColon < 0) {\n    retval.scheme = inUrl;\n    return retval;\n  }\n\n  retval.scheme = decodeURIComponent(inUrl.substring(0, firstColon)).toLowerCase();\n  inUrl = inUrl.substring(firstColon + 1);\n  retval.schemeSpecificPart = inUrl;\n\n  if (!retval.schemeSpecificPart.startsWith(\"//\")) //not an internet host format\n    return retval;\n\n  inUrl = inUrl.substring(2);\n\n  //Find the first slash, it terminates the user..port part\n  let firstSlash = inUrl.indexOf(\"/\");\n  if (firstSlash < 0)\n    firstSlash = inUrl.length;\n\n  const firstAt = inUrl.indexOf(\"@\");\n  if (firstAt >= 0 && firstAt < firstSlash) {\n    //Username and possible password are present\n    const pwdColon = inUrl.indexOf(\":\");\n    if (pwdColon >= 0 && pwdColon < firstAt) {\n      retval.user = decodeURIComponent(inUrl.substring(0, pwdColon));\n      retval.password = decodeURIComponent(inUrl.substring(pwdColon + 1, firstAt));\n    } else {\n      retval.user = decodeURIComponent(inUrl.substring(0, firstAt));\n    }\n    inUrl = inUrl.substring(firstAt + 1);\n    firstSlash = inUrl.indexOf(\"/\");\n    if (firstSlash < 0)\n      firstSlash = inUrl.length;\n  }\n\n  //Common mistake, at least in http* urls, specifying a ? right after the URL (ADDME perhaps this shoud apply for all URLs? check rfc)\n  if (retval.scheme === \"http\" || retval.scheme === \"https\") {\n    const firstQuestionMark = inUrl.indexOf(\"?\");\n    if (firstQuestionMark >= 0 && firstQuestionMark < firstSlash) {\n      firstSlash = firstQuestionMark;\n      missingSlash = true;\n    }\n  }\n\n  let closingBracket = 0;\n  if (inUrl.startsWith(\"[\")) //RFC3986 IP-literal\n    closingBracket = inUrl.indexOf(\"]\");\n\n  if (closingBracket > 0) { //Indeed an IP-literal\n    retval.host = decodeURIComponent(inUrl.substring(1, closingBracket));\n    if (inUrl[closingBracket + 1] === ':') //port follows\n      retval.port = parseInt(decodeURIComponent(inUrl.substring(closingBracket + 2, firstSlash - 1)), 0) || 0;\n    else\n      retval.port = getSchemeDefaultPort(retval.scheme);\n  } else {\n    const portColon = inUrl.indexOf(\":\");\n    if (portColon >= 0 && portColon < firstSlash) {\n      retval.host = decodeURIComponent(inUrl.substring(0, portColon));\n      retval.port = parseInt(decodeURIComponent(inUrl.substring(portColon + 1, firstSlash)), 0) || 0;\n      retval.specifiedPort = true;\n      retval.isDefaultPort = retval.port === getSchemeDefaultPort(retval.scheme);\n    } else {\n      retval.host = decodeURIComponent(inUrl.substring(0, firstSlash));\n      retval.port = getSchemeDefaultPort(retval.scheme);\n      retval.isDefaultPort = true;\n    }\n  }\n\n  retval.urlPathSlash = !(missingSlash || firstSlash === inUrl.length);\n  retval.urlPath = inUrl.substring(firstSlash + (missingSlash ? 0 : 1));\n  retval.secure = [\"aas\", \"ftps\", \"https\", \"imaps\", \"ldaps\", \"shttp\", \"sips\", \"ssh\", \"sftp\"].includes(retval.scheme);\n  if (retval.host)\n    retval.origin = retval.scheme + \"://\" + retval.host + (retval.isDefaultPort ? \"\" : \":\" + retval.port);\n  return retval;\n}\n\nfunction getSchemeDefaultPort(scheme: string) {\n  switch (scheme) {//port numbers from RFC1738\n    case \"ftp\": return 21;\n    case \"http\": return 80;\n    case \"ws\": return 80;\n    case \"gopher\": return 70;\n    case \"nntp\": return 119;\n    case \"telnet\": return 23;\n    case \"wais\": return 210;\n    case \"prospero\": return 1525;\n    //well known protocols\n    case \"https\": return 443;\n    case \"wss\": return 443;\n    case \"ldap\": return 389;\n    case \"ldaps\": return 636;\n    case \"smtp\": return 25;\n    default: return 0;\n  }\n}\n\n\n/** Test whether an URL is a valid url. This function verifies that an URL looks\n * like an URL. If the scheme is recognized, more  stringent checks are performed\n * @returns True if the url appears to be a well-formed url\n */\nexport function isValidUrl(url: string): boolean {\n  // test: no control characters or spaces (0x00 - 0x20)\n  // test: starts with 'scheme' ':' anychar +\n  // test: scheme only has letters, numbers, '-', '.' or '+' (and is not empty)\n  // Unpack url\n  // test: for http/https schema, hostname is not empty and port is in range 1-65535\n\n  // eslint-disable-next-line no-control-regex\n  if (!url.match(/^[-.+a-zA-Z0-9]+:[^\\x00-\\x20]+$/))\n    return false;\n  const unpacked = unpackUrl(url);\n  if (unpacked.scheme !== \"http\" && unpacked.scheme !== \"https\")\n    return true;\n  if (unpacked.port < 1 || unpacked.port > 65535 || !unpacked.host)\n    return false;\n  return true;\n}\n\n/** Uppercases a string using the C-locale (so only the ASCII characters a-z are uppercased)\n * @param str - String to uppercase\n * @returns Uppercased string\n */\nexport function toCLocaleUppercase(str: string) {\n  return str.replaceAll(/[a-z]+/g, part => part.toUpperCase());\n}\n\n/** Lowercases a string using the C-locale (so only the ASCII characters A-Z are lowercased)\n * @param str - String to lowercase\n * @returns Lowercased string\n */\nexport function toCLocaleLowercase(str: string) {\n  return str.replaceAll(/[A-Z]+/g, part => part.toLowerCase());\n}\n\n/** Calculate the levenshtein distance between two strings */\nexport function levenshteinDistance(a: string, b: string): number {\n  /* calculateLevenshteinDistance is adopted from https://github.com/gustf/js-levenshtein/blob/master/index.js, licensed MIT © Gustaf Andersson\n    Picked over fastest-levenshtein because a permanent 256KB memory area for a bit more speed doesn't seem worth it\n  */\n  function _min(d0: number, d1: number, d2: number, bx: number, ay: number) {\n    return d0 < d1 || d2 < d1\n      ? d0 > d2\n        ? d2 + 1\n        : d0 + 1\n      : bx === ay\n        ? d1\n        : d1 + 1;\n  }\n\n  if (a === b) {\n    return 0;\n  }\n\n  if (a.length > b.length) {\n    const tmp = a;\n    a = b;\n    b = tmp;\n  }\n\n  let la = a.length;\n  let lb = b.length;\n\n  while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n    la--;\n    lb--;\n  }\n\n  let offset = 0;\n\n  while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n    offset++;\n  }\n\n  la -= offset;\n  lb -= offset;\n\n  if (la === 0 || lb < 3) {\n    return lb;\n  }\n\n  let x = 0;\n  let y, d0, d1, d2, d3, dd = 0, dy, ay, bx0, bx1, bx2, bx3;\n\n  const vector: number[] = [];\n\n  for (y = 0; y < la; y++) {\n    vector.push(y + 1);\n    vector.push(a.charCodeAt(offset + y));\n  }\n\n  const len = vector.length - 1;\n\n  for (; x < lb - 3;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    bx1 = b.charCodeAt(offset + (d1 = x + 1));\n    bx2 = b.charCodeAt(offset + (d2 = x + 2));\n    bx3 = b.charCodeAt(offset + (d3 = x + 3));\n    dd = (x += 4);\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      ay = vector[y + 1];\n      d0 = _min(dy, d0, d1, bx0, ay);\n      d1 = _min(d0, d1, d2, bx1, ay);\n      d2 = _min(d1, d2, d3, bx2, ay);\n      dd = _min(d2, d3, dd, bx3, ay);\n      vector[y] = dd;\n      d3 = d2;\n      d2 = d1;\n      d1 = d0;\n      d0 = dy;\n    }\n  }\n\n  for (; x < lb;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    dd = ++x;\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);\n      d0 = dy;\n    }\n  }\n\n  return dd;\n}\n\n/** Return the length of the string in bytes when UTF-8 encoded */\nexport function getUTF8Length(str: string) {\n  return new TextEncoder().encode(str).length;\n}\n\n/** Truncate the string so it's at most len UTF-8 bytes long */\nexport function limitUTF8Length(str: string, len: number) {\n  // TextEncoder.encodeInto writes into the given array until there's no more room to add more valid UTF-8 sequences from the\n  // source. We can use this property to limit the number of bytes by creating an array that has room for at most the given\n  // number of bytes.\n  const utf8array = new Uint8Array(len);\n  // This function returns the actual number of bytes written to the array\n  const { written } = new TextEncoder().encodeInto(str, utf8array);\n  // Decode only the actually written bytes\n  return new TextDecoder().decode(utf8array.subarray(0, written));\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any -- Cannot specify this without using any */\n\nexport interface EmplaceHandler<ValueType> {\n  insert?: () => ValueType;\n  update?: (current: ValueType) => ValueType;\n}\n\nfunction binarySearchImpl<A, K>(compareFn: (element: A, key: K) => number, contents: A[], searchfor: K, upper_bound: boolean): { present: boolean; index: number } {\n  let first = 0;\n  let len = contents.length;\n  let present = false;\n\n  const cmpbound = upper_bound ? 1 : 0;\n  let unsorted_cmp = 0; // if this is non-0 and cmp is this value, we have an unsorted list\n  while (len > 0) {\n    const half = Math.floor(len / 2);\n    const middle = first + half;\n    const cmp = compareFn(contents[middle], searchfor);\n    if (cmp === 0) {\n      present = true;\n      unsorted_cmp = upper_bound ? -1 : 1;\n    } else if (cmp === unsorted_cmp)\n      throw new Error(`The provided array was not properly sorted!`);\n\n    if (cmp < cmpbound) {\n      first = middle + 1;\n      len -= half;\n      --len;\n    } else {\n      len = half;\n    }\n  }\n  return { present, index: first };\n}\n\n//emplace is based on https://github.com/tc39/proposal-upsert (a Map.prototype.emplace)\n/** Place a value into a Map\n * @param map - The map to place the value into\n * @param key - The key to add/replace\n * @param handler - Callbacks for inserting or updating the value\n * @returns The value that was placed into the map.\n * @throws If the key is not found and no insert handler is provided\n */\nexport function emplace<T extends Map<any, any> | WeakMap<any, any>>(\n  map: T,\n  key: T extends Map<infer K, any> ? K : T extends WeakMap<infer K, any> ? K : never,\n  handler?: T extends Map<any, infer V> ? EmplaceHandler<V> : T extends WeakMap<any, infer V> ? EmplaceHandler<V> : never):\n  T extends Map<any, infer V> ? V : T extends WeakMap<any, infer V> ? V : never {\n  let current = map.get(key);\n  if (current !== undefined) {\n    if (handler?.update) {\n      current = handler.update(current);\n      map.set(key, current);\n    }\n    return current;\n  }\n\n  if (!handler?.insert)\n    throw new Error(\"Key not found and no insert handler provided\");\n\n  const setvalue = handler.insert();\n  map.set(key, setvalue);\n  return setvalue;\n}\n\n// the `| keyof X` is needed to be able to use a `keyof X` type as key parameter in DistributedPick or DistributedOmit in generics\nexport type DistributedKeys<X extends object> = (X extends object ? keyof X : never) | keyof X;\n\n/** Applies Pick to all types in a union. Allows all keys that are present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = pick(a, [\"t\", \"a\", \"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @returns Type with only the specified keys (distributed over the union if present)\n*/\nexport type DistributedPick<X extends object, Y extends DistributedKeys<X>> = X extends object ? Pick<X, keyof X & Y> : never;\n\n/** Applies Omit to all types in a union. Allows all keys that are not present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = omit(a, [\"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @returns Type with only the specified keys left out (distributed over the union if present)\n*/\nexport type DistributedOmit<X extends object, Y extends DistributedKeys<X>> = X extends object ? Omit<X, keyof X & Y> : never;\n\n/** Returns an object with a selection of properties\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @param obj - Object to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting object\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedPick<T, K>;\n\n/** Returns an array with a selection of properties\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to return\n    @param arr - Array to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting array\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedPick<T, K>>;\n\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedPick<T, K> | Array<DistributedPick<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => pick(elt, keys));\n  const ret = {} as T;\n  keys.forEach((key: K) => {\n    if (key in value)\n      ret[key] = value[key];\n  });\n  return ret as object as DistributedPick<T, K>;\n}\n\n/** Returns an object with a selection of properties left out\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @param obj - Object to leave properties out of\n    @param keys - Names of the properties to remove\n    @returns Resulting object\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedOmit<T, K>;\n\n/** Returns an array with a selection of properties left out\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to leave out\n    @param arr - Array to leave properties out of\n    @param keys - Names of the properties to leave out\n    @returns Resulting array\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedOmit<T, K>>;\n\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedOmit<T, K> | Array<DistributedOmit<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => omit(elt, keys));\n  const ret = {} as T;\n  for (const [key, val] of Object.entries(value)) {\n    if (!keys.includes(key as K))\n      ret[key as K] = val;\n  }\n  return ret as object as DistributedOmit<T, K>;\n}\n\n/** Shuffle an array in-place\n * @param array - Array to shuffle\n * @returns The shuffled array\n*/\nexport function shuffle<T>(array: T[]): T[] {\n  for (let i = array.length - 1; i > 0; i--) {\n    const j = Math.floor(Math.random() * (i + 1));\n    [array[i], array[j]] = [array[j], array[i]];\n  }\n  return array;\n}\n\n/** Returns (and TypeScript-asserts) that the specified function is truthy. Handy for adjusting the type of an array when\n * filtering out falsy values\n * @example\n * const myarray: Array&lt;number | null&gt; = [0, null];\n * const filtered: number[] = myarray.filter(isTruthy);\n **/\nexport function isTruthy<T>(a: T): a is (T & {}) {\n  return Boolean(a);\n}\n\n/** Append to array, without overflowing the stack (eg V8 overflows at more than 32K entries)\n * @param array - Array to append to\n * @param values - Values to append\n*/\nexport function appendToArray<T>(array: T[], values: ReadonlyArray<NoInfer<T>>): void {\n  if (values.length < 1000)\n    array.push(...values); //push should be safe enough\n  else for (const value of values) //performance wise this appears just as fast as tricks with pushing blocks of slices\n    array.push(value);\n\n  //not returning the original array to make it clear we're not creating a new one\n}\n\ntype TypedEntriesInternal<T extends object, K extends keyof T> = K extends keyof T ? [K, T[K]] : never;\n\n/** Returns a union of [ key, value ] types for an object */\nexport type TypedEntries<T extends object> = T extends object ? TypedEntriesInternal<T, keyof T & string> : never;\n\n/** Returns an array of key/values of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.entries returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedEntries<T extends object>(obj: T): Array<TypedEntries<T>> {\n  return Object.entries(obj) as Array<TypedEntries<T>>;\n}\n\n/** Returns an array of keys of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.keys returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedKeys<T extends object>(obj: T): Array<keyof T & string> {\n  return Object.keys(obj) as Array<keyof T & string>;\n}\n\n/** Given a union of [key, value] types, returns the object constructed from those pairs. Exists because\n *  Object.fromEntries does not take the type of the keys and values into account.\n * @typeParam T - Union of [key, value] pairs\n */\nexport type TypedFromEntries<T extends [string, unknown]> = { [C in T as C[0]]: C[1] };\n\n/** Returns an object from an iterable of [key, value] pairs, with exact types. Exists because Object.fromEntries\n * doesn't take the type of the keys and values into account.\n * @param entries - Iterable of [key, value] pairs\n * @returns An object with the same keys and values as the input\n */\nexport function typedFromEntries<T extends [string, unknown]>(entries: Iterable<T>): TypedFromEntries<T> {\n  return Object.fromEntries(entries) as TypedFromEntries<T>;\n}\n\n\nexport class SortedMultiSet<V> {\n  private contents: V[] = [];\n\n  constructor(private compareFn: (lhs: V, rhs: V) => number, contents?: V[]) {\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): V | undefined {\n    return this.contents.at(index);\n  }\n\n  add(value: V): number {\n    const pos = this.upperBound(value);\n    this.contents.splice(pos, 0, value);\n    return pos;\n  }\n\n  addMultiple(values: V[]): void {\n    for (const value of values) {\n      this.add(value);\n    }\n  }\n\n  delete(key: V): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<V>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<V>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<V>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): V[] {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<V, void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<V>): V[] {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<V>): Iterable<V> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n\nexport class SortedMultiMap<K, V> {\n  private compareFn;\n  private contents: Array<[K, V]> = [];\n\n  constructor(compareFn: (lhs: K, rhs: K) => number, contents?: Array<[K, V]>) {\n    this.compareFn = (element: [K, V], key: K) => compareFn(element[0], key);\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): [K, V] | undefined {\n    return this.contents.at(index);\n  }\n\n  add(key: K, value: V): number {\n    const pos = this.upperBound(key);\n    this.contents.splice(pos, 0, [key, value]);\n    return pos;\n  }\n\n  addMultiple(values: Array<[K, V]>) {\n    for (const [key, value] of values) {\n      this.add(key, value);\n    }\n  }\n\n  delete(key: K): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<K>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<K>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<K>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): Array<[K, V]> {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<[K, V], void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<K>): Array<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<K>): Iterable<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n","const unlock = Symbol(\"unlock\");\n\n/** A mutex which is only visible in the current JavaScript VM\n\n    @example\n```ts\nconst mutex = new LocalMutex;\n\nusing lock = await mutex.lock();\nlock.release();\n\n// If you'll be relying on automatic release\nusing lock = await mutex.lock();\nvoid(lock);\n```\n\n*/\nexport class LocalMutex {\n  private locked = false;\n  private unlockList = new Array<() => void>;\n\n  /** Lock this mutex\n   * @returns Lock object. Use with `using` to ensure automatic unlock\n   */\n  async lock() {\n    if (this.locked) {\n      const defer = Promise.withResolvers<void>();\n      this.unlockList.push(() => defer.resolve());\n      await defer.promise;\n    } else {\n      this.locked = true;\n    }\n    return new LocalLock(this);\n  }\n\n  [unlock](): void {\n    if (this.unlockList.length > 0)\n      (this.unlockList.shift()!)(); //we're fair... unlock longest waiter\n    else\n      this.locked = false;\n  }\n}\n\n/** Instance of a LocalMutex lock */\nclass LocalLock implements Disposable {\n  private mutex: LocalMutex | null;\n\n  constructor(mutex: LocalMutex) {\n    this.mutex = mutex;\n  }\n  /** Explicitly release the lock\n   * @throws Error if the lock is already released\n  */\n  release() {\n    if (!this.mutex)\n      throw new Error(\"Lock already released\");\n\n    this.mutex[unlock]();\n    this.mutex = null;\n  }\n  [Symbol.dispose]() {\n    this.mutex?.[unlock]();\n  }\n}\n\nexport type { LocalLock };\n","import type { FormControlElement } from \"@webhare/dompack\";\n\nexport const CustomEvent = globalThis.CustomEvent;\n/** Wrap an event to ensure it's target is a HTMLElement\n * @typeParam EventType - The expected event type\n * @typeParam CurrentTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n * @typeParam RelatedTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n*/\nexport type DocEvent<EventType extends Event, CurrentTargetType extends HTMLElement = HTMLElement, RelatedTargetType extends HTMLElement = HTMLElement> = EventType & {\n  target: HTMLElement;\n  currentTarget: CurrentTargetType;\n  relatedTarget: RelatedTargetType | null;\n};\n\nexport type DomEventOptions =\n  {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    relatedTarget?: EventTarget;\n    detail?: object;\n  };\n\nexport function dispatchDomEvent(element: EventTarget, eventtype: string, options?: DomEventOptions) {\n  //see here https://developer.mozilla.org/en-US/docs/Web/Events whether an event is bubbles/cancelabel\n  options = {\n    bubbles: [\n      \"input\", \"change\", \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\"\n    ].includes(eventtype),\n    cancelable: [\n      \"animationstart\", \"animationcancel\", \"animationend\", \"animationiteration\",\n      \"beforeunload\",\n      \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\",\n      \"transitionstart\", \"transitioncancel\", \"transitionend\", \"transitionrun\"\n    ].includes(eventtype),\n    ...options\n  };\n\n  if (!element || !(element as Node).ownerDocument)\n    return true; //the element has left the dom... so there's no more bubbling. just drop it\n\n  //FIXME the load/scroll is buggy and we should be probably be using new Event (but an earlier attempt at that triggered quite a few test failures)\n  const createtype = /*[\"load\",\"scroll\"].includes(eventtype) === \"load\" ? \"UIEvents\" :*/[\"focus\", \"blur\", \"focusin\", \"focusout\"].includes(eventtype) ? \"FocusEvent\" : eventtype === \"click\" ? \"MouseEvents\" : \"HTMLEvents\";\n  //we verified its non-null ness above but TS doesn't really understand that\n  const evt = (element as Node).ownerDocument!.createEvent(createtype);\n  evt.initEvent(eventtype, options.bubbles, options.cancelable);\n  if (options.detail)\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we should just rewrite to new Event\n    (evt as any).detail = options.detail;\n  if (options.relatedTarget) //its a readonly prop, so redefine it\n    Object.defineProperty(evt, 'relatedTarget', { value: options.relatedTarget, writable: false });\n\n  //TODO: Should we keep this code?\n  // @ts-ignore IScroll is a custom Window property set by IScroll\n  if (eventtype === 'click' && window.IScroll)\n    // @ts-ignore _constructed is a custom Event property used by IScroll\n    evt._constructed = true; //ensure IScroll doesn't blindly cancel our synthetic clicks\n\n  return element.dispatchEvent(evt);\n}\n\n/** Fire the proper modified events (input and/or change) on the element after changing its value\n * @param element - Element to receive event\n * @param options - Event options\n * @deprecated Use changeValue so we can figure out the proper events to fire\n */\nexport function fireModifiedEvents(element: FormControlElement, options?: DomEventOptions) {\n  dispatchDomEvent(element, 'input', options);\n  dispatchDomEvent(element, 'change', options);\n}\n\n//manually fire 'onchange' events. needed for event simulation - DEPRECATED\n/**\n * @param element - Element to receive event\n * @param type - Event type\n * @param options - Event options\n * @deprecated Use dispatchDomEvent instead\n */\nexport function fireHTMLEvent(element: EventTarget, type: string, options?: DomEventOptions) {\n  return dispatchDomEvent(element, type, options);\n}\n\ntype CustomEventParams =\n  {\n    /** Whether this event should bubble up in the DOM */\n    bubbles: boolean;\n    /** Whether this event can be cancelled */\n    cancelable: boolean;\n    /** Custom event information */\n    detail?: unknown;\n    /** Handler to execute if the default isn't prevented by a event listener */\n    defaulthandler?: (evt: CustomEvent) => void;\n  };\n\n/** Fire a custom event\n    @param node - node to fire the event on\n    @param event - event type. You should add this event to the GlobalEventHandlersEventMap for validation in dispatchCustomEvent calls and addEventListener callbacks.\n    @param params - Event options\n    @returns true if the default wasn't prevented\n */\n\nexport function dispatchCustomEvent<K extends string>(\n  node: EventTarget,\n  event: K,\n  params: CustomEventParams & (K extends keyof GlobalEventHandlersEventMap ?\n    GlobalEventHandlersEventMap[K] extends CustomEvent ?\n    { detail: GlobalEventHandlersEventMap[K][\"detail\"] } : unknown : unknown)) {\n\n  if (!params)\n    throw new Error(`Missing dispatchCustomEvent params`);\n  ['bubbles', 'cancelable'].forEach(prop => {\n    if (!(prop in params))\n      throw new Error(`Missing '${prop}' in dispatchCustomEvent params`);\n  });\n\n  const evt = new CustomEvent(event, {\n    bubbles: params.bubbles,\n    cancelable: params.cancelable,\n    detail: params.detail\n  });\n  let defaultaction = true;\n  try {\n    if (!node.dispatchEvent(evt))\n      defaultaction = false; //defaultPrevented is unreliable on IE11, so double check\n  } finally {\n    if (!evt.defaultPrevented && params.defaulthandler && defaultaction) {\n      params.defaulthandler(evt);\n    }\n  }\n  return defaultaction && !evt.defaultPrevented;\n}\n\n/**\n     Change the value of a form element, and fire the correct events as if it were a user change\n *\n    @param element - Element to change\n    @param newvalue - New value\n */\nexport function changeValue(element: FormControlElement, newvalue: string | number | boolean) {\n  if (element.matches(`input[type=radio], input[type=checkbox]`)) {\n    if (Boolean((element as HTMLInputElement).checked) === Boolean(newvalue))\n      return;\n    (element as HTMLInputElement).checked = Boolean(newvalue);\n  } else {\n    //FIXME it's not really clean to assume that this element is changeable - throw for non input/select..\n    const asString = String(newvalue);\n    if ((element as HTMLInputElement).value === asString)\n      return;\n\n    (element as HTMLInputElement).value = String(newvalue);\n  }\n  dispatchDomEvent(element as EventTarget, 'input');\n  dispatchDomEvent(element as EventTarget, 'change');\n}\n\nlet keydata: { mapping: { [key: string]: string } };\n\nfunction initKeyMapping() {\n  keydata =\n  {\n    // Mapping from keyIdentifier/key to key. If not found, translate U+XXXX to the unicode char and return that.\n\n    // List of all current key mappings (and current inconsistencies\n    // at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values\n    mapping:\n    {\n      \"Del\": \"Delete\", // IE/edge use 'Del' instead of 'Delete'\n      \"Esc\": \"Escape\", // IE/edge use 'Esc' instead of 'Escape'\n      \"OS\": \"Meta\", // Meta key is called OS on IE 9 and Firefox (tested v50)\n      \"Win\": \"Meta\", // Meta key is called Win on IE/Edge\n      \"Scroll\": \"ScrollLock\", // More IE/Edge, from tests\n      \"PrintScreen\": \"Print\", // More IE/Edge, from tests\n      \"MozHomeScreen\": \"GoHome\", // Prior to Firefox 37, the Home button generated a key code of \"Exit\". Starting in Firefox 37, the button generates the key code \"MozHomeScreen\".\n\n      // Internet Explorer 9 and Firefox 36 and earlier return \"Left\", \"Right\", \"Up\", and \"Down\" for the arrow keys, instead of \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", and \"ArrowDown\".\n      \"Left\": \"ArrowLeft\",\n      \"Right\": \"ArrowRight\",\n      \"Up\": \"ArrowUp\",\n      \"Down\": \"ArrowDown\",\n      // More IE and old Firefox stuff\n      \"Crsel\": \"CrSel\",\n      \"Exsel\": \"ExSel\",\n      \"Nonconvert\": \"NonConvert\",\n      // Internet Explorer 9 and Firefox 36 and earlier report \"Apps\" instead of \"ContextMenu\" for the context menu key.\n      \"Apps\": \"ContextMenu\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"MediaNextTrack\" and \"MediaPreviousTrack\" instead of \"MediaTrackNext\" and \"MediaTrackPrevious\".\n      \"MediaNextTrack\": \"MediaTrackNext\",\n      \"MediaPreviousTrack\": \"MediaTrackPrevious\",\n      // In Internet Explorer 9, and prior to Firefox 49, \"AudioVolumeUp\", \"AudioVolumeDown\", and \"AudioVolumeMute\" were \"VolumeUp\", \"VolumeDown\", and \"VolumeMute\".\n      // In Firefox 49 they were updated to match the latest specification. The old names are still used on Boot to Gecko.\n      \"VolumeUp\": \"AudioVolumeUp\",\n      \"VolumeDown\": \"AudioVolumeDown\",\n      \"VolumeMute\": \"AudioVolumeMute\",\n      // Firefox added proper support for the \"TV\" key in Firefox 37; before that, this key generated the key code \"Live\".\n      \"Live\": \"TV\",\n      // Internet Explorer 9 and Firefox 36 and earlier identify the zoom toggle button as \"Zoom\". Firefox 37 corrects this to \"ZoomToggle\".\n      \"Zoom\": \"ZoomToggle\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"SelectMedia\" instead of \"LaunchMediaPlayer\". Firefox 37 through Firefox 48 use \"MediaSelect\". Firefox 49 has been updated to match the latest specification, and to return \"LaunchMediaPlayer\".\n      \"SelectMedia\": \"LaunchMediaPlayer\",\n      \"MediaSelect\": \"LaunchMediaPlayer\",\n      // Google Chrome returns \"LaunchCalculator\" instead of \"LaunchApplication1\". See Chromium bug 612743 for more information.\n      // Google Chrome returns \"LaunchMyComputer\" instead of \"LaunchApplication2\". See Chromium bug 612743 for more information.\n      // (LaunchCalculator and LaunchMyComputer are valid too, so no translation)\n\n      // While older browsers used words like \"Add\", \"Decimal\", \"Multiply\", and so forth modern browsers identify these using the actual character (\"+\", \".\", \"*\", and so forth).\n      \"Multiply\": \"*\",\n      \"Add\": \"+\",\n      \"Divide\": \"/\",\n      \"Subtract\": \"-\",\n      \"Decimal\": \".\", // (mozilla Key_Values doc says depends on region)\n      \"Separator\": \".\", // (mozilla Key_Values doc says depends on region)\n\n      // keyIdenfier spec mapping of non-printable keys: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      // Used in safari\n      \"U+0008\": \"Backspace\",\n      \"U+0009\": \"Tab\",\n      \"U+000D\": \"Enter\",\n      \"U+0018\": \"Cancel\",\n      \"U+001B\": \"Escape\",\n      \"U+007F\": \"Delete\",\n      \"U+0300\": \"DeadGrave\",\n      \"U+0301\": \"DeadEacute\",\n      \"U+0302\": \"DeadCircumflex\",\n      \"U+0303\": \"DeadTilde\",\n      \"U+0304\": \"DeadMacron\",\n      \"U+0306\": \"DeadBreve\",\n      \"U+0307\": \"DeadAboveDot\",\n      \"U+0308\": \"DeadUmlaut\",\n      \"U+030A\": \"DeadAboveRing\",\n      \"U+030B\": \"DeadDoubleacute\",\n      \"U+030C\": \"DeadCaron\",\n      \"U+0327\": \"DeadCedilla\",\n      \"U+0328\": \"DeadOgonek\",\n      \"U+0345\": \"DeadIota\",\n      \"U+3099\": \"DeadVoicedSound\",\n      \"U+309A\": \"DeadSemivoicedSound\",\n\n      // keyIdenfier spec mapping to characters: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      \"Exclamation\": \"!\",\n      \"DoubleQuote\": \"\\\"\",\n      \"Hash\": \"#\",\n      \"Dollar\": \"$\",\n      \"Ampersand\": \"&\",\n      \"LeftParen\": \"(\",\n      \"RightParen\": \")\",\n      \"Asterisk\": \"*\",\n      \"Plus\": \"+\",\n      \"Percent\": \"%\",\n      \"Comma\": \",\",\n      \"HyphenMinus\": \"-\",\n      \"Period\": \".\",\n      \"Solidus\": \"/\",\n      \"Colon\": \":\",\n      \"Semicolon\": \";\",\n      \"LessThan\": \"<\",\n      \"Equals\": \"=\",\n      \"GreaterThan\": \">\",\n      \"QuestionMark\": \"?\",\n      \"At\": \"@\",\n      \"LeftSquareBracket\": \"[\",\n      \"Backslash\": \"\\\\\",\n      \"RightSquareBracket\": \"]\",\n      \"Circumflex\": \"^\",\n      \"Underscore\": \"_\",\n      \"Grave\": \"`\",\n      \"LeftCurlyBracket\": \"{\",\n      \"Pipe\": \"|\",\n      \"RightCurlyBracket\": \"}\",\n      \"Euro\": \"€\",\n      \"InvertedExclamation\": \"¡\",\n\n      // Safari fixes: viewed in local tests\n      \"U+0010\": \"ContextMenu\"\n    }\n  };\n}\n\nexport type NormalizedKeyboardEvent =\n  {\n    type: string;\n    target: EventTarget | null;\n    key: string;\n    code: string;\n    ctrlKey: boolean;\n    altKey: boolean;\n    location: number;\n    shiftKey: boolean;\n    metaKey: boolean;\n    repeat: boolean;\n    isComposing: boolean;\n  };\n\n/**\n     Returns normalized keyboard event properties, following the current W3C UI Events spec\n *\n    @param evt - Keyboard event\n    @returns Normalized keyboard event data\n */\nexport function normalizeKeyboardEventData(evt: KeyboardEvent): NormalizedKeyboardEvent {\n  // event.key is supported from chrome:51, edge, ff: 29, ie: 9, not in safari\n  // event.keyIdentifier in chrome 26-54, opera 15-41, safara: 5.1\n  // safari doesn't provide either in keypress events, use U+evt.keyCode (uppercase 4-byte hex)\n\n  let key = evt.key;\n  if (!keydata)\n    initKeyMapping();\n  if (keydata.mapping[key])\n    key = keydata.mapping[key];\n  else if (key.startsWith(\"U+\")) // U+xxxx code\n    key = String.fromCodePoint(parseInt(key.substring(2), 16));\n\n  // Seen in chrome 56.0.2924.76 on linux, numpad '.' without numlock returns key \"\\u0000\"\n  if (evt.key === \"\\u0000\" && evt.code === \"NumpadDecimal\")\n    key = \".\";\n\n  return (\n    {\n      type: evt.type,\n      target: evt.target,\n      key: key,\n      code: evt.code || \"Unidentified\",\n      ctrlKey: evt.ctrlKey,\n      altKey: evt.altKey,\n      location: evt.location,\n      shiftKey: evt.shiftKey,\n      metaKey: evt.metaKey,\n      repeat: evt.repeat,\n      isComposing: evt.isComposing\n    });\n}\n\n/**\n * Stop, fully, an event\n *\n * @param event - Event to stop\n */\nexport function stop(event: Event) {\n  event.preventDefault();\n  event.stopImmediatePropagation();\n}\n\n/** Add an event listener to HTMLElements inside a document (which allows us to ensure that 'target' is a HTMLElement for easier typings) */\nexport function addDocEventListener<CurrentTargetType extends HTMLElement, Type extends keyof HTMLElementEventMap>(node: CurrentTargetType, type: Type, listener: (this: CurrentTargetType, ev: DocEvent<HTMLElementEventMap[Type], CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\n\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void {\n  node.addEventListener(type, listener as EventListener, options);\n}\n","import { debugFlags } from '@webhare/env';\nimport * as domevents from '../../../modules/system/js/dompack/src/events';\nimport \"@webhare/tsrun/src/polyfills\";\n\nlet locallocks: BusyLock[] = [];\nlet modallocked = false;\nlet uiwatcher: NodeJS.Timeout | null = null;\nlet installedanticancelhandler = false;\n\nlet currentbusymodaldialog: HTMLDialogElement | null = null;\nlet currentbusymodaluserdialog: HTMLDialogElement | null = null;\nlet busymodalcontent: string | HTMLElement | HTMLDialogElement | undefined;\nlet mylockmgr: LockManager | undefined;\n\nexport type BusyModalEvent = CustomEvent<{ show: boolean }>;\n\n// As 'Lock' already exists on the Web (https://developer.mozilla.org/docs/Web/API/Lock) and it's seldom used just use a longer name. Available since WH 5.4\nexport interface UIBusyLock extends Disposable {\n  release(): void;\n  [Symbol.dispose](): void;\n}\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:busymodal\": BusyModalEvent;\n  }\n  interface Window {\n    __dompack_busylockmanager?: LockManager;\n  }\n\n  // __dompack_busylockmanager: LockManager | undefined;  //\n}\n\nfunction getLockmgr(): LockManager {\n  if (!mylockmgr) {\n    mylockmgr = getParentLockManager() || new LockManager;\n    if (typeof window !== \"undefined\")\n      window.__dompack_busylockmanager = mylockmgr;\n  }\n  return mylockmgr;\n}\n\nfunction anyModalLocks() {\n  return locallocks.some(l => l.modal);\n}\n\n/* scheduleCheckUIFree is invoked by release() or when waitUIFree is explicitly called. the call from release() should\n   be a 'fast' path. We schedule a full check for the next tick if there's a chance it might actually find a free UI */\nfunction scheduleCheckUIFree() {\n  if (!uiwatcher && locallocks.length === 0)\n    uiwatcher = setTimeout(() => checkUIFree(), 0);\n}\n\n/* check if the UI is actually free. if so, remove busymodals and resolve waitUIFrees for the benefit of testfw  */\nfunction checkUIFree() {\n  uiwatcher = null;\n\n  if (modallocked && !anyModalLocks()) { //did the last frame-level *modal* lock just get released?\n    modallocked = false;\n    toggleBusyModal(false);\n  }\n\n  if (locallocks.length === 0) {\n    const lockmgr = getLockmgr();\n    lockmgr.busyframes.delete(window); //we won't release our block in the lockmanager until we've had a chance to remove our modal layer\n    lockmgr.checkUIFree(); //to resolve any waitUIFrees. runs in the top-level frame. note that lockmgr cares about ALL ui locks, not just modals\n  }\n}\n\nfunction isDialogElement(el: unknown): boolean {\n  return typeof el === \"object\" && (el as HTMLElement).matches?.(\"dialog\") || false;\n}\n\nfunction checkCancelEvent(evt: Event) {\n  if (modallocked)\n    evt.preventDefault();\n}\n\nfunction toggleBusyModal(show: boolean) {\n  //'islock' is legacy non-camel version. TypeScript typing should help us transition (since 5.3). 'as' shuts up the warning TODO remove 'islock' and the 'as'\n  if (!domevents.dispatchCustomEvent(window, 'dompack:busymodal', { bubbles: true, cancelable: true, detail: { show: show, islock: show } as BusyModalEvent['detail'] }))\n    return; //cancelled!\n\n  if (!installedanticancelhandler) {\n    //capture cancel, as it doesn't bubble up\n    addEventListener(\"cancel\", evt => checkCancelEvent(evt), { capture: true });\n    installedanticancelhandler = true;\n  }\n\n  if (show) {\n    if (isDialogElement(busymodalcontent)) { //the user provided us with an element\n      currentbusymodaluserdialog = busymodalcontent as HTMLDialogElement;\n      currentbusymodaluserdialog.showModal();\n    } else if (busymodalcontent) { //we'll create our own dialog\n      const dialog = document.createElement('dialog');\n      const toembed = typeof busymodalcontent === \"string\" ? document.createTextNode(busymodalcontent) : busymodalcontent.cloneNode(true);\n      dialog.className = \"dompack-busydialog\";\n      dialog.role = \"status\";\n      dialog.ariaLive = \"off\";\n      dialog.append(toembed);\n      document.body.appendChild(dialog);\n      currentbusymodaldialog = dialog;\n      dialog.showModal();\n      return;\n    }\n\n    document.documentElement.classList.add(\"dompack--busymodal\");\n    return;\n  }\n\n  //hiding\n  document.documentElement.classList.remove(\"dompack--busymodal\");\n  if (currentbusymodaluserdialog)\n    currentbusymodaluserdialog.close();\n  if (currentbusymodaldialog) { //we added a dialog to the dom\n    currentbusymodaldialog.close();\n    document.body.removeChild(currentbusymodaldialog);\n    currentbusymodaldialog = null;\n  }\n}\n\nclass LockManager {\n  locks: BusyLock[];\n  busyframes: Set<Window> = new Set;\n  busycounter: number;\n  deferreduipromise: PromiseWithResolvers<boolean> | null;\n\n  //this object is not for external consumption\n  constructor() {\n    this.locks = [];\n    this.busycounter = 0;\n    this.deferreduipromise = null;\n  }\n  add(lock: BusyLock) {\n    this.locks.push(lock);\n    const returnvalue = this.busycounter++;\n    return returnvalue;\n  }\n  release(lock: BusyLock) {\n    const pos = this.locks.indexOf(lock);\n    if (pos === -1) {\n      if (debugFlags.bus) {\n        console.error(\"Duplicate release of busy lock #\" + lock.locknum);\n        console.log(\"Lock allocated:\");\n        console.log(lock.acquirestack);\n        console.log(\"Lock first released:\");\n        console.log(lock.releasestack);\n      }\n      throw new Error(\"Duplicate release of busy lock\");\n    }\n\n    this.locks.splice(pos, 1);\n  }\n  getNumLocks() {\n    return this.locks.length;\n  }\n  //used by child windows to schedule a check in *our* frame (eg before they themselves are unloaded)\n  scheduleCheckUIFree() {\n    scheduleCheckUIFree();\n  }\n  checkUIFree() {\n    if (this.locks.length === 0 && this.busyframes.size === 0 && this.deferreduipromise) {\n      this.deferreduipromise.resolve(true);\n      this.deferreduipromise = null;\n    }\n  }\n  waitUIFree() {\n    if (!this.deferreduipromise)\n      this.deferreduipromise = Promise.withResolvers();\n\n    scheduleCheckUIFree(); //ensures uiwait is released at next tick if no locks are present at all\n    return this.deferreduipromise.promise;\n  }\n  logLocks() {\n    this.locks.forEach(lock => console.log('[bus] lock #' + lock.locknum, lock.acquirestack, lock));\n    console.log(\"[bus] total \" + this.locks.length + \" locks\");\n  }\n  getLockIds() {\n    return this.locks.map(l => \"#\" + l.locknum).join(\", \");\n  }\n}\n\n/** Configure an (accessible) modal dialog\n * @param bmc - What to show in the dialog: either a text or DOM fragment to clone.\n *              If a <dialog> element is passed, this dialog will be used instead of creating a new one.\n */\nexport function setupBusyModal(bmc: NonNullable<typeof busymodalcontent>) {\n  busymodalcontent = bmc;\n}\n\ninterface LockOptions {\n  ///Whether this lock should enable a modality laayer\n  modal?: boolean;\n}\n\nclass BusyLock implements UIBusyLock {\n  modal: boolean;\n  locknum: number;\n  acquirestack: string | undefined;\n  releasestack: string | undefined;\n\n  constructor(options?: LockOptions) {\n    //legacy non-camel name is 'ismodal'\n    this.modal = options?.modal ?? (options as { ismodal?: boolean })?.ismodal ?? false;\n\n    const lockmgr = getLockmgr();\n    this.locknum = lockmgr.add(this);\n    lockmgr.busyframes.add(window);\n    locallocks.push(this);\n\n    if (this.modal && !modallocked) {\n      modallocked = true;\n      toggleBusyModal(true);\n    }\n\n    if (debugFlags.bus) {\n      this.acquirestack = (new Error).stack;\n      console.trace('[bus] Busy lock #' + this.locknum + ' taken. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n  }\n\n  [Symbol.dispose]() {\n    if (debugFlags.bus)\n      this.releasestack = (new Error).stack;\n\n    const lockmgr = getLockmgr();\n    lockmgr.release(this);\n    const lockpos = locallocks.indexOf(this);\n    locallocks.splice(lockpos, 1);\n\n    if (debugFlags.bus) {\n      console.trace('[bus] Busy lock #' + this.locknum + ' released. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n\n    scheduleCheckUIFree();\n  }\n\n  release() {\n    this[Symbol.dispose]();\n  }\n}\n\n/** Return a promise resolving as soon as the UI (any accessible frame) is free for at least one tick */\nexport function waitUIFree() {\n  return getLockmgr().waitUIFree();\n}\n\n/**\n     flag userinterface as busy. tests then know not to interact with the UI until the busy flag is released\n *\n    @param options - Options.<br>\n                   - modal: true/false - Whether the lock is a modal lock\n */\nexport function flagUIBusy(options?: LockOptions): UIBusyLock {\n  return new BusyLock(options);\n}\n\nexport function getUIBusyCounter() {\n  return getLockmgr().busycounter;\n}\n\nfunction getParentLockManager(): LockManager | null {\n  try { //we're accessing a parent window, so we may hit security exceptions\n    if (!(window.parent?.__dompack_busylockmanager))\n      return null;\n\n    //if we connected to a parent...  deregister our locks, eg. if parent navigated our frame away\n    window.addEventListener(\"pagehide\", () => {\n      if (debugFlags.bus)\n        console.log(\"[bus] Frame unloading, \" + locallocks.length + \" locks pending.\", locallocks.map(l => \"#\" + l.locknum).join(\", \"), locallocks);\n\n      //switch to local instance in case anyone still tries to touch these locks during unload\n      const lockmgr = getLockmgr();\n      const locallockmgr = new LockManager;\n      locallocks.forEach(lock => { lockmgr.release(lock); locallockmgr.add(lock); });\n      locallocks = [];\n\n      lockmgr.busyframes.delete(window); //explicitly remove us so we won't be waited upon\n      lockmgr.scheduleCheckUIFree();\n      mylockmgr = locallockmgr;\n    });\n\n    return window.parent.__dompack_busylockmanager;\n  } catch (e) {\n    return null;\n  }\n}\n","/** Rect describing an elements position */\nexport type Rect = {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n  width: number;\n  height: number;\n};\n\n/** Elements you can set a value on and would have to trigger change and/or input events */\nexport type FormControlElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Types that support querySelector(All) */\ntype QuerySelectorAble = ParentNode | ShadowRoot;\n\nexport function qS<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E | null;\nexport function qS<E extends Element = HTMLElement>(selector: string): E | null;\n\n/** Match the first element using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The first matching element or null\n */\nexport function qS<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E | null {\n  if (typeof node_or_selector === 'string')\n    return document.querySelector<E>(node_or_selector);\n  else if (selector)\n    return node_or_selector.querySelector<E>(selector);\n  return null;\n}\n\n\nexport function qR<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E;\nexport function qR<E extends Element = HTMLElement>(selector: string): E;\n\n/** Match a specific element using a CSS selector, requiring it to exist and be unique\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested element. Throw it the selector doesn't match exactly one element\n */\nexport function qR<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E {\n  const matches = qSA<E>(node_or_selector as QuerySelectorAble, selector as string);\n  if (matches.length === 1)\n    return matches[0];\n\n  if (typeof node_or_selector !== 'string') {\n    console.error(`${matches.length} elements match selector \\`${selector}\\` with startingpoint`, node_or_selector, matches);\n    throw new Error(`${matches.length} elements match selector \\`${selector}\\` given startingpoint '${node_or_selector.nodeName}'`);\n  } else {\n    console.error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`, matches);\n    throw new Error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`);\n  }\n}\n\nexport function qSA<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E[];\nexport function qSA<E extends Element = HTMLElement>(selector: string): E[];\n\n/** Find multiple elements using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested elements.\n */\nexport function qSA<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E[] {\n  if (typeof node_or_selector === 'string')\n    return Array.from(document.querySelectorAll(node_or_selector));\n  else if (selector)\n    return Array.from(node_or_selector.querySelectorAll(selector));\n\n  return [];\n}\n\n/** Return whether the passed element is a FormControlElement */\nexport function isFormControl(field: Element): field is FormControlElement {\n  return isHTMLElement(field) && [\"INPUT\", \"SELECT\", \"TEXTAREA\"].includes(field.tagName);\n}\n\n/** Return whether the passed element is an editable text field */\nexport function isEditControl(field: Element): field is HTMLElement {\n  return isHTMLElement(field) && ([\"INPUT\", \"TEXTAREA\"].includes(field.tagName) || field.isContentEditable);\n}\n\n/** Test whether node is an Element, even if it's in a different iframe */\nexport function isElement(node: unknown): node is Element {\n  //TODO What is actually going on if defaultView is missing?\n  if (!node || typeof node !== \"object\")\n    return false;\n\n  /* Getting the proto doesn't always work:\n  const proto = (node as Element).ownerDocument.defaultView?.Element;\n  (because our iframes derive off about? not sure) so until someone finds the real answer, we'll do a heuristic\n  */\n\n  /** Analyzing node.constructor.name doesn't work because custom elements don't necessarily have their constructor's name ending in Element\n  return Boolean(\"ownerDocument\" in node && node.constructor.name.match(/Element$/));\n  */\n\n  return Boolean(\"ownerDocument\" in node && (node as Element).nodeType === 1);\n\n}\n\n/** Test whether node is a HTMLElement, even if it's in a different iframe */\nexport function isHTMLElement(node: unknown): node is HTMLElement {\n  return isElement(node) && \"accessKey\" in node;\n}\n\n/**\n * get the relative bound difference between two elements, and return a writable copy\n *\n * @param node - The node for which you need coordinates\n * @param relativeto - Optional reference point. If not set, you just get a 'normal' coordinate object\n */\nexport function getRelativeBounds(node: Element, relativeto?: Element): Rect {\n  if (!relativeto)\n    relativeto = node.ownerDocument.documentElement;\n\n  const nodecoords = node.getBoundingClientRect();\n  const relcoords = relativeto.getBoundingClientRect();\n  return {\n    top: nodecoords.top - relcoords.top,\n    left: nodecoords.left - relcoords.left,\n    right: nodecoords.right - relcoords.left,\n    bottom: nodecoords.bottom - relcoords.top,\n    width: nodecoords.width,\n    height: nodecoords.height\n  };\n}\n","\n/* Regex to identify dimensionless style sttributes. copied from old version of preact/src/constants.js (MIT)\n   meant to capture:\n  { boxFlex:1, boxFlexGroup:1, columnCount:1, fillOpacity:1, flex:1, flexGrow:1,\n    flexPositive:1, flexShrink:1, flexNegative:1, fontWeight:1, lineClamp:1, lineHeight:1,\n    opacity:1, order:1, orphans:1, strokeOpacity:1, widows:1, zIndex:1, zoom:1\n*/\nconst IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;\n\nexport { qS, qSA } from '@webhare/dompack/src/tree.ts';\n\nfunction generateInsertList(nodes: Array<string | Node>) {\n  if (nodes.length === 1)\n    return typeof nodes[0] === 'string' ? document.createTextNode(nodes[0]) : nodes[0];\n\n  const frag = document.createDocumentFragment();\n  nodes.forEach(node => frag.appendChild(typeof node === 'string' ? document.createTextNode(node) : node));\n  return frag;\n}\n\n/** @deprecated Use node.matches() */\nexport function matches(node: Element, selector: string): boolean {\n  //only invoke 'matches' if it exists. it *should* but past versions of dompack.matches would check for it too (and thus not fail if you passed in a string instead of a Node)\n  return node.matches?.(selector);\n}\n/** @deprecated Use node.closest() */\nexport function closest(node: Element, selector: string) {\n  if (node.closest)\n    return node.closest(selector);\n  //TODO: Warn about out-of-date browser?\n  let testNode: Element | null = node;\n  for (; testNode && !matches(testNode, selector); testNode = testNode.parentElement)\n    /*iterate*/;\n  return testNode;\n}\n//implements contains. TODO we only really need this on IE11, which doesn't consider a text node a child, we can probably fall back to native elsewhere ?\n/** @deprecated Use node.contains() */\nexport function contains(ancestor: Node, child: Node) {\n  if (ancestor.contains)\n    return ancestor.contains(child);\n  //TODO: Warn about out-of-date browser?\n  for (let testNode: Node | null = child; testNode; testNode = testNode.parentNode)\n    if (testNode === ancestor)\n      return true;\n  return false;\n}\n//insert a range of nodes before a node: https://dom.spec.whatwg.org/#dom-childnode-before\n/** @deprecated Use node.before() */\nexport function before(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.before) {\n    node.before(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node);\n}\n//insert a range of nodes after a node: https://dom.spec.whatwg.org/#dom-childnode-after\n/** @deprecated Use node.after() */\nexport function after(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.after) {\n    node.after(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node.nextSibling);\n}\n//replace node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-replacewith\n/** @deprecated Use node.replaceWith() */\nexport function replaceWith(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.replaceWith) {\n    node.replaceWith(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.replaceChild(generateInsertList(nodes), node);\n}\n//remove node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-remove\n/** @deprecated Use node.remove() */\nexport function remove(node: ChildNode) {\n  if (node.remove) {\n    node.remove();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.removeChild(node);\n}\n//insert nodes at start: https://dom.spec.whatwg.org/#dom-parentnode-prepend\n/** @deprecated Use node.prepend() */\nexport function prepend(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.prepend) {\n    node.prepend(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.insertBefore(generateInsertList(nodes), node.firstChild);\n}\n//insert nodes at end: https://dom.spec.whatwg.org/#dom-parentnode-append\n/** @deprecated Use node.append() */\nexport function append(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.append) {\n    node.append(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.appendChild(generateInsertList(nodes));\n}\n\n/**\n * Toggle a single class\n *\n * @param node - Node to modify\n * @param classname - Class to toggle\n * @param settoggle - true to enable, false to disable, undefined to toggle\n * @deprecated Just use classList.toggle on the node itself\n */\n/** @deprecated Use classList.toggle() */\nexport function toggleClass(node: Element, classname: string, settoggle?: boolean) {\n  if (arguments.length === 2) //in old dompack, 2 argument version toggled and 3 argument version toggled off. match that behavior\n    node.classList.toggle(classname);\n  else\n    node.classList.toggle(classname, settoggle);\n}\n\n/**\n     Toggle classes in a node\n *\n    @param node - Node which classes to toggle\n    @param toggles - Object, all keys will be added/removed based on the truthyness of their values\n */\nexport function toggleClasses(node: Element, toggles: { [key: string]: boolean }) {\n  if (typeof (toggles) !== \"object\")\n    throw new Error(\"Expected an object with keys as classnames\");\n  Object.keys(toggles).forEach(key => node.classList[toggles[key] ? \"add\" : \"remove\"](key));\n}\n\n/* remove the contents of an existing node */\n/** @deprecated Use node.replaceChildren() */\nexport function empty(node: Element) {\n  if (node.replaceChildren) {\n    node.replaceChildren();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  while (node.lastChild)\n    node.removeChild(node.lastChild);\n}\n\nexport function isDomReady() {\n  //ensure no domready events can run if there will never be a dom\n  return typeof document !== \"undefined\" && (document.readyState === \"interactive\" || document.readyState === \"complete\");\n}\n\n/* run the specified function 'on ready'. adds to DOMContentLoaded if dom is not ready yet. Exceptions/rejections from the ready handler will not be fatal to the rest of code execution */\nexport function onDomReady(callback: () => unknown | Promise<unknown>) {\n  if (isDomReady()) {\n    try {\n      void callback(); //Ignore unhandled rejections\n    } catch (e) { // We don't want our caller to 'stop' due to a domready exception as its usually the toplevel initialization code, so log the exception ourselves\n      void Promise.reject(new Error(\"Synchronous onDomReady handler failed\", { cause: e })); //Let it propagate as a standard unhandled rejection\n    }\n  } else\n    document.addEventListener(\"DOMContentLoaded\", () => void callback());\n}\n\n//parse JSON data, throw with more info on parse failure\nexport function getJSONAttribute<T>(node: Element, attributename: string): T | null {\n  try {\n    if (node.hasAttribute(attributename))\n      return JSON.parse(node.getAttribute(attributename) as string);\n  } catch (e) {\n    console.error(\"JSON parse failure on attribute '\" + attributename + \"' of node\", node);\n    throw e;\n  }\n  return null;\n}\n\n/**\n     Get the base URI of the current document. IE11 doesn't implement document.baseURI\n *\n    @param doc - Document to query. Defaults to window.document\n    @deprecated Use document.baseURI\n */\nexport function getBaseURI(doc: Document | undefined) {\n  if (!doc)\n    doc = window.document;\n  if (doc.baseURI)\n    return doc.baseURI;\n\n  const base = doc.querySelector('base');\n  if (base && base.href)\n    return base.href;\n  return doc.URL;\n}\n\n/**\n     Sets multiple styles on a node, automatically adding 'px' to numbers when appropriate\n    (can be used as replacement for Mootools .setStyles)\n *\n * @param node - Node to update\n * @param value - Styles to set\n */\nexport function setStyles(node: HTMLElement, value?: string | { [key: string]: string | number }) {\n  if (!value)\n    node.style.cssText = '';\n  else if (typeof value === 'string')\n    node.style.cssText = value || '';\n  else {\n    for (const [key, propvalue] of Object.entries(value)) {\n      // for numbers, add 'px' if the constant isn't dimensionless (eg zIndex)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n      (node.style as any)[key] = typeof value[key] === 'number' && IS_NON_DIMENSIONAL.test(key) === false\n        ? propvalue + 'px'\n        : propvalue;\n    }\n  }\n}\n","import * as domtree from './tree';\nimport * as domevents from './events';\n\nexport type TakeFocusEvent = CustomEvent<{ options?: FocusOptions }>;\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:takefocus\": TakeFocusEvent;\n  }\n}\n\ntype RegistrationHandler<E extends Element = HTMLElement> = (node: E, index?: number) => void;\ntype ComponentRegistration<E extends Element = HTMLElement> =\n  {\n    selector: string;\n    handler: RegistrationHandler<E>;\n    index: number;\n    num: number;\n    afterdomready: boolean;\n  };\n\nconst components: Array<ComponentRegistration<Element>> = [];\nconst map = new WeakMap();\n\n//is a node completely in the dom? if we can find a sibling anywhere, it must be closed\nfunction isNodeCompletelyInDom(node: Element | null) {\n  for (; node; node = node.parentElement)\n    if (node.nextSibling)\n      return true;\n  return false;\n}\nfunction processRegistration<E extends Element>(item: E, reg: ComponentRegistration<E>, domready: boolean) {\n  if (!domready && !isNodeCompletelyInDom(item))\n    return; //not safe to register\n\n  if (!map.has(item))\n    map.set(item, [reg.num]);\n  else {\n    const list = map.get(item);\n    if (list.includes(reg.num))\n      return;\n    list.push(reg.num);\n  }\n  reg.handler(item, reg.index++); //note: if an exception is reported from Object.handler,\n}\nfunction applyRegistration<E extends Element>(reg: ComponentRegistration<E>, startnode?: Element) {\n  const domready = domtree.isDomReady();\n  if (reg.afterdomready && !domready)\n    return;\n\n  const items = Array.from((startnode || document).querySelectorAll(reg.selector)) as E[];\n  if (startnode?.matches(reg.selector))\n    items.unshift(startnode as E); //if startnode matches it has to be an E\n\n  items.forEach(item => {\n    try {\n      processRegistration<E>(item, reg, domready);\n    } catch (e) {\n      console.error(\"Exception handling registration of\", item, \"for rule\", reg.selector);\n      console.log(\"Registration\", reg);\n      if (e instanceof Error) {\n        console.log(e, e.stack);\n        if (window.onerror) {\n          // Send to onerror to trigger exception reporting\n          try {\n            // @ts-ignore: fileName, lineNumber and columnNumber are non-standard\n            window.onerror(e.message, e.fileName || \"\", e.lineNumber || 1, e.columNumber || 1, e);\n          } catch (e2) { }\n        }\n      } else\n        console.log(e);\n    }\n  });\n}\n\n/* A focus implementation that allows the node to intercept focused, allowing eg\n   radio/checkbox replacements to redirect focus but also explicitly preventing\n   focus of a disabled element\n   Returns true when the focus operation was successfull or handled by an event handler.\n   @param node Node to focus\n   @param options.preventScroll Prevent scroll to focused element\n*/\nexport function focus(node: Element, options?: FocusOptions) {\n  if (!domevents.dispatchCustomEvent(node, 'dompack:takefocus', { bubbles: true, cancelable: true, detail: { options } }))\n    return true;\n\n  if (typeof (node as HTMLElement).focus !== \"function\" || (node as HTMLInputElement).disabled)\n    return false;\n\n  (node as HTMLInputElement).focus(options);\n  return true;\n}\n\n/**\n * @param node - Node to show\n * @param options - Scroll options\n * @deprecated invoke scrollIntoView directly  on the nodes\n */\nexport function scrollIntoView(node: Element, options?: ScrollIntoViewOptions) {\n  node.scrollIntoView(options);\n  return true;\n}\n\n/**\n    Register a component for auto-initialization.\n\n    @param selector - Selector the component must match\n    @param handler - Handler\n    @param options - Any unrecognized options are passed to the handler\n\n    The handler will be invoked with two parameters\n    - the node to register\n    - the index of the node (a unique counter for this selector - first is 0)\n */\n\nexport function register<E extends Element = HTMLElement>(selector: string, handler: RegistrationHandler<E>, options?: { afterdomready: boolean }) {\n  const newreg: ComponentRegistration<E> =\n  {\n    selector: selector,\n    handler: handler,\n    index: 0,\n    num: components.length,\n    afterdomready: !options || options.afterdomready\n  };\n  if (components.length === 0 && !domtree.isDomReady()) //first component... we'll need a ready handler\n    domtree.onDomReady(() => registerMissed());\n\n  components.push(newreg as ComponentRegistration<Element>);\n  applyRegistration(newreg);\n}\n\n// register any components we missed on previous scans\nexport function registerMissed(startnode?: Element) {\n  const todo = components.slice(0);\n  todo.forEach(item => applyRegistration(item, startnode));\n}\n","import { buildCookieHeader, type CookieOptions } from '@webhare/dompack/src/cookiebuilder';\nimport { escapeRegExp, parseTyped, stringify } from '@webhare/std';\n\nconst backup: {\n  sessionStorage?: Record<string, string>;\n  localStorage?: Record<string, string>;\n} = {};\ntype BrowserStorage = keyof typeof backup;\n\nexport function listCookies() {\n  return document.cookie.split(';').map(cookie => {\n    const parts = cookie.split('=');\n    return { name: decodeURIComponent(parts[0].trim()), value: decodeURIComponent(parts[1] || '') };\n  });\n}\n\nexport function setCookie(key: string, value: string, options?: CookieOptions) {\n  document.cookie = buildCookieHeader(key, value, options);\n}\n\nexport function getCookie(key: string): string | null {\n  const value = document.cookie.match('(?:^|;)\\\\s*' + escapeRegExp(key) + '=([^;]*)');\n  return (value) ? decodeURIComponent(value[1]) : null;\n}\n\nexport function deleteCookie(key: string, options?: CookieOptions) {\n  setCookie(key, '', { ...options, duration: -1, expires: undefined });\n}\n\nfunction get(storage: BrowserStorage, key: string): unknown | null {\n  let foundvalue: string | undefined | null = backup[storage]?.[key];\n  if (foundvalue) //if it's in the backups storage encoding can't fail either\n    return parseTyped(foundvalue);\n\n  try {\n    foundvalue = window[storage].getItem(key);\n    if (foundvalue)\n      return parseTyped(foundvalue);\n  } catch (e) {\n    //we ignore parse failures\n  }\n  return null;\n}\n\nfunction set(storage: BrowserStorage, key: string, value: unknown) {\n  const tostore = value !== null && value !== undefined ? stringify(value, { typed: true }) : null;\n  try {\n    if (tostore !== null)\n      window[storage].setItem(key, tostore);\n    else\n      window[storage].removeItem(key);\n    return;\n  } catch (e) {\n    //ignore\n  }\n\n  const store = (backup[storage] ||= {});\n  if (tostore !== null)\n    store[key] = tostore;\n  else\n    delete store[key];\n}\n\nexport function getSession<T>(key: string): T | null {\n  return get(\"sessionStorage\", key) as T | null;\n}\nexport function setSession<T>(key: string, value: T | null) {\n  set(\"sessionStorage\", key, value);\n}\nexport function getLocal<T>(key: string): T | null {\n  return get(\"localStorage\", key) as T | null;\n}\nexport function setLocal<T>(key: string, value: T | null) {\n  set(\"localStorage\", key, value);\n}\n","/* Identify devices for the purpose of analytics/tracing\n   NOT a library for feature detection!\n   Originally based on Mootools.Browser\n*/\n\nexport type Platform = \"windows\" | \"ios\" | \"webos\" | \"android\" | \"linux\" | \"mac\" | \"other\";\nexport type Device = \"desktop\" | \"mobile\" | \"tablet\" | \"\";\n\n/** Valid KeyboardEvent.key values (next to 'plain' keys)\n    This list was built from https://www.w3.org/TR/uievents-key/\n    using `console.log([...new Set([...document.querySelectorAll(\".key-table-key .key\")].map(_ => _.textContent))].toSorted().join(' | '))`\n*/\nexport type KeyAttributeValue = \"AVRInput\" | \"AVRPower\" | \"Accept\" | \"Again\" | \"AllCandidates\" | \"Alphanumeric\" | \"Alt\" | \"AltGraph\" | \"AppSwitch\" | \"ArrowDown\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"Attn\" | \"AudioBalanceLeft\" | \"AudioBalanceRight\" | \"AudioBassBoostDown\" | \"AudioBassBoostToggle\" | \"AudioBassBoostUp\" | \"AudioFaderFront\" | \"AudioFaderRear\" | \"AudioSurroundModeNext\" | \"AudioTrebleDown\" | \"AudioTrebleUp\" | \"AudioVolumeDown\" | \"AudioVolumeMute\" | \"AudioVolumeUp\" | \"Backspace\" | \"BrightnessDown\" | \"BrightnessUp\" | \"BrowserBack\" | \"BrowserFavorites\" | \"BrowserForward\" | \"BrowserHome\" | \"BrowserRefresh\" | \"BrowserSearch\" | \"BrowserStop\" | \"Call\" | \"Camera\" | \"CameraFocus\" | \"Cancel\" | \"CapsLock\" | \"ChannelDown\" | \"ChannelUp\" | \"Clear\" | \"Close\" | \"ClosedCaptionToggle\" | \"CodeInput\" | \"ColorF0Red\" | \"ColorF1Green\" | \"ColorF2Yellow\" | \"ColorF3Blue\" | \"ColorF4Grey\" | \"ColorF5Brown\" | \"Compose\" | \"ContextMenu\" | \"Control\" | \"Convert\" | \"Copy\" | \"CrSel\" | \"Cut\" | \"DVR\" | \"Dead\" | \"Delete\" | \"Dimmer\" | \"DisplaySwap\" | \"Eisu\" | \"Eject\" | \"End\" | \"EndCall\" | \"Enter\" | \"EraseEof\" | \"Escape\" | \"ExSel\" | \"Execute\" | \"Exit\" | \"F1\" | \"F10\" | \"F11\" | \"F12\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"FavoriteClear0\" | \"FavoriteClear1\" | \"FavoriteClear2\" | \"FavoriteClear3\" | \"FavoriteRecall0\" | \"FavoriteRecall1\" | \"FavoriteRecall2\" | \"FavoriteRecall3\" | \"FavoriteStore0\" | \"FavoriteStore1\" | \"FavoriteStore2\" | \"FavoriteStore3\" | \"FinalMode\" | \"Find\" | \"Fn\" | \"FnLock\" | \"GoBack\" | \"GoHome\" | \"GroupFirst\" | \"GroupLast\" | \"GroupNext\" | \"GroupPrevious\" | \"Guide\" | \"GuideNextDay\" | \"GuidePreviousDay\" | \"HangulMode\" | \"HanjaMode\" | \"Hankaku\" | \"HeadsetHook\" | \"Help\" | \"Hibernate\" | \"Hiragana\" | \"HiraganaKatakana\" | \"Home\" | \"Hyper\" | \"Info\" | \"Insert\" | \"InstantReplay\" | \"JunjaMode\" | \"KanaMode\" | \"KanjiMode\" | \"Katakana\" | \"Key11\" | \"Key12\" | \"LastNumberRedial\" | \"LaunchApplication1\" | \"LaunchApplication2\" | \"LaunchCalendar\" | \"LaunchContacts\" | \"LaunchMail\" | \"LaunchMediaPlayer\" | \"LaunchMusicPlayer\" | \"LaunchPhone\" | \"LaunchScreenSaver\" | \"LaunchSpreadsheet\" | \"LaunchWebBrowser\" | \"LaunchWebCam\" | \"LaunchWordProcessor\" | \"Link\" | \"ListProgram\" | \"LiveContent\" | \"Lock\" | \"LogOff\" | \"MailForward\" | \"MailReply\" | \"MailSend\" | \"MannerMode\" | \"MediaApps\" | \"MediaAudioTrack\" | \"MediaClose\" | \"MediaFastForward\" | \"MediaLast\" | \"MediaNextTrack\" | \"MediaPause\" | \"MediaPlay\" | \"MediaPlayPause\" | \"MediaPreviousTrack\" | \"MediaRecord\" | \"MediaRewind\" | \"MediaSkipBackward\" | \"MediaSkipForward\" | \"MediaStepBackward\" | \"MediaStepForward\" | \"MediaStop\" | \"MediaTopMenu\" | \"MediaTrackNext\" | \"MediaTrackPrevious\" | \"Meta\" | \"MicrophoneToggle\" | \"MicrophoneVolumeDown\" | \"MicrophoneVolumeMute\" | \"MicrophoneVolumeUp\" | \"ModeChange\" | \"NavigateIn\" | \"NavigateNext\" | \"NavigateOut\" | \"NavigatePrevious\" | \"New\" | \"NextCandidate\" | \"NextFavoriteChannel\" | \"NextUserProfile\" | \"NonConvert\" | \"Notification\" | \"NumLock\" | \"OnDemand\" | \"Open\" | \"PageDown\" | \"PageUp\" | \"Pairing\" | \"Paste\" | \"Pause\" | \"PinPDown\" | \"PinPMove\" | \"PinPToggle\" | \"PinPUp\" | \"Play\" | \"PlaySpeedDown\" | \"PlaySpeedReset\" | \"PlaySpeedUp\" | \"Power\" | \"PowerOff\" | \"PreviousCandidate\" | \"Print\" | \"PrintScreen\" | \"Process\" | \"Props\" | \"RandomToggle\" | \"RcLowBattery\" | \"RecordSpeedNext\" | \"Redo\" | \"RfBypass\" | \"Romaji\" | \"STBInput\" | \"STBPower\" | \"Save\" | \"ScanChannelsToggle\" | \"ScreenModeNext\" | \"ScrollLock\" | \"Select\" | \"Settings\" | \"Shift\" | \"SingleCandidate\" | \"Soft1\" | \"Soft2\" | \"Soft3\" | \"Soft4\" | \"SpeechCorrectionList\" | \"SpeechInputToggle\" | \"SpellCheck\" | \"SplitScreenToggle\" | \"Standby\" | \"Subtitle\" | \"Super\" | \"Symbol\" | \"SymbolLock\" | \"TV\" | \"TV3DMode\" | \"TVAntennaCable\" | \"TVAudioDescription\" | \"TVAudioDescriptionMixDown\" | \"TVAudioDescriptionMixUp\" | \"TVContentsMenu\" | \"TVDataService\" | \"TVInput\" | \"TVInputComponent1\" | \"TVInputComponent2\" | \"TVInputComposite1\" | \"TVInputComposite2\" | \"TVInputHDMI1\" | \"TVInputHDMI2\" | \"TVInputHDMI3\" | \"TVInputHDMI4\" | \"TVInputVGA1\" | \"TVMediaContext\" | \"TVNetwork\" | \"TVNumberEntry\" | \"TVPower\" | \"TVRadioService\" | \"TVSatellite\" | \"TVSatelliteBS\" | \"TVSatelliteCS\" | \"TVSatelliteToggle\" | \"TVTerrestrialAnalog\" | \"TVTerrestrialDigital\" | \"TVTimer\" | \"Tab\" | \"Teletext\" | \"Undo\" | \"Unidentified\" | \"VideoModeNext\" | \"VoiceDial\" | \"WakeUp\" | \"Wink\" | \"Zenkaku\" | \"ZenkakuHankaku\" | \"ZoomIn\" | \"ZoomOut\" | \"ZoomToggle\";\n\nexport type UserAgentInfo =\n  {\n    /** Browser name, eg 'chrome' or 'firefox' */\n    name: string;\n    /** Browser numeric version (eg 97) */\n    version: number;\n    /** Platform the browser is running on (eg 'windows') */\n    platform: Platform;\n    /** Type of device (eg 'desktop' or 'tablet' for an iPad) */\n    device: Device;\n    /** platform-browsername-version eg ios-safari-11 */\n    triplet: string;\n  };\n\nexport function parseUserAgent(ua: string): UserAgentInfo {\n  ua = ua.toLowerCase();\n\n  // chrome is included in the edge UA, so need to check for edge first, before checking if it's chrome.\n  // safari is included in the miuibrowser UA, so need to check for miuibrowser first, before checking if it's safari.\n  let UA: RegExpMatchArray | null = ua.match(/(edge|miuibrowser)[\\s/:]([\\w\\d.]+)/);\n  if (!UA)\n    UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\\s/:]([\\w\\d.]+)?.*?(safari|(?:rv[\\s/:]|version[\\s/:])([\\w\\d.]+)|$)/);\n  if (!UA) { //try ios 11.4.1\n    UA = ua.match(/; cpu os ([\\d]+)/);\n    if (UA)\n      UA = ['', 'safari', UA[1]];\n  }\n  if (!UA)\n    UA = ['', 'unknown', \"0\"];\n\n  if (UA[1] === 'trident') {\n    UA[1] = 'ie';\n    if (UA[4]) UA[2] = UA[4];\n  } else if (UA[1] === 'crios') {\n    UA[1] = 'chrome';\n  }\n\n  let platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];\n  if (platform === 'win')\n    platform = 'windows';\n\n  const name = (UA[1] === 'version') ? UA[3] : UA[1];\n  const version = parseInt((UA[1] === 'opera' && UA[4]) ? UA[4] : UA[2]);\n  const device = ua.match(/ipad/) ? 'tablet' : ['ios', 'webos', 'android'].includes(platform) ? 'mobile' : ['mac', 'windows', 'linux'].includes(platform) ? 'desktop' : '';\n\n  return {\n    name,\n    version,\n    platform: platform as Platform,\n    device,\n    triplet: platform + '-' + name + '-' + version\n  };\n}\n\n/**\n * Is the native 'multiselect' modifier for this platform pressed? (Cmd for Mac, Ctrl for Windows/Linux)\n *\n * @param event - Event to check\n */\nexport function isMultiSelectKey(event: KeyboardEvent | MouseEvent): boolean {\n  return browser.platform === 'mac' ? event.metaKey : event.ctrlKey;\n}\n\n/**\n * Is the native 'copy' modifier for this platform pressed?\n *\n * @param event - Event to check\n */\nexport function isCopyKey(event: KeyboardEvent | MouseEvent): boolean {\n  return browser.platform === 'mac' ? event.altKey : event.ctrlKey;\n}\n\n/** @deprecated Use getBrowser() instead, available since WH5.6.3. We will remove `browser` in the future to improve tree shaking */\nexport const browser: Readonly<UserAgentInfo> = Object.freeze(parseUserAgent(globalThis.navigator?.userAgent || \"\"));\n\n/** Get browser information */\nexport function getBrowser(): Readonly<UserAgentInfo> {\n  //Offer this as a function to improve treeshakability\n  return browser;\n}\n\n//CSS Query used to find valid submittors\nexport const submitselector = 'input[type=submit],input[type=image],button[type=submit],button:not([type])';\n//Must match possible types returned by the submitselector\nexport type SubmitSelectorType = HTMLInputElement | HTMLButtonElement;\n","import { isHTMLElement } from \"@webhare/dompack\";\nimport type { CMSConfig } from \"@mod-system/js/internal/generation/gen_misc_ts\";\n\nlet config: CMSConfig | undefined;\n\nfunction forwardPublisherNavigation(event: Event) {\n  /* we watch for clicks.. as we only want to update the Publisher's selection for user triggered actions (otherwise we'd\n     start navigation in response to JS or internal link autoredirects) */\n  if (!isHTMLElement(event.target) || !config?.interfaceServers)\n    return;\n\n  const navaction = event.target.closest<HTMLAnchorElement>('a[href]');\n  if (!navaction)\n    return;\n\n  const desturl = navaction.href;\n  if (desturl.split('#')[0] !== location.href.split('#')[0]) { //it's actual navigation...\n    for (const origin of config.interfaceServers) {\n      try {\n        window.top?.postMessage({ type: \"webhare-navigation\", location: desturl }, origin);\n      } catch (ignore) {\n        //ignore crossdomain errors\n      }\n    }\n  }\n}\n\nasync function configureForCMS() {\n  try {\n    const res = await fetch(\"/.wh/ea/config/cms.json\");\n    config = await res.json();\n  } catch (e) {\n    console.log(\"Failed to get CMS configuration\", e);\n    return;\n  }\n  window.addEventListener(\"click\", forwardPublisherNavigation);\n}\n\nif (typeof window !== \"undefined\" && window !== window.top) { //if we're in an iframe, we may be running in WebHare and need to forward navigation events\n  //we have no way to detect whether we're in a WebHare iframe or a 3rd party iframe. assume it's webhare and grab the interface servers\n  void configureForCMS();\n}\n","// The dot lattice behind the page-base login (shell.witty, loginscreen): a slow diagonal wave raises the dots' size and\n// brightness in the brand's login_pattern color. Plain-TS port of the SPA's LoginBackground.vue, same shader.\n// data-state on the canvas tells what it does: running, paused (tab hidden), still (reduced motion) or unsupported (no WebGL).\n\nconst VERTEX = \"attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }\";\nconst FRAGMENT = `\nprecision highp float;\nuniform vec2 resolution;\nuniform float time;\nuniform vec3 pattern;\nfloat hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\nfloat noise(vec2 p) {\n  vec2 i = floor(p), f = fract(p);\n  vec2 u = f * f * (3.0 - 2.0 * f);\n  return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);\n}\nvoid main() {\n  float cell = 22.0 * (resolution.y / 900.0) + 10.0;\n  vec2 p = gl_FragCoord.xy / cell;\n  vec2 id = floor(p), f = fract(p) - 0.5;\n  vec2 uv = id * cell / resolution.y;\n  float wave = sin(uv.x * 3.0 + uv.y * 1.6 - time * 0.35) * 0.5 + 0.5;\n  float ripple = noise(uv * 3.0 + time * 0.05);\n  float level = pow(wave, 4.0) * 0.8 + ripple * 0.2;\n  float r = mix(0.06, 0.16, level);\n  float dot = 1.0 - smoothstep(r - 0.03, r, length(f));\n  vec3 c = mix(vec3(0.16), pattern, level) * dot * mix(0.35, 1.0, level);\n  gl_FragColor = vec4(c, 1.0);\n}`;\n\nfunction hexToRgb(color: string): [number, number, number] {\n  // shell.ts always passes the brand's normalized #rrggbb\n  return [1, 3, 5].map(i => Number.parseInt(color.slice(i, i + 2), 16) / 255) as [number, number, number];\n}\n\nfunction start(el: HTMLCanvasElement): void {\n  const gl = el.getContext(\"webgl\", { antialias: false, alpha: false });\n  if (!gl) {\n    el.dataset.state = \"unsupported\"; // the screen stays plain ink\n    return;\n  }\n\n  const compile = (type: number, source: string) => {\n    const shader = gl.createShader(type);\n    if (!shader)\n      throw new Error(\"Could not create a shader\");\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))\n      throw new Error(`Login background shader failed: ${gl.getShaderInfoLog(shader)}`);\n    return shader;\n  };\n  const program = gl.createProgram();\n  if (!program)\n    throw new Error(\"Could not create a shader program\");\n  gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n  gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\n  gl.linkProgram(program);\n  gl.useProgram(program);\n\n  // One triangle that covers the whole viewport\n  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n  const position = gl.getAttribLocation(program, \"p\");\n  gl.enableVertexAttribArray(position);\n  gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n\n  const resolution = gl.getUniformLocation(program, \"resolution\");\n  const time = gl.getUniformLocation(program, \"time\");\n  gl.uniform3fv(gl.getUniformLocation(program, \"pattern\"), hexToRgb(el.dataset.pattern ?? \"\"));\n\n  const still = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  const startedAt = performance.now();\n  let frame = 0;\n\n  const draw = (now: number) => {\n    gl.uniform2f(resolution, el.width, el.height);\n    // Start mid-wave, so a reduced-motion still frame shows the pattern and not a blank lattice.\n    gl.uniform1f(time, still ? 20 : (now - startedAt) / 1000 + 20);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n  };\n  const loop = (now: number) => {\n    draw(now);\n    frame = requestAnimationFrame(loop);\n  };\n  const resize = () => {\n    const ratio = Math.min(devicePixelRatio, 2);\n    el.width = Math.max(1, Math.round(el.clientWidth * ratio));\n    el.height = Math.max(1, Math.round(el.clientHeight * ratio));\n    gl.viewport(0, 0, el.width, el.height);\n    if (still)\n      draw(performance.now());\n  };\n  const onVisibility = () => {\n    cancelAnimationFrame(frame);\n    if (still)\n      return;\n    const visible = document.visibilityState === \"visible\";\n    if (visible)\n      frame = requestAnimationFrame(loop);\n    el.dataset.state = visible ? \"running\" : \"paused\";\n  };\n\n  new ResizeObserver(resize).observe(el);\n  resize();\n  if (still) {\n    draw(performance.now());\n    el.dataset.state = \"still\";\n  }\n  document.addEventListener(\"visibilitychange\", onVisibility);\n  onVisibility();\n}\n\n// Module scripts run after parsing, so the canvas is there on the login page; every other page skips this.\nconst canvas = document.querySelector<HTMLCanvasElement>(\"canvas[data-companyos-login-background]\");\nif (canvas)\n  start(canvas);\n","// Password login on a regular page (login.witty): WRDAuth's setupWRDAuth submits the form, this only shows its refusal.\nimport \"./tokens.scss\";\nimport \"./login.scss\";\nimport \"./login-background\";\n\n// Unknown account and wrong password read the same, so the form does not reveal which addresses exist.\nconst MESSAGES: Partial<Record<string, string>> = {\n  \"incorrect-login-password\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"incorrect-email-password\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"unknown-account\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"account-disabled\": \"Dit account is uitgeschakeld.\",\n  // The CompanyOS login customizer refuses accounts without the site login right with this code.\n  \"internal-error\": \"Dit account heeft geen toegang.\",\n};\n\naddEventListener(\"wh:wrdauth-loginfailed\", event => {\n  const form = event.target instanceof Element ? event.target.closest<HTMLFormElement>(\".companyos-login__form\") : null;\n  const error = form?.querySelector<HTMLElement>(\"[data-companyos-login-error]\");\n  if (!form || !error)\n    return;\n  event.preventDefault();\n  error.textContent = MESSAGES[(event as CustomEvent<{ code?: string }>).detail?.code ?? \"\"] ?? \"Inloggen is niet gelukt. Probeer het opnieuw.\";\n  error.hidden = false;\n  for (const input of form.querySelectorAll(\"input.companyos-login__input\"))\n    input.setAttribute(\"aria-invalid\", \"true\");\n  form.querySelector<HTMLInputElement>(\"[name=password]\")?.focus();\n});\n\n// Development test logins (`testlogins` in login.witty): fill the real form and let WRDAuth submit it, as the SPA does.\naddEventListener(\"click\", event => {\n  const button = event.target instanceof Element ? event.target.closest<HTMLButtonElement>(\".companyos-login__testlogin\") : null;\n  const form = button?.closest(\".companyos-login\")?.querySelector<HTMLFormElement>(\".companyos-login__form\");\n  if (!button || !form)\n    return;\n  form.querySelector<HTMLInputElement>(\"[name=login]\")!.value = button.dataset.login ?? \"\";\n  form.querySelector<HTMLInputElement>(\"[name=password]\")!.value = button.dataset.password ?? \"\";\n  form.requestSubmit();\n});\n\naddEventListener(\"input\", event => {\n  const form = event.target instanceof Element ? event.target.closest<HTMLFormElement>(\".companyos-login__form\") : null;\n  if (!form)\n    return;\n  form.querySelector<HTMLElement>(\"[data-companyos-login-error]\")!.hidden = true;\n  for (const input of form.querySelectorAll(\"input.companyos-login__input\"))\n    input.removeAttribute(\"aria-invalid\");\n});\n","import { register } from \"dompack\";\n\n// WebHare renders array add/delete controls as empty <span>s (publisher/lib/internal/forms/rendering.whlib): no role,\n// no label and no keyboard access. Until the platform renders buttons, give them those here. The platform's own click\n// handler stays in charge of adding and removing rows.\nregister<HTMLElement>(\".wh-form__arrayadd, .wh-form__arraydelete\", node => {\n  node.setAttribute(\"role\", \"button\");\n  node.tabIndex = 0;\n  node.addEventListener(\"keydown\", event => {\n    if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      node.click();\n    }\n  });\n});\n","var UNKNOWN_FUNCTION = '<unknown>';\n/**\n * This parses the different stack traces and puts them into one format\n * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)\n */\n\nfunction parse(stackString) {\n  var lines = stackString.split('\\n');\n  return lines.reduce(function (stack, line) {\n    var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);\n\n    if (parseResult) {\n      stack.push(parseResult);\n    }\n\n    return stack;\n  }, []);\n}\nvar chromeRe = /^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nvar chromeEvalRe = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nfunction parseChrome(line) {\n  var parts = chromeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n  var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n  var submatch = chromeEvalRe.exec(parts[2]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line/column number\n    parts[2] = submatch[1]; // url\n\n    parts[3] = submatch[2]; // line\n\n    parts[4] = submatch[3]; // column\n  }\n\n  return {\n    file: !isNative ? parts[2] : null,\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: isNative ? [parts[2]] : [],\n    lineNumber: parts[3] ? +parts[3] : null,\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar winjsRe = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseWinjs(line) {\n  var parts = winjsRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar geckoRe = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar geckoEvalRe = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nfunction parseGecko(line) {\n  var parts = geckoRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n  var submatch = geckoEvalRe.exec(parts[3]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line number\n    parts[3] = submatch[1];\n    parts[4] = submatch[2];\n    parts[5] = null; // no column when eval\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: parts[2] ? parts[2].split(',') : [],\n    lineNumber: parts[4] ? +parts[4] : null,\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar javaScriptCoreRe = /^\\s*(?:([^@]*)(?:\\((.*?)\\))?@)?(\\S.*?):(\\d+)(?::(\\d+))?\\s*$/i;\n\nfunction parseJSC(line) {\n  var parts = javaScriptCoreRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[4],\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar nodeRe = /^\\s*at (?:((?:\\[object object\\])?[^\\\\/]+(?: \\[as \\S+\\])?) )?\\(?(.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseNode(line) {\n  var parts = nodeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nexport { parse };\n","import * as stacktrace_parser from \"stacktrace-parser\";\n\nexport type StackTraceItem = {\n  filename: string;\n  line: number;\n  col: number;\n  func: string;\n};\n\nexport type StackTrace = StackTraceItem[];\n\nexport function parseTrace(e: Error): StackTrace {\n  if (!e?.stack)\n    return [];\n\n  const trace = stacktrace_parser.parse(e.stack);\n  return trace.map(i => ({ filename: i.file || \"\", line: i.lineNumber || 1, col: i.column || 1, func: (i.methodName || \"\") }));\n}\n\nexport function getStackTrace(): StackTrace {\n  return parseTrace(new Error()).slice(1);\n}\n\nexport function formatTrace(trace: StackTraceItem[]): string {\n  return trace.map(e =>\n    `    at ${e.func} (${e.filename}:${e.line}:${e.col})`).join(\"\\n\");\n}\n\nexport function prependStackTrace(error: Error, trace: StackTrace) {\n  if (!error.stack)\n    return; //no stack to manipulate\n\n  const stacklines = error.stack?.split(\"\\n\") || [];\n  const tracelines = formatTrace(trace);\n  error.stack = (stacklines[0] ? stacklines[0] + \"\\n\" : \"\") + tracelines + '\\n' + (stacklines.slice(1).join(\"\\n\"));\n  return error;\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/rpc\" {\n  export interface KnownRPCServices {\n    /* Filled by generated services.ts files */\n  }\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyFunctionReturnType } from \"@webhare/js-api-tools\";\nimport { omit, parseTyped, stringify } from \"@webhare/std\";\n\n//Preload interface definitions. To solve this cleaner we would have to do some sort of auto-inject but how to robustly do that accross IDEs/Tscs ?\n\n//@ts-ignore Ignore if it doesn't exist\nimport type { } from \"@mod-platform/generated/ts/services.ts\";\n//@ts-ignore Ignore if it doesn't exist\nimport type { } from \"wh:ts/services.ts\";\n\nfunction isAbsolute(url: string) {\n  return url.startsWith(\"http:\") || url.startsWith(\"https:\");\n}\n\nfunction getBaseURL() {\n  if (!backendBase)\n    throw new Error(`You must set the baseUrl option when using the RPC Client outside Webhare`);\n  return isAbsolute(backendBase) ? backendBase : new URL(backendBase, location.origin);\n}\n\nexport interface RPCClientOptions {\n  /** Custom request update. Use to eg. set keepalive or add debug variables to the URL */\n  onBeforeRequest?: (url: URL, requestInit: RequestInit & { headers: Headers }) => void;\n  /** Response callback. Use this if you need to capture details on the incoming respones. May be invoked multiple times per request, eg due to 429 errors! */\n  onResponse?: (response: Response) => void;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n}\n\n/** RPC Response format */\nexport type RPCResponse = ({\n  /** Result. Not present if the function didn't return anything */\n  result?: unknown;\n} | {\n  /** Error message */\n  error: string;\n  /** Captured stack trace (if 'etr' debugFlag is set) */\n  trace?: StackTrace;\n}) & {\n  /** Captured console log entries (if 'etr' debugFlag is set) */\n  consoleLog?: Array<{\n    //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n    /** Date when console function was called */\n    when: string;\n    /** `console` method that was called (eg 'log') */\n    method: string;\n    /** Logged data */\n    data: string;\n    /** Location of caller */\n    location?: {\n      filename: string;\n      line: number;\n      col: number;\n      func: string;\n    };\n    /** Codecontext */\n    codeContextId?: string;\n  }>;\n};\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCClientOptions;\n  abortcontroller?: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, options: RPCClientOptions, callurl: URL, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    if (options.timeout || options.signal) {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl.toString();\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller?.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller?.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, fetchpromise: Promise<Response>) {\n    let response;\n    for (; ;) { //loop to handle \"429 Conflict\"s\n      try { //we should only guard the fetch call and specifically *not* the onResponse callback\n        response = await fetchpromise;\n      } catch (exception) {\n        if (this.client.debug)\n          console.log(`[rpc] Exception invoking '${method}'`, exception);\n\n        if (this.aborted)\n          throw new Error(`RPC Aborted`);\n        else if (this.timedout)\n          throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n        else\n          throw new Error(`RPC Failed: exception: ` + exception);\n      }\n\n      this.options.onResponse?.(response); //allow hooks to capture headers\n\n      if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n        const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n        if (this.client.debug)\n          console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n        await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n        fetchpromise = fetch(this._callurl, this._fetchoptions);\n        continue;\n      }\n      break;\n    }\n\n    let jsonresponse: RPCResponse;\n    try {\n      jsonresponse = parseTyped(await response.text());\n      if (jsonresponse.consoleLog) {\n        for (const logitem of jsonresponse.consoleLog) {\n          //should we log 'when'? it's getting more and more noisy then though....\n          //TODO should we match the remote's method (after validating) or just keep everything at 'log' ?\n          console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n        }\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] Received response to '${method}'`, omit(jsonresponse, [\"consoleLog\", \"trace\"]));\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] Response was not valid JSON`, exception);\n      throw new Error(\"RPC Failed: Invalid response received\", { cause: exception });\n    }\n\n    if (\"error\" in jsonresponse) {\n      const err = new Error(`RPC Error: ${jsonresponse.error}`);\n      if (jsonresponse.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (this.options.debug) {\n        console.group();\n        console.warn(\"RPC failed:\", err);\n        if (requestStack) {\n          console.warn(\"Stack at calling point\");\n          console.log(requestStack);\n        }\n        console.groupEnd();\n      }\n\n      throw err;\n    }\n\n    return jsonresponse.result;\n  }\n}\n\nclass RPCClient {\n  readonly url: string;\n  options: RPCClientOptions;\n\n  constructor(url: string, options?: RPCClientOptions) {\n    this.url = url;\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    //We'll delay the baseurl calculation until the first call to allow for the backendBase to be set up\n    const callurl = isAbsolute(this.url) ? new URL(this.url + method) : new URL(this.url + method, this.options.baseUrl || getBaseURL());\n\n    let requestStack: StackTrace | null = null;\n\n    const fetchoptions: RequestInit & { headers: Headers } = {\n      method: \"POST\",\n      headers: new Headers({\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      }),\n      body: stringify(params, { typed: true }),\n    };\n\n    if (typeof location !== \"undefined\")\n      callurl.searchParams.set(\"pathname\", location.pathname);\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] Invoking '${method}'`, params);\n    }\n\n    this.options.onBeforeRequest?.(callurl, fetchoptions);\n    return new ControlledCall(this, method, requestStack, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCClientOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<Service extends keyof KnownRPCServices | object> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if ([\"then\", \"catch\", \"finally\"].includes(prop)) //do not appear like our object is a promise\n      return undefined;\n\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCClientOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return rpc(this.client.url as (Service extends keyof KnownRPCServices ? Service : string), newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\ntype OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;\n\nexport type OmitRPCContextArgs<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? OmitFirstArg<ServiceType[K]> : never;\n};\n\n/** Creates an async version of the functions in a class, removes context parameters\n * @typeParam ServiceType - Type definition of the service class that implements this service.\n*/\ntype ConvertToRPCInterface<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- using any is needed for this type definition\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? PromisifyFunctionReturnType<ServiceType[K]> : never;\n};\n\ntype ExtractInterface<Service extends object> = ConvertToRPCInterface<Service> & ServiceBase<ConvertToRPCInterface<Service>>;\n\n/** Get the client interface type as would be returned by createClient\n * @typeParam Service - either the `module:service` name or the interface to implement. If you want to pass the implementation's type you should wrap it into `OmitRPCContextArgs`.\n*/\nexport type GetRPCClientInterface<Service extends (keyof KnownRPCServices) | object> = Service extends keyof KnownRPCServices ? ExtractInterface<OmitRPCContextArgs<KnownRPCServices[Service]>> : Service extends object ? ExtractInterface<Service> : never;\n\n/** Create a WebHare RPC client\n  @param service - URL (https://<ORIGIN>/.wh/rpc/module/service/) or service name (module:service) to invoke\n*/\nexport function rpc<Service extends keyof KnownRPCServices>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\n\nexport function rpc<Service extends keyof KnownRPCServices | object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service> {\n  //NOTE: needed the separate overloads to get Intellisense to list the known services for createRPClient's first argument\n\n  if (!service)\n    throw new Error(`You must specify either a WebHare rpcService name or a full URL`);\n\n  const servicematch = service.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n  if (servicematch)\n    service = `/.wh/rpc/${servicematch[1]}/${servicematch[2]}/` as (Service extends keyof KnownRPCServices ? Service : string);\n  else if (!service.endsWith('/'))\n    throw new Error(`Service URL must end in a slash`);\n\n  const rpcclient = new RPCClient(service, options);\n  return new Proxy({}, new ServiceProxy<GetRPCClientInterface<Service>>(rpcclient)) as GetRPCClientInterface<Service>;\n}\n","import type { NavigateInstruction } from \"@webhare/env\";\n\n/** Login failure reasons that can also be used by custom isLoginDenied checks */\nexport type LoginErrorCode = \"internal-error\" | \"incorrect-login-password\" | \"incorrect-email-password\" | \"account-disabled\" | \"unknown-account\" | \"require-external-login\";\n\n/** Login reasons that require further client side work but are not errors per-se */\nexport type LoginIncompleteCode = \"totp\" | \"incomplete-account\";\n\nexport type LoginTweaks = {\n  /** Limit session duration (development servers only) */\n  limitExpiry?: number;\n  /** Language code */\n  lang?: string;\n};\n\nexport type LoginResult = {\n  loggedIn: boolean;\n  navigateTo: NavigateInstruction;\n} | {\n  loggedIn: false;\n  code: LoginErrorCode;\n  error?: string;\n};\n\nexport type LogoutResult = { success: true } | {\n  error: string;\n  code: LoginErrorCode | LoginIncompleteCode;\n};\n\nexport const PublicCookieSuffix = \"_publicauthdata\";\n\n/* APIs and types shared between the client and server */\nexport function getCompleteAccountNavigation(token: string, pathname: string): NavigateInstruction {\n  return {\n    type: \"redirect\", //TODO or use a \"form\" too? went for a session now as an excursion to followup GET pages is much more likely in this procedure than with totp\n    url: \"/.wh/common/authpages/?wrd_pwdaction=completeaccount&token=\" + encodeURIComponent(token || '') + \"&pathname=\" + encodeURIComponent(pathname)\n  };\n}\n","import { createClient } from \"@webhare/jsonrpc-client\";\nimport { type NavigateInstruction, navigateTo } from \"@webhare/env\";\nimport * as dompack from '@webhare/dompack';\nimport type { LoginOptions } from \"@webhare/auth/src/identity\";\nimport { rpc } from \"@webhare/rpc/src/rpc\";\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { getFrontendData } from '@webhare/frontend/src/init';\nimport { PublicCookieSuffix, type LoginErrorCode, type LoginResult, type LoginTweaks } from \"@webhare/auth/src/shared\";\nimport { parseTyped } from \"@webhare/std\";\nimport type WRDAuthenticationProvider from \"@mod-wrd/js/auth\";\n\n/** WRDAuth configuration */\nexport interface WRDAuthOptions {\n  /** Callback that is invoked after a succesful login. If not set the page will be reloaded. */\n  onLogin?: () => Promise<void> | void;\n}\n\nexport interface PublicAuthData {\n  expiresMs: number;\n  userInfo?: object | null;\n  persistent?: boolean;\n}\n\ndeclare module \"@webhare/frontend\" {\n  interface FrontendDataTypes {\n    \"wrd:auth\": {\n      /** WRDAuth cookiename (used to store userinfo and expiry) */\n      cookiename: string;\n    };\n  }\n}\n\ndeclare global {\n  interface Window {\n    $wh$legacyAuthProvider: WRDAuthenticationProvider;\n    triggerWebHareSSO?: (tag: string, options?: SSOLoginOptions) => Promise<void>;\n  }\n}\n\n/** Current authoptions. undefined if setupWRDAuth hasn't been invoked yet */\nlet authOptions: WRDAuthOptions | undefined;\n\n/** Get current login cookie. If empty, wrdauth is not initialized here */\nfunction getCookieName(): string | null {\n  const settings = getFrontendData(\"wrd:auth\", { allowMissing: true });\n  return settings?.cookiename || null;\n}\n\nfunction getAuthLocalData(): PublicAuthData | null {\n  const c = getCookieName();\n  if (!c)\n    return null;\n\n  try {\n    return parseTyped(dompack.getCookie(c + PublicCookieSuffix)!) as PublicAuthData;\n  } catch {\n    return null;\n  }\n}\n\nasync function submitLoginForm(node: HTMLFormElement, event: SubmitEvent) {\n  if (node.propWhFormhandler)\n    return; //already handled by publisher forms so we'll defer to that\n  dompack.stop(event);\n\n  const username = (node.elements.namedItem(\"login\") as HTMLInputElement)?.value;\n  const password = (node.elements.namedItem(\"password\") as HTMLInputElement)?.value;\n  const site = (node.elements.namedItem(\"site\") as HTMLInputElement)?.value || undefined;\n  const returnto = (node.elements.namedItem(\"returnto\") as HTMLInputElement)?.value || undefined;\n  const persistentlogin = (node.elements.namedItem(\"persistent\") as HTMLInputElement)?.checked;\n  if (!login || !password)\n    throw new Error(`submitLoginForm: required elements login/password not set or missing`);\n\n  using lock = dompack.flagUIBusy({ modal: true });\n  void (lock);\n\n  const loginresult = await login(username, password, {\n    persistent: persistentlogin,\n    site,\n    returnTo: returnto ? new URL(returnto, location.href).toString() : location.href.split('#')[0]\n  });\n  if (loginresult.loggedIn) {\n    refreshLoginStatus();\n    if (loginresult.navigateTo.type === \"redirect\" && loginresult.navigateTo.url.split('#')[0] === location.href.split('#')[0]  //stay on same page\n      && authOptions?.onLogin) {\n\n      if (loginresult.navigateTo.url.includes('#')) //execute any #hash instruction\n        history.replaceState(null, \"\", loginresult.navigateTo.url.substring(loginresult.navigateTo.url.indexOf('#')));\n\n      await authOptions.onLogin();\n    } else {\n      //Reload the page to get the new login status - TODO put this behind a 'login state change' event and allow users to cancel it if they can deal with login/logout on-page\n      console.log(\"Post login redirect\", loginresult.navigateTo);\n      navigateTo(loginresult.navigateTo);\n    }\n  } else if (\"navigateTo\" in loginresult) {\n    console.log(\"Login incomplete, redirecting to\", loginresult.navigateTo);\n    navigateTo(loginresult.navigateTo);\n  } else\n    failLogin(loginresult.error ?? loginresult.code, { code: loginresult.code, data: \"\" }, node); //FIXME restore the code & data members from old wrdauth\n}\n\nfunction refreshLoginStatus() {\n  const loggedIn = isLoggedIn();\n  document.documentElement.classList.toggle(\"wh-wrdauth--isloggedin\", loggedIn);\n\n  window.$wh$legacyAuthProvider?.refresh();\n}\n\n/** Return whether a user's currently logged in */\nexport function isLoggedIn(): boolean {\n  return (getAuthLocalData()?.expiresMs || 0) > Date.now();\n}\n\n/** Setup WRDAuth frontend integration */\nexport function setupWRDAuth(options?: WRDAuthOptions) {\n  if (authOptions)\n    throw new Error(`Duplicate setupWRDAuth call`);\n\n  authOptions = { ...options };\n\n  dompack.register<HTMLFormElement>('form.wh-wrdauth__loginform,form.wh-wrdauth-login__form', node => {\n    node.setAttribute(\"data-wh-wrdauth-attached\", \"\");\n    dompack.addDocEventListener(node, \"submit\", evt => submitLoginForm(node, evt));\n  });\n  dompack.register('.wh-wrdauth__logout', node => {\n    function handleLogoutClick(event: Event) {\n      dompack.stop(event);\n\n      //letting rejections escape - our trigger is generally setup in HTML so there's nothing to catch but uncaught rejection handlers anyway\n      if (node instanceof HTMLAnchorElement && node.href && node.href.split('#')[0] !== location.href.split('#')[0]) { //logout link sending you elsewhere\n        void doLogout().then(() => {\n          console.log(\"Logout complete, redirecting to\", node.href);\n          navigateTo({ type: \"redirect\", url: node.href });\n        });\n      } else {\n        void logout(); //TODO what if the logout only changed the anchor? but what's the usecase for that?\n      }\n    }\n\n    dompack.addDocEventListener(node, \"click\", event => handleLogoutClick(event));\n  });\n\n  dompack.onDomReady(() => {\n    if (\"$wh$wrdauth\" in window) {\n      console.error(\"Both setupWRDAuth from @webhare/frontend and @mod-wrd/js/auth are present in this page. Mixing these is not supported!\");\n    }\n  });\n\n  refreshLoginStatus();\n}\n\nfunction failLogin(message: string, response: { code: LoginErrorCode; data: string }, form: HTMLFormElement) {\n  const evtdetail = {\n    message: message,\n    code: response.code,\n    data: response.data\n  };\n\n  const cancelled = !dompack.dispatchCustomEvent(form || document.documentElement, \"wh:wrdauth-loginfailed\", { bubbles: true, cancelable: true, detail: evtdetail });\n  if (!cancelled) {\n    //TODO depending on error we may need to change a different field?\n    const loginfield = dompack.qR<HTMLInputElement>(form, \"input[name=password]\");\n    loginfield.setCustomValidity(message);\n    // loginfield.reportValidity(); //this actually blocks wh-form error handling from showing the error in-page when so desired\n    loginfield.focus();\n  }\n}\n\n/** Retrieve userinfo if set by onFrontendUserInfo in your WRDAuth customizer */\nexport function getUserInfo<T extends object = object>(): T | null {\n  return isLoggedIn() ? getAuthLocalData()?.userInfo as T | null : null;\n}\n\nfunction getLoginTweaks(): LoginTweaks {\n  const tweaks: LoginTweaks = {};\n\n  const urlvars = new URL(location.href);\n  if (urlvars.searchParams.has(\"wrdauth_limit_expiry\"))\n    tweaks.limitExpiry = parseInt(urlvars.searchParams.get(\"wrdauth_limit_expiry\") || '0') || undefined;\n\n  const lang = document.documentElement.getAttribute(\"lang\");\n  if (lang)\n    tweaks.lang = lang;\n\n  return tweaks;\n}\n\n/** Implements the common username/password flows */\nexport async function login(username: string, password: string, options: LoginOptions = {}): Promise<LoginResult> {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  const result = await rpc(\"platform:authservice\").login(username, password, cookieName, dompack.getBrowser().triplet, { ...options, ...getLoginTweaks() });\n  if (result.loggedIn && !getAuthLocalData())\n    throw new Error(\"Login succeeded but no auth data was set in the cookie\");\n\n  return result;\n}\n\n/** Execute and verify cookie clearance to prepare for logging out */\nasync function doLogout() {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  await rpc(\"platform:authservice\").logout(cookieName, dompack.getBrowser().triplet);\n\n  if (getAuthLocalData())\n    throw new Error(\"Logged out but we still have auth data in the cookie\");\n}\n\n/** Logout the current user */\nexport async function logout() {\n  await doLogout();\n  console.log(\"Reloading to process the new logged out status\");\n  navigateTo({ type: \"reload\" }); //TODO put this behind a 'login state change' event\n}\n\nexport interface MyService {\n  startLogin2(urlpath: string, tag: string, options: { passive?: boolean }): Promise<NavigateInstruction>;\n}\n\ninterface SSOLoginOptions {\n  passive?: boolean;\n}\n\nexport async function startSSOLogin(tag: string, options?: SSOLoginOptions): Promise<void> {\n  const client = createClient<MyService>(\"wrd:auth\");\n\n  //Launch SSO login for the current page.\n  //TODO also pass getLoginTweaks() at least to OIDC logins as soon as we've ported this to authservice\n  navigateTo(await client.startLogin2(location.pathname + location.search + location.hash, tag, { passive: options?.passive }));\n}\n\n/** Configure WebHare external auth buttons (even hidden ones) to listen for bookmarklet login requests */\nexport function setupWebHareSSOTrigger(): void {\n  window.triggerWebHareSSO = startSSOLogin;\n}\n","import { qSA } from \"@webhare/dompack\";\nimport { debugFlags } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { DataLayerEntry } from \"./gtm-types\";\n\ndeclare global {\n  interface Window {\n    dataLayer: DataLayerEntry[];\n  }\n}\n\n//ADDME if we ever figure out a bundler trick to flush this command to the top of all imports/loads, that would be great (we could consider *ALWAYS* putting this in the generated startup code, or we'd need to do a tree pre-walk to see if gtm.es is loaded anywhere)\nwindow.dataLayer ||= [];\nlet lastSeen: DataLayerEntry | undefined;\n\nfunction showDataLayerUpdates() {\n  if (typeof window.dataLayer === 'undefined')\n    return; //not set up (yet?)\n\n  if (debugFlags.anl)\n    window.dataLayer.slice(window.dataLayer.indexOf(lastSeen!) + 1).forEach(entry => console.log(\"[anl] dataLayer.push:\", entry));\n\n  lastSeen = window.dataLayer[window.dataLayer.length - 1];\n}\n\n/** Push to the dataLayer\n * @param vars - The variables to push\n * @param options - Options for the push\n *   timeout Time before any eventCallback is forcibly called (default 200ms)\n*/\nexport function pushToDataLayer(vars: DataLayerEntry, options?: { timeout?: number }) {\n  if (vars.eventCallback) { //we'll wrap the callback into a promise to ensure it's only invoked once\n    const savecallback = vars.eventCallback;\n    let newcallback: () => void;\n    void (new Promise<void>(resolve => newcallback = resolve)).then(() => savecallback());\n    setTimeout(() => newcallback, options?.timeout || 200);\n  }\n\n  window.dataLayer.push(vars);\n  showDataLayerUpdates();\n}\n\nfunction collectFormValues(formnode: HTMLFormElement): Record<string, unknown> {\n  const donefields: Record<string, boolean> = {};\n  const outdata: Record<string, unknown> = {};\n\n  const multifields = qSA<HTMLInputElement>(formnode, 'input[type=radio], input[type=checkbox]');\n  for (const multifield of multifields) {\n    if (!multifield.name || donefields[multifield.name])\n      continue; //we did this one\n\n    donefields[multifield.name] = true;\n\n    let idx = 0;\n    const values = [];\n    const labels = [];\n    const checkboxes = multifields.filter(node => node.name === multifield.name);\n\n    for (const node of checkboxes.filter(cbox => cbox.checked)) {\n      const keyname = 'form_' + multifield.name + (idx ? '_' + idx : '');\n      let labelsfornode = node.dataset.gtmTag || qSA(`label[for=\"${CSS.escape(node.id)}\"]`).map(labelnode => labelnode.textContent).filter(labelnode => Boolean(labelnode)).join(' ');\n      labelsfornode = labelsfornode.trim(); //TODO normalize whitespace\n      outdata[keyname] = node.value;\n      outdata[keyname + '_label'] = labelsfornode;\n\n      ++idx;\n      values.push(node.value);\n      labels.push(labelsfornode);\n    }\n\n    if (values.length) {\n      const allkeyname = 'form_' + multifield.name + '_all';\n      outdata[allkeyname] = values.join(';');\n      outdata[allkeyname + '_label'] = labels.join(';');\n    }\n  }\n\n  for (const field of formnode.querySelectorAll<HTMLSelectElement | HTMLInputElement>('input:not([type=radio]):not([type=checkbox]),select,textarea')) {\n    if (!field.name || donefields[field.name])\n      continue;\n\n    donefields[field.name] = true;\n\n    const val = field.value;\n    outdata['form_' + field.name] = val;\n    if (field.matches('select')) {\n      const opt = (field as HTMLSelectElement).options[(field as HTMLSelectElement).selectedIndex];\n      if (opt)\n        outdata['form_' + field.name + '_label'] = opt.dataset.gtmTag || opt.textContent;\n    }\n  }\n  return outdata;\n}\n\n/** Setup the dataLayer */\nlet didinit: boolean | undefined;\nexport function setupGTM() {\n  if (!didinit) {\n    didinit = true;\n    if (debugFlags.anl)\n      setInterval(showDataLayerUpdates, 100);\n  }\n}\n\n/** Setup dataLayer events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `wh-platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalyticsForGTM(options?: { eventPrefix: string }): void {\n  setupGTM(); //ensurse the GTM basics are installed\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    //we use the same prefixing as pxl events would\n    const entry: DataLayerEntry = {\n      event: `${options?.eventPrefix || \"platform:form_\"}${e.detail.event}`\n    };\n\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        entry[`formmeta_${key}`] = val;\n\n    const form = e.target as HTMLFormElement | undefined;\n    if (form?.dataset.gtmSubmit) {\n      //When set, we push both the form: variable in gtmSubmit and the current form field avlues\n      Object.assign(entry, JSON.parse(form.dataset.gtmSubmit));\n      Object.assign(entry, collectFormValues(form));\n    }\n\n    pushToDataLayer(entry);\n  });\n}\n\nfunction processClickDataLayerTags(event: MouseEvent) {\n  const entry: Record<string, unknown> = {};\n\n  for (let node = event.target as HTMLElement | undefined | null; node; node = node?.parentElement)\n    for (const attr of node.attributes)\n      if (attr.nodeName.startsWith(\"data-wh-datalayer-onclick-\")) {\n        const key = attr.nodeName.substring(26);\n        if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n          entry[key] = attr.nodeValue || \"\";\n      } else if (attr.nodeName === \"data-wh-datalayer-onclick\") { //JSON setter\n        const data = JSON.parse(attr.nodeValue!);\n        for (const [key, value] of Object.entries(data))\n          if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n            entry[key] = value;\n      }\n\n  if (Object.keys(entry).length)\n    pushToDataLayer(entry as DataLayerEntry);\n}\n\n/** Setup support for data-wh-datalayer-onclick-xxx=\"yyy\" attributes. When clicking an element with these attributes the JSON from the attribute and all parents are merged together and pushed to the dataLayer  */\nexport function setupDataLayerTags() {\n  //we capture so we can also simply set variables for any existing GTM handlers\n  window.addEventListener(\"click\", processClickDataLayerTags, { capture: true });\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/frontend\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/frontend\" {\n}\n\nimport { onDomReady } from \"@webhare/dompack\";\nimport \"../styling/reset.css\"; // Reset CSS - this will be dropped somewhere post WH5.6!\nexport { frontendConfig, getFrontendData, getSiteRoot } from \"./init\";\nexport { startSSOLogin, login, setupWRDAuth, isLoggedIn, logout, getUserInfo, setupWebHareSSOTrigger } from \"./auth\";\nexport { loadAssetPack, setupAuthorMode, type AuthorModeOptions } from \"./authormode\";\nexport { setPxlOptions, sendPxl, getPxlUserId, getPxlSessionId, setupFormAnalytics, type PxlData } from \"./pxl\";\nexport { getRemoteIPAddress, getGeoIPInfo, type GetIPInfoOptions, type GeoIPInfoResult } from \"./analytics\";\nexport { setupGTM, setupFormAnalyticsForGTM, pushToDataLayer, setupDataLayerTags } from \"./gtm\";\nexport { setupLinksInNewWindow, type LinkOpenOptions } from \"./linkhandler\";\n\nexport type * from \"./gtm-types\";\n\n// we shouldn't deprecate navigateTo exported from frontend. in fact it makes more sense to export it from frontend than env as it's browser-only\nexport { navigateTo } from \"@webhare/env\";\n\n/** Registry for data we receive from the backend */\nexport interface FrontendDataTypes {\n}\n\n/** Registry for expected PXL formats */\nexport interface PxlDataTypes {\n}\n\n/** Test whether the current page is being iframed in the WebHare test framework */\nexport function isInTestFramework(): boolean {\n  if (window.top !== window) { //in a frame\n    try {\n      if ((window.top as { __testframework?: unknown })?.__testframework)\n        return true;//we're inside a testframe, pretend to be the parent\n    } catch (ignore) {\n    }\n  }\n  return false;\n}\n\nfunction postRenderChecks() {\n  const log = document.getElementById(\"wh-console-log\");\n  if (log) {\n    const logtext = atob(log.textContent || \"\");\n    console.group(\"[etr] Server-side console output\");\n    console.log(logtext);\n    console.groupEnd();\n  }\n}\n\nonDomReady(postRenderChecks);\n","import { rpc as createRpcClient, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport type { RPC } from \"@mod-companyos/js/rpc\";\n\nexport type CompanyosRPC = OmitRPCContextArgs<typeof RPC>;\n\nexport const DEFAULT_SCHEMA = \"companyos:companyos\";\n\nconst client: CompanyosRPC = createRpcClient<CompanyosRPC>(\"companyos:rpc\");\n\nexport function useRpc(): CompanyosRPC {\n  return client;\n}\n","// Navigation that differs per visitor. The published shell and dashboard mark such items with data-companyos-app and\n// hide them; this asks the visitor's app session and reveals the confirmed ones. Convenience only: the server still\n// checks every action. Also forwards an old SPA bookmark (#/ip-toegang) on the dashboard to its page.\nimport { isLoggedIn } from \"@webhare/frontend\";\nimport { DEFAULT_SCHEMA, useRpc } from \"../../companyos/frontend/composables/useRpc\";\n\n/** On `<html>`: \"anonymous\", \"ready\" or \"failed\" once the app items are settled; absent while pending or unused. */\nexport const APPS_STATE_ATTRIBUTE = \"data-companyos-apps\";\n\nasync function revealApps(): Promise<void> {\n  const root = document.documentElement;\n  const items = [...document.querySelectorAll<HTMLElement>(\"[data-companyos-app]\")];\n  // Two asset packs on one page both import the page base; one session request is enough\n  if (!items.length || root.hasAttribute(APPS_STATE_ATTRIBUTE))\n    return;\n  if (!isLoggedIn()) {\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"anonymous\");\n    return;\n  }\n  root.setAttribute(APPS_STATE_ATTRIBUTE, \"\");\n  try {\n    const { visibleAppIds, canManageApps } = await useRpc().getAppSession({ schema: DEFAULT_SCHEMA });\n    // \"settings\" is always available in the catalog, but on the page base it is the apps-per-user page: show it only\n    // to who may manage apps (sysop or a declared app manager right), the same check as its RPC.\n    const isVisible = (appId: string) => appId === \"settings\" ? canManageApps : visibleAppIds.includes(appId);\n    for (const item of items)\n      item.hidden = !isVisible(item.dataset.companyosApp!);\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"ready\");\n  } catch (error) {\n    // Items stay hidden: nobody sees a link the session could not confirm\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"failed\");\n    console.error(\"Could not load the CompanyOS app session\", error);\n  }\n}\n\nconst trimSlashes = (path: string) => path.replace(/^\\/+|\\/+$/g, \"\");\n\n/** The SPA routed on the hash (#/ip-toegang/...); the longest matching dashboard tile path wins. */\nfunction followSpaBookmark(): void {\n  const dashboard = document.querySelector(\"[data-companyos-dashboard]\");\n  if (!dashboard || !location.hash.startsWith(\"#/\"))\n    return;\n  const wanted = trimSlashes(decodeURIComponent(location.hash.slice(2)));\n  const target = [...dashboard.querySelectorAll<HTMLAnchorElement>(\"a[data-companyos-path]\")]\n    .map(link => ({ link, path: trimSlashes(link.dataset.companyosPath!) }))\n    .filter(({ path }) => path && (wanted === path || wanted.startsWith(`${path}/`)))\n    .sort((a, b) => b.path.length - a.path.length)[0];\n  if (target)\n    location.replace(target.link.href);\n}\n\nfunction start() {\n  followSpaBookmark();\n  void revealApps();\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","export type Theme = \"dark\" | \"light\";\n\nexport interface ThemeEnvironment {\n  readStoredTheme: () => Theme | null;\n  writeStoredTheme: (theme: Theme) => void;\n  applyTheme: (theme: Theme) => void;\n}\n\n/** Owns page theme policy without Vue or browser globals, so fixed overlays can preserve preferences. */\nexport class ThemeController {\n  readonly #environment: ThemeEnvironment;\n  #theme: Theme = \"dark\";\n  #fixedTheme: Theme | undefined;\n\n  public constructor(environment: ThemeEnvironment) {\n    this.#environment = environment;\n  }\n\n  public get theme(): Theme {\n    return this.#theme;\n  }\n\n  public get canSwitchTheme(): boolean {\n    return this.#fixedTheme === undefined;\n  }\n\n  /** Applies a fixed theme without touching storage, or restores the user's standalone preference. */\n  public initialize(options: { fixedTheme?: Theme } = {}): void {\n    this.#fixedTheme = options.fixedTheme;\n    // Keep this short-circuited: even reading a previous preference is forbidden for fixed overlays.\n    this.#theme = options.fixedTheme ?? this.#environment.readStoredTheme() ?? \"dark\";\n    this.#environment.applyTheme(this.#theme);\n  }\n\n  public setTheme(next: Theme): void {\n    if (!this.canSwitchTheme)\n      return;\n    this.#theme = next;\n    this.#environment.applyTheme(next);\n    this.#environment.writeStoredTheme(next);\n  }\n\n  public toggleTheme(): void {\n    this.setTheme(this.#theme === \"dark\" ? \"light\" : \"dark\");\n  }\n}\n","// The visitor's light/dark choice on page base pages. The head script in shell.witty applied the stored choice before\n// the first paint; this switches it and stores it under the SPA's key (companyos:<brand>:theme), shared by the account\n// menu (account.ts) and the login's toggle below, so a choice made on one page carries over to the other.\nimport { ThemeController, type Theme } from \"../../companyos/frontend/lib/theme\";\n\nexport function createPageTheme({ storageKey, onApply }: { storageKey: string; onApply: (theme: Theme) => void }): ThemeController {\n  const root = document.documentElement;\n  const controller = new ThemeController({\n    readStoredTheme: () => root.classList.contains(\"dark\") ? \"dark\" : \"light\",\n    writeStoredTheme(next) {\n      try {\n        localStorage.setItem(storageKey, next);\n      } catch {\n        // Storage denied: the theme still applies to this page view\n      }\n    },\n    applyTheme(next) {\n      root.classList.toggle(\"dark\", next === \"dark\");\n      onApply(next);\n    },\n  });\n  controller.initialize();\n  return controller;\n}\n\n/** The login's toggle button (shell.witty, loginscreen): pressed is dark. */\nfunction start() {\n  const button = document.querySelector<HTMLButtonElement>(\"[data-companyos-theme-toggle]\");\n  // Two asset packs on one page both import the page base; one setup is enough\n  if (!button || button.dataset.companyosThemeReady !== undefined)\n    return;\n  button.dataset.companyosThemeReady = \"\";\n  const theme = createPageTheme({ storageKey: button.dataset.companyosThemeKey!, onApply: next => button.setAttribute(\"aria-pressed\", String(next === \"dark\")) });\n  button.addEventListener(\"click\", () => theme.toggleTheme());\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","// The account menu in the shell header (shell.witty): who is logged in, the light or dark theme, and logout.\n// Menu button pattern: Enter, Space and the arrow keys open it, Escape closes it and returns focus to the button,\n// Tab or a click elsewhere closes it. The published HTML holds no visitor data: the name comes from WRDAuth's cached\n// fields (siteprofile `cachefields`), the theme from localStorage, which the head script already applied before paint.\nimport { getUserInfo, isLoggedIn } from \"@webhare/frontend\";\nimport type { Theme } from \"../../companyos/frontend/lib/theme\";\nimport { createPageTheme } from \"./theme\";\n\ninterface CachedUserInfo {\n  wrd_fullname?: string;\n  wrd_firstname?: string;\n  wrd_lastname?: string;\n  wrd_contact_email?: string;\n}\n\n/** The same fallbacks as the SPA header (ShellHeader.vue): full name, first and last name, e-mail, \"Account\". */\nfunction displayName(info: CachedUserInfo | null): string {\n  const combined = `${info?.wrd_firstname?.trim() ?? \"\"} ${info?.wrd_lastname?.trim() ?? \"\"}`.trim();\n  return info?.wrd_fullname?.trim() || combined || info?.wrd_contact_email?.trim() || \"Account\";\n}\n\nfunction setupAccount(account: HTMLElement): void {\n  account.hidden = !isLoggedIn();\n  if (account.hidden)\n    return;\n  const info = getUserInfo<CachedUserInfo>();\n  for (const name of account.querySelectorAll(\"[data-companyos-account-name]\"))\n    name.textContent = displayName(info);\n  const email = account.querySelector<HTMLElement>(\"[data-companyos-account-email]\")!;\n  email.textContent = info?.wrd_contact_email?.trim() ?? \"\";\n  email.hidden = !email.textContent;\n\n  const button = account.querySelector<HTMLButtonElement>(\"[aria-haspopup=menu]\")!;\n  const popover = account.querySelector<HTMLElement>(\"[data-companyos-account-popover]\")!;\n  const items = [...popover.querySelectorAll<HTMLElement>(\"[role^=menuitem]\")];\n  const theme = createPageTheme({\n    storageKey: account.dataset.companyosThemeKey!,\n    onApply(next) {\n      for (const item of items.filter(candidate => candidate.dataset.companyosTheme))\n        item.setAttribute(\"aria-checked\", String(item.dataset.companyosTheme === next));\n    },\n  });\n\n  const isOpen = () => !popover.hidden;\n  function open(focus: \"first\" | \"last\") {\n    popover.hidden = false;\n    button.setAttribute(\"aria-expanded\", \"true\");\n    items[focus === \"first\" ? 0 : items.length - 1].focus();\n  }\n  function close({ restoreFocus }: { restoreFocus: boolean }) {\n    if (!isOpen())\n      return;\n    popover.hidden = true;\n    button.setAttribute(\"aria-expanded\", \"false\");\n    if (restoreFocus)\n      button.focus();\n  }\n\n  button.addEventListener(\"click\", () => isOpen() ? close({ restoreFocus: true }) : open(\"first\"));\n  button.addEventListener(\"keydown\", event => {\n    if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\")\n      return;\n    event.preventDefault();\n    open(event.key === \"ArrowDown\" ? \"first\" : \"last\");\n  });\n  popover.addEventListener(\"keydown\", event => {\n    const index = items.indexOf(document.activeElement as HTMLElement);\n    const targets: Record<string, number> = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 };\n    const move = targets[event.key];\n    if (move !== undefined) {\n      event.preventDefault();\n      items[(move + items.length) % items.length].focus();\n    } else if (event.key === \"Escape\") {\n      event.preventDefault();\n      close({ restoreFocus: true });\n    } else if (event.key === \" \" && document.activeElement instanceof HTMLAnchorElement) {\n      // A link has no Space activation of its own; the logout link is one, so WRDAuth's handler stays in charge\n      event.preventDefault();\n      document.activeElement.click();\n    }\n  });\n  for (const item of items.filter(candidate => candidate.dataset.companyosTheme))\n    item.addEventListener(\"click\", () => {\n      theme.setTheme(item.dataset.companyosTheme as Theme);\n      close({ restoreFocus: true });\n    });\n  account.addEventListener(\"focusout\", event => {\n    if (!account.contains(event.relatedTarget as Node | null))\n      close({ restoreFocus: false });\n  });\n  // A click on something that takes no focus (Safari does not focus a clicked button) leaves no focusout\n  document.addEventListener(\"pointerdown\", event => {\n    if (!account.contains(event.target as Node))\n      close({ restoreFocus: false });\n  });\n}\n\nfunction start() {\n  const account = document.querySelector<HTMLElement>(\"[data-companyos-account]\");\n  // Two asset packs on one page both import the page base; one setup is enough\n  if (account && !account.dataset.companyosAccountReady) {\n    account.dataset.companyosAccountReady = \"\";\n    setupAccount(account);\n  }\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n  global.ShadowRoot &&\n  (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n  'adoptedStyleSheets' in Document.prototype &&\n  'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array<CSSResultOrNative | CSSResultArray>;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap<TemplateStringsArray, CSSStyleSheet>();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n  // This property needs to remain unminified.\n  ['_$cssResult$'] = true;\n  readonly cssText: string;\n  private _styleSheet?: CSSStyleSheet;\n  private _strings: TemplateStringsArray | undefined;\n\n  private constructor(\n    cssText: string,\n    strings: TemplateStringsArray | undefined,\n    safeToken: symbol\n  ) {\n    if (safeToken !== constructionToken) {\n      throw new Error(\n        'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n      );\n    }\n    this.cssText = cssText;\n    this._strings = strings;\n  }\n\n  // This is a getter so that it's lazy. In practice, this means stylesheets\n  // are not created until the first element instance is made.\n  get styleSheet(): CSSStyleSheet | undefined {\n    // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n    // constructable.\n    let styleSheet = this._styleSheet;\n    const strings = this._strings;\n    if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n      const cacheable = strings !== undefined && strings.length === 1;\n      if (cacheable) {\n        styleSheet = cssTagCache.get(strings);\n      }\n      if (styleSheet === undefined) {\n        (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n          this.cssText\n        );\n        if (cacheable) {\n          cssTagCache.set(strings, styleSheet);\n        }\n      }\n    }\n    return styleSheet;\n  }\n\n  toString(): string {\n    return this.cssText;\n  }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n  new (\n    cssText: string,\n    strings: TemplateStringsArray | undefined,\n    safeToken: symbol\n  ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n  // This property needs to remain unminified.\n  if ((value as CSSResult)['_$cssResult$'] === true) {\n    return (value as CSSResult).cssText;\n  } else if (typeof value === 'number') {\n    return value;\n  } else {\n    throw new Error(\n      `Value passed to 'css' function must be a 'css' function result: ` +\n        `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n        `to ensure page security.`\n    );\n  }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n  new (CSSResult as ConstructableCSSResult)(\n    typeof value === 'string' ? value : String(value),\n    undefined,\n    constructionToken\n  );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n  strings: TemplateStringsArray,\n  ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n  const cssText =\n    strings.length === 1\n      ? strings[0]\n      : values.reduce(\n          (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n          strings[0]\n        );\n  return new (CSSResult as ConstructableCSSResult)(\n    cssText,\n    strings,\n    constructionToken\n  );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic the native feature](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n  renderRoot: ShadowRoot,\n  styles: Array<CSSResultOrNative>\n) => {\n  if (supportsAdoptingStyleSheets) {\n    (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n      s instanceof CSSStyleSheet ? s : s.styleSheet!\n    );\n  } else {\n    for (const s of styles) {\n      const style = document.createElement('style');\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const nonce = (global as any)['litNonce'];\n      if (nonce !== undefined) {\n        style.setAttribute('nonce', nonce);\n      }\n      style.textContent = (s as CSSResult).cssText;\n      renderRoot.appendChild(style);\n    }\n  }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n  let cssText = '';\n  for (const rule of sheet.cssRules) {\n    cssText += rule.cssText;\n  }\n  return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n  supportsAdoptingStyleSheets ||\n  (NODE_MODE && global.CSSStyleSheet === undefined)\n    ? (s: CSSResultOrNative) => s\n    : (s: CSSResultOrNative) =>\n        s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n  getCompatibleStyle,\n  adoptStyles,\n  CSSResultGroup,\n  CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n  ReactiveController,\n  ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n  ReactiveController,\n  ReactiveControllerHost,\n} from './reactive-controller.js';\n\n/**\n * Removes the `readonly` modifier from properties in the union K.\n *\n * This is a safer way to cast a value to a type with a mutable version of a\n * readonly field, than casting to an interface with the field re-declared\n * because it preserves the type of all the fields and warns on typos.\n */\ntype Mutable<T, K extends keyof T> = Omit<T, K> & {\n  -readonly [P in keyof Pick<T, K>]: P extends K ? T[P] : never;\n};\n\n// TODO (justinfagnani): Add `hasOwn` here when we ship ES2022\nconst {\n  is,\n  defineProperty,\n  getOwnPropertyDescriptor,\n  getOwnPropertyNames,\n  getOwnPropertySymbols,\n  getPrototypeOf,\n} = Object;\n\nconst NODE_MODE = false;\n\n// Lets a minifier replace globalThis references with a minified name\nconst global = globalThis;\n\nif (NODE_MODE) {\n  global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n  .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n  ? (trustedTypes.emptyScript as unknown as '')\n  : '';\n\nconst polyfillSupport = DEV_MODE\n  ? global.reactiveElementPolyfillSupportDevMode\n  : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n  // Ensure warnings are issued only 1x, even if multiple versions of Lit\n  // are loaded.\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += ` See https://lit.dev/msg/${code} for more information.`;\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n\n  queueMicrotask(() => {\n    issueWarning(\n      'dev-mode',\n      `Lit is in dev mode. Not recommended for production!`\n    );\n\n    // Issue polyfill support warning.\n    if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n      issueWarning(\n        'polyfill-support-missing',\n        `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n          `the \\`polyfill-support\\` module has not been loaded.`\n      );\n    }\n  });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry = Update;\n    export interface Update {\n      kind: 'update';\n    }\n  }\n}\n\ninterface DebugLoggingWindow {\n  // Even in dev mode, we generally don't want to emit these events, as that's\n  // another level of cost, so only emit them when DEV_MODE is true _and_ when\n  // window.emitLitDebugEvents is true.\n  emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n  ? (event: ReactiveUnstable.DebugLog.Entry) => {\n      const shouldEmit = (global as unknown as DebugLoggingWindow)\n        .emitLitDebugLogEvents;\n      if (!shouldEmit) {\n        return;\n      }\n      global.dispatchEvent(\n        new CustomEvent<ReactiveUnstable.DebugLog.Entry>('lit-debug', {\n          detail: event,\n        })\n      );\n    }\n  : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n  prop: P,\n  _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter<Type = unknown, TypeHint = unknown> {\n  /**\n   * Called to convert an attribute value to a property\n   * value.\n   */\n  fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n  /**\n   * Called to convert a property value to an attribute\n   * value.\n   *\n   * It returns unknown instead of string, to be compatible with\n   * https://github.com/WICG/trusted-types (and similar efforts).\n   */\n  toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter<Type = unknown, TypeHint = unknown> =\n  | ComplexAttributeConverter<Type>\n  | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration<Type = unknown, TypeHint = unknown> {\n  /**\n   * When set to `true`, indicates the property is internal private state. The\n   * property should not be set by users. When using TypeScript, this property\n   * should be marked as `private` or `protected`, and it is also a common\n   * practice to use a leading `_` in the name. The property is not added to\n   * `observedAttributes`.\n   */\n  readonly state?: boolean;\n\n  /**\n   * Indicates how and whether the property becomes an observed attribute.\n   * If the value is `false`, the property is not added to `observedAttributes`.\n   * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n   * becomes `foobar`). If a string, the string value is observed (e.g\n   * `attribute: 'foo-bar'`).\n   */\n  readonly attribute?: boolean | string;\n\n  /**\n   * Indicates the type of the property. This is used only as a hint for the\n   * `converter` to determine how to convert the attribute\n   * to/from a property.\n   */\n  readonly type?: TypeHint;\n\n  /**\n   * Indicates how to convert the attribute to/from a property. If this value\n   * is a function, it is used to convert the attribute value a the property\n   * value. If it's an object, it can have keys for `fromAttribute` and\n   * `toAttribute`. If no `toAttribute` function is provided and\n   * `reflect` is set to `true`, the property value is set directly to the\n   * attribute. A default `converter` is used if none is provided; it supports\n   * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n   * when a property changes and the converter is used to update the attribute,\n   * the property is never updated again as a result of the attribute changing,\n   * and vice versa.\n   */\n  readonly converter?: AttributeConverter<Type, TypeHint>;\n\n  /**\n   * Indicates if the property should reflect to an attribute.\n   * If `true`, when the property is set, the attribute is set using the\n   * attribute name determined according to the rules for the `attribute`\n   * property option and the value of the property converted using the rules\n   * from the `converter` property option.\n   */\n  readonly reflect?: boolean;\n\n  /**\n   * A function that indicates if a property should be considered changed when\n   * it is set. The function should take the `newValue` and `oldValue` and\n   * return `true` if an update should be requested.\n   */\n  hasChanged?(value: Type, oldValue: Type): boolean;\n\n  /**\n   * Indicates whether an accessor will be created for this property. By\n   * default, an accessor will be generated for this property that requests an\n   * update when set. If this flag is `true`, no accessor will be created, and\n   * it will be the user's responsibility to call\n   * `this.requestUpdate(propertyName, oldValue)` to request an update when\n   * the property changes.\n   */\n  readonly noAccessor?: boolean;\n\n  /**\n   * Whether this property is wrapping accessors. This is set by `@property`\n   * to control the initial value change and reflection logic.\n   *\n   * @internal\n   */\n  wrapped?: boolean;\n\n  /**\n   * When `true`, uses the initial value of the property as the default value,\n   * which changes how attributes are handled:\n   *  - The initial value does *not* reflect, even if the `reflect` option is `true`.\n   *    Subsequent changes to the property will reflect, even if they are equal to the\n   *     default value.\n   *  - When the attribute is removed, the property is set to the default value\n   *  - The initial value will not trigger an old value in the `changedProperties` map\n   *    argument to update lifecycle methods.\n   *\n   * When set, properties must be initialized, either with a field initializer, or an\n   * assignment in the constructor. Not initializing the property may lead to\n   * improper handling of subsequent property assignments.\n   *\n   * While this behavior is opt-in, most properties that reflect to attributes should\n   * use `useDefault: true` so that their initial values do not reflect.\n   */\n  useDefault?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n  readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map<PropertyKey, PropertyDeclaration>;\n\ntype AttributeMap = Map<string, PropertyKey>;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues<this>` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map<PropertyKey, unknown>`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map<PropertyKey, unknown>`, but if a developer uses\n// `PropertyValues<this>` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues<T = any> = T extends object\n  ? PropertyValueMap<T>\n  : Map<PropertyKey, unknown>;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap<T> extends Map<PropertyKey, unknown> {\n  get<K extends keyof T>(k: K): T[K] | undefined;\n  set<K extends keyof T>(key: K, value: T[K]): this;\n  has<K extends keyof T>(k: K): boolean;\n  delete<K extends keyof T>(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n  toAttribute(value: unknown, type?: unknown): unknown {\n    switch (type) {\n      case Boolean:\n        value = value ? emptyStringForBooleanAttribute : null;\n        break;\n      case Object:\n      case Array:\n        // if the value is `null` or `undefined` pass this through\n        // to allow removing/no change behavior.\n        value = value == null ? value : JSON.stringify(value);\n        break;\n    }\n    return value;\n  },\n\n  fromAttribute(value: string | null, type?: unknown) {\n    let fromValue: unknown = value;\n    switch (type) {\n      case Boolean:\n        fromValue = value !== null;\n        break;\n      case Number:\n        fromValue = value === null ? null : Number(value);\n        break;\n      case Object:\n      case Array:\n        // Do *not* generate exception when invalid JSON is set as elements\n        // don't normally complain on being mis-configured.\n        // TODO(sorvell): Do generate exception in *dev mode*.\n        try {\n          // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n          fromValue = JSON.parse(value!) as unknown;\n        } catch (e) {\n          fromValue = null;\n        }\n        break;\n    }\n    return fromValue;\n  },\n};\n\nexport interface HasChanged {\n  (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean =>\n  !is(value, old);\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n  attribute: true,\n  type: String,\n  converter: defaultConverter,\n  reflect: false,\n  useDefault: false,\n  hasChanged: notEqual,\n};\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind =\n  | 'change-in-update'\n  | 'migration'\n  | 'async-perform-update';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n// Temporary, until google3 is on TypeScript 5.2\ndeclare global {\n  interface SymbolConstructor {\n    readonly metadata: unique symbol;\n  }\n}\n\n// Ensure metadata is enabled. TypeScript does not polyfill\n// Symbol.metadata, so we must ensure that it exists.\n(Symbol as {metadata: symbol}).metadata ??= Symbol('metadata');\n\ndeclare global {\n  // This is public global API, do not change!\n  // eslint-disable-next-line no-var\n  var litPropertyMetadata: WeakMap<\n    object,\n    Map<PropertyKey, PropertyDeclaration>\n  >;\n}\n\n// Map from a class's metadata object to property options\n// Note that we must use nullish-coalescing assignment so that we only use one\n// map even if we load multiple version of this module.\nglobal.litPropertyMetadata ??= new WeakMap<\n  object,\n  Map<PropertyKey, PropertyDeclaration>\n>();\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclasses to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n  // In the Node build, this `extends` clause will be substituted with\n  // `(globalThis.HTMLElement ?? HTMLElement)`.\n  //\n  // This way, we will first prefer any global `HTMLElement` polyfill that the\n  // user has assigned, and then fall back to the `HTMLElement` shim which has\n  // been imported (see note at the top of this file about how this import is\n  // generated by Rollup). Note that the `HTMLElement` variable has been\n  // shadowed by this import, so it no longer refers to the global.\n  extends HTMLElement\n  implements ReactiveControllerHost\n{\n  // Note: these are patched in only in DEV_MODE.\n  /**\n   * Read or set all the enabled warning categories for this class.\n   *\n   * This property is only used in development builds.\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static enabledWarnings?: WarningKind[];\n\n  /**\n   * Enable the given warning category for this class.\n   *\n   * This method only exists in development builds, so it should be accessed\n   * with a guard like:\n   *\n   * ```ts\n   * // Enable for all ReactiveElement subclasses\n   * ReactiveElement.enableWarning?.('migration');\n   *\n   * // Enable for only MyElement and subclasses\n   * MyElement.enableWarning?.('migration');\n   * ```\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static enableWarning?: (warningKind: WarningKind) => void;\n\n  /**\n   * Disable the given warning category for this class.\n   *\n   * This method only exists in development builds, so it should be accessed\n   * with a guard like:\n   *\n   * ```ts\n   * // Disable for all ReactiveElement subclasses\n   * ReactiveElement.disableWarning?.('migration');\n   *\n   * // Disable for only MyElement and subclasses\n   * MyElement.disableWarning?.('migration');\n   * ```\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static disableWarning?: (warningKind: WarningKind) => void;\n\n  /**\n   * Adds an initializer function to the class that is called during instance\n   * construction.\n   *\n   * This is useful for code that runs against a `ReactiveElement`\n   * subclass, such as a decorator, that needs to do work for each\n   * instance, such as setting up a `ReactiveController`.\n   *\n   * ```ts\n   * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n   *   target.addInitializer((instance: ReactiveElement) => {\n   *     // This is run during construction of the element\n   *     new MyController(instance);\n   *   });\n   * }\n   * ```\n   *\n   * Decorating a field will then cause each instance to run an initializer\n   * that adds a controller:\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   @myDecorator foo;\n   * }\n   * ```\n   *\n   * Initializers are stored per-constructor. Adding an initializer to a\n   * subclass does not add it to a superclass. Since initializers are run in\n   * constructors, initializers will run in order of the class hierarchy,\n   * starting with superclasses and progressing to the instance's class.\n   *\n   * @nocollapse\n   */\n  static addInitializer(initializer: Initializer) {\n    this.__prepare();\n    (this._initializers ??= []).push(initializer);\n  }\n\n  static _initializers?: Initializer[];\n\n  /*\n   * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n   * all static methods and properties with initializers.  Reference:\n   * - https://github.com/google/closure-compiler/issues/1776\n   */\n\n  /**\n   * Maps attribute names to properties; for example `foobar` attribute to\n   * `fooBar` property. Created lazily on user subclasses when finalizing the\n   * class.\n   * @nocollapse\n   */\n  private static __attributeToPropertyMap: AttributeMap;\n\n  /**\n   * Marks class as having been finalized, which includes creating properties\n   * from `static properties`, but does *not* include all properties created\n   * from decorators.\n   * @nocollapse\n   */\n  protected static finalized: true | undefined;\n\n  /**\n   * Memoized list of all element properties, including any superclass\n   * properties. Created lazily on user subclasses when finalizing the class.\n   *\n   * @nocollapse\n   * @category properties\n   */\n  static elementProperties: PropertyDeclarationMap;\n\n  /**\n   * User-supplied object that maps property names to `PropertyDeclaration`\n   * objects containing options for configuring reactive properties. When\n   * a reactive property is set the element will update and render.\n   *\n   * By default properties are public fields, and as such, they should be\n   * considered as primarily settable by element users, either via attribute or\n   * the property itself.\n   *\n   * Generally, properties that are changed by the element should be private or\n   * protected fields and should use the `state: true` option. Properties\n   * marked as `state` do not reflect from the corresponding attribute\n   *\n   * However, sometimes element code does need to set a public property. This\n   * should typically only be done in response to user interaction, and an event\n   * should be fired informing the user; for example, a checkbox sets its\n   * `checked` property when clicked and fires a `changed` event. Mutating\n   * public properties should typically not be done for non-primitive (object or\n   * array) properties. In other cases when an element needs to manage state, a\n   * private property set with the `state: true` option should be used. When\n   * needed, state properties can be initialized via public properties to\n   * facilitate complex interactions.\n   * @nocollapse\n   * @category properties\n   */\n  static properties: PropertyDeclarations;\n\n  /**\n   * Memoized list of all element styles.\n   * Created lazily on user subclasses when finalizing the class.\n   * @nocollapse\n   * @category styles\n   */\n  static elementStyles: Array<CSSResultOrNative> = [];\n\n  /**\n   * Array of styles to apply to the element. The styles should be defined\n   * using the {@linkcode css} tag function, via constructible stylesheets, or\n   * imported from native CSS module scripts.\n   *\n   * Note on Content Security Policy:\n   *\n   * Element styles are implemented with `<style>` tags when the browser doesn't\n   * support adopted StyleSheets. To use such `<style>` tags with the style-src\n   * CSP directive, the style-src value must either include 'unsafe-inline' or\n   * `nonce-<base64-value>` with `<base64-value>` replaced be a server-generated\n   * nonce.\n   *\n   * To provide a nonce to use on generated `<style>` elements, set\n   * `window.litNonce` to a server-generated nonce in your page's HTML, before\n   * loading application code:\n   *\n   * ```html\n   * <script>\n   *   // Generated and unique per request:\n   *   window.litNonce = 'a1b2c3d4';\n   * </script>\n   * ```\n   * @nocollapse\n   * @category styles\n   */\n  static styles?: CSSResultGroup;\n\n  /**\n   * Returns a list of attributes corresponding to the registered properties.\n   * @nocollapse\n   * @category attributes\n   */\n  static get observedAttributes() {\n    // Ensure we've created all properties\n    this.finalize();\n    // this.__attributeToPropertyMap is only undefined after finalize() in\n    // ReactiveElement itself. ReactiveElement.observedAttributes is only\n    // accessed with ReactiveElement as the receiver when a subclass or mixin\n    // calls super.observedAttributes\n    return (\n      this.__attributeToPropertyMap && [...this.__attributeToPropertyMap.keys()]\n    );\n  }\n\n  private __instanceProperties?: PropertyValues = undefined;\n\n  /**\n   * Creates a property accessor on the element prototype if one does not exist\n   * and stores a {@linkcode PropertyDeclaration} for the property with the\n   * given options. The property setter calls the property's `hasChanged`\n   * property option or uses a strict identity check to determine whether or not\n   * to request an update.\n   *\n   * This method may be overridden to customize properties; however,\n   * when doing so, it's important to call `super.createProperty` to ensure\n   * the property is setup correctly. This method calls\n   * `getPropertyDescriptor` internally to get a descriptor to install.\n   * To customize what properties do when they are get or set, override\n   * `getPropertyDescriptor`. To customize the options for a property,\n   * implement `createProperty` like this:\n   *\n   * ```ts\n   * static createProperty(name, options) {\n   *   options = Object.assign(options, {myOption: true});\n   *   super.createProperty(name, options);\n   * }\n   * ```\n   *\n   * @nocollapse\n   * @category properties\n   */\n  static createProperty(\n    name: PropertyKey,\n    options: PropertyDeclaration = defaultPropertyDeclaration\n  ) {\n    // If this is a state property, force the attribute to false.\n    if (options.state) {\n      (options as Mutable<PropertyDeclaration, 'attribute'>).attribute = false;\n    }\n    this.__prepare();\n    // Whether this property is wrapping accessors.\n    // Helps control the initial value change and reflection logic.\n    if (this.prototype.hasOwnProperty(name)) {\n      options = Object.create(options);\n      options.wrapped = true;\n    }\n    this.elementProperties.set(name, options);\n    if (!options.noAccessor) {\n      const key = DEV_MODE\n        ? // Use Symbol.for in dev mode to make it easier to maintain state\n          // when doing HMR.\n          Symbol.for(`${String(name)} (@property() cache)`)\n        : Symbol();\n      const descriptor = this.getPropertyDescriptor(name, key, options);\n      if (descriptor !== undefined) {\n        defineProperty(this.prototype, name, descriptor);\n      }\n    }\n  }\n\n  /**\n   * Returns a property descriptor to be defined on the given named property.\n   * If no descriptor is returned, the property will not become an accessor.\n   * For example,\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   static getPropertyDescriptor(name, key, options) {\n   *     const defaultDescriptor =\n   *         super.getPropertyDescriptor(name, key, options);\n   *     const setter = defaultDescriptor.set;\n   *     return {\n   *       get: defaultDescriptor.get,\n   *       set(value) {\n   *         setter.call(this, value);\n   *         // custom action.\n   *       },\n   *       configurable: true,\n   *       enumerable: true\n   *     }\n   *   }\n   * }\n   * ```\n   *\n   * @nocollapse\n   * @category properties\n   */\n  protected static getPropertyDescriptor(\n    name: PropertyKey,\n    key: string | symbol,\n    options: PropertyDeclaration\n  ): PropertyDescriptor | undefined {\n    const {get, set} = getOwnPropertyDescriptor(this.prototype, name) ?? {\n      get(this: ReactiveElement) {\n        return this[key as keyof typeof this];\n      },\n      set(this: ReactiveElement, v: unknown) {\n        (this as unknown as Record<string | symbol, unknown>)[key] = v;\n      },\n    };\n    if (DEV_MODE && get == null) {\n      if ('value' in (getOwnPropertyDescriptor(this.prototype, name) ?? {})) {\n        throw new Error(\n          `Field ${JSON.stringify(String(name))} on ` +\n            `${this.name} was declared as a reactive property ` +\n            `but it's actually declared as a value on the prototype. ` +\n            `Usually this is due to using @property or @state on a method.`\n        );\n      }\n      issueWarning(\n        'reactive-property-without-getter',\n        `Field ${JSON.stringify(String(name))} on ` +\n          `${this.name} was declared as a reactive property ` +\n          `but it does not have a getter. This will be an error in a ` +\n          `future version of Lit.`\n      );\n    }\n    return {\n      get,\n      set(this: ReactiveElement, value: unknown) {\n        const oldValue = get?.call(this);\n        set?.call(this, value);\n        this.requestUpdate(name, oldValue, options);\n      },\n      configurable: true,\n      enumerable: true,\n    };\n  }\n\n  /**\n   * Returns the property options associated with the given property.\n   * These options are defined with a `PropertyDeclaration` via the `properties`\n   * object or the `@property` decorator and are registered in\n   * `createProperty(...)`.\n   *\n   * Note, this method should be considered \"final\" and not overridden. To\n   * customize the options for a given property, override\n   * {@linkcode createProperty}.\n   *\n   * @nocollapse\n   * @final\n   * @category properties\n   */\n  static getPropertyOptions(name: PropertyKey) {\n    return this.elementProperties.get(name) ?? defaultPropertyDeclaration;\n  }\n\n  // Temporary, until google3 is on TypeScript 5.2\n  declare static [Symbol.metadata]: object & Record<PropertyKey, unknown>;\n\n  /**\n   * Initializes static own properties of the class used in bookkeeping\n   * for element properties, initializers, etc.\n   *\n   * Can be called multiple times by code that needs to ensure these\n   * properties exist before using them.\n   *\n   * This method ensures the superclass is finalized so that inherited\n   * property metadata can be copied down.\n   * @nocollapse\n   */\n  private static __prepare() {\n    if (\n      this.hasOwnProperty(JSCompiler_renameProperty('elementProperties', this))\n    ) {\n      // Already prepared\n      return;\n    }\n    // Finalize any superclasses\n    const superCtor = getPrototypeOf(this) as typeof ReactiveElement;\n    superCtor.finalize();\n\n    // Create own set of initializers for this class if any exist on the\n    // superclass and copy them down. Note, for a small perf boost, avoid\n    // creating initializers unless needed.\n    if (superCtor._initializers !== undefined) {\n      this._initializers = [...superCtor._initializers];\n    }\n    // Initialize elementProperties from the superclass\n    this.elementProperties = new Map(superCtor.elementProperties);\n  }\n\n  /**\n   * Finishes setting up the class so that it's ready to be registered\n   * as a custom element and instantiated.\n   *\n   * This method is called by the ReactiveElement.observedAttributes getter.\n   * If you override the observedAttributes getter, you must either call\n   * super.observedAttributes to trigger finalization, or call finalize()\n   * yourself.\n   *\n   * @nocollapse\n   */\n  protected static finalize() {\n    if (this.hasOwnProperty(JSCompiler_renameProperty('finalized', this))) {\n      return;\n    }\n    this.finalized = true;\n    this.__prepare();\n\n    // Create properties from the static properties block:\n    if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n      const props = this.properties;\n      const propKeys = [\n        ...getOwnPropertyNames(props),\n        ...getOwnPropertySymbols(props),\n      ] as Array<keyof typeof props>;\n      for (const p of propKeys) {\n        this.createProperty(p, props[p]);\n      }\n    }\n\n    // Create properties from standard decorator metadata:\n    const metadata = this[Symbol.metadata];\n    if (metadata !== null) {\n      const properties = litPropertyMetadata.get(metadata);\n      if (properties !== undefined) {\n        for (const [p, options] of properties) {\n          this.elementProperties.set(p, options);\n        }\n      }\n    }\n\n    // Create the attribute-to-property map\n    this.__attributeToPropertyMap = new Map();\n    for (const [p, options] of this.elementProperties) {\n      const attr = this.__attributeNameForProperty(p, options);\n      if (attr !== undefined) {\n        this.__attributeToPropertyMap.set(attr, p);\n      }\n    }\n\n    this.elementStyles = this.finalizeStyles(this.styles);\n\n    if (DEV_MODE) {\n      if (this.hasOwnProperty('createProperty')) {\n        issueWarning(\n          'no-override-create-property',\n          'Overriding ReactiveElement.createProperty() is deprecated. ' +\n            'The override will not be called with standard decorators'\n        );\n      }\n      if (this.hasOwnProperty('getPropertyDescriptor')) {\n        issueWarning(\n          'no-override-get-property-descriptor',\n          'Overriding ReactiveElement.getPropertyDescriptor() is deprecated. ' +\n            'The override will not be called with standard decorators'\n        );\n      }\n    }\n  }\n\n  /**\n   * Options used when calling `attachShadow`. Set this property to customize\n   * the options for the shadowRoot; for example, to create a closed\n   * shadowRoot: `{mode: 'closed'}`.\n   *\n   * Note, these options are used in `createRenderRoot`. If this method\n   * is customized, options should be respected if possible.\n   * @nocollapse\n   * @category rendering\n   */\n  static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n  /**\n   * Takes the styles the user supplied via the `static styles` property and\n   * returns the array of styles to apply to the element.\n   * Override this method to integrate into a style management system.\n   *\n   * Styles are deduplicated preserving the _last_ instance in the list. This\n   * is a performance optimization to avoid duplicated styles that can occur\n   * especially when composing via subclassing. The last item is kept to try\n   * to preserve the cascade order with the assumption that it's most important\n   * that last added styles override previous styles.\n   *\n   * @nocollapse\n   * @category styles\n   */\n  protected static finalizeStyles(\n    styles?: CSSResultGroup\n  ): Array<CSSResultOrNative> {\n    const elementStyles = [];\n    if (Array.isArray(styles)) {\n      // Dedupe the flattened array in reverse order to preserve the last items.\n      // Casting to Array<unknown> works around TS error that\n      // appears to come from trying to flatten a type CSSResultArray.\n      const set = new Set((styles as Array<unknown>).flat(Infinity).reverse());\n      // Then preserve original order by adding the set items in reverse order.\n      for (const s of set) {\n        elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n      }\n    } else if (styles !== undefined) {\n      elementStyles.push(getCompatibleStyle(styles));\n    }\n    return elementStyles;\n  }\n\n  /**\n   * Node or ShadowRoot into which element DOM should be rendered. Defaults\n   * to an open shadowRoot.\n   * @category rendering\n   */\n  readonly renderRoot!: HTMLElement | DocumentFragment;\n\n  /**\n   * Returns the property name for the given attribute `name`.\n   * @nocollapse\n   */\n  private static __attributeNameForProperty(\n    name: PropertyKey,\n    options: PropertyDeclaration\n  ) {\n    const attribute = options.attribute;\n    return attribute === false\n      ? undefined\n      : typeof attribute === 'string'\n        ? attribute\n        : typeof name === 'string'\n          ? name.toLowerCase()\n          : undefined;\n  }\n\n  // Initialize to an unresolved Promise so we can make sure the element has\n  // connected before first update.\n  private __updatePromise!: Promise<boolean>;\n\n  /**\n   * True if there is a pending update as a result of calling `requestUpdate()`.\n   * Should only be read.\n   * @category updates\n   */\n  isUpdatePending = false;\n\n  /**\n   * Is set to `true` after the first update. The element code cannot assume\n   * that `renderRoot` exists before the element `hasUpdated`.\n   * @category updates\n   */\n  hasUpdated = false;\n\n  /**\n   * Map with keys for any properties that have changed since the last\n   * update cycle with previous values.\n   *\n   * @internal\n   */\n  _$changedProperties!: PropertyValues;\n\n  /**\n   * Records property default values when the\n   * `useDefault` option is used.\n   */\n  private __defaultValues?: Map<PropertyKey, unknown>;\n\n  /**\n   * Properties that should be reflected when updated.\n   */\n  private __reflectingProperties?: Set<PropertyKey>;\n\n  /**\n   * Name of currently reflecting property\n   */\n  private __reflectingProperty: PropertyKey | null = null;\n\n  /**\n   * Set of controllers.\n   */\n  private __controllers?: Set<ReactiveController>;\n\n  constructor() {\n    super();\n    this.__initialize();\n  }\n\n  /**\n   * Internal only override point for customizing work done when elements\n   * are constructed.\n   */\n  private __initialize() {\n    this.__updatePromise = new Promise<boolean>(\n      (res) => (this.enableUpdating = res)\n    );\n    this._$changedProperties = new Map();\n    // This enqueues a microtask that must run before the first update, so it\n    // must be called before requestUpdate()\n    this.__saveInstanceProperties();\n    // ensures first update will be caught by an early access of\n    // `updateComplete`\n    this.requestUpdate();\n    (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n      i(this)\n    );\n  }\n\n  /**\n   * Registers a `ReactiveController` to participate in the element's reactive\n   * update cycle. The element automatically calls into any registered\n   * controllers during its lifecycle callbacks.\n   *\n   * If the element is connected when `addController()` is called, the\n   * controller's `hostConnected()` callback will be immediately called.\n   * @category controllers\n   */\n  addController(controller: ReactiveController) {\n    (this.__controllers ??= new Set()).add(controller);\n    // If a controller is added after the element has been connected,\n    // call hostConnected. Note, re-using existence of `renderRoot` here\n    // (which is set in connectedCallback) to avoid the need to track a\n    // first connected state.\n    if (this.renderRoot !== undefined && this.isConnected) {\n      controller.hostConnected?.();\n    }\n  }\n\n  /**\n   * Removes a `ReactiveController` from the element.\n   * @category controllers\n   */\n  removeController(controller: ReactiveController) {\n    this.__controllers?.delete(controller);\n  }\n\n  /**\n   * Fixes any properties set on the instance before upgrade time.\n   * Otherwise these would shadow the accessor and break these properties.\n   * The properties are stored in a Map which is played back after the\n   * constructor runs.\n   */\n  private __saveInstanceProperties() {\n    const instanceProperties = new Map<PropertyKey, unknown>();\n    const elementProperties = (this.constructor as typeof ReactiveElement)\n      .elementProperties;\n    for (const p of elementProperties.keys() as IterableIterator<keyof this>) {\n      if (this.hasOwnProperty(p)) {\n        instanceProperties.set(p, this[p]);\n        delete this[p];\n      }\n    }\n    if (instanceProperties.size > 0) {\n      this.__instanceProperties = instanceProperties;\n    }\n  }\n\n  /**\n   * Returns the node into which the element should render and by default\n   * creates and returns an open shadowRoot. Implement to customize where the\n   * element's DOM is rendered. For example, to render into the element's\n   * childNodes, return `this`.\n   *\n   * @return Returns a node into which to render.\n   * @category rendering\n   */\n  protected createRenderRoot(): HTMLElement | DocumentFragment {\n    const renderRoot =\n      this.shadowRoot ??\n      this.attachShadow(\n        (this.constructor as typeof ReactiveElement).shadowRootOptions\n      );\n    adoptStyles(\n      renderRoot,\n      (this.constructor as typeof ReactiveElement).elementStyles\n    );\n    return renderRoot;\n  }\n\n  /**\n   * On first connection, creates the element's renderRoot, sets up\n   * element styling, and enables updating.\n   * @category lifecycle\n   */\n  connectedCallback() {\n    // Create renderRoot before controllers `hostConnected`\n    (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n      this.createRenderRoot();\n    this.enableUpdating(true);\n    this.__controllers?.forEach((c) => c.hostConnected?.());\n  }\n\n  /**\n   * Note, this method should be considered final and not overridden. It is\n   * overridden on the element instance with a function that triggers the first\n   * update.\n   * @category updates\n   */\n  protected enableUpdating(_requestedUpdate: boolean) {}\n\n  /**\n   * Allows for `super.disconnectedCallback()` in extensions while\n   * reserving the possibility of making non-breaking feature additions\n   * when disconnecting at some point in the future.\n   * @category lifecycle\n   */\n  disconnectedCallback() {\n    this.__controllers?.forEach((c) => c.hostDisconnected?.());\n  }\n\n  /**\n   * Synchronizes property values when attributes change.\n   *\n   * Specifically, when an attribute is set, the corresponding property is set.\n   * You should rarely need to implement this callback. If this method is\n   * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n   * called.\n   *\n   * See [responding to attribute changes](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#responding_to_attribute_changes)\n   * on MDN for more information about the `attributeChangedCallback`.\n   * @category attributes\n   */\n  attributeChangedCallback(\n    name: string,\n    _old: string | null,\n    value: string | null\n  ) {\n    this._$attributeToProperty(name, value);\n  }\n\n  private __propertyToAttribute(name: PropertyKey, value: unknown) {\n    const elemProperties: PropertyDeclarationMap = (\n      this.constructor as typeof ReactiveElement\n    ).elementProperties;\n    const options = elemProperties.get(name)!;\n    const attr = (\n      this.constructor as typeof ReactiveElement\n    ).__attributeNameForProperty(name, options);\n    if (attr !== undefined && options.reflect === true) {\n      const converter =\n        (options.converter as ComplexAttributeConverter)?.toAttribute !==\n        undefined\n          ? (options.converter as ComplexAttributeConverter)\n          : defaultConverter;\n      const attrValue = converter.toAttribute!(value, options.type);\n      if (\n        DEV_MODE &&\n        (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n          'migration'\n        ) &&\n        attrValue === undefined\n      ) {\n        issueWarning(\n          'undefined-attribute-value',\n          `The attribute value for the ${name as string} property is ` +\n            `undefined on element ${this.localName}. The attribute will be ` +\n            `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n            `the attribute would not have changed.`\n        );\n      }\n      // Track if the property is being reflected to avoid\n      // setting the property again via `attributeChangedCallback`. Note:\n      // 1. this takes advantage of the fact that the callback is synchronous.\n      // 2. will behave incorrectly if multiple attributes are in the reaction\n      // stack at time of calling. However, since we process attributes\n      // in `update` this should not be possible (or an extreme corner case\n      // that we'd like to discover).\n      // mark state reflecting\n      this.__reflectingProperty = name;\n      if (attrValue == null) {\n        this.removeAttribute(attr);\n      } else {\n        this.setAttribute(attr, attrValue as string);\n      }\n      // mark state not reflecting\n      this.__reflectingProperty = null;\n    }\n  }\n\n  /** @internal */\n  _$attributeToProperty(name: string, value: string | null) {\n    const ctor = this.constructor as typeof ReactiveElement;\n    // Note, hint this as an `AttributeMap` so closure clearly understands\n    // the type; it has issues with tracking types through statics\n    const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n    // Use tracking info to avoid reflecting a property value to an attribute\n    // if it was just set because the attribute changed.\n    if (propName !== undefined && this.__reflectingProperty !== propName) {\n      const options = ctor.getPropertyOptions(propName);\n      const converter =\n        typeof options.converter === 'function'\n          ? {fromAttribute: options.converter}\n          : options.converter?.fromAttribute !== undefined\n            ? options.converter\n            : defaultConverter;\n      // mark state reflecting\n      this.__reflectingProperty = propName;\n      const convertedValue = converter.fromAttribute!(value, options.type);\n      this[propName as keyof this] =\n        convertedValue ??\n        this.__defaultValues?.get(propName) ??\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        (convertedValue as any);\n      // mark state not reflecting\n      this.__reflectingProperty = null;\n    }\n  }\n\n  /**\n   * Requests an update which is processed asynchronously. This should be called\n   * when an element should update based on some state not triggered by setting\n   * a reactive property. In this case, pass no arguments. It should also be\n   * called when manually implementing a property setter. In this case, pass the\n   * property `name` and `oldValue` to ensure that any configured property\n   * options are honored.\n   *\n   * @param name name of requesting property\n   * @param oldValue old value of requesting property\n   * @param options property options to use instead of the previously\n   *     configured options\n   * @param useNewValue if true, the newValue argument is used instead of\n   *     reading the property value. This is important to use if the reactive\n   *     property is a standard private accessor, as opposed to a plain\n   *     property, since private members can't be dynamically read by name.\n   * @param newValue the new value of the property. This is only used if\n   *     `useNewValue` is true.\n   * @category updates\n   */\n  requestUpdate(\n    name?: PropertyKey,\n    oldValue?: unknown,\n    options?: PropertyDeclaration,\n    useNewValue = false,\n    newValue?: unknown\n  ): void {\n    // If we have a property key, perform property update steps.\n    if (name !== undefined) {\n      if (DEV_MODE && (name as unknown) instanceof Event) {\n        issueWarning(\n          ``,\n          `The requestUpdate() method was called with an Event as the property name. This is probably a mistake caused by binding this.requestUpdate as an event listener. Instead bind a function that will call it with no arguments: () => this.requestUpdate()`\n        );\n      }\n      const ctor = this.constructor as typeof ReactiveElement;\n      if (useNewValue === false) {\n        newValue = this[name as keyof this];\n      }\n      options ??= ctor.getPropertyOptions(name);\n      const changed =\n        (options.hasChanged ?? notEqual)(newValue, oldValue) ||\n        // When there is no change, check a corner case that can occur when\n        // 1. there's a initial value which was not reflected\n        // 2. the property is subsequently set to this value.\n        // For example, `prop: {useDefault: true, reflect: true}`\n        // and el.prop = 'foo'. This should be considered a change if the\n        // attribute is not set because we will now reflect the property to the attribute.\n        (options.useDefault &&\n          options.reflect &&\n          newValue === this.__defaultValues?.get(name) &&\n          !this.hasAttribute(ctor.__attributeNameForProperty(name, options)!));\n      if (changed) {\n        this._$changeProperty(name, oldValue, options);\n      } else {\n        // Abort the request if the property should not be considered changed.\n        return;\n      }\n    }\n    if (this.isUpdatePending === false) {\n      this.__updatePromise = this.__enqueueUpdate();\n    }\n  }\n\n  /**\n   * @internal\n   */\n  _$changeProperty(\n    name: PropertyKey,\n    oldValue: unknown,\n    {useDefault, reflect, wrapped}: PropertyDeclaration,\n    initializeValue?: unknown\n  ) {\n    // Record default value when useDefault is used. This allows us to\n    // restore this value when the attribute is removed.\n    if (useDefault && !(this.__defaultValues ??= new Map()).has(name)) {\n      this.__defaultValues.set(\n        name,\n        initializeValue ?? oldValue ?? this[name as keyof this]\n      );\n      // if this is not wrapping an accessor, it must be an initial setting\n      // and in this case we do not want to record the change or reflect.\n      if (wrapped !== true || initializeValue !== undefined) {\n        return;\n      }\n    }\n    // TODO (justinfagnani): Create a benchmark of Map.has() + Map.set(\n    // vs just Map.set()\n    if (!this._$changedProperties.has(name)) {\n      // On the initial change, the old value should be `undefined`, except\n      // with `useDefault`\n      if (!this.hasUpdated && !useDefault) {\n        oldValue = undefined;\n      }\n      this._$changedProperties.set(name, oldValue);\n    }\n    // Add to reflecting properties set.\n    // Note, it's important that every change has a chance to add the\n    // property to `__reflectingProperties`. This ensures setting\n    // attribute + property reflects correctly.\n    if (reflect === true && this.__reflectingProperty !== name) {\n      (this.__reflectingProperties ??= new Set<PropertyKey>()).add(name);\n    }\n  }\n\n  /**\n   * Sets up the element to asynchronously update.\n   */\n  private async __enqueueUpdate() {\n    this.isUpdatePending = true;\n    try {\n      // Ensure any previous update has resolved before updating.\n      // This `await` also ensures that property changes are batched.\n      await this.__updatePromise;\n    } catch (e) {\n      // Refire any previous errors async so they do not disrupt the update\n      // cycle. Errors are refired so developers have a chance to observe\n      // them, and this can be done by implementing\n      // `window.onunhandledrejection`.\n      Promise.reject(e);\n    }\n    const result = this.scheduleUpdate();\n    // If `scheduleUpdate` returns a Promise, we await it. This is done to\n    // enable coordinating updates with a scheduler. Note, the result is\n    // checked to avoid delaying an additional microtask unless we need to.\n    if (result != null) {\n      await result;\n    }\n    return !this.isUpdatePending;\n  }\n\n  /**\n   * Schedules an element update. You can override this method to change the\n   * timing of updates by returning a Promise. The update will await the\n   * returned Promise, and you should resolve the Promise to allow the update\n   * to proceed. If this method is overridden, `super.scheduleUpdate()`\n   * must be called.\n   *\n   * For instance, to schedule updates to occur just before the next frame:\n   *\n   * ```ts\n   * override protected async scheduleUpdate(): Promise<unknown> {\n   *   await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n   *   super.scheduleUpdate();\n   * }\n   * ```\n   * @category updates\n   */\n  protected scheduleUpdate(): void | Promise<unknown> {\n    const result = this.performUpdate();\n    if (\n      DEV_MODE &&\n      (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n        'async-perform-update'\n      ) &&\n      typeof (result as unknown as Promise<unknown> | undefined)?.then ===\n        'function'\n    ) {\n      issueWarning(\n        'async-perform-update',\n        `Element ${this.localName} returned a Promise from performUpdate(). ` +\n          `This behavior is deprecated and will be removed in a future ` +\n          `version of ReactiveElement.`\n      );\n    }\n    return result;\n  }\n\n  /**\n   * Performs an element update. Note, if an exception is thrown during the\n   * update, `firstUpdated` and `updated` will not be called.\n   *\n   * Call `performUpdate()` to immediately process a pending update. This should\n   * generally not be needed, but it can be done in rare cases when you need to\n   * update synchronously.\n   *\n   * @category updates\n   */\n  protected performUpdate(): void {\n    // Abort any update if one is not pending when this is called.\n    // This can happen if `performUpdate` is called early to \"flush\"\n    // the update.\n    if (!this.isUpdatePending) {\n      return;\n    }\n    debugLogEvent?.({kind: 'update'});\n    if (!this.hasUpdated) {\n      // Create renderRoot before first update. This occurs in `connectedCallback`\n      // but is done here to support out of tree calls to `enableUpdating`/`performUpdate`.\n      (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n        this.createRenderRoot();\n      if (DEV_MODE) {\n        // Produce warning if any reactive properties on the prototype are\n        // shadowed by class fields. Instance fields set before upgrade are\n        // deleted by this point, so any own property is caused by class field\n        // initialization in the constructor.\n        const ctor = this.constructor as typeof ReactiveElement;\n        const shadowedProperties = [...ctor.elementProperties.keys()].filter(\n          (p) => this.hasOwnProperty(p) && p in getPrototypeOf(this)\n        );\n        if (shadowedProperties.length) {\n          throw new Error(\n            `The following properties on element ${this.localName} will not ` +\n              `trigger updates as expected because they are set using class ` +\n              `fields: ${shadowedProperties.join(', ')}. ` +\n              `Native class fields and some compiled output will overwrite ` +\n              `accessors used for detecting changes. See ` +\n              `https://lit.dev/msg/class-field-shadowing ` +\n              `for more information.`\n          );\n        }\n      }\n      // Mixin instance properties once, if they exist.\n      if (this.__instanceProperties) {\n        // TODO (justinfagnani): should we use the stored value? Could a new value\n        // have been set since we stored the own property value?\n        for (const [p, value] of this.__instanceProperties) {\n          this[p as keyof this] = value as this[keyof this];\n        }\n        this.__instanceProperties = undefined;\n      }\n      // Trigger initial value reflection and populate the initial\n      // `changedProperties` map, but only for the case of properties created\n      // via `createProperty` on accessors, which will not have already\n      // populated the `changedProperties` map since they are not set.\n      // We can't know if these accessors had initializers, so we just set\n      // them anyway - a difference from experimental decorators on fields and\n      // standard decorators on auto-accessors.\n      // For context see:\n      // https://github.com/lit/lit/pull/4183#issuecomment-1711959635\n      const elementProperties = (this.constructor as typeof ReactiveElement)\n        .elementProperties;\n      if (elementProperties.size > 0) {\n        for (const [p, options] of elementProperties) {\n          const {wrapped} = options;\n          const value = this[p as keyof this];\n          if (\n            wrapped === true &&\n            !this._$changedProperties.has(p) &&\n            value !== undefined\n          ) {\n            this._$changeProperty(p, undefined, options, value);\n          }\n        }\n      }\n    }\n    let shouldUpdate = false;\n    const changedProperties = this._$changedProperties;\n    try {\n      shouldUpdate = this.shouldUpdate(changedProperties);\n      if (shouldUpdate) {\n        this.willUpdate(changedProperties);\n        this.__controllers?.forEach((c) => c.hostUpdate?.());\n        this.update(changedProperties);\n      } else {\n        this.__markUpdated();\n      }\n    } catch (e) {\n      // Prevent `firstUpdated` and `updated` from running when there's an\n      // update exception.\n      shouldUpdate = false;\n      // Ensure element can accept additional updates after an exception.\n      this.__markUpdated();\n      throw e;\n    }\n    // The update is no longer considered pending and further updates are now allowed.\n    if (shouldUpdate) {\n      this._$didUpdate(changedProperties);\n    }\n  }\n\n  /**\n   * Invoked before `update()` to compute values needed during the update.\n   *\n   * Implement `willUpdate` to compute property values that depend on other\n   * properties and are used in the rest of the update process.\n   *\n   * ```ts\n   * willUpdate(changedProperties) {\n   *   // only need to check changed properties for an expensive computation.\n   *   if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n   *     this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n   *   }\n   * }\n   *\n   * render() {\n   *   return html`SHA: ${this.sha}`;\n   * }\n   * ```\n   *\n   * @category updates\n   */\n  protected willUpdate(_changedProperties: PropertyValues): void {}\n\n  // Note, this is an override point for polyfill-support.\n  // @internal\n  _$didUpdate(changedProperties: PropertyValues) {\n    this.__controllers?.forEach((c) => c.hostUpdated?.());\n    if (!this.hasUpdated) {\n      this.hasUpdated = true;\n      this.firstUpdated(changedProperties);\n    }\n    this.updated(changedProperties);\n    if (\n      DEV_MODE &&\n      this.isUpdatePending &&\n      (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n        'change-in-update'\n      )\n    ) {\n      issueWarning(\n        'change-in-update',\n        `Element ${this.localName} scheduled an update ` +\n          `(generally because a property was set) ` +\n          `after an update completed, causing a new update to be scheduled. ` +\n          `This is inefficient and should be avoided unless the next update ` +\n          `can only be scheduled as a side effect of the previous update.`\n      );\n    }\n  }\n\n  private __markUpdated() {\n    this._$changedProperties = new Map();\n    this.isUpdatePending = false;\n  }\n\n  /**\n   * Returns a Promise that resolves when the element has completed updating.\n   * The Promise value is a boolean that is `true` if the element completed the\n   * update without triggering another update. The Promise result is `false` if\n   * a property was set inside `updated()`. If the Promise is rejected, an\n   * exception was thrown during the update.\n   *\n   * To await additional asynchronous work, override the `getUpdateComplete`\n   * method. For example, it is sometimes useful to await a rendered element\n   * before fulfilling this Promise. To do this, first await\n   * `super.getUpdateComplete()`, then any subsequent state.\n   *\n   * @return A promise of a boolean that resolves to true if the update completed\n   *     without triggering another update.\n   * @category updates\n   */\n  get updateComplete(): Promise<boolean> {\n    return this.getUpdateComplete();\n  }\n\n  /**\n   * Override point for the `updateComplete` promise.\n   *\n   * It is not safe to override the `updateComplete` getter directly due to a\n   * limitation in TypeScript which means it is not possible to call a\n   * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n   * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n   * This method should be overridden instead. For example:\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   override async getUpdateComplete() {\n   *     const result = await super.getUpdateComplete();\n   *     await this._myChild.updateComplete;\n   *     return result;\n   *   }\n   * }\n   * ```\n   *\n   * @return A promise of a boolean that resolves to true if the update completed\n   *     without triggering another update.\n   * @category updates\n   */\n  protected getUpdateComplete(): Promise<boolean> {\n    return this.__updatePromise;\n  }\n\n  /**\n   * Controls whether or not `update()` should be called when the element requests\n   * an update. By default, this method always returns `true`, but this can be\n   * customized to control when to update.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n    return true;\n  }\n\n  /**\n   * Updates the element. This method reflects property values to attributes.\n   * It can be overridden to render and keep updated element DOM.\n   * Setting properties inside this method will *not* trigger\n   * another update.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected update(_changedProperties: PropertyValues) {\n    // The forEach() expression will only run when __reflectingProperties is\n    // defined, and it returns undefined, setting __reflectingProperties to\n    // undefined\n    this.__reflectingProperties &&= this.__reflectingProperties.forEach((p) =>\n      this.__propertyToAttribute(p, this[p as keyof this])\n    ) as undefined;\n    this.__markUpdated();\n  }\n\n  /**\n   * Invoked whenever the element is updated. Implement to perform\n   * post-updating tasks via DOM APIs, for example, focusing an element.\n   *\n   * Setting properties inside this method will trigger the element to update\n   * again after this update cycle completes.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected updated(_changedProperties: PropertyValues) {}\n\n  /**\n   * Invoked when the element is first updated. Implement to perform one time\n   * work on the element after update.\n   *\n   * ```ts\n   * firstUpdated() {\n   *   this.renderRoot.getElementById('my-text-area').focus();\n   * }\n   * ```\n   *\n   * Setting properties inside this method will trigger the element to update\n   * again after this update cycle completes.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n// Assigned here to work around a jscompiler bug with static fields\n// when compiling to ES5.\n// https://github.com/google/closure-compiler/issues/3177\n(ReactiveElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('elementProperties', ReactiveElement)\n] = new Map();\n(ReactiveElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('finalized', ReactiveElement)\n] = new Map();\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n  // Default warning set.\n  ReactiveElement.enabledWarnings = [\n    'change-in-update',\n    'async-perform-update',\n  ];\n  const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n    if (\n      !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n    ) {\n      ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n    }\n  };\n  ReactiveElement.enableWarning = function (\n    this: typeof ReactiveElement,\n    warning: WarningKind\n  ) {\n    ensureOwnWarnings(this);\n    if (!this.enabledWarnings!.includes(warning)) {\n      this.enabledWarnings!.push(warning);\n    }\n  };\n  ReactiveElement.disableWarning = function (\n    this: typeof ReactiveElement,\n    warning: WarningKind\n  ) {\n    ensureOwnWarnings(this);\n    const i = this.enabledWarnings!.indexOf(warning);\n    if (i >= 0) {\n      this.enabledWarnings!.splice(i, 1);\n    }\n  };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('2.1.2');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. Loading multiple versions ` +\n        `is not recommended.`\n    );\n  });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry =\n      | TemplatePrep\n      | TemplateInstantiated\n      | TemplateInstantiatedAndUpdated\n      | TemplateUpdating\n      | BeginRender\n      | EndRender\n      | CommitPartEntry\n      | SetPartValue;\n    export interface TemplatePrep {\n      kind: 'template prep';\n      template: Template;\n      strings: TemplateStringsArray;\n      clonableTemplate: HTMLTemplateElement;\n      parts: TemplatePart[];\n    }\n    export interface BeginRender {\n      kind: 'begin render';\n      id: number;\n      value: unknown;\n      container: RenderRootNode;\n      options: RenderOptions | undefined;\n      part: ChildPart | undefined;\n    }\n    export interface EndRender {\n      kind: 'end render';\n      id: number;\n      value: unknown;\n      container: RenderRootNode;\n      options: RenderOptions | undefined;\n      part: ChildPart;\n    }\n    export interface TemplateInstantiated {\n      kind: 'template instantiated';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      fragment: Node;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface TemplateInstantiatedAndUpdated {\n      kind: 'template instantiated and updated';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      fragment: Node;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface TemplateUpdating {\n      kind: 'template updating';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface SetPartValue {\n      kind: 'set part';\n      part: Part;\n      value: unknown;\n      valueIndex: number;\n      values: unknown[];\n      templateInstance: TemplateInstance;\n    }\n\n    export type CommitPartEntry =\n      | CommitNothingToChildEntry\n      | CommitText\n      | CommitNode\n      | CommitAttribute\n      | CommitProperty\n      | CommitBooleanAttribute\n      | CommitEventListener\n      | CommitToElementBinding;\n\n    export interface CommitNothingToChildEntry {\n      kind: 'commit nothing to child';\n      start: ChildNode;\n      end: ChildNode | null;\n      parent: Disconnectable | undefined;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitText {\n      kind: 'commit text';\n      node: Text;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitNode {\n      kind: 'commit node';\n      start: Node;\n      parent: Disconnectable | undefined;\n      value: Node;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitAttribute {\n      kind: 'commit attribute';\n      element: Element;\n      name: string;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitProperty {\n      kind: 'commit property';\n      element: Element;\n      name: string;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitBooleanAttribute {\n      kind: 'commit boolean attribute';\n      element: Element;\n      name: string;\n      value: boolean;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitEventListener {\n      kind: 'commit event listener';\n      element: Element;\n      name: string;\n      value: unknown;\n      oldListener: unknown;\n      options: RenderOptions | undefined;\n      // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n      removeListener: boolean;\n      // True if we're adding a new event listener (e.g. because first render, or settings changed)\n      addListener: boolean;\n    }\n\n    export interface CommitToElementBinding {\n      kind: 'commit to element binding';\n      element: Element;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n  }\n}\n\ninterface DebugLoggingWindow {\n  // Even in dev mode, we generally don't want to emit these events, as that's\n  // another level of cost, so only emit them when DEV_MODE is true _and_ when\n  // window.emitLitDebugEvents is true.\n  emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n  ? (event: LitUnstable.DebugLog.Entry) => {\n      const shouldEmit = (global as unknown as DebugLoggingWindow)\n        .emitLitDebugLogEvents;\n      if (!shouldEmit) {\n        return;\n      }\n      global.dispatchEvent(\n        new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n          detail: event,\n        })\n      );\n    }\n  : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += code\n      ? ` See https://lit.dev/msg/${code} for more information.`\n      : '';\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n\n  queueMicrotask(() => {\n    issueWarning(\n      'dev-mode',\n      `Lit is in dev mode. Not recommended for production!`\n    );\n  });\n}\n\nconst wrap =\n  ENABLE_SHADYDOM_NOPATCH &&\n  global.ShadyDOM?.inUse &&\n  global.ShadyDOM?.noPatch === true\n    ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n    : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\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 = trustedTypes\n  ? trustedTypes.createPolicy('lit-html', {\n      createHTML: (s) => s,\n    })\n  : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n *     is being written to. Note that this is just an exemplar node, the write\n *     may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n *     be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n  node: Node,\n  name: string,\n  type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n *     the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n *     unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n  _node: Node,\n  _name: string,\n  _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n  if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n    return;\n  }\n  if (sanitizerFactoryInternal !== noopSanitizer) {\n    throw new Error(\n      `Attempted to overwrite existing lit-html security policy.` +\n        ` setSanitizeDOMValueFactory should be called at most once.`\n    );\n  }\n  sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n  sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n  return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n  NODE_MODE && global.document === undefined\n    ? ({\n        createTreeWalker() {\n          return {};\n        },\n      } as unknown as Document)\n    : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n  value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n  isArray(value) ||\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n *   (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n *  * The name: any character except a whitespace character, (\"), ('), \">\",\n *    \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\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 */\nconst tagEndRegex = new RegExp(\n  `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n  'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n  // This property needs to remain unminified.\n  ['_$litType$']: T;\n  strings: TemplateStringsArray;\n  values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n  | UncompiledTemplateResult<T>\n  | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n  UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n  // This is a factory in order to make template initialization lazy\n  // and allow ShadyRenderOptions scope to be passed in.\n  // This property needs to remain unminified.\n  ['_$litType$']: CompiledTemplate;\n  values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n  // el is overridden to be optional. We initialize it on first render\n  el?: HTMLTemplateElement;\n\n  // The prepared HTML string to create a template element from.\n  // The type is a TemplateStringsArray to guarantee that the value came from\n  // source code, preventing a JSON injection attack.\n  h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n  <T extends ResultType>(type: T) =>\n  (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n    // Warn against templates octal escape sequences\n    // We do this here rather than in render so that the warning is closer to the\n    // template definition.\n    if (DEV_MODE && strings.some((s) => s === undefined)) {\n      console.warn(\n        'Some template strings are undefined.\\n' +\n          'This is probably caused by illegal octal escape sequences.'\n      );\n    }\n    if (DEV_MODE) {\n      // Import static-html.js results in a circular dependency which g3 doesn't\n      // handle. Instead we know that static values must have the field\n      // `_$litStatic$`.\n      if (\n        values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n      ) {\n        issueWarning(\n          '',\n          `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n            `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n        );\n      }\n    }\n    return {\n      // This property needs to remain unminified.\n      ['_$litType$']: type,\n      strings,\n      values,\n    };\n  };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n *   <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n *     ${rect}\n *   </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n *   <math>\n *     ${num}\n *   </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n *  user.isAdmin\n *    ? html`<button>DELETE</button>`\n *    : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n  /**\n   * An object to use as the `this` value for event listeners. It's often\n   * useful to set this to the host component rendering a template.\n   */\n  host?: object;\n  /**\n   * A DOM node before which to render content in the container.\n   */\n  renderBefore?: ChildNode | null;\n  /**\n   * Node used for cloning the template (`importNode` will be called on this\n   * node). This controls the `ownerDocument` of the rendered DOM, along with\n   * any inherited context. Defaults to the global `document`.\n   */\n  creationScope?: {importNode(node: Node, deep?: boolean): Node};\n  /**\n   * The initial connected state for the top-level part being rendered. If no\n   * `isConnected` option is set, `AsyncDirective`s will be connected by\n   * default. Set to `false` if the initial render occurs in a disconnected tree\n   * and `AsyncDirective`s should see `isConnected === false` for their initial\n   * render. The `part.setConnected()` method must be used subsequent to initial\n   * render to change the connected state of the part.\n   */\n  isConnected?: boolean;\n}\n\n/**\n * The root DOM node for rendering.\n */\nexport type RenderRootNode = HTMLElement | SVGElement | DocumentFragment;\n\nconst walker = d.createTreeWalker(\n  d,\n  129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n  _$parent?: DirectiveParent;\n  _$isConnected: boolean;\n  __directive?: Directive;\n  __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n  tsa: TemplateStringsArray,\n  stringFromTSA: string\n): TrustedHTML {\n  // A security check to prevent spoofing of Lit template results.\n  // In the future, we may be able to replace this with Array.isTemplateObject,\n  // though we might need to make that check inside of the html and svg\n  // functions, because precompiled templates don't come in as\n  // TemplateStringArray objects.\n  if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n    let message = 'invalid template strings array';\n    if (DEV_MODE) {\n      message = `\n          Internal Error: expected template strings to be an array\n          with a 'raw' field. Faking a template strings array by\n          calling html or svg like an ordinary function is effectively\n          the same as calling unsafeHtml and can lead to major security\n          issues, e.g. opening your code up to XSS attacks.\n          If you're using the html or svg tagged template functions normally\n          and still seeing this error, please file a bug at\n          https://github.com/lit/lit/issues/new?template=bug_report.md\n          and include information about your build tooling, if any.\n        `\n        .trim()\n        .replace(/\\n */g, '\\n');\n    }\n    throw new Error(message);\n  }\n  return policy !== undefined\n    ? policy.createHTML(stringFromTSA)\n    : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n *     to avoid object fields since this code is shared with non-minified SSR\n *     code)\n */\nconst getTemplateHtml = (\n  strings: TemplateStringsArray,\n  type: ResultType\n): [TrustedHTML, Array<string>] => {\n  // Insert makers into the template HTML to represent the position of\n  // bindings. The following code scans the template strings to determine the\n  // syntactic position of the bindings. They can be in text position, where\n  // we insert an HTML comment, attribute value position, where we insert a\n  // sentinel string and re-write the attribute name, or inside a tag where\n  // we insert the sentinel string.\n  const l = strings.length - 1;\n  // Stores the case-sensitive bound attribute names in the order of their\n  // parts. ElementParts are also reflected in this array as undefined\n  // rather than a string, to disambiguate from attribute bindings.\n  const attrNames: Array<string> = [];\n  let html =\n    type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n  // When we're inside a raw text tag (not it's text content), the regex\n  // will still be tagRegex so we can find attributes, but will switch to\n  // this regex when the tag ends.\n  let rawTextEndRegex: RegExp | undefined;\n\n  // The current parsing state, represented as a reference to one of the\n  // regexes\n  let regex = textEndRegex;\n\n  for (let i = 0; i < l; i++) {\n    const s = strings[i];\n    // The index of the end of the last attribute name. When this is\n    // positive at end of a string, it means we're in an attribute value\n    // position and need to rewrite the attribute name.\n    // We also use a special value of -2 to indicate that we encountered\n    // the end of a string in attribute name position.\n    let attrNameEndIndex = -1;\n    let attrName: string | undefined;\n    let lastIndex = 0;\n    let match!: RegExpExecArray | null;\n\n    // The conditions in this loop handle the current parse state, and the\n    // assignments to the `regex` variable are the state transitions.\n    while (lastIndex < s.length) {\n      // Make sure we start searching from where we previously left off\n      regex.lastIndex = lastIndex;\n      match = regex.exec(s);\n      if (match === null) {\n        break;\n      }\n      lastIndex = regex.lastIndex;\n      if (regex === textEndRegex) {\n        if (match[COMMENT_START] === '!--') {\n          regex = commentEndRegex;\n        } else if (match[COMMENT_START] !== undefined) {\n          // We started a weird comment, like </{\n          regex = comment2EndRegex;\n        } else if (match[TAG_NAME] !== undefined) {\n          if (rawTextElement.test(match[TAG_NAME])) {\n            // Record if we encounter a raw-text element. We'll switch to\n            // this regex at the end of the tag.\n            rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n          }\n          regex = tagEndRegex;\n        } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n          if (DEV_MODE) {\n            throw new Error(\n              'Bindings in tag names are not supported. Please use static templates instead. ' +\n                'See https://lit.dev/docs/templates/expressions/#static-expressions'\n            );\n          }\n          regex = tagEndRegex;\n        }\n      } else if (regex === tagEndRegex) {\n        if (match[ENTIRE_MATCH] === '>') {\n          // End of a tag. If we had started a raw-text element, use that\n          // regex\n          regex = rawTextEndRegex ?? textEndRegex;\n          // We may be ending an unquoted attribute value, so make sure we\n          // clear any pending attrNameEndIndex\n          attrNameEndIndex = -1;\n        } else if (match[ATTRIBUTE_NAME] === undefined) {\n          // Attribute name position\n          attrNameEndIndex = -2;\n        } else {\n          attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n          attrName = match[ATTRIBUTE_NAME];\n          regex =\n            match[QUOTE_CHAR] === undefined\n              ? tagEndRegex\n              : match[QUOTE_CHAR] === '\"'\n                ? doubleQuoteAttrEndRegex\n                : singleQuoteAttrEndRegex;\n        }\n      } else if (\n        regex === doubleQuoteAttrEndRegex ||\n        regex === singleQuoteAttrEndRegex\n      ) {\n        regex = tagEndRegex;\n      } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n        regex = textEndRegex;\n      } else {\n        // Not one of the five state regexes, so it must be the dynamically\n        // created raw text regex and we're at the close of that element.\n        regex = tagEndRegex;\n        rawTextEndRegex = undefined;\n      }\n    }\n\n    if (DEV_MODE) {\n      // If we have a attrNameEndIndex, which indicates that we should\n      // rewrite the attribute name, assert that we're in a valid attribute\n      // position - either in a tag, or a quoted attribute value.\n      console.assert(\n        attrNameEndIndex === -1 ||\n          regex === tagEndRegex ||\n          regex === singleQuoteAttrEndRegex ||\n          regex === doubleQuoteAttrEndRegex,\n        'unexpected parse state B'\n      );\n    }\n\n    // We have four cases:\n    //  1. We're in text position, and not in a raw text element\n    //     (regex === textEndRegex): insert a comment marker.\n    //  2. We have a non-negative attrNameEndIndex which means we need to\n    //     rewrite the attribute name to add a bound attribute suffix.\n    //  3. We're at the non-first binding in a multi-binding attribute, use a\n    //     plain marker.\n    //  4. We're somewhere else inside the tag. If we're in attribute name\n    //     position (attrNameEndIndex === -2), add a sequential suffix to\n    //     generate a unique attribute name.\n\n    // Detect a binding next to self-closing tag end and insert a space to\n    // separate the marker from the tag end:\n    const end =\n      regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n    html +=\n      regex === textEndRegex\n        ? s + nodeMarker\n        : attrNameEndIndex >= 0\n          ? (attrNames.push(attrName!),\n            s.slice(0, attrNameEndIndex) +\n              boundAttributeSuffix +\n              s.slice(attrNameEndIndex)) +\n            marker +\n            end\n          : s + marker + (attrNameEndIndex === -2 ? i : end);\n  }\n\n  const htmlResult: string | TrustedHTML =\n    html +\n    (strings[l] || '<?>') +\n    (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n  // Returned as an array for terseness\n  return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n  /** @internal */\n  el!: HTMLTemplateElement;\n\n  parts: Array<TemplatePart> = [];\n\n  constructor(\n    // This property needs to remain unminified.\n    {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n    options?: RenderOptions\n  ) {\n    let node: Node | null;\n    let nodeIndex = 0;\n    let attrNameIndex = 0;\n    const partCount = strings.length - 1;\n    const parts = this.parts;\n\n    // Create template element\n    const [html, attrNames] = getTemplateHtml(strings, type);\n    this.el = Template.createElement(html, options);\n    walker.currentNode = this.el.content;\n\n    // Re-parent SVG or MathML nodes into template root\n    if (type === SVG_RESULT || type === MATHML_RESULT) {\n      const wrapper = this.el.content.firstChild!;\n      wrapper.replaceWith(...wrapper.childNodes);\n    }\n\n    // Walk the template to find binding markers and create TemplateParts\n    while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n      if (node.nodeType === 1) {\n        if (DEV_MODE) {\n          const tag = (node as Element).localName;\n          // Warn if `textarea` includes an expression and throw if `template`\n          // does since these are not supported. We do this by checking\n          // innerHTML for anything that looks like a marker. This catches\n          // cases like bindings in textarea there markers turn into text nodes.\n          if (\n            /^(?:textarea|template)$/i!.test(tag) &&\n            (node as Element).innerHTML.includes(marker)\n          ) {\n            const m =\n              `Expressions are not supported inside \\`${tag}\\` ` +\n              `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n              `information.`;\n            if (tag === 'template') {\n              throw new Error(m);\n            } else issueWarning('', m);\n          }\n        }\n        // TODO (justinfagnani): for attempted dynamic tag names, we don't\n        // increment the bindingIndex, and it'll be off by 1 in the element\n        // and off by two after it.\n        if ((node as Element).hasAttributes()) {\n          for (const name of (node as Element).getAttributeNames()) {\n            if (name.endsWith(boundAttributeSuffix)) {\n              const realName = attrNames[attrNameIndex++];\n              const value = (node as Element).getAttribute(name)!;\n              const statics = value.split(marker);\n              const m = /([.?@])?(.*)/.exec(realName)!;\n              parts.push({\n                type: ATTRIBUTE_PART,\n                index: nodeIndex,\n                name: m[2],\n                strings: statics,\n                ctor:\n                  m[1] === '.'\n                    ? PropertyPart\n                    : m[1] === '?'\n                      ? BooleanAttributePart\n                      : m[1] === '@'\n                        ? EventPart\n                        : AttributePart,\n              });\n              (node as Element).removeAttribute(name);\n            } else if (name.startsWith(marker)) {\n              parts.push({\n                type: ELEMENT_PART,\n                index: nodeIndex,\n              });\n              (node as Element).removeAttribute(name);\n            }\n          }\n        }\n        // TODO (justinfagnani): benchmark the regex against testing for each\n        // of the 3 raw text element names.\n        if (rawTextElement.test((node as Element).tagName)) {\n          // For raw text elements we need to split the text content on\n          // markers, create a Text node for each segment, and create\n          // a TemplatePart for each marker.\n          const strings = (node as Element).textContent!.split(marker);\n          const lastIndex = strings.length - 1;\n          if (lastIndex > 0) {\n            (node as Element).textContent = trustedTypes\n              ? (trustedTypes.emptyScript as unknown as '')\n              : '';\n            // Generate a new text node for each literal section\n            // These nodes are also used as the markers for child parts\n            for (let i = 0; i < lastIndex; i++) {\n              (node as Element).append(strings[i], createMarker());\n              // Walk past the marker node we just added\n              walker.nextNode();\n              parts.push({type: CHILD_PART, index: ++nodeIndex});\n            }\n            // Note because this marker is added after the walker's current\n            // node, it will be walked to in the outer loop (and ignored), so\n            // we don't need to adjust nodeIndex here\n            (node as Element).append(strings[lastIndex], createMarker());\n          }\n        }\n      } else if (node.nodeType === 8) {\n        const data = (node as Comment).data;\n        if (data === markerMatch) {\n          parts.push({type: CHILD_PART, index: nodeIndex});\n        } else {\n          let i = -1;\n          while ((i = (node as Comment).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            parts.push({type: COMMENT_PART, index: nodeIndex});\n            // Move to the end of the match\n            i += marker.length - 1;\n          }\n        }\n      }\n      nodeIndex++;\n    }\n\n    if (DEV_MODE) {\n      // If there was a duplicate attribute on a tag, then when the tag is\n      // parsed into an element the attribute gets de-duplicated. We can detect\n      // this mismatch if we haven't precisely consumed every attribute name\n      // when preparing the template. This works because `attrNames` is built\n      // from the template string and `attrNameIndex` comes from processing the\n      // resulting DOM.\n      if (attrNames.length !== attrNameIndex) {\n        throw new Error(\n          `Detected duplicate attribute bindings. This occurs if your template ` +\n            `has duplicate attributes on an element tag. For example ` +\n            `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n            `duplicate \"disabled\" attribute. The error was detected in ` +\n            `the following template: \\n` +\n            '`' +\n            strings.join('${...}') +\n            '`'\n        );\n      }\n    }\n\n    // We could set walker.currentNode to another node here to prevent a memory\n    // leak, but every time we prepare a template, we immediately render it\n    // and re-use the walker in new TemplateInstance._clone().\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'template prep',\n        template: this,\n        clonableTemplate: this.el,\n        parts: this.parts,\n        strings,\n      });\n  }\n\n  // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n  /** @nocollapse */\n  static createElement(html: TrustedHTML, _options?: RenderOptions) {\n    const el = d.createElement('template');\n    el.innerHTML = html as unknown as string;\n    return el;\n  }\n}\n\nexport interface Disconnectable {\n  _$parent?: Disconnectable;\n  _$disconnectableChildren?: Set<Disconnectable>;\n  // Rather than hold connection state on instances, Disconnectables recursively\n  // fetch the connection state from the RootPart they are connected in via\n  // getters up the Disconnectable tree via _$parent references. This pushes the\n  // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n  // needing to pass all Disconnectables (parts, template instances, and\n  // directives) their connection state each time it changes, which would be\n  // costly for trees that have no AsyncDirectives.\n  _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n  part: ChildPart | AttributePart | ElementPart,\n  value: unknown,\n  parent: DirectiveParent = part,\n  attributeIndex?: number\n): unknown {\n  // Bail early if the value is explicitly noChange. Note, this means any\n  // nested directive is still attached and is not run.\n  if (value === noChange) {\n    return value;\n  }\n  let currentDirective =\n    attributeIndex !== undefined\n      ? (parent as AttributePart).__directives?.[attributeIndex]\n      : (parent as ChildPart | ElementPart | Directive).__directive;\n  const nextDirectiveConstructor = isPrimitive(value)\n    ? undefined\n    : // This property needs to remain unminified.\n      (value as DirectiveResult)['_$litDirective$'];\n  if (currentDirective?.constructor !== nextDirectiveConstructor) {\n    // This property needs to remain unminified.\n    currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n    if (nextDirectiveConstructor === undefined) {\n      currentDirective = undefined;\n    } else {\n      currentDirective = new nextDirectiveConstructor(part as PartInfo);\n      currentDirective._$initialize(part, parent, attributeIndex);\n    }\n    if (attributeIndex !== undefined) {\n      ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n        currentDirective;\n    } else {\n      (parent as ChildPart | Directive).__directive = currentDirective;\n    }\n  }\n  if (currentDirective !== undefined) {\n    value = resolveDirective(\n      part,\n      currentDirective._$resolve(part, (value as DirectiveResult).values),\n      currentDirective,\n      attributeIndex\n    );\n  }\n  return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n  _$template: Template;\n  _$parts: Array<Part | undefined> = [];\n\n  /** @internal */\n  _$parent: ChildPart;\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  constructor(template: Template, parent: ChildPart) {\n    this._$template = template;\n    this._$parent = parent;\n  }\n\n  // Called by ChildPart parentNode getter\n  get parentNode() {\n    return this._$parent.parentNode;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  // This method is separate from the constructor because we need to return a\n  // DocumentFragment and we don't want to hold onto it with an instance field.\n  _clone(options: RenderOptions | undefined) {\n    const {\n      el: {content},\n      parts: parts,\n    } = this._$template;\n    const fragment = (options?.creationScope ?? d).importNode(content, true);\n    walker.currentNode = fragment;\n\n    let node = walker.nextNode()!;\n    let nodeIndex = 0;\n    let partIndex = 0;\n    let templatePart = parts[0];\n\n    while (templatePart !== undefined) {\n      if (nodeIndex === templatePart.index) {\n        let part: Part | undefined;\n        if (templatePart.type === CHILD_PART) {\n          part = new ChildPart(\n            node as HTMLElement,\n            node.nextSibling,\n            this,\n            options\n          );\n        } else if (templatePart.type === ATTRIBUTE_PART) {\n          part = new templatePart.ctor(\n            node as HTMLElement,\n            templatePart.name,\n            templatePart.strings,\n            this,\n            options\n          );\n        } else if (templatePart.type === ELEMENT_PART) {\n          part = new ElementPart(node as HTMLElement, this, options);\n        }\n        this._$parts.push(part);\n        templatePart = parts[++partIndex];\n      }\n      if (nodeIndex !== templatePart?.index) {\n        node = walker.nextNode()!;\n        nodeIndex++;\n      }\n    }\n    // We need to set the currentNode away from the cloned tree so that we\n    // don't hold onto the tree even if the tree is detached and should be\n    // freed.\n    walker.currentNode = d;\n    return fragment;\n  }\n\n  _update(values: Array<unknown>) {\n    let i = 0;\n    for (const part of this._$parts) {\n      if (part !== undefined) {\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'set part',\n            part,\n            value: values[i],\n            valueIndex: i,\n            values,\n            templateInstance: this,\n          });\n        if ((part as AttributePart).strings !== undefined) {\n          (part as AttributePart)._$setValue(values, part as AttributePart, i);\n          // The number of values the part consumes is part.strings.length - 1\n          // since values are in between template spans. We increment i by 1\n          // later in the loop, so increment it by part.strings.length - 2 here\n          i += (part as AttributePart).strings!.length - 2;\n        } else {\n          part._$setValue(values[i]);\n        }\n      }\n      i++;\n    }\n  }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n  readonly type: typeof ATTRIBUTE_PART;\n  readonly index: number;\n  readonly name: string;\n  readonly ctor: typeof AttributePart;\n  readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n  readonly type: typeof CHILD_PART;\n  readonly index: number;\n};\ntype ElementTemplatePart = {\n  readonly type: typeof ELEMENT_PART;\n  readonly index: number;\n};\ntype CommentTemplatePart = {\n  readonly type: typeof COMMENT_PART;\n  readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n  | ChildTemplatePart\n  | AttributeTemplatePart\n  | ElementTemplatePart\n  | CommentTemplatePart;\n\nexport type Part =\n  | ChildPart\n  | AttributePart\n  | PropertyPart\n  | BooleanAttributePart\n  | ElementPart\n  | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n  readonly type = CHILD_PART;\n  readonly options: RenderOptions | undefined;\n  _$committedValue: unknown = nothing;\n  /** @internal */\n  __directive?: Directive;\n  /** @internal */\n  _$startNode: ChildNode;\n  /** @internal */\n  _$endNode: ChildNode | null;\n  private _textSanitizer: ValueSanitizer | undefined;\n  /** @internal */\n  _$parent: Disconnectable | undefined;\n  /**\n   * Connection state for RootParts only (i.e. ChildPart without _$parent\n   * returned from top-level `render`). This field is unused otherwise. The\n   * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n   * with this field (and a different _$isConnected getter), but the subclass\n   * caused a perf regression, possibly due to making call sites polymorphic.\n   * @internal\n   */\n  __isConnected: boolean;\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    // ChildParts that are not at the root should always be created with a\n    // parent; only RootChildNode's won't, so they return the local isConnected\n    // state\n    return this._$parent?._$isConnected ?? this.__isConnected;\n  }\n\n  // The following fields will be patched onto ChildParts when required by\n  // AsyncDirective\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n  /** @internal */\n  _$notifyConnectionChanged?(\n    isConnected: boolean,\n    removeFromParent?: boolean,\n    from?: number\n  ): void;\n  /** @internal */\n  _$reparentDisconnectables?(parent: Disconnectable): void;\n\n  constructor(\n    startNode: ChildNode,\n    endNode: ChildNode | null,\n    parent: TemplateInstance | ChildPart | undefined,\n    options: RenderOptions | undefined\n  ) {\n    this._$startNode = startNode;\n    this._$endNode = endNode;\n    this._$parent = parent;\n    this.options = options;\n    // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n    // no _$parent); the value on a non-root-part is \"don't care\", but checking\n    // for parent would be more code\n    this.__isConnected = options?.isConnected ?? true;\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      // Explicitly initialize for consistent class shape.\n      this._textSanitizer = undefined;\n    }\n  }\n\n  /**\n   * The parent node into which the part renders its content.\n   *\n   * A ChildPart's content consists of a range of adjacent child nodes of\n   * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n   * `.endNode`).\n   *\n   * - If both `.startNode` and `.endNode` are non-null, then the part's content\n   * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n   *\n   * - If `.startNode` is non-null but `.endNode` is null, then the part's\n   * content consists of all siblings following `.startNode`, up to and\n   * including the last child of `.parentNode`. If `.endNode` is non-null, then\n   * `.startNode` will always be non-null.\n   *\n   * - If both `.endNode` and `.startNode` are null, then the part's content\n   * consists of all child nodes of `.parentNode`.\n   */\n  get parentNode(): Node {\n    let parentNode: Node = wrap(this._$startNode).parentNode!;\n    const parent = this._$parent;\n    if (\n      parent !== undefined &&\n      parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n    ) {\n      // If the parentNode is a DocumentFragment, it may be because the DOM is\n      // still in the cloned fragment during initial render; if so, get the real\n      // parentNode the part will be committed into by asking the parent.\n      parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n    }\n    return parentNode;\n  }\n\n  /**\n   * The part's leading marker node, if any. See `.parentNode` for more\n   * information.\n   */\n  get startNode(): Node | null {\n    return this._$startNode;\n  }\n\n  /**\n   * The part's trailing marker node, if any. See `.parentNode` for more\n   * information.\n   */\n  get endNode(): Node | null {\n    return this._$endNode;\n  }\n\n  _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n    if (DEV_MODE && this.parentNode === null) {\n      throw new Error(\n        `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n      );\n    }\n    value = resolveDirective(this, value, directiveParent);\n    if (isPrimitive(value)) {\n      // Non-rendering child values. It's important that these do not render\n      // empty text nodes to avoid issues with preventing default <slot>\n      // fallback content.\n      if (value === nothing || value == null || value === '') {\n        if (this._$committedValue !== nothing) {\n          debugLogEvent &&\n            debugLogEvent({\n              kind: 'commit nothing to child',\n              start: this._$startNode,\n              end: this._$endNode,\n              parent: this._$parent,\n              options: this.options,\n            });\n          this._$clear();\n        }\n        this._$committedValue = nothing;\n      } else if (value !== this._$committedValue && value !== noChange) {\n        this._commitText(value);\n      }\n      // This property needs to remain unminified.\n    } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n      this._commitTemplateResult(value as TemplateResult);\n    } else if ((value as Node).nodeType !== undefined) {\n      if (DEV_MODE && this.options?.host === value) {\n        this._commitText(\n          `[probable mistake: rendered a template's host in itself ` +\n            `(commonly caused by writing \\${this} in a template]`\n        );\n        console.warn(\n          `Attempted to render the template host`,\n          value,\n          `inside itself. This is almost always a mistake, and in dev mode `,\n          `we render some warning text. In production however, we'll `,\n          `render it, which will usually result in an error, and sometimes `,\n          `in the element disappearing from the DOM.`\n        );\n        return;\n      }\n      this._commitNode(value as Node);\n    } else if (isIterable(value)) {\n      this._commitIterable(value);\n    } else {\n      // Fallback, will render the string representation\n      this._commitText(value);\n    }\n  }\n\n  private _insert<T extends Node>(node: T) {\n    return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n      node,\n      this._$endNode\n    );\n  }\n\n  private _commitNode(value: Node): void {\n    if (this._$committedValue !== value) {\n      this._$clear();\n      if (\n        ENABLE_EXTRA_SECURITY_HOOKS &&\n        sanitizerFactoryInternal !== noopSanitizer\n      ) {\n        const parentNodeName = this._$startNode.parentNode?.nodeName;\n        if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n          let message = 'Forbidden';\n          if (DEV_MODE) {\n            if (parentNodeName === 'STYLE') {\n              message =\n                `Lit does not support binding inside style nodes. ` +\n                `This is a security risk, as style injection attacks can ` +\n                `exfiltrate data and spoof UIs. ` +\n                `Consider instead using css\\`...\\` literals ` +\n                `to compose styles, and do dynamic styling with ` +\n                `css custom properties, ::parts, <slot>s, ` +\n                `and by mutating the DOM rather than stylesheets.`;\n            } else {\n              message =\n                `Lit does not support binding inside script nodes. ` +\n                `This is a security risk, as it could allow arbitrary ` +\n                `code execution.`;\n            }\n          }\n          throw new Error(message);\n        }\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit node',\n          start: this._$startNode,\n          parent: this._$parent,\n          value: value,\n          options: this.options,\n        });\n      this._$committedValue = this._insert(value);\n    }\n  }\n\n  private _commitText(value: unknown): void {\n    // If the committed value is a primitive it means we called _commitText on\n    // the previous render, and we know that this._$startNode.nextSibling is a\n    // Text node. We can now just replace the text content (.data) of the node.\n    if (\n      this._$committedValue !== nothing &&\n      isPrimitive(this._$committedValue)\n    ) {\n      const node = wrap(this._$startNode).nextSibling as Text;\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        if (this._textSanitizer === undefined) {\n          this._textSanitizer = createSanitizer(node, 'data', 'property');\n        }\n        value = this._textSanitizer(value);\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit text',\n          node,\n          value,\n          options: this.options,\n        });\n      (node as Text).data = value as string;\n    } else {\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        const textNode = d.createTextNode('');\n        this._commitNode(textNode);\n        // When setting text content, for security purposes it matters a lot\n        // what the parent is. For example, <style> and <script> need to be\n        // handled with care, while <span> does not. So first we need to put a\n        // text node into the document, then we can sanitize its content.\n        if (this._textSanitizer === undefined) {\n          this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n        }\n        value = this._textSanitizer(value);\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'commit text',\n            node: textNode,\n            value,\n            options: this.options,\n          });\n        textNode.data = value as string;\n      } else {\n        this._commitNode(d.createTextNode(value as string));\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'commit text',\n            node: wrap(this._$startNode).nextSibling as Text,\n            value,\n            options: this.options,\n          });\n      }\n    }\n    this._$committedValue = value;\n  }\n\n  private _commitTemplateResult(\n    result: TemplateResult | CompiledTemplateResult\n  ): void {\n    // This property needs to remain unminified.\n    const {values, ['_$litType$']: type} = result;\n    // If $litType$ is a number, result is a plain TemplateResult and we get\n    // the template from the template cache. If not, result is a\n    // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n    // to create the <template> element the first time we see it.\n    const template: Template | CompiledTemplate =\n      typeof type === 'number'\n        ? this._$getTemplate(result as UncompiledTemplateResult)\n        : (type.el === undefined &&\n            (type.el = Template.createElement(\n              trustFromTemplateString(type.h, type.h[0]),\n              this.options\n            )),\n          type);\n\n    if ((this._$committedValue as TemplateInstance)?._$template === template) {\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template updating',\n          template,\n          instance: this._$committedValue as TemplateInstance,\n          parts: (this._$committedValue as TemplateInstance)._$parts,\n          options: this.options,\n          values,\n        });\n      (this._$committedValue as TemplateInstance)._update(values);\n    } else {\n      const instance = new TemplateInstance(template as Template, this);\n      const fragment = instance._clone(this.options);\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template instantiated',\n          template,\n          instance,\n          parts: instance._$parts,\n          options: this.options,\n          fragment,\n          values,\n        });\n      instance._update(values);\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template instantiated and updated',\n          template,\n          instance,\n          parts: instance._$parts,\n          options: this.options,\n          fragment,\n          values,\n        });\n      this._commitNode(fragment);\n      this._$committedValue = instance;\n    }\n  }\n\n  // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n  /** @internal */\n  _$getTemplate(result: UncompiledTemplateResult) {\n    let template = templateCache.get(result.strings);\n    if (template === undefined) {\n      templateCache.set(result.strings, (template = new Template(result)));\n    }\n    return template;\n  }\n\n  private _commitIterable(value: Iterable<unknown>): void {\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\n    // If value is an array, then the previous render was of an\n    // iterable and value will contain the ChildParts from the previous\n    // render. If value is not an array, clear this part and make a new\n    // array for ChildParts.\n    if (!isArray(this._$committedValue)) {\n      this._$committedValue = [];\n      this._$clear();\n    }\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._$committedValue as ChildPart[];\n    let partIndex = 0;\n    let itemPart: ChildPart | undefined;\n\n    for (const item of value) {\n      if (partIndex === itemParts.length) {\n        // If no existing part, create a new one\n        // TODO (justinfagnani): test perf impact of always creating two parts\n        // instead of sharing parts between nodes\n        // https://github.com/lit/lit/issues/1266\n        itemParts.push(\n          (itemPart = new ChildPart(\n            this._insert(createMarker()),\n            this._insert(createMarker()),\n            this,\n            this.options\n          ))\n        );\n      } else {\n        // Reuse an existing part\n        itemPart = itemParts[partIndex];\n      }\n      itemPart._$setValue(item);\n      partIndex++;\n    }\n\n    if (partIndex < itemParts.length) {\n      // itemParts always have end nodes\n      this._$clear(\n        itemPart && wrap(itemPart._$endNode!).nextSibling,\n        partIndex\n      );\n      // Truncate the parts array so _value reflects the current state\n      itemParts.length = partIndex;\n    }\n  }\n\n  /**\n   * Removes the nodes contained within this Part from the DOM.\n   *\n   * @param start Start node to clear from, for clearing a subset of the part's\n   *     DOM (used when truncating iterables)\n   * @param from  When `start` is specified, the index within the iterable from\n   *     which ChildParts are being removed, used for disconnecting directives\n   *     in those Parts.\n   *\n   * @internal\n   */\n  _$clear(\n    start: ChildNode | null = wrap(this._$startNode).nextSibling,\n    from?: number\n  ) {\n    this._$notifyConnectionChanged?.(false, true, from);\n    while (start !== this._$endNode) {\n      // The non-null assertion is safe because if _$startNode.nextSibling is\n      // null, then _$endNode is also null, and we would not have entered this\n      // loop.\n      const n = wrap(start!).nextSibling;\n      wrap(start!).remove();\n      start = n;\n    }\n  }\n\n  /**\n   * Implementation of RootPart's `isConnected`. Note that this method\n   * should only be called on `RootPart`s (the `ChildPart` returned from a\n   * top-level `render()` call). It has no effect on non-root ChildParts.\n   * @param isConnected Whether to set\n   * @internal\n   */\n  setConnected(isConnected: boolean) {\n    if (this._$parent === undefined) {\n      this.__isConnected = isConnected;\n      this._$notifyConnectionChanged?.(isConnected);\n    } else if (DEV_MODE) {\n      throw new Error(\n        'part.setConnected() may only be called on a ' +\n          'RootPart returned from render().'\n      );\n    }\n  }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n  /**\n   * Sets the connection state for `AsyncDirective`s contained within this root\n   * ChildPart.\n   *\n   * lit-html does not automatically monitor the connectedness of DOM rendered;\n   * as such, it is the responsibility of the caller to `render` to ensure that\n   * `part.setConnected(false)` is called before the part object is potentially\n   * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n   * any resources being held. If a `RootPart` that was previously\n   * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n   * re-connect), `setConnected(true)` should be called.\n   *\n   * @param isConnected Whether directives within this tree should be connected\n   * or not\n   */\n  setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n  readonly type:\n    | typeof ATTRIBUTE_PART\n    | typeof PROPERTY_PART\n    | typeof BOOLEAN_ATTRIBUTE_PART\n    | typeof EVENT_PART = ATTRIBUTE_PART;\n  readonly element: HTMLElement;\n  readonly name: string;\n  readonly options: RenderOptions | undefined;\n\n  /**\n   * If this attribute part represents an interpolation, this contains the\n   * static strings of the interpolation. For single-value, complete bindings,\n   * this is undefined.\n   */\n  readonly strings?: ReadonlyArray<string>;\n  /** @internal */\n  _$committedValue: unknown | Array<unknown> = nothing;\n  /** @internal */\n  __directives?: Array<Directive | undefined>;\n  /** @internal */\n  _$parent: Disconnectable;\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  protected _sanitizer: ValueSanitizer | undefined;\n\n  get tagName() {\n    return this.element.tagName;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  constructor(\n    element: HTMLElement,\n    name: string,\n    strings: ReadonlyArray<string>,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    this.element = element;\n    this.name = name;\n    this._$parent = parent;\n    this.options = options;\n    if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n      this._$committedValue = new Array(strings.length - 1).fill(new String());\n      this.strings = strings;\n    } else {\n      this._$committedValue = nothing;\n    }\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      this._sanitizer = undefined;\n    }\n  }\n\n  /**\n   * Sets the value of this part by resolving the value from possibly multiple\n   * values and static strings and committing it to the DOM.\n   * If this part is single-valued, `this._strings` will be undefined, and the\n   * method will be called with a single value argument. If this part is\n   * multi-value, `this._strings` will be defined, and the method is called\n   * with the value array of the part's owning TemplateInstance, and an offset\n   * into the value array from which the values should be read.\n   * This method is overloaded this way to eliminate short-lived array slices\n   * of the template instance values, and allow a fast-path for single-valued\n   * parts.\n   *\n   * @param value The part value, or an array of values for multi-valued parts\n   * @param valueIndex the index to start reading values from. `undefined` for\n   *   single-valued parts\n   * @param noCommit causes the part to not commit its value to the DOM. Used\n   *   in hydration to prime attribute parts with their first-rendered value,\n   *   but not set the attribute, and in SSR to no-op the DOM operation and\n   *   capture the value for serialization.\n   *\n   * @internal\n   */\n  _$setValue(\n    value: unknown | Array<unknown>,\n    directiveParent: DirectiveParent = this,\n    valueIndex?: number,\n    noCommit?: boolean\n  ) {\n    const strings = this.strings;\n\n    // Whether any of the values has changed, for dirty-checking\n    let change = false;\n\n    if (strings === undefined) {\n      // Single-value binding case\n      value = resolveDirective(this, value, directiveParent, 0);\n      change =\n        !isPrimitive(value) ||\n        (value !== this._$committedValue && value !== noChange);\n      if (change) {\n        this._$committedValue = value;\n      }\n    } else {\n      // Interpolation case\n      const values = value as Array<unknown>;\n      value = strings[0];\n\n      let i, v;\n      for (i = 0; i < strings.length - 1; i++) {\n        v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n        if (v === noChange) {\n          // If the user-provided value is `noChange`, use the previous value\n          v = (this._$committedValue as Array<unknown>)[i];\n        }\n        change ||=\n          !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n        if (v === nothing) {\n          value = nothing;\n        } else if (value !== nothing) {\n          value += (v ?? '') + strings[i + 1];\n        }\n        // We always record each value, even if one is `nothing`, for future\n        // change detection.\n        (this._$committedValue as Array<unknown>)[i] = v;\n      }\n    }\n    if (change && !noCommit) {\n      this._commitValue(value);\n    }\n  }\n\n  /** @internal */\n  _commitValue(value: unknown) {\n    if (value === nothing) {\n      (wrap(this.element) as Element).removeAttribute(this.name);\n    } else {\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        if (this._sanitizer === undefined) {\n          this._sanitizer = sanitizerFactoryInternal(\n            this.element,\n            this.name,\n            'attribute'\n          );\n        }\n        value = this._sanitizer(value ?? '');\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit attribute',\n          element: this.element,\n          name: this.name,\n          value,\n          options: this.options,\n        });\n      (wrap(this.element) as Element).setAttribute(\n        this.name,\n        (value ?? '') as string\n      );\n    }\n  }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n  override readonly type = PROPERTY_PART;\n\n  /** @internal */\n  override _commitValue(value: unknown) {\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      if (this._sanitizer === undefined) {\n        this._sanitizer = sanitizerFactoryInternal(\n          this.element,\n          this.name,\n          'property'\n        );\n      }\n      value = this._sanitizer(value);\n    }\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit property',\n        element: this.element,\n        name: this.name,\n        value,\n        options: this.options,\n      });\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (this.element as any)[this.name] = value === nothing ? undefined : value;\n  }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n  override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n  /** @internal */\n  override _commitValue(value: unknown) {\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit boolean attribute',\n        element: this.element,\n        name: this.name,\n        value: !!(value && value !== nothing),\n        options: this.options,\n      });\n    (wrap(this.element) as Element).toggleAttribute(\n      this.name,\n      !!value && value !== nothing\n    );\n  }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n  Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n  override readonly type = EVENT_PART;\n\n  constructor(\n    element: HTMLElement,\n    name: string,\n    strings: ReadonlyArray<string>,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    super(element, name, strings, parent, options);\n\n    if (DEV_MODE && this.strings !== undefined) {\n      throw new Error(\n        `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n          'invalid content. Event listeners in templates must have exactly ' +\n          'one expression and no surrounding text.'\n      );\n    }\n  }\n\n  // EventPart does not use the base _$setValue/_resolveValue implementation\n  // since the dirty checking is more complex\n  /** @internal */\n  override _$setValue(\n    newListener: unknown,\n    directiveParent: DirectiveParent = this\n  ) {\n    newListener =\n      resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n    if (newListener === noChange) {\n      return;\n    }\n    const oldListener = this._$committedValue;\n\n    // If the new value is nothing or any options change we have to remove the\n    // part as a listener.\n    const shouldRemoveListener =\n      (newListener === nothing && oldListener !== nothing) ||\n      (newListener as EventListenerWithOptions).capture !==\n        (oldListener as EventListenerWithOptions).capture ||\n      (newListener as EventListenerWithOptions).once !==\n        (oldListener as EventListenerWithOptions).once ||\n      (newListener as EventListenerWithOptions).passive !==\n        (oldListener as EventListenerWithOptions).passive;\n\n    // If the new value is not nothing and we removed the listener, we have\n    // to add the part as a listener.\n    const shouldAddListener =\n      newListener !== nothing &&\n      (oldListener === nothing || shouldRemoveListener);\n\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit event listener',\n        element: this.element,\n        name: this.name,\n        value: newListener,\n        options: this.options,\n        removeListener: shouldRemoveListener,\n        addListener: shouldAddListener,\n        oldListener,\n      });\n    if (shouldRemoveListener) {\n      this.element.removeEventListener(\n        this.name,\n        this,\n        oldListener as EventListenerWithOptions\n      );\n    }\n    if (shouldAddListener) {\n      this.element.addEventListener(\n        this.name,\n        this,\n        newListener as EventListenerWithOptions\n      );\n    }\n    this._$committedValue = newListener;\n  }\n\n  handleEvent(event: Event) {\n    if (typeof this._$committedValue === 'function') {\n      this._$committedValue.call(this.options?.host ?? this.element, event);\n    } else {\n      (this._$committedValue as EventListenerObject).handleEvent(event);\n    }\n  }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n  readonly type = ELEMENT_PART;\n\n  /** @internal */\n  __directive?: Directive;\n\n  // This is to ensure that every Part has a _$committedValue\n  _$committedValue: undefined;\n\n  /** @internal */\n  _$parent!: Disconnectable;\n\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  options: RenderOptions | undefined;\n\n  constructor(\n    public element: Element,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    this._$parent = parent;\n    this.options = options;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  _$setValue(value: unknown): void {\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit to element binding',\n        element: this.element,\n        value,\n        options: this.options,\n      });\n    resolveDirective(this, value);\n  }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n  // Used in lit-ssr\n  _boundAttributeSuffix: boundAttributeSuffix,\n  _marker: marker,\n  _markerMatch: markerMatch,\n  _HTML_RESULT: HTML_RESULT,\n  _getTemplateHtml: getTemplateHtml,\n  // Used in tests and private-ssr-support\n  _TemplateInstance: TemplateInstance,\n  _isIterable: isIterable,\n  _resolveDirective: resolveDirective,\n  _ChildPart: ChildPart,\n  _AttributePart: AttributePart,\n  _BooleanAttributePart: BooleanAttributePart,\n  _EventPart: EventPart,\n  _PropertyPart: PropertyPart,\n  _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n  ? global.litHtmlPolyfillSupportDevMode\n  : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\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(global.litHtmlVersions ??= []).push('3.3.3');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. ` +\n        `Loading multiple versions is not recommended.`\n    );\n  });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n *   value](https://lit.dev/docs/templates/expressions/#child-expressions),\n *   typically a {@linkcode TemplateResult} created by evaluating a template tag\n *   like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n *   the rendered value to the container, and subsequent renders will\n *   efficiently update the rendered value if the same result type was\n *   previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n  value: unknown,\n  container: RenderRootNode,\n  options?: RenderOptions\n): RootPart => {\n  if (DEV_MODE && container == null) {\n    // Give a clearer error message than\n    //     Uncaught TypeError: Cannot read properties of null (reading\n    //     '_$litPart$')\n    // which reads like an internal Lit error.\n    throw new TypeError(`The container to render into may not be ${container}`);\n  }\n  const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n  const partOwnerNode = options?.renderBefore ?? container;\n  // This property needs to remain unminified.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n  debugLogEvent &&\n    debugLogEvent({\n      kind: 'begin render',\n      id: renderId,\n      value,\n      container,\n      options,\n      part,\n    });\n  if (part === undefined) {\n    const endNode = options?.renderBefore ?? null;\n    // This property needs to remain unminified.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n      container.insertBefore(createMarker(), endNode),\n      endNode,\n      undefined,\n      options ?? {}\n    );\n  }\n  part._$setValue(value);\n  debugLogEvent &&\n    debugLogEvent({\n      kind: 'end render',\n      id: renderId,\n      value,\n      container,\n      options,\n      part,\n    });\n  return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n  render.setSanitizer = setSanitizer;\n  render.createSanitizer = createSanitizer;\n  if (DEV_MODE) {\n    render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n      _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * The main LitElement module, which defines the {@linkcode LitElement} base\n * class and related APIs.\n *\n * LitElement components can define a template and a set of observed\n * properties. Changing an observed property triggers a re-render of the\n * element.\n *\n * Import {@linkcode LitElement} and {@linkcode html} from this module to\n * create a component:\n *\n *  ```js\n * import {LitElement, html} from 'lit-element';\n *\n * class MyElement extends LitElement {\n *\n *   // Declare observed properties\n *   static get properties() {\n *     return {\n *       adjective: {}\n *     }\n *   }\n *\n *   constructor() {\n *     this.adjective = 'awesome';\n *   }\n *\n *   // Define the element's template\n *   render() {\n *     return html`<p>your ${adjective} template here</p>`;\n *   }\n * }\n *\n * customElements.define('my-element', MyElement);\n * ```\n *\n * `LitElement` extends {@linkcode ReactiveElement} and adds lit-html\n * templating. The `ReactiveElement` class is provided for users that want to\n * build their own custom element base classes that don't use lit-html.\n *\n * @packageDocumentation\n */\nimport {PropertyValues, ReactiveElement} from '@lit/reactive-element';\nimport {render, RenderOptions, noChange, RootPart} from 'lit-html';\nexport * from '@lit/reactive-element';\nexport * from 'lit-html';\n\nimport {LitUnstable} from 'lit-html';\nimport {ReactiveUnstable} from '@lit/reactive-element';\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Unstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry =\n      | LitUnstable.DebugLog.Entry\n      | ReactiveUnstable.DebugLog.Entry;\n  }\n}\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n  prop: P,\n  _obj: unknown\n): P => prop;\n\nconst DEV_MODE = true;\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n  // Ensure warnings are issued only 1x, even if multiple versions of Lit\n  // are loaded.\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += ` See https://lit.dev/msg/${code} for more information.`;\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n}\n\n/**\n * Base element class that manages element properties and attributes, and\n * renders a lit-html template.\n *\n * To define a component, subclass `LitElement` and implement a\n * `render` method to provide the component's template. Define properties\n * using the {@linkcode LitElement.properties properties} property or the\n * {@linkcode property} decorator.\n */\nexport class LitElement extends ReactiveElement {\n  // This property needs to remain unminified.\n  static ['_$litElement$'] = true;\n\n  /**\n   * @category rendering\n   */\n  readonly renderOptions: RenderOptions = {host: this};\n\n  private __childPart: RootPart | undefined = undefined;\n\n  /**\n   * @category rendering\n   */\n  protected override createRenderRoot() {\n    const renderRoot = super.createRenderRoot();\n    // When adoptedStyleSheets are shimmed, they are inserted into the\n    // shadowRoot by createRenderRoot. Adjust the renderBefore node so that\n    // any styles in Lit content render before adoptedStyleSheets. This is\n    // important so that adoptedStyleSheets have precedence over styles in\n    // the shadowRoot.\n    this.renderOptions.renderBefore ??= renderRoot!.firstChild as ChildNode;\n    return renderRoot;\n  }\n\n  /**\n   * Updates the element. This method reflects property values to attributes\n   * and calls `render` to render DOM via lit-html. Setting properties inside\n   * this method will *not* trigger another update.\n   * @param changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected override update(changedProperties: PropertyValues) {\n    // Setting properties in `render` should not trigger an update. Since\n    // updates are allowed after super.update, it's important to call `render`\n    // before that.\n    const value = this.render();\n    if (!this.hasUpdated) {\n      this.renderOptions.isConnected = this.isConnected;\n    }\n    super.update(changedProperties);\n    this.__childPart = render(value, this.renderRoot, this.renderOptions);\n  }\n\n  /**\n   * Invoked when the component is added to the document's DOM.\n   *\n   * In `connectedCallback()` you should setup tasks that should only occur when\n   * the element is connected to the document. The most common of these is\n   * adding event listeners to nodes external to the element, like a keydown\n   * event handler added to the window.\n   *\n   * ```ts\n   * connectedCallback() {\n   *   super.connectedCallback();\n   *   addEventListener('keydown', this._handleKeydown);\n   * }\n   * ```\n   *\n   * Typically, anything done in `connectedCallback()` should be undone when the\n   * element is disconnected, in `disconnectedCallback()`.\n   *\n   * @category lifecycle\n   */\n  override connectedCallback() {\n    super.connectedCallback();\n    this.__childPart?.setConnected(true);\n  }\n\n  /**\n   * Invoked when the component is removed from the document's DOM.\n   *\n   * This callback is the main signal to the element that it may no longer be\n   * used. `disconnectedCallback()` should ensure that nothing is holding a\n   * reference to the element (such as event listeners added to nodes external\n   * to the element), so that it is free to be garbage collected.\n   *\n   * ```ts\n   * disconnectedCallback() {\n   *   super.disconnectedCallback();\n   *   window.removeEventListener('keydown', this._handleKeydown);\n   * }\n   * ```\n   *\n   * An element may be re-connected after being disconnected.\n   *\n   * @category lifecycle\n   */\n  override disconnectedCallback() {\n    super.disconnectedCallback();\n    this.__childPart?.setConnected(false);\n  }\n\n  /**\n   * Invoked on each update to perform rendering tasks. This method may return\n   * any value renderable by lit-html's `ChildPart` - typically a\n   * `TemplateResult`. Setting properties inside this method will *not* trigger\n   * the element to update.\n   * @category rendering\n   */\n  protected render(): unknown {\n    return noChange;\n  }\n}\n\n/**\n * Ensure this class is marked as `finalized` as an optimization ensuring\n * it will not needlessly try to `finalize`.\n *\n * Note this property name is a string to prevent breaking Closure JS Compiler\n * optimizations. See @lit/reactive-element for more information.\n */\n(LitElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('finalized', LitElement)\n] = true;\n\n// Install hydration if available\nglobal.litElementHydrateSupport?.({LitElement});\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n  ? global.litElementPolyfillSupportDevMode\n  : global.litElementPolyfillSupport;\npolyfillSupport?.({LitElement});\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports  mangled in the\n * client side code, we export a _$LE object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-html, since this module re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LE = {\n  _$attributeToProperty: (\n    el: LitElement,\n    name: string,\n    value: string | null\n  ) => {\n    // eslint-disable-next-line\n    (el as any)._$attributeToProperty(name, value);\n  },\n  // eslint-disable-next-line\n  _$changedProperties: (el: LitElement) => (el as any)._$changedProperties,\n};\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for LitElement usage.\n(global.litElementVersions ??= []).push('4.2.2');\nif (DEV_MODE && global.litElementVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. Loading multiple versions ` +\n        `is not recommended.`\n    );\n  });\n}\n","/**\n * Asks before a document with unsaved form input is left: links, reload and closing through the browser's own\n * beforeunload dialog, logout through a confirmation before WRDAuth ends the session.\n *\n * Markup contract: `<form data-companyos-unsaved-guard>`, optionally with `[data-companyos-unsaved-scope]` parts that are\n * saved separately (eg one section per submit button). Without scopes the form is one scope. An unsaved scope carries\n * `data-companyos-unsaved`. The form engine stays the only value model: input marks the scope, and only WebHare's\n * `wh:form-submitted` for that scope clears it. A failed submission keeps it, and so does input elsewhere.\n */\n\n/** Present on a scope (or a form without scopes) with input that was not saved yet. */\nexport const UNSAVED_ATTRIBUTE = \"data-companyos-unsaved\";\n\nconst GUARD = \"form[data-companyos-unsaved-guard]\";\nconst SCOPE = \"[data-companyos-unsaved-scope]\";\n\n/** The scope that was submitted last, per form, so its save only clears that scope. */\nconst submittedScopes = new WeakMap<HTMLFormElement, Element>();\n/** Set once leaving was confirmed (logout), so the page does not ask a second time. */\nlet leaving = false;\n\nfunction scopeOf(node: EventTarget | null): Element | null {\n  const form = node instanceof Element ? node.closest<HTMLFormElement>(GUARD) : null;\n  if (!form)\n    return null;\n  const scope = (node as Element).closest(SCOPE);\n  return scope && form.contains(scope) ? scope : form;\n}\n\n/** Whether any guarded form in `root` has unsaved input. */\nexport function hasUnsavedChanges(root: ParentNode = document): boolean {\n  return Boolean(root.querySelector(`${GUARD}[${UNSAVED_ATTRIBUTE}], ${GUARD} [${UNSAVED_ATTRIBUTE}]`));\n}\n\nfunction markUnsaved(event: Event) {\n  scopeOf(event.target)?.setAttribute(UNSAVED_ATTRIBUTE, \"\");\n}\n\n// Two asset packs on one page may both carry this module; a second set of listeners would ask twice.\nconst REGISTERED = Symbol.for(\"companyos:unsaved-guard\");\nif (!(REGISTERED in globalThis)) {\n  Object.assign(globalThis, { [REGISTERED]: true });\n  register();\n}\n\nfunction register() {\n  addEventListener(\"input\", markUnsaved, true);\n  addEventListener(\"change\", markUnsaved, true);\n  addEventListener(\"click\", event => {\n    // Adding or removing an array row changes the value without an input event\n    if (event.target instanceof Element && event.target.closest(\".wh-form__arrayadd, .wh-form__arraydelete\"))\n      markUnsaved(event);\n  }, true);\n\n  addEventListener(\"submit\", event => {\n    const form = event.target;\n    if (!(form instanceof HTMLFormElement) || !form.matches(GUARD))\n      return;\n    // Implicit submission has no submitter; then the field being edited tells which scope is meant\n    const scope = scopeOf(event.submitter ?? document.activeElement);\n    submittedScopes.set(form, scope && form.contains(scope) ? scope : form);\n  }, true);\n\n  // Bubble phase on window: runs after the form's own handlers, which may still write saved values back into fields\n  addEventListener(\"wh:form-submitted\", event => {\n    const form = event.target;\n    if (!(form instanceof HTMLFormElement) || !form.matches(GUARD))\n      return;\n    const scope = submittedScopes.get(form) ?? form;\n    scope.removeAttribute(UNSAVED_ATTRIBUTE);\n    if (scope === form)\n      for (const node of form.querySelectorAll(`[${UNSAVED_ATTRIBUTE}]`))\n        node.removeAttribute(UNSAVED_ATTRIBUTE);\n  });\n\n  addEventListener(\"beforeunload\", event => {\n    if (leaving || !hasUnsavedChanges())\n      return;\n    event.preventDefault();\n    // Older Safari only asks when returnValue is set; the browser shows its own text either way\n    event.returnValue = \"\";\n  });\n\n  // Capture on window runs before WRDAuth's own handler on the link, which ends the session before it navigates\n  addEventListener(\"click\", event => {\n    if (!(event.target instanceof Element) || !event.target.closest(\".wh-wrdauth__logout\") || !hasUnsavedChanges())\n      return;\n    // eslint-disable-next-line no-alert -- a synchronous question is the only way to stop the click before WRDAuth acts\n    if (confirm(\"Er zijn wijzigingen die nog niet zijn opgeslagen. Toch uitloggen?\")) {\n      leaving = true;\n      return;\n    }\n    event.preventDefault();\n    event.stopImmediatePropagation();\n  }, true);\n}\n","import { LitElement, html } from \"lit\";\nimport { UNSAVED_ATTRIBUTE } from \"./unsaved\";\n\n/**\n * Turns a native in-page section navigation into section buttons that show one section at a time.\n *\n * Markup contract: `<companyos-sections for=\"<host id>\"><nav aria-label=\"...\"><a href=\"#<section id>\">...</a></nav></companyos-sections>`.\n * Only sections inside the host (default: the parent element) that a link names are touched, so several instances can\n * live on one page. The sections themselves, and every field and handler in them, stay where WebHare rendered them:\n * this element only toggles `hidden`. Without JavaScript the anchors keep working as plain in-page links.\n * A section with unsaved input (see unsaved.ts) gets a marker on its button, and a server error for a field in a hidden\n * section shows that section, so WebHare can focus the field.\n */\nexport class CompanyosSections extends LitElement {\n  #sections: Array<{ section: HTMLElement; label: string }> = [];\n  #label = \"\";\n  #active: HTMLElement | null = null;\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    if (this.#sections.length)\n      return; // A reconnect (DOM move) keeps the adopted sections and selection\n    // Defined before the parser reached our children: adopt once they exist\n    if (document.readyState === \"loading\")\n      document.addEventListener(\"DOMContentLoaded\", () => this.#adopt(), { once: true });\n    else\n      this.#adopt();\n  }\n\n  public override render() {\n    return html`<nav aria-label=${this.#label}>${this.#sections.map(({ section, label }) => html`\n      <button type=\"button\" aria-controls=${section.id} aria-current=${section === this.#active ? \"true\" : \"false\"}\n        @click=${() => this.#select({ section, focus: true })}>${label}${isUnsaved(section)\n          ? html`<span class=\"companyos-sections__unsaved\"> (niet opgeslagen)</span>` : \"\"}</button>`)}</nav>`;\n  }\n\n  #adopt() {\n    const nav = this.querySelector(\"nav\");\n    const hostId = this.getAttribute(\"for\");\n    const host = hostId ? document.getElementById(hostId) : this.parentElement;\n    if (!nav || !host || this.#sections.length)\n      return;\n\n    for (const link of nav.querySelectorAll<HTMLAnchorElement>(\"a[href^='#']\")) {\n      const section = host.querySelector<HTMLElement>(`#${CSS.escape(link.getAttribute(\"href\")!.slice(1))}`);\n      if (section)\n        this.#sections.push({ section, label: link.textContent?.trim() ?? \"\" });\n    }\n    if (!this.#sections.length)\n      return; // Nothing we can control: leave the native navigation in place\n\n    this.#label = nav.getAttribute(\"aria-label\") ?? \"\";\n    nav.remove();\n    new MutationObserver(() => this.requestUpdate()).observe(host, { subtree: true, attributeFilter: [UNSAVED_ATTRIBUTE] });\n    // wh:form-response comes before WebHare focuses the first failing field, which only works in a visible section\n    host.addEventListener(\"wh:form-response\", event => this.#revealError({ host, event }));\n    const selected = this.#sections.find(({ section }) => `#${section.id}` === location.hash) ?? this.#sections[0];\n    this.#select({ section: selected.section, focus: false });\n  }\n\n  #revealError({ host, event }: { host: HTMLElement; event: Event }) {\n    const errors = (event as CustomEvent<{ errors?: Array<{ name?: string }> }>).detail?.errors ?? [];\n    const name = errors.find(error => error.name)?.name;\n    const field = name ? host.querySelector(`[name=\"${CSS.escape(name)}\"], [data-wh-form-name=\"${CSS.escape(name)}\"]`) : null;\n    const target = this.#sections.find(({ section }) => section.contains(field));\n    if (target && target.section !== this.#active)\n      this.#select({ section: target.section, focus: false });\n  }\n\n  #select({ section, focus }: { section: HTMLElement; focus: boolean }) {\n    this.#active = section;\n    for (const entry of this.#sections)\n      entry.section.hidden = entry.section !== section;\n    this.requestUpdate();\n    if (focus) {\n      const heading = section.querySelector<HTMLElement>(\"h1, h2, h3, h4, h5, h6\");\n      if (heading) {\n        heading.tabIndex = -1;\n        heading.focus();\n      }\n    }\n  }\n}\n\nfunction isUnsaved(section: HTMLElement) {\n  return section.hasAttribute(UNSAVED_ATTRIBUTE) || Boolean(section.querySelector(`[${UNSAVED_ATTRIBUTE}]`));\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"companyos-sections\": CompanyosSections;\n  }\n}\n\n// Two asset packs on one page may both carry this module; the second define would throw.\nif (!customElements.get(\"companyos-sections\"))\n  customElements.define(\"companyos-sections\", CompanyosSections);\n","import type { IconName } from \"../components/icons/icon-data\";\n\n/** A row action; icons are rendered only when the consumer explicitly supplies one.\n    Use kind for edit/delete actions whose identifiers are specific to the consumer.\n*/\nexport interface ContextMenuAction {\n  id: string;\n  label?: string;\n  kind?: \"edit\" | \"delete\";\n  icon?: IconName;\n  separatorBefore?: boolean;\n  danger?: boolean;\n  disabled?: boolean;\n}\n\nfunction actionKind(action: ContextMenuAction): ContextMenuAction[\"kind\"] {\n  return action.kind ?? (action.id === \"edit\" || action.id === \"delete\" ? action.id : undefined);\n}\n\nfunction actionRank(action: ContextMenuAction): number {\n  const kind = actionKind(action);\n  return kind === \"edit\" ? 0 : kind === \"delete\" ? 1 : 2;\n}\n\n/** Applies shared menu conventions without mutating the supplied actions.\n    Edit/delete lead the menu with generic labels, and delete is always destructive.\n    Other actions retain their order and group boundaries after one separating rule.\n    Identifiers edit/delete remain supported for callers that do not supply kind.\n*/\nexport function getMenuActions(options: {\n  actions: readonly ContextMenuAction[];\n}): Array<ContextMenuAction & { label: string }> {\n  const ordered = options.actions.toSorted((left, right) => actionRank(left) - actionRank(right));\n  const firstOtherAction = ordered.findIndex(action => !actionKind(action));\n  return ordered.map((action, index) => {\n    const kind = actionKind(action);\n    if (kind === \"edit\")\n      return { ...action, label: \"Bewerken\", separatorBefore: false };\n    if (kind === \"delete\")\n      return { ...action, label: \"Verwijderen\", danger: true, separatorBefore: false };\n    const normalized = { ...action, label: action.label ?? action.id };\n    return index === firstOtherAction && firstOtherAction > 0 ? { ...normalized, separatorBefore: true } : normalized;\n  });\n}\n\n/** Clamps a measured menu to an eight-pixel viewport margin.\n    When a menu itself exceeds the viewport, its top-left edge remains reachable.\n*/\nexport function getMenuPosition(options: {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n  viewportWidth: number;\n  viewportHeight: number;\n}): { x: number; y: number } {\n  return {\n    x: Math.max(8, Math.min(options.x, options.viewportWidth - options.width - 8)),\n    y: Math.max(8, Math.min(options.y, options.viewportHeight - options.height - 8)),\n  };\n}\n","// Types and rules of the public screen List (components/screen/List.vue), kept Vue-free so they can be unit tested.\nimport type { ContextMenuAction } from \"./context-menu\";\n\ninterface ListColumnBase<Column extends string> {\n  key: Column;\n  label: string;\n  minWidth: number;\n  defaultWidth: number;\n  flexible?: boolean;\n}\n\n/** A text column (the default kind). `key` doubles as the sort key. */\nexport interface ListTextColumn<Item extends object, Column extends string = string> extends ListColumnBase<Column> {\n  kind?: \"text\";\n  sortable?: boolean;\n  align?: \"left\" | \"center\" | \"right\";\n  emphasis?: boolean;\n  /** Without it the cell shows `item[key]`. */\n  value?: (item: Item) => string | number;\n  /** Secondary text color for the cells (not the heading). */\n  tone?: \"secondary\";\n  /** Tabular figures for the cells. */\n  numeric?: boolean;\n  /** A small label after the text, such as \"Vergrendeld\"; `description` completes its accessible name and title. */\n  badge?: (item: Item) => { label: string; description?: string } | undefined;\n}\n\n/** A read-only check per row (role checkbox, aria-readonly): shows a stored boolean, takes no input or focus. */\nexport interface ListCheckColumn<Item extends object, Column extends string = string> extends ListColumnBase<Column> {\n  kind: \"check\";\n  checked: (item: Item) => boolean;\n  /** Accessible name of the check in this row, e.g. \"10.0.0.1: toegang tot CRM\". */\n  checkLabel: (item: Item) => string;\n}\n\n/** A column of a screen List: typed configuration, no cell slots. */\nexport type ListColumn<Item extends object, Column extends string = string> = ListTextColumn<Item, Column> | ListCheckColumn<Item, Column>;\n\nexport interface ListSort<Column extends string = string> {\n  key: Column;\n  direction: \"asc\" | \"desc\";\n}\n\n/** A row menu action; the same shape as the DataTable row actions (edit/delete lead the menu). */\nexport type ListRowAction = ContextMenuAction;\n\n/** Clicking the sorted column reverses its direction; any other column starts ascending. */\nexport function nextListSort<Column extends string>(options: { current: ListSort<Column> | undefined; key: Column }): ListSort<Column> {\n  return { key: options.key, direction: options.current?.key === options.key && options.current.direction === \"asc\" ? \"desc\" : \"asc\" };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing} from '../lit-html.js';\n\n/**\n * For AttributeParts, sets the attribute if the value is defined and removes\n * the attribute if the value is undefined.\n *\n * For other part types, this directive is a no-op.\n */\nexport const ifDefined = <T>(value: T) => value ?? nothing;\n","// GENERATED FILE, DO NOT EDIT BY HAND.\n// Run scripts/dev/generate-icons.mjs after changing the ICONS list in that script. Geometry comes\n// from @carbon/icons (Apache-2.0).\n//\n// Each entry is a list of [svgTagName, attributes] pairs, rendered by Icon.vue into an\n// <svg viewBox=\"0 0 32 32\" fill=\"currentColor\">.\n\nexport type IconNode = Array<[string, Record<string, string>]>;\n\nexport type IconName =\n  | \"add\"\n  | \"analytics\"\n  | \"arrow--left\"\n  | \"arrow--right\"\n  | \"asleep\"\n  | \"checkmark\"\n  | \"checkmark--outline\"\n  | \"chevron--down\"\n  | \"chevron--left\"\n  | \"chevron--right\"\n  | \"circle--solid\"\n  | \"close\"\n  | \"connect\"\n  | \"copy\"\n  | \"dashboard\"\n  | \"document\"\n  | \"edit\"\n  | \"email\"\n  | \"error--filled\"\n  | \"fit-to-screen\"\n  | \"flag\"\n  | \"flow\"\n  | \"hourglass\"\n  | \"light\"\n  | \"link\"\n  | \"logout\"\n  | \"magic-wand\"\n  | \"menu\"\n  | \"overflow-menu--vertical\"\n  | \"party-popper\"\n  | \"pause--outline\"\n  | \"play--filled--alt\"\n  | \"play--outline\"\n  | \"redo\"\n  | \"renew\"\n  | \"restart\"\n  | \"search\"\n  | \"send\"\n  | \"settings\"\n  | \"settings--adjust\"\n  | \"skip--forward\"\n  | \"stop--filled\"\n  | \"store\"\n  | \"time\"\n  | \"trash-can\"\n  | \"undo\"\n  | \"user--avatar\"\n  | \"user--follow\"\n  | \"zoom--in\"\n  | \"zoom--out\";\n\nexport const ICON_DATA: Record<IconName, IconNode> = {\n  \"add\": [[\"path\",{\"d\":\"M17 15 17 8 15 8 15 15 8 15 8 17 15 17 15 24 17 24 17 17 24 17 24 15z\"}]],\n  \"analytics\": [[\"path\",{\"d\":\"M4,2H2V28a2,2,0,0,0,2,2H30V28H4Z\"}],[\"path\",{\"d\":\"M30,9H23v2h3.59L19,18.59l-4.29-4.3a1,1,0,0,0-1.42,0L6,21.59,7.41,23,14,16.41l4.29,4.3a1,1,0,0,0,1.42,0L28,12.41V16h2Z\"}]],\n  \"arrow--left\": [[\"path\",{\"d\":\"M14 26 15.41 24.59 7.83 17 28 17 28 15 7.83 15 15.41 7.41 14 6 4 16 14 26z\"}]],\n  \"arrow--right\": [[\"path\",{\"d\":\"M18 6 16.57 7.393 24.15 15 4 15 4 17 24.15 17 16.57 24.573 18 26 28 16 18 6z\"}]],\n  \"asleep\": [[\"path\",{\"d\":\"M13.5025,5.4136A15.0755,15.0755,0,0,0,25.096,23.6082a11.1134,11.1134,0,0,1-7.9749,3.3893c-.1385,0-.2782.0051-.4178,0A11.0944,11.0944,0,0,1,13.5025,5.4136M14.98,3a1.0024,1.0024,0,0,0-.1746.0156A13.0959,13.0959,0,0,0,16.63,28.9973c.1641.006.3282,0,.4909,0a13.0724,13.0724,0,0,0,10.702-5.5556,1.0094,1.0094,0,0,0-.7833-1.5644A13.08,13.08,0,0,1,15.8892,4.38,1.0149,1.0149,0,0,0,14.98,3Z\"}]],\n  \"checkmark\": [[\"path\",{\"d\":\"M13 24 4 15 5.414 13.586 13 21.171 26.586 7.586 28 9 13 24z\"}]],\n  \"checkmark--outline\": [[\"path\",{\"d\":\"M14 21.414 9 16.413 10.413 15 14 18.586 21.585 11 23 12.415 14 21.414z\"}],[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Zm0,26A12,12,0,1,1,28,16,12,12,0,0,1,16,28Z\"}]],\n  \"chevron--down\": [[\"path\",{\"d\":\"M16 22 6 12 7.4 10.6 16 19.2 24.6 10.6 26 12z\"}]],\n  \"chevron--left\": [[\"path\",{\"d\":\"M10 16 20 6 21.4 7.4 12.8 16 21.4 24.6 20 26z\"}]],\n  \"chevron--right\": [[\"path\",{\"d\":\"M22 16 12 26 10.6 24.6 19.2 16 10.6 7.4 12 6z\"}]],\n  \"circle--solid\": [[\"circle\",{\"cx\":\"16\",\"cy\":\"16\",\"r\":\"14\"}]],\n  \"close\": [[\"path\",{\"d\":\"M17.4141 16 24 9.4141 22.5859 8 16 14.5859 9.4143 8 8 9.4141 14.5859 16 8 22.5859 9.4143 24 16 17.4141 22.5859 24 24 22.5859 17.4141 16z\"}]],\n  \"connect\": [[\"path\",{\"d\":\"M23,16a7,7,0,0,0-4.18,1.39L14.6,13.17A6.86,6.86,0,0,0,16,9a7,7,0,1,0-2.81,5.59l4.21,4.22A7,7,0,1,0,23,16ZM4,9a5,5,0,1,1,5,5A5,5,0,0,1,4,9Z\",\"transform\":\"translate(0 .01)\"}]],\n  \"copy\": [[\"path\",{\"d\":\"M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z\"}],[\"path\",{\"d\":\"M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z\"}]],\n  \"dashboard\": [[\"path\",{\"d\":\"M24 21H26V26H24z\"}],[\"path\",{\"d\":\"M20 16H22V26H20z\"}],[\"path\",{\"d\":\"M11,26a5.0059,5.0059,0,0,1-5-5H8a3,3,0,1,0,3-3V16a5,5,0,0,1,0,10Z\"}],[\"path\",{\"d\":\"M28,2H4A2.002,2.002,0,0,0,2,4V28a2.0023,2.0023,0,0,0,2,2H28a2.0027,2.0027,0,0,0,2-2V4A2.0023,2.0023,0,0,0,28,2Zm0,9H14V4H28ZM12,4v7H4V4ZM4,28V13H28.0007l.0013,15Z\"}]],\n  \"document\": [[\"path\",{\"d\":\"M25.7,9.3l-7-7C18.5,2.1,18.3,2,18,2H8C6.9,2,6,2.9,6,4v24c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V10C26,9.7,25.9,9.5,25.7,9.3 z M18,4.4l5.6,5.6H18V4.4z M24,28H8V4h8v6c0,1.1,0.9,2,2,2h6V28z\"}],[\"path\",{\"d\":\"M10 22H22V24H10z\"}],[\"path\",{\"d\":\"M10 16H22V18H10z\"}]],\n  \"edit\": [[\"path\",{\"d\":\"M2 26H30V28H2z\"}],[\"path\",{\"d\":\"M25.4,9c0.8-0.8,0.8-2,0-2.8c0,0,0,0,0,0l-3.6-3.6c-0.8-0.8-2-0.8-2.8,0c0,0,0,0,0,0l-15,15V24h6.4L25.4,9z M20.4,4L24,7.6 l-3,3L17.4,7L20.4,4z M6,22v-3.6l10-10l3.6,3.6l-10,10H6z\"}]],\n  \"email\": [[\"path\",{\"d\":\"M28,6H4A2,2,0,0,0,2,8V24a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V8A2,2,0,0,0,28,6ZM25.8,8,16,14.78,6.2,8ZM4,24V8.91l11.43,7.91a1,1,0,0,0,1.14,0L28,8.91V24Z\"}]],\n  \"error--filled\": [[\"path\",{\"fill\":\"none\",\"d\":\"M14.9 7.2H17.1V24.799H14.9z\",\"data-icon-path\":\"inner-path\",\"transform\":\"rotate(-45 16 16)\"}],[\"path\",{\"d\":\"M16,2A13.914,13.914,0,0,0,2,16,13.914,13.914,0,0,0,16,30,13.914,13.914,0,0,0,30,16,13.914,13.914,0,0,0,16,2Zm5.4449,21L9,10.5557,10.5557,9,23,21.4448Z\"}]],\n  \"fit-to-screen\": [[\"path\",{\"d\":\"M22 16 24 16 24 8 16 8 16 10 22 10 22 16z\"}],[\"path\",{\"d\":\"M8 24 16 24 16 22 10 22 10 16 8 16 8 24z\"}],[\"path\",{\"d\":\"M26,28H6a2.0023,2.0023,0,0,1-2-2V6A2.0023,2.0023,0,0,1,6,4H26a2.0023,2.0023,0,0,1,2,2V26A2.0023,2.0023,0,0,1,26,28ZM6,6V26H26.0012L26,6Z\"}]],\n  \"flag\": [[\"path\",{\"d\":\"M6,30H4V2H28l-5.8,9L28,20H6ZM6,18H24.33L19.8,11l4.53-7H6Z\"}]],\n  \"flow\": [[\"path\",{\"d\":\"M27,22.14V17a2,2,0,0,0-2-2H17V9.86a4,4,0,1,0-2,0V15H7a2,2,0,0,0-2,2v5.14a4,4,0,1,0,2,0V17H25v5.14a4,4,0,1,0,2,0ZM8,26a2,2,0,1,1-2-2A2,2,0,0,1,8,26ZM14,6a2,2,0,1,1,2,2A2,2,0,0,1,14,6ZM26,28a2,2,0,1,1,2-2A2,2,0,0,1,26,28Z\"}]],\n  \"hourglass\": [[\"path\",{\"d\":\"M15 19H17V21H15z\"}],[\"path\",{\"d\":\"M15 23H17V25H15z\"}],[\"path\",{\"d\":\"M23,11.67V4h3V2H6V4H9v7.67a2,2,0,0,0,.4,1.2L11.75,16,9.4,19.13a2,2,0,0,0-.4,1.2V28H6v2H26V28H23V20.33a2,2,0,0,0-.4-1.2L20.25,16l2.35-3.13A2,2,0,0,0,23,11.67ZM21,4v7H11V4Zm0,16.33V28H11V20.33L14.25,16,12,13h8l-2.25,3Z\"}]],\n  \"light\": [[\"path\",{\"d\":\"M15 2H17V7H15z\"}],[\"path\",{\"d\":\"M21.668 6.854H26.625999999999998V8.854H21.668z\",\"transform\":\"rotate(-45 24.147 7.853)\"}],[\"path\",{\"d\":\"M25 15H30V17H25z\"}],[\"path\",{\"d\":\"M23.147 21.668H25.147V26.625999999999998H23.147z\",\"transform\":\"rotate(-45 24.147 24.146)\"}],[\"path\",{\"d\":\"M15 25H17V30H15z\"}],[\"path\",{\"d\":\"M5.375 23.147H10.333V25.147H5.375z\",\"transform\":\"rotate(-45 7.853 24.146)\"}],[\"path\",{\"d\":\"M2 15H7V17H2z\"}],[\"path\",{\"d\":\"M6.854 5.375H8.854V10.333H6.854z\",\"transform\":\"rotate(-45 7.854 7.853)\"}],[\"path\",{\"d\":\"M16,12a4,4,0,1,1-4,4,4.0045,4.0045,0,0,1,4-4m0-2a6,6,0,1,0,6,6,6,6,0,0,0-6-6Z\"}]],\n  \"link\": [[\"path\",{\"d\":\"M29.25,6.76a6,6,0,0,0-8.5,0l1.42,1.42a4,4,0,1,1,5.67,5.67l-8,8a4,4,0,1,1-5.67-5.66l1.41-1.42-1.41-1.42-1.42,1.42a6,6,0,0,0,0,8.5A6,6,0,0,0,17,25a6,6,0,0,0,4.27-1.76l8-8A6,6,0,0,0,29.25,6.76Z\"}],[\"path\",{\"d\":\"M4.19,24.82a4,4,0,0,1,0-5.67l8-8a4,4,0,0,1,5.67,0A3.94,3.94,0,0,1,19,14a4,4,0,0,1-1.17,2.85L15.71,19l1.42,1.42,2.12-2.12a6,6,0,0,0-8.51-8.51l-8,8a6,6,0,0,0,0,8.51A6,6,0,0,0,7,28a6.07,6.07,0,0,0,4.28-1.76L9.86,24.82A4,4,0,0,1,4.19,24.82Z\"}]],\n  \"logout\": [[\"path\",{\"d\":\"M6,30H18a2.0023,2.0023,0,0,0,2-2V25H18v3H6V4H18V7h2V4a2.0023,2.0023,0,0,0-2-2H6A2.0023,2.0023,0,0,0,4,4V28A2.0023,2.0023,0,0,0,6,30Z\"}],[\"path\",{\"d\":\"M20.586 20.586 24.172 17 10 17 10 15 24.172 15 20.586 11.414 22 10 28 16 22 22 20.586 20.586z\"}]],\n  \"magic-wand\": [[\"path\",{\"d\":\"M29.4141,24,12,6.5859a2.0476,2.0476,0,0,0-2.8281,0l-2.586,2.586a2.0021,2.0021,0,0,0,0,2.8281L23.999,29.4141a2.0024,2.0024,0,0,0,2.8281,0l2.587-2.5865a1.9993,1.9993,0,0,0,0-2.8281ZM8,10.5859,10.5859,8l5,5-2.5866,2.5869-5-5ZM25.4131,28l-11-10.999L17,14.4141l11,11Z\"}],[\"path\",{\"d\":\"M2.586 14.586H5.414V17.414H2.586z\",\"transform\":\"rotate(-45 4 16)\"}],[\"path\",{\"d\":\"M14.586 2.586H17.414V5.414H14.586z\",\"transform\":\"rotate(-45 16 4)\"}],[\"path\",{\"d\":\"M2.586 2.586H5.414V5.414H2.586z\",\"transform\":\"rotate(-45 4 4)\"}]],\n  \"menu\": [[\"path\",{\"d\":\"M4 6H28V8H4z\"}],[\"path\",{\"d\":\"M4 24H28V26H4z\"}],[\"path\",{\"d\":\"M4 12H28V14H4z\"}],[\"path\",{\"d\":\"M4 18H28V20H4z\"}]],\n  \"overflow-menu--vertical\": [[\"circle\",{\"cx\":\"16\",\"cy\":\"8\",\"r\":\"2\"}],[\"circle\",{\"cx\":\"16\",\"cy\":\"16\",\"r\":\"2\"}],[\"circle\",{\"cx\":\"16\",\"cy\":\"24\",\"r\":\"2\"}]],\n  \"party-popper\": [[\"path\",{\"d\":\"M5,28c-.2607,0-.5161-.1016-.707-.293-.2749-.2744-.3657-.6836-.2329-1.0488L12.0601,4.6582c.1172-.3213.3896-.5605.7231-.6343.3335-.0757.6821.0269.9238.269l14,14c.2422.2412.3428.5898.2695.9238-.0742.333-.3135.6064-.6348.7227L5.3418,27.9395c-.1113.041-.2271.0605-.3418.0605ZM9.1367,18.5508l-2.4648,6.7773,6.7773-2.4648-4.3125-4.3125ZM9.8906,16.4766l5.6328,5.6328,3.793-1.3789-8.0464-8.0464-1.3794,3.7925ZM12.0239,10.6099l9.3657,9.3657,3.793-1.3789L13.4033,6.8174l-1.3794,3.7925ZM30,13h-4v-2h4v2ZM25.0127,8.4019l-1.4141-1.4141,3.3926-3.3931,1.4141,1.4141-3.3926,3.3931ZM21,6h-2V2h2v4Z\"}]],\n  \"pause--outline\": [[\"path\",{\"d\":\"M14 10 12 10 12 22 14 22 14 10 14 10z\"}],[\"path\",{\"d\":\"M20 10 18 10 18 22 20 22 20 10 20 10z\"}],[\"path\",{\"d\":\"M16,4A12,12,0,1,1,4,16,12,12,0,0,1,16,4m0-2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Z\"}]],\n  \"play--filled--alt\": [[\"path\",{\"d\":\"M7,28a1,1,0,0,1-1-1V5a1,1,0,0,1,1.4819-.8763l20,11a1,1,0,0,1,0,1.7525l-20,11A1.0005,1.0005,0,0,1,7,28Z\"}]],\n  \"play--outline\": [[\"path\",{\"d\":\"M11,23a1,1,0,0,1-1-1V10a1,1,0,0,1,1.4473-.8945l12,6a1,1,0,0,1,0,1.789l-12,6A1.001,1.001,0,0,1,11,23Zm1-11.3821v8.7642L20.7642,16Z\"}],[\"path\",{\"d\":\"M16,4A12,12,0,1,1,4,16,12,12,0,0,1,16,4m0-2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Z\"}]],\n  \"redo\": [[\"path\",{\"d\":\"M12,10H24.1851L20.5977,6.4141,22,5,28,11,22,17l-1.4023-1.4146L24.1821,12H12a6,6,0,0,0,0,12h8v2H12a8,8,0,0,1,0-16Z\"}]],\n  \"renew\": [[\"path\",{\"d\":\"M12,10H6.78A11,11,0,0,1,27,16h2A13,13,0,0,0,6,7.68V4H4v8h8Z\"}],[\"path\",{\"d\":\"M20,22h5.22A11,11,0,0,1,5,16H3a13,13,0,0,0,23,8.32V28h2V20H20Z\"}]],\n  \"restart\": [[\"path\",{\"d\":\"M26,18A10,10,0,1,1,16,8h6.1821l-3.5844,3.5854L20,13l6-6L20,1,18.5977,2.414,22.1851,6H16A12,12,0,1,0,28,18Z\"}]],\n  \"search\": [[\"path\",{\"d\":\"M29,27.5859l-7.5521-7.5521a11.0177,11.0177,0,1,0-1.4141,1.4141L27.5859,29ZM4,13a9,9,0,1,1,9,9A9.01,9.01,0,0,1,4,13Z\"}]],\n  \"send\": [[\"path\",{\"d\":\"M27.45,15.11l-22-11a1,1,0,0,0-1.08.12,1,1,0,0,0-.33,1L7,16,4,26.74A1,1,0,0,0,5,28a1,1,0,0,0,.45-.11l22-11a1,1,0,0,0,0-1.78Zm-20.9,10L8.76,17H18V15H8.76L6.55,6.89,24.76,16Z\"}]],\n  \"settings\": [[\"path\",{\"d\":\"M27,16.76c0-.25,0-.5,0-.76s0-.51,0-.77l1.92-1.68A2,2,0,0,0,29.3,11L26.94,7a2,2,0,0,0-1.73-1,2,2,0,0,0-.64.1l-2.43.82a11.35,11.35,0,0,0-1.31-.75l-.51-2.52a2,2,0,0,0-2-1.61H13.64a2,2,0,0,0-2,1.61l-.51,2.52a11.48,11.48,0,0,0-1.32.75L7.43,6.06A2,2,0,0,0,6.79,6,2,2,0,0,0,5.06,7L2.7,11a2,2,0,0,0,.41,2.51L5,15.24c0,.25,0,.5,0,.76s0,.51,0,.77L3.11,18.45A2,2,0,0,0,2.7,21L5.06,25a2,2,0,0,0,1.73,1,2,2,0,0,0,.64-.1l2.43-.82a11.35,11.35,0,0,0,1.31.75l.51,2.52a2,2,0,0,0,2,1.61h4.72a2,2,0,0,0,2-1.61l.51-2.52a11.48,11.48,0,0,0,1.32-.75l2.42.82a2,2,0,0,0,.64.1,2,2,0,0,0,1.73-1L29.3,21a2,2,0,0,0-.41-2.51ZM25.21,24l-3.43-1.16a8.86,8.86,0,0,1-2.71,1.57L18.36,28H13.64l-.71-3.55a9.36,9.36,0,0,1-2.7-1.57L6.79,24,4.43,20l2.72-2.4a8.9,8.9,0,0,1,0-3.13L4.43,12,6.79,8l3.43,1.16a8.86,8.86,0,0,1,2.71-1.57L13.64,4h4.72l.71,3.55a9.36,9.36,0,0,1,2.7,1.57L25.21,8,27.57,12l-2.72,2.4a8.9,8.9,0,0,1,0,3.13L27.57,20Z\"}],[\"path\",{\"d\":\"M16,22a6,6,0,1,1,6-6A5.94,5.94,0,0,1,16,22Zm0-10a3.91,3.91,0,0,0-4,4,3.91,3.91,0,0,0,4,4,3.91,3.91,0,0,0,4-4A3.91,3.91,0,0,0,16,12Z\"}]],\n  \"settings--adjust\": [[\"path\",{\"d\":\"M30,8h-4.1c-0.5-2.3-2.5-4-4.9-4s-4.4,1.7-4.9,4H2v2h14.1c0.5,2.3,2.5,4,4.9,4s4.4-1.7,4.9-4H30V8z M21,12c-1.7,0-3-1.3-3-3 s1.3-3,3-3s3,1.3,3,3S22.7,12,21,12z\"}],[\"path\",{\"d\":\"M2,24h4.1c0.5,2.3,2.5,4,4.9,4s4.4-1.7,4.9-4H30v-2H15.9c-0.5-2.3-2.5-4-4.9-4s-4.4,1.7-4.9,4H2V24z M11,20c1.7,0,3,1.3,3,3 s-1.3,3-3,3s-3-1.3-3-3S9.3,20,11,20z\"}]],\n  \"skip--forward\": [[\"path\",{\"d\":\"M5,28a1,1,0,0,1-1-1V5a1,1,0,0,1,.5-.87,1,1,0,0,1,1,0l19,11a1,1,0,0,1,0,1.74l-19,11A1,1,0,0,1,5,28ZM6,6.73V25.27L22,16Z\"}],[\"path\",{\"d\":\"M28 4H30V28H28z\"}]],\n  \"stop--filled\": [[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Zm6,18a2,2,0,0,1-2,2H12a2,2,0,0,1-2-2V12a2,2,0,0,1,2-2h8a2,2,0,0,1,2,2Z\"}]],\n  \"store\": [[\"path\",{\"d\":\"M30,10.68l-2-6A1,1,0,0,0,27,4H5a1,1,0,0,0-1,.68l-2,6A1.19,1.19,0,0,0,2,11v6a1,1,0,0,0,1,1H4V28H6V18h6V28H28V18h1a1,1,0,0,0,1-1V11A1.19,1.19,0,0,0,30,10.68ZM26,26H14V18H26Zm2-10H24V12H22v4H17V12H15v4H10V12H8v4H4V11.16L5.72,6H26.28L28,11.16Z\"}]],\n  \"time\": [[\"path\",{\"d\":\"M16,30A14,14,0,1,1,30,16,14,14,0,0,1,16,30ZM16,4A12,12,0,1,0,28,16,12,12,0,0,0,16,4Z\"}],[\"path\",{\"d\":\"M20.59 22 15 16.41 15 7 17 7 17 15.58 22 20.59 20.59 22z\"}]],\n  \"trash-can\": [[\"path\",{\"d\":\"M12 12H14V24H12z\"}],[\"path\",{\"d\":\"M18 12H20V24H18z\"}],[\"path\",{\"d\":\"M4,6V8H6V28a2,2,0,0,0,2,2H24a2,2,0,0,0,2-2V8h2V6ZM8,28V8H24V28Z\"}],[\"path\",{\"d\":\"M12 2H20V4H12z\"}]],\n  \"undo\": [[\"path\",{\"d\":\"M20,10H7.8149l3.5874-3.5859L10,5,4,11,10,17l1.4023-1.4146L7.8179,12H20a6,6,0,0,1,0,12H12v2h8a8,8,0,0,0,0-16Z\"}]],\n  \"user--avatar\": [[\"path\",{\"d\":\"M16,8a5,5,0,1,0,5,5A5,5,0,0,0,16,8Zm0,8a3,3,0,1,1,3-3A3.0034,3.0034,0,0,1,16,16Z\"}],[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14.0158,14.0158,0,0,0,16,2ZM10,26.3765V25a3.0033,3.0033,0,0,1,3-3h6a3.0033,3.0033,0,0,1,3,3v1.3765a11.8989,11.8989,0,0,1-12,0Zm13.9925-1.4507A5.0016,5.0016,0,0,0,19,20H13a5.0016,5.0016,0,0,0-4.9925,4.9258,12,12,0,1,1,15.985,0Z\"}]],\n  \"user--follow\": [[\"path\",{\"d\":\"M32 14 28 14 28 10 26 10 26 14 22 14 22 16 26 16 26 20 28 20 28 16 32 16 32 14z\"}],[\"path\",{\"d\":\"M12,4A5,5,0,1,1,7,9a5,5,0,0,1,5-5m0-2a7,7,0,1,0,7,7A7,7,0,0,0,12,2Z\"}],[\"path\",{\"d\":\"M22,30H20V25a5,5,0,0,0-5-5H9a5,5,0,0,0-5,5v5H2V25a7,7,0,0,1,7-7h6a7,7,0,0,1,7,7Z\"}]],\n  \"zoom--in\": [[\"path\",{\"d\":\"M18 12 14 12 14 8 12 8 12 12 8 12 8 14 12 14 12 18 14 18 14 14 18 14 18 12z\"}],[\"path\",{\"d\":\"M21.4479,20A10.856,10.856,0,0,0,24,13,11,11,0,1,0,13,24a10.856,10.856,0,0,0,7-2.5521L27.5859,29,29,27.5859ZM13,22a9,9,0,1,1,9-9A9.01,9.01,0,0,1,13,22Z\"}]],\n  \"zoom--out\": [[\"path\",{\"d\":\"M8 12H18V14H8z\"}],[\"path\",{\"d\":\"M21.4479,20A10.856,10.856,0,0,0,24,13,11,11,0,1,0,13,24a10.856,10.856,0,0,0,7-2.5521L27.5859,29,29,27.5859ZM13,22a9,9,0,1,1,9-9A9.01,9.01,0,0,1,13,22Z\"}]],\n};\n","import { svg, html } from \"lit\";\nimport { ifDefined } from \"lit/directives/if-defined.js\";\nimport { ICON_DATA, type IconName } from \"../../../companyos/frontend/components/icons/icon-data\";\n\n/** One Carbon glyph from the generated table the SPA uses (scripts/dev/generate-icons.mjs); decorative only. */\nexport function icon(name: IconName, size = 16) {\n  return html`<svg class=\"companyos-icon\" width=${size} height=${size} viewBox=\"0 0 32 32\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\">${\n    ICON_DATA[name].map(([tag, attrs]) => tag === \"circle\"\n      ? svg`<circle cx=${attrs.cx} cy=${attrs.cy} r=${attrs.r}></circle>`\n      : svg`<path d=${attrs.d} transform=${ifDefined(attrs.transform)} fill=${ifDefined(attrs.fill)}></path>`)}</svg>`;\n}\n","import { LitElement, html, nothing, type PropertyValues } from \"lit\";\nimport { getMenuActions, getMenuPosition } from \"../../../companyos/frontend/lib/context-menu\";\nimport { nextListSort, type ListColumn, type ListRowAction, type ListSort, type ListTextColumn } from \"../../../companyos/frontend/lib/list\";\nimport { icon } from \"./icon\";\n\ntype Key = string | number;\ntype Item = object;\n\n/** Cell controls keep their own interaction instead of opening the row (the SPA's DataTable rule). */\nconst CONTROL = \"button, a, input, label, select, textarea, [contenteditable=true], [role=button], [role=checkbox], [role=switch]\";\nconst FIELD = \"input, select, textarea, [contenteditable=true]\";\n\n/**\n * Rows in columns, as the SPA's screen List: `columns` is typed configuration (lib/list.ts), never cell markup.\n * Single selection that follows the arrow keys once something is selected, Enter selects, Home and End jump,\n * double-click fires `open-row`, \"/\" outside a field fires `search-request`. The list owns the sort toggle and\n * `aria-sort`; the consumer orders `items` itself on `sort-change`. Row actions open a menu (`row-action`).\n * `selectable = false` is the matrix form: no selection, rows take no focus, keys do nothing, double-click still opens.\n * An empty-state child (`<div class=\"companyos-list__empty\">`) shows only while there are no items.\n * Events, all bubbling CustomEvents: `select-row` (detail: key), `sort-change` (ListSort), `open-row` (item),\n * `row-action` ({ item, actionId }), `search-request`.\n */\nexport class CompanyosList extends LitElement {\n  public static override properties = {\n    label: {}, items: { attribute: false }, itemKey: { attribute: false }, itemLabel: { attribute: false },\n    columns: { attribute: false }, rowActions: { attribute: false }, selected: { attribute: false }, sort: { attribute: false },\n    selectable: { type: Boolean }, disabled: { type: Boolean },\n  };\n  declare public label: string;\n  declare public items: readonly Item[];\n  declare public itemKey: (item: never) => Key;\n  /** Names a row in its menu button (\"Acties voor ...\"). */\n  declare public itemLabel: (item: never) => string;\n  declare public columns: ReadonlyArray<ListColumn<never>>;\n  declare public rowActions: readonly ListRowAction[] | ((item: never) => readonly ListRowAction[]) | undefined;\n  /** The selected row's key; undefined is no selection. */\n  declare public selected: Key | undefined;\n  declare public sort: ListSort | undefined;\n  declare public selectable: boolean;\n  declare public disabled: boolean;\n  #cursor: Key | undefined;\n  // A context menu opens at the pointer; the row menu button anchors it below the button\n  #menu: { item: Item; trigger: HTMLElement; point?: { x: number; y: number } } | null = null;\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.items = [];\n    this.itemKey = item => String(item);\n    this.itemLabel = item => String(item);\n    this.columns = [];\n    this.rowActions = undefined;\n    this.selected = undefined;\n    this.sort = undefined;\n    this.selectable = true;\n    this.disabled = false;\n  }\n\n  // The table goes in its own first child; an empty-state child of the consumer stays after it\n  public override createRenderRoot() {\n    const root = document.createElement(\"div\");\n    root.className = \"companyos-list__scroller\";\n    this.prepend(root);\n    return root;\n  }\n\n  /** Moves keyboard focus to the row with `key`, or to the first row when it is not shown (after a detail panel closes). */\n  public async focusRow(key: Key): Promise<void> {\n    this.#cursor = this.#keys().includes(key) ? key : this.#keys()[0];\n    this.requestUpdate();\n    await this.updateComplete;\n    const row = [...this.renderRoot.querySelectorAll<HTMLElement>(\"tbody > tr\")].find(element => element.dataset.rowKey === String(this.#cursor));\n    row?.focus({ preventScroll: true });\n    row?.scrollIntoView({ block: \"nearest\", inline: \"nearest\" });\n  }\n\n  protected override willUpdate(changed: PropertyValues<this>) {\n    super.willUpdate(changed);\n    const keys = this.#keys();\n    if (this.#cursor === undefined || !keys.includes(this.#cursor))\n      this.#cursor = keys[0];\n    if (this.#menu && !this.items.includes(this.#menu.item))\n      this.#menu = null;\n  }\n\n  public override render() {\n    const actions = Boolean(this.rowActions);\n    return html`<table class=\"companyos-list__table\" aria-label=${this.label} aria-busy=${this.disabled ? \"true\" : \"false\"} @keydown=${this.#onKeydown}>\n      <colgroup>${this.columns.map(column => html`<col style=${column.flexible ? `min-width: ${column.minWidth}px` : `width: ${column.defaultWidth}px`}>`)}${actions ? html`<col style=\"width: 48px\">` : nothing}</colgroup>\n      <thead><tr>${this.columns.map(column => this.#heading(column))}${actions ? html`<th scope=\"col\" class=\"companyos-list__heading companyos-list__actions\"><span class=\"companyos-sr-only\">Acties</span></th>` : nothing}</tr></thead>\n      <tbody>${this.items.map(item => this.#row(item))}</tbody>\n    </table>${this.#menu ? this.#renderMenu(this.#menu) : nothing}`;\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    this.toggleAttribute(\"empty\", !this.items.length);\n    const menu = this.renderRoot.querySelector<HTMLElement>(\".companyos-list__menu\");\n    if (menu && !menu.matches(\":popover-open\")) {\n      menu.showPopover();\n      const trigger = this.#menu!.trigger.getBoundingClientRect();\n      const anchor = this.#menu!.point ?? { x: trigger.right - menu.offsetWidth, y: trigger.bottom + 4 };\n      const position = getMenuPosition({ ...anchor, width: menu.offsetWidth, height: menu.offsetHeight, viewportWidth: innerWidth, viewportHeight: innerHeight });\n      menu.style.left = `${position.x}px`;\n      menu.style.top = `${position.y}px`;\n      menu.querySelector<HTMLElement>(\"[role=menuitem]:not(:disabled)\")?.focus();\n    }\n  }\n\n  #keys(): Key[] {\n    return this.items.map(item => this.itemKey(item as never));\n  }\n\n  #heading(column: ListColumn<never>) {\n    const sortable = column.kind !== \"check\" && column.sortable;\n    const sorted = sortable && this.sort?.key === column.key ? this.sort.direction : undefined;\n    const align = column.kind === \"check\" ? \"center\" : column.align ?? \"left\";\n    return html`<th scope=\"col\" class=\"companyos-list__heading companyos-list__cell--${align}\" data-column=${column.key}\n        aria-sort=${sortable ? sorted === \"asc\" ? \"ascending\" : sorted === \"desc\" ? \"descending\" : \"none\" : nothing}>${sortable\n      ? html`<button type=\"button\" class=\"companyos-list__sort\" ?disabled=${this.disabled} @click=${() => this.#onSort(column.key)}>${column.label}${sorted\n        ? html`<span class=\"companyos-list__sort-icon companyos-list__sort-icon--${sorted}\">${icon(\"chevron--down\", 14)}</span>` : nothing}</button>`\n      : column.label}</th>`;\n  }\n\n  #row(item: Item) {\n    const key = this.itemKey(item as never);\n    const selected = this.selectable && this.selected === key;\n    return html`<tr class=\"companyos-list__row ${this.selectable ? \"companyos-list__row--selectable\" : \"\"}\" data-row-key=${key}\n        tabindex=${this.selectable ? this.#cursor === key ? 0 : -1 : nothing} aria-selected=${this.selectable ? String(selected) : nothing}\n        @focusin=${() => { this.#cursor = key; }} @click=${() => this.#select(item)} @dblclick=${(event: MouseEvent) => this.#onDoubleClick({ event, item })}\n        @contextmenu=${(event: MouseEvent) => this.#onContextMenu({ event, item })}>\n      ${this.columns.map(column => column.kind === \"check\" ? this.#checkCell({ item, column }) : this.#textCell({ item, column }))}\n      ${this.rowActions ? html`<td class=\"companyos-list__cell companyos-list__actions\"><button type=\"button\" class=\"companyos-list__menu-trigger\" ?disabled=${this.disabled}\n        aria-label=\"Acties voor ${this.itemLabel(item as never)}\" aria-haspopup=\"menu\" aria-expanded=${this.#menu?.item === item ? \"true\" : \"false\"}\n        @click=${(event: MouseEvent) => this.#openMenu({ item, trigger: event.currentTarget as HTMLElement })}>${icon(\"overflow-menu--vertical\", 20)}</button></td>` : nothing}\n    </tr>`;\n  }\n\n  #textCell({ item, column }: { item: Item; column: ListTextColumn<never> }) {\n    const raw = column.value ? column.value(item as never) : (item as Record<string, unknown>)[column.key];\n    const text = typeof raw === \"number\" ? raw : String(raw ?? \"\");\n    const badge = column.badge?.(item as never);\n    return html`<td class=\"companyos-list__cell companyos-list__cell--${column.align ?? \"left\"} ${column.emphasis ? \"companyos-list__cell--emphasis\" : \"\"}\n        ${column.tone === \"secondary\" ? \"companyos-list__cell--secondary\" : \"\"} ${column.numeric ? \"companyos-list__cell--numeric\" : \"\"}\" data-column=${column.key}>\n      <span class=\"companyos-list__content\"><span class=\"companyos-list__text\" title=${text}>${text}</span>${badge ? html`<span class=\"companyos-list__badge\" role=\"img\"\n        aria-label=${badge.description ? `${badge.label}: ${badge.description}` : badge.label} title=${badge.description || badge.label}>${badge.label}</span>` : nothing}</span></td>`;\n  }\n\n  #checkCell({ item, column }: { item: Item; column: Extract<ListColumn<never>, { kind: \"check\" }> }) {\n    const checked = column.checked(item as never);\n    return html`<td class=\"companyos-list__cell companyos-list__cell--center\" data-column=${column.key}>\n      <span class=\"companyos-list__check\" role=\"checkbox\" aria-readonly=\"true\" aria-checked=${String(checked)} aria-label=${column.checkLabel(item as never)}>${checked ? icon(\"checkmark\", 16) : nothing}</span></td>`;\n  }\n\n  #renderMenu({ item }: { item: Item }) {\n    const actions = getMenuActions({ actions: typeof this.rowActions === \"function\" ? this.rowActions(item as never) : this.rowActions ?? [] });\n    return html`<div class=\"companyos-list__menu\" popover=\"auto\" role=\"menu\" aria-label=\"Acties voor ${this.itemLabel(item as never)}\"\n        @toggle=${this.#onMenuToggle} @keydown=${this.#onMenuKeydown}>${actions.map(action => html`\n      ${action.separatorBefore ? html`<div class=\"companyos-list__menu-separator\" role=\"separator\"></div>` : nothing}\n      <button type=\"button\" role=\"menuitem\" tabindex=\"-1\" class=\"companyos-list__menu-item ${action.danger ? \"companyos-list__menu-item--danger\" : \"\"}\"\n        ?disabled=${action.disabled} @click=${() => this.#onAction({ item, actionId: action.id })}>${action.label}</button>`)}</div>`;\n  }\n\n  #emit(type: string, detail?: unknown): void {\n    this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }));\n  }\n\n  #select(item: Item): void {\n    if (this.disabled || !this.selectable)\n      return;\n    this.#cursor = this.itemKey(item as never);\n    this.#emit(\"select-row\", this.#cursor);\n  }\n\n  #onSort(key: string): void {\n    this.#emit(\"sort-change\", nextListSort({ current: this.sort, key }));\n  }\n\n  #onDoubleClick({ event, item }: { event: MouseEvent; item: Item }): void {\n    if (this.disabled || (event.target instanceof Element && event.target.closest(CONTROL)))\n      return;\n    this.#emit(\"open-row\", item);\n  }\n\n  #onContextMenu({ event, item }: { event: MouseEvent; item: Item }): void {\n    if (this.disabled || !this.rowActions)\n      return;\n    event.preventDefault();\n    const trigger = (event.currentTarget as HTMLElement).querySelector<HTMLElement>(\".companyos-list__menu-trigger\");\n    if (trigger)\n      this.#openMenu({ item, trigger, point: { x: event.clientX, y: event.clientY } });\n  }\n\n  #onKeydown = (event: KeyboardEvent): void => {\n    if (event.target instanceof Element && event.target.closest(`${FIELD}, .companyos-list__menu`))\n      return;\n    if (event.key === \"/\") {\n      event.preventDefault();\n      this.#emit(\"search-request\");\n      return;\n    }\n    if (this.disabled || !this.selectable || !this.items.length)\n      return;\n    const keys = this.#keys();\n    const index = keys.indexOf(this.#cursor!);\n    let target: number;\n    switch (event.key) {\n      case \"ArrowDown\": target = index < 0 ? 0 : Math.min(keys.length - 1, index + 1); break;\n      case \"ArrowUp\": target = index < 0 ? 0 : Math.max(0, index - 1); break;\n      case \"Home\": target = 0; break;\n      case \"End\": target = keys.length - 1; break;\n      case \"Enter\":\n        if (event.target instanceof Element && event.target.closest(\"button, a\"))\n          return;\n        event.preventDefault();\n        if (index >= 0)\n          this.#select(this.items[index]);\n        return;\n      default: return;\n    }\n    event.preventDefault();\n    void this.focusRow(keys[target]);\n    // The cursor moves; the selection only follows once there is one\n    if (this.selected !== undefined)\n      this.#select(this.items[target]);\n  };\n\n  #openMenu(menu: { item: Item; trigger: HTMLElement; point?: { x: number; y: number } }): void {\n    if (this.disabled)\n      return;\n    this.#menu = menu;\n    this.requestUpdate();\n  }\n\n  #closeMenu({ focusTrigger }: { focusTrigger: boolean }): void {\n    const trigger = this.#menu?.trigger;\n    this.#menu = null;\n    this.requestUpdate();\n    if (focusTrigger && trigger?.isConnected)\n      trigger.focus();\n  }\n\n  // Light dismiss and Escape close the popover; focus goes back to the trigger unless the user clicked elsewhere\n  #onMenuToggle = (event: ToggleEvent): void => {\n    if (event.newState === \"closed\" && this.#menu) {\n      const active = document.activeElement;\n      this.#closeMenu({ focusTrigger: !active || active === document.body || (event.currentTarget as Element).contains(active) });\n    }\n  };\n\n  #onMenuKeydown = (event: KeyboardEvent): void => {\n    const items = [...(event.currentTarget as Element).querySelectorAll<HTMLElement>(\"[role=menuitem]:not(:disabled)\")];\n    const index = items.indexOf(document.activeElement as HTMLElement);\n    const next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 }[event.key];\n    if (next === undefined) {\n      if (event.key === \"Tab\")\n        this.#closeMenu({ focusTrigger: true });\n      return;\n    }\n    event.preventDefault();\n    items[(next + items.length) % items.length]?.focus();\n  };\n\n  #onAction({ item, actionId }: { item: Item; actionId: string }): void {\n    this.#closeMenu({ focusTrigger: true });\n    this.#emit(\"row-action\", { item, actionId });\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"companyos-list\": CompanyosList;\n  }\n}\n\nif (!customElements.get(\"companyos-list\"))\n  customElements.define(\"companyos-list\", CompanyosList);\n","import { LitElement, html, nothing, type PropertyValues } from \"lit\";\n\nlet lastId = 0;\n\n/**\n * A modal form dialog on a native `<dialog>`, as the SPA's screen Dialog: focus moves in on open and back to the\n * opener on close, Escape, the backdrop and `requestClose()` are one path (ignored while pending, a discard question\n * when dirty), fields and buttons are disabled while pending, a loading backdrop with a minimum time, the form error\n * and focus on the first invalid field or that error after a failed save. The rest of the page is inert (showModal).\n *\n * Content: the element's own children at first connect. Children with `slot=\"actions\"` become the footer (put a\n * `type=\"submit\"` button there), all others the body. They are moved into the dialog once, together with any template\n * markers of a parent Lit template, so later updates of that template keep working.\n * Events (bubbling CustomEvents): `dialog-submit`, and `dialog-cancel` with detail `{ discard }`.\n * Stays shown while `loadingVisible` after `open` turned false, so the loading minimum is not cut off.\n */\nexport class CompanyosDialog extends LitElement {\n  public static override properties = {\n    open: { type: Boolean }, heading: {}, description: {}, pending: { type: Boolean },\n    loadingVisible: { type: Boolean, attribute: \"loading-visible\" }, dirty: { type: Boolean }, error: {},\n    alert: { type: Boolean }, pendingLabel: { attribute: \"pending-label\" },\n  };\n  declare public open: boolean;\n  declare public heading: string;\n  declare public description: string;\n  declare public pending: boolean;\n  declare public loadingVisible: boolean;\n  declare public dirty: boolean;\n  /** The form-level message; field messages belong to the fields (aria-invalid plus their own text). */\n  declare public error: string;\n  /** Role alertdialog, for a confirmation. */\n  declare public alert: boolean;\n  declare public pendingLabel: string;\n  readonly #id = `companyos-dialog-${++lastId}`;\n  #content: ChildNode[] | null = null;\n  #opener: HTMLElement | null = null;\n  #discardOrigin: HTMLElement | null = null;\n  #confirmingDiscard = false;\n\n  public constructor() {\n    super();\n    this.open = false;\n    this.heading = \"\";\n    this.description = \"\";\n    this.pending = false;\n    this.loadingVisible = false;\n    this.dirty = false;\n    this.error = \"\";\n    this.alert = false;\n    this.pendingLabel = \"Bezig...\";\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    // Before the first render appends the dialog: what is here now is the consumer's content\n    this.#content ??= [...this.childNodes];\n    super.connectedCallback();\n  }\n\n  /** Escape, the backdrop and a cancel button all end here. */\n  public requestClose(): void {\n    if (this.#actionsDisabled())\n      return;\n    if (!this.dirty) {\n      this.dispatchEvent(new CustomEvent(\"dialog-cancel\", { detail: { discard: false }, bubbles: true }));\n      return;\n    }\n    const active = document.activeElement;\n    this.#discardOrigin = active instanceof HTMLElement && this.#dialog()?.contains(active) && active !== this.#dialog() ? active : null;\n    this.#confirmingDiscard = true;\n    this.requestUpdate();\n    void this.updateComplete.then(() => this.querySelector<HTMLButtonElement>(\".companyos-dialog__discard button\")?.focus());\n  }\n\n  public override render() {\n    const disabled = this.#actionsDisabled();\n    return html`<dialog class=\"companyos-dialog\" role=${this.alert ? \"alertdialog\" : \"dialog\"} aria-modal=\"true\" aria-labelledby=\"${this.#id}-title\"\n        aria-describedby=${this.description ? `${this.#id}-description` : nothing} aria-busy=${this.pending ? \"true\" : \"false\"}\n        @cancel=${this.#onCancel} @close=${this.#onClose} @click=${this.#onBackdrop}>\n      <header class=\"companyos-dialog__header\">\n        <h2 id=\"${this.#id}-title\" class=\"companyos-dialog__title\">${this.heading}</h2>\n        ${this.description ? html`<p id=\"${this.#id}-description\" class=\"companyos-dialog__description\">${this.description}</p>` : nothing}\n      </header>\n      <form class=\"companyos-form companyos-dialog__form\" novalidate @submit=${this.#onSubmit}>\n        <div class=\"companyos-dialog__body\">\n          <div class=\"companyos-dialog__loading\" aria-busy=${this.pending ? \"true\" : \"false\"}>\n            <fieldset class=\"companyos-dialog__fields\" ?disabled=${disabled} ?inert=${this.loadingVisible}></fieldset>\n            <span class=\"companyos-sr-only\" role=\"status\" aria-live=\"polite\">${this.pending ? this.pendingLabel : \"\"}</span>\n            ${this.loadingVisible ? html`<div class=\"companyos-dialog__backdrop\" data-pending=${this.pending ? \"true\" : \"false\"}>\n              <div class=\"companyos-dialog__indicator\"><span class=\"companyos-dialog__spinner\" aria-hidden=\"true\"></span><span>${this.pendingLabel}</span></div></div>` : nothing}\n          </div>\n          ${this.error ? html`<p class=\"companyos-dialog__error\" role=\"alert\" tabindex=\"-1\">${this.error}</p>` : nothing}\n          ${this.#confirmingDiscard ? html`<div class=\"companyos-dialog__discard\" role=\"alert\">\n            <p class=\"companyos-dialog__discard-text\">Je wijzigingen zijn nog niet opgeslagen.</p>\n            <div class=\"companyos-buttonbar companyos-buttonbar--start\">\n              <button type=\"button\" class=\"companyos-button\" @click=${this.#keepEditing}>Verder bewerken</button>\n              <button type=\"button\" class=\"companyos-button companyos-button--danger\" @click=${this.#discard}>Sluiten zonder opslaan</button>\n            </div></div>` : nothing}\n        </div>\n        <fieldset class=\"companyos-dialog__actions companyos-buttonbar\" ?disabled=${disabled}></fieldset>\n      </form>\n    </dialog>`;\n  }\n\n  protected override firstUpdated(changed: PropertyValues<this>) {\n    super.firstUpdated(changed);\n    const fields = this.querySelector(\".companyos-dialog__fields\")!;\n    const actions = this.querySelector(\".companyos-dialog__actions\")!;\n    for (const node of this.#content ?? [])\n      (node instanceof Element && node.getAttribute(\"slot\") === \"actions\" ? actions : fields).append(node);\n    actions.toggleAttribute(\"hidden\", !actions.children.length);\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    const dialog = this.#dialog()!;\n    if (changed.has(\"open\"))\n      this.#confirmingDiscard = false;\n    const shown = this.open || (dialog.open && this.loadingVisible);\n    if (shown && !dialog.open) {\n      const active = document.activeElement;\n      this.#opener = active instanceof HTMLElement && active !== document.body ? active : null;\n      dialog.showModal();\n    } else if (!shown && dialog.open) {\n      dialog.close();\n      // Chrome restores focus on close by itself (removing this kept the focus check green); not every browser does\n      if (this.#opener?.isConnected)\n        this.#opener.focus();\n      this.#opener = null;\n    }\n    const wasReady = (changed.has(\"pending\") ? changed.get(\"pending\") : this.pending) === false\n      && (changed.has(\"loadingVisible\") ? changed.get(\"loadingVisible\") : this.loadingVisible) === false;\n    if (this.open && !wasReady && this.#ready())\n      this.#focusAfterSave(dialog);\n  }\n\n  #dialog(): HTMLDialogElement | null {\n    return this.querySelector(\":scope > dialog\");\n  }\n\n  #actionsDisabled(): boolean {\n    return this.pending || !this.open;\n  }\n\n  #ready(): boolean {\n    return !this.pending && !this.loadingVisible;\n  }\n\n  // The submit button was disabled while pending, which leaves focus on <body>: move it to where the news is\n  #focusAfterSave(dialog: HTMLDialogElement): void {\n    const invalid = dialog.querySelector<HTMLElement>(\"[aria-invalid=true]:not(:disabled)\");\n    if (invalid)\n      invalid.focus();\n    else if (!dialog.contains(document.activeElement))\n      dialog.querySelector<HTMLElement>(\".companyos-dialog__error\")?.focus();\n  }\n\n  #onSubmit = (event: SubmitEvent): void => {\n    event.preventDefault();\n    if (!this.#actionsDisabled())\n      this.dispatchEvent(new CustomEvent(\"dialog-submit\", { bubbles: true }));\n  };\n\n  #onCancel = (event: Event): void => {\n    event.preventDefault();\n    this.requestClose();\n  };\n\n  // A second Escape without user activation closes a dialog without a cancel event (close watcher rules): stay open\n  #onClose = (): void => {\n    const dialog = this.#dialog()!;\n    if (this.open && this.isConnected && !dialog.open) {\n      dialog.showModal();\n      this.requestClose();\n    }\n  };\n\n  // Native dialog sends backdrop clicks to the dialog itself, as well as clicks on its border\n  #onBackdrop = (event: MouseEvent): void => {\n    const dialog = this.#dialog()!;\n    if (event.target !== dialog)\n      return;\n    const rect = dialog.getBoundingClientRect();\n    if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom)\n      this.requestClose();\n  };\n\n  #keepEditing = (): void => {\n    this.#confirmingDiscard = false;\n    const origin = this.#discardOrigin;\n    this.#discardOrigin = null;\n    this.requestUpdate();\n    // The focused confirmation button is removed with the panel: hand focus back to where it came from\n    void this.updateComplete.then(() => {\n      const target = origin?.isConnected && !origin.matches(\":disabled\") ? origin\n        : this.querySelector<HTMLElement>(\".companyos-dialog__fields :is(input, select, textarea, button):not(:disabled)\");\n      target?.focus({ preventScroll: true });\n    });\n  };\n\n  #discard = (): void => {\n    this.dispatchEvent(new CustomEvent(\"dialog-cancel\", { detail: { discard: true }, bubbles: true }));\n  };\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"companyos-dialog\": CompanyosDialog;\n  }\n}\n\nif (!customElements.get(\"companyos-dialog\"))\n  customElements.define(\"companyos-dialog\", CompanyosDialog);\n","export interface TabItem {\n  key: string;\n  label: string;\n  disabled?: boolean;\n  /** Content panels reserve space for a heading; list panels meet their toolbar directly. */\n  panelLayout?: \"content\" | \"list\";\n}\n\n/** Keep a reachable tab when an integration removes or disables the current selection. */\nexport function activeTabKey(options: { items: readonly TabItem[]; selected: string }): string | null {\n  return options.items.find(item => item.key === options.selected && !item.disabled)?.key\n    ?? options.items.find(item => !item.disabled)?.key\n    ?? null;\n}\n\n/** Automatic keyboard activation follows the visible enabled order, including wraparound. */\nexport function nextTabKey(options: { items: readonly TabItem[]; current: string; key: string }): string | null {\n  const enabled = options.items.filter(item => !item.disabled);\n  if (!enabled.length) return null;\n  const index = enabled.findIndex(item => item.key === options.current);\n  switch (options.key) {\n    case \"Home\": return enabled[0].key;\n    case \"End\": return enabled[enabled.length - 1].key;\n    case \"ArrowRight\": return enabled[(index + 1) % enabled.length].key;\n    case \"ArrowLeft\": return enabled[(index < 0 ? 0 : index + enabled.length - 1) % enabled.length].key;\n    default: return null;\n  }\n}\n","import { LitElement, html, type PropertyValues } from \"lit\";\nimport { activeTabKey, nextTabKey, type TabItem } from \"../../../companyos/frontend/lib/tabs\";\n\nlet lastId = 0;\n\n/**\n * Tabs over the panels that are its own children: `<companyos-tabs label=\"...\"><section data-tab=\"ips\"\n * data-tab-title=\"IP-adressen\">...</section>...</companyos-tabs>`. A panel with `data-tab-disabled` is shown in the\n * tablist but cannot be selected. The panels stay where the page or the parent template put them (light DOM); this\n * element only renders the tablist before them and toggles `hidden`, so a panel keeps its state when you switch.\n * Roles, roving tabindex, the keyboard (arrows, Home and End over the enabled tabs with wraparound, automatic\n * activation) and the fallback to the first enabled tab are those of the SPA's screen Tabs (lib/tabs.ts).\n * `selected` is the panel's `data-tab`; a user choice sets it and fires `tab-change` (detail: the value).\n * Not `<companyos-sections>`: that one switches sections of a server-rendered form with plain buttons.\n */\nexport class CompanyosTabs extends LitElement {\n  public static override properties = { label: {}, selected: {} };\n  declare public label: string;\n  declare public selected: string;\n  readonly #id = `companyos-tabs-${++lastId}`;\n  #observer: MutationObserver | undefined;\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.selected = \"\";\n  }\n\n  // The tablist goes in its own first child, before the panels\n  public override createRenderRoot() {\n    const root = document.createElement(\"div\");\n    root.className = \"companyos-tabs__list\";\n    this.prepend(root);\n    return root;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    // Only own panels matter, not every change a panel's content makes\n    this.#observer = new MutationObserver(records => {\n      if (records.some(record => record.target === this || record.target.parentNode === this))\n        this.requestUpdate();\n    });\n    this.#observer.observe(this, { childList: true, attributes: true, subtree: true, attributeFilter: [\"data-tab\", \"data-tab-title\", \"data-tab-disabled\"] });\n  }\n\n  public override disconnectedCallback() {\n    super.disconnectedCallback();\n    this.#observer?.disconnect();\n  }\n\n  public override render() {\n    const items = this.#items();\n    const active = this.#active(items);\n    return html`<div role=\"tablist\" aria-label=${this.label} @keydown=${(event: KeyboardEvent) => this.#onKey({ event, items, active })}>${items.map(item => html`\n      <button type=\"button\" role=\"tab\" id=${this.#tabId(item.key)} aria-controls=${this.#panelId(item.key)} aria-selected=${item.key === active ? \"true\" : \"false\"}\n        tabindex=${item.key === active ? 0 : -1} ?disabled=${item.disabled} @click=${() => this.#select(item.key)}>${item.label}</button>`)}</div>`;\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    const items = this.#items();\n    const active = this.#active(items);\n    for (const panel of this.#panels()) {\n      const value = panel.dataset.tab!;\n      panel.id ||= this.#panelId(value);\n      panel.setAttribute(\"role\", \"tabpanel\");\n      panel.setAttribute(\"aria-labelledby\", this.#tabId(value));\n      panel.tabIndex = 0;\n      panel.hidden = value !== active;\n    }\n    // The model follows the fallback, as in the SPA: after rendering, and only when there is a reachable tab\n    if (active !== null && active !== this.selected)\n      this.#select(active);\n  }\n\n  #panels(): HTMLElement[] {\n    return [...this.children].filter((child): child is HTMLElement => child instanceof HTMLElement && child.dataset.tab !== undefined);\n  }\n\n  #items(): TabItem[] {\n    return this.#panels().map(panel => ({ key: panel.dataset.tab!, label: panel.dataset.tabTitle ?? \"\", disabled: panel.hasAttribute(\"data-tab-disabled\") }));\n  }\n\n  #active(items: TabItem[]): string | null {\n    // No enabled tab: the current one stays shown\n    return activeTabKey({ items, selected: this.selected }) ?? (items.some(item => item.key === this.selected) ? this.selected : null);\n  }\n\n  #panelId(value: string): string {\n    return `${this.#id}-panel-${value}`;\n  }\n\n  #tabId(value: string): string {\n    return `${this.#id}-tab-${value}`;\n  }\n\n  #select(value: string): void {\n    if (value === this.selected)\n      return;\n    this.selected = value;\n    this.dispatchEvent(new CustomEvent(\"tab-change\", { detail: value, bubbles: true }));\n  }\n\n  #onKey({ event, items, active }: { event: KeyboardEvent; items: TabItem[]; active: string | null }): void {\n    const target = nextTabKey({ items, current: active ?? \"\", key: event.key });\n    if (!target)\n      return;\n    event.preventDefault();\n    this.#select(target);\n    void this.updateComplete.then(() => this.renderRoot.querySelector<HTMLButtonElement>(`#${CSS.escape(this.#tabId(target))}`)?.focus());\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"companyos-tabs\": CompanyosTabs;\n  }\n}\n\nif (!customElements.get(\"companyos-tabs\"))\n  customElements.define(\"companyos-tabs\", CompanyosTabs);\n","export type ToastTone = \"success\" | \"info\" | \"error\";\nexport type ToastPauseReason = \"hover\" | \"focus\";\n\nexport interface ToastMessage {\n  id: number;\n  message: string;\n  tone: ToastTone;\n}\n\nexport interface ToastOptions {\n  message: string;\n  tone?: ToastTone;\n}\n\n/** A replaceable clock lets tests verify expiry without real-time delays. */\nexport interface ToastClock {\n  now: () => number;\n  schedule: (options: { callback: () => void; delayMs: number }) => () => void;\n}\n\ninterface ToastEntry {\n  message: ToastMessage;\n  remainingMs: number;\n  startedAt: number;\n  pauses: Set<ToastPauseReason>;\n  cancel?: () => void;\n}\n\nconst browserClock: ToastClock = {\n  now: () => performance.now(),\n  schedule: ({ callback, delayMs }) => {\n    const timer = setTimeout(callback, delayMs);\n    return () => clearTimeout(timer);\n  },\n};\n\n/**\n * Owns one app's transient notifications. Keep at most three, each visible for six seconds\n * of unpaused time. Clear on logout/unmount so messages never leak into another session.\n */\nexport class ToastController {\n  readonly #clock: ToastClock;\n  readonly #onChange: (messages: readonly ToastMessage[]) => void;\n  readonly #entries = new Map<number, ToastEntry>();\n  #nextId = 0;\n\n  public constructor(options: { clock?: ToastClock; onChange?: (messages: readonly ToastMessage[]) => void } = {}) {\n    this.#clock = options.clock ?? browserClock;\n    this.#onChange = options.onChange ?? (() => {});\n  }\n\n  public get messages(): readonly ToastMessage[] {\n    return [...this.#entries.values()].map(entry => entry.message);\n  }\n\n  public show(options: ToastOptions): number {\n    const id = ++this.#nextId;\n    const entry: ToastEntry = {\n      message: { id, message: options.message, tone: options.tone ?? \"info\" },\n      remainingMs: 6000,\n      startedAt: this.#clock.now(),\n      pauses: new Set(),\n    };\n    if (this.#entries.size >= 3) {\n      const oldest = this.messages[0];\n      if (oldest) this.dismiss(oldest.id);\n    }\n    this.#entries.set(id, entry);\n    this.#schedule(entry);\n    this.#publish();\n    return id;\n  }\n\n  public dismiss(id: number): void {\n    this.#entries.get(id)?.cancel?.();\n    this.#entries.delete(id);\n    this.#publish();\n  }\n\n  public pause(options: { id: number; reason: ToastPauseReason }): void {\n    const entry = this.#entries.get(options.id);\n    if (!entry || entry.pauses.has(options.reason)) return;\n    if (!entry.pauses.size) {\n      entry.remainingMs = Math.max(0, entry.remainingMs - (this.#clock.now() - entry.startedAt));\n      entry.cancel?.();\n      entry.cancel = undefined;\n    }\n    entry.pauses.add(options.reason);\n  }\n\n  public resume(options: { id: number; reason: ToastPauseReason }): void {\n    const entry = this.#entries.get(options.id);\n    // Hover and keyboard focus may overlap; neither may resume the other's pause.\n    if (!entry?.pauses.delete(options.reason) || entry.pauses.size) return;\n    this.#schedule(entry);\n  }\n\n  public clear(): void {\n    for (const entry of this.#entries.values()) entry.cancel?.();\n    this.#entries.clear();\n    this.#publish();\n  }\n\n  #schedule(entry: ToastEntry): void {\n    entry.startedAt = this.#clock.now();\n    entry.cancel = this.#clock.schedule({ delayMs: entry.remainingMs, callback: () => this.dismiss(entry.message.id) });\n  }\n\n  #publish(): void {\n    this.#onChange(this.messages);\n  }\n}\n","import { html, render } from \"lit\";\nimport { ToastController, type ToastMessage, type ToastOptions } from \"../../../companyos/frontend/lib/toasts\";\nimport { icon } from \"./icon\";\n\n/** The one live region per page, under <body> outside the page's main content. */\nconst REGION_CLASS = \"companyos-toasts\";\n\nlet controller: ToastController | undefined;\n\n// Created before the first message, so assistive technology hears additions (as ToastHost in the SPA)\nfunction ensure(): ToastController {\n  if (controller)\n    return controller;\n  const region = document.createElement(\"div\");\n  region.className = REGION_CLASS;\n  region.setAttribute(\"role\", \"region\");\n  region.setAttribute(\"aria-label\", \"Meldingen\");\n  region.setAttribute(\"aria-live\", \"polite\");\n  region.setAttribute(\"aria-relevant\", \"additions\");\n  region.setAttribute(\"aria-atomic\", \"false\");\n  document.body.append(region);\n  const created = new ToastController({ onChange: messages => render(messages.map(message => toast(created, message)), region) });\n  controller = created;\n  return created;\n}\n\nfunction toast(owner: ToastController, { id, message, tone }: ToastMessage) {\n  return html`<div class=\"companyos-toast companyos-toast--${tone}\"\n      @mouseenter=${() => owner.pause({ id, reason: \"hover\" })} @mouseleave=${() => owner.resume({ id, reason: \"hover\" })}\n      @focusin=${() => owner.pause({ id, reason: \"focus\" })} @focusout=${() => owner.resume({ id, reason: \"focus\" })}>\n    ${tone === \"success\" ? icon(\"checkmark--outline\", 20) : \"\"}\n    <p class=\"companyos-toast__message\">${message}</p>\n    <button class=\"companyos-toast__close\" type=\"button\" aria-label=\"Melding sluiten: ${message}\" @click=${() => owner.dismiss(id)}>${icon(\"close\", 20)}</button>\n  </div>`;\n}\n\n/**\n * Shows a short notification in the page's live region (at most three, six seconds each, paused on hover and focus).\n * Returns its id for `dismissToast`. Nothing is persisted: a new document starts without messages.\n */\nexport function showToast(options: ToastOptions): number {\n  return ensure().show(options);\n}\n\nexport function dismissToast(id: number): void {\n  controller?.dismiss(id);\n}\n\n// The region exists from DOM ready on every page that imports the screen entry, before any message\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", () => ensure(), { once: true });\nelse\n  ensure();\n","/** A cancellable timer seam keeps visual timing testable without delaying the operation. */\nexport interface LoadingClock {\n  now: () => number;\n  schedule: (options: { callback: () => void; delayMs: number }) => () => void;\n}\n\nexport interface LoadingState {\n  pending: boolean;\n  visible: boolean;\n}\n\nexport interface LoadingOptions {\n  delayMs?: number;\n  minimumMs?: number;\n  clock?: LoadingClock;\n  onChange?: (state: LoadingState) => void;\n}\n\nconst browserClock: LoadingClock = {\n  now: () => performance.now(),\n  schedule: ({ callback, delayMs }) => {\n    const timer = setTimeout(callback, delayMs);\n    return () => clearTimeout(timer);\n  },\n};\n\n/**\n * Tracks overlapping operations separately from backdrop visibility. Results and errors settle\n * immediately; the 200ms delay and 500ms minimum apply only to presentation. Dispose cancels\n * timers and aborts each operation's signal, including when its owner navigates away.\n */\nexport class LoadingController {\n  readonly #clock: LoadingClock;\n  readonly #delayMs: number;\n  readonly #minimumMs: number;\n  readonly #onChange: (state: LoadingState) => void;\n  readonly #operations = new Set<AbortController>();\n  #visible = false;\n  #visibleSince = 0;\n  #cancelShow?: () => void;\n  #cancelHide?: () => void;\n  #disposed = false;\n  #revision = 0;\n\n  public constructor(options: LoadingOptions = {}) {\n    this.#clock = options.clock ?? browserClock;\n    this.#delayMs = Math.max(0, options.delayMs ?? 200);\n    this.#minimumMs = Math.max(0, options.minimumMs ?? 500);\n    this.#onChange = options.onChange ?? (() => {});\n  }\n\n  public get state(): LoadingState {\n    return { pending: this.#operations.size > 0, visible: this.#visible };\n  }\n\n  public async run<T>(operation: (context: { signal: AbortSignal }) => Promise<T>): Promise<T> {\n    if (this.#disposed)\n      throw new Error(\"Loading controller is disposed\");\n    const revision = this.#revision;\n    const abort = new AbortController();\n    this.#operations.add(abort);\n    this.#cancelHide?.();\n    this.#cancelHide = undefined;\n    if (!this.#visible && !this.#cancelShow) {\n      this.#cancelShow = this.#clock.schedule({ delayMs: this.#delayMs, callback: () => {\n        this.#cancelShow = undefined;\n        if (this.#disposed || !this.#operations.size) return;\n        this.#visible = true;\n        this.#visibleSince = this.#clock.now();\n        this.#publish();\n      } });\n    }\n    this.#publish();\n    try {\n      return await operation({ signal: abort.signal });\n    } finally {\n      this.#operations.delete(abort);\n      if (!this.#disposed && revision === this.#revision) {\n        if (!this.#operations.size) this.#finishPresentation();\n        this.#publish();\n      }\n    }\n  }\n\n  /** Cancel presentation and abort current work while allowing reuse after KeepAlive navigation. */\n  public cancel(): void {\n    ++this.#revision;\n    this.#cancelShow?.();\n    this.#cancelHide?.();\n    this.#cancelShow = undefined;\n    this.#cancelHide = undefined;\n    for (const operation of this.#operations) operation.abort();\n    this.#operations.clear();\n    this.#visible = false;\n    this.#publish();\n  }\n\n  public dispose(): void {\n    this.#disposed = true;\n    this.cancel();\n  }\n\n  #finishPresentation(): void {\n    this.#cancelShow?.();\n    this.#cancelShow = undefined;\n    const remaining = this.#minimumMs - (this.#clock.now() - this.#visibleSince);\n    if (!this.#visible || remaining <= 0) {\n      this.#visible = false;\n      return;\n    }\n    this.#cancelHide = this.#clock.schedule({ delayMs: remaining, callback: () => {\n      this.#cancelHide = undefined;\n      this.#visible = false;\n      this.#publish();\n    } });\n  }\n\n  #publish(): void {\n    this.#onChange(this.state);\n  }\n}\n","export type FieldErrors<Field extends string = string> = Partial<Record<Field, string>>;\n\n/** Translate domain/API failures to this safe presentation contract before returning from save. */\nexport class FormSubmissionError<Field extends string = string> extends Error {\n  public readonly fieldErrors: FieldErrors<Field>;\n\n  public constructor(options: { message?: string; fieldErrors?: FieldErrors<Field> }) {\n    super(options.message ?? \"\");\n    this.name = \"FormSubmissionError\";\n    this.fieldErrors = options.fieldErrors ?? {};\n  }\n}\n","// Loading and create/edit dialog state for Lit screens: the Vue-free counterparts of useLoading and useCrudDialog\n// (webdesigns/companyos/frontend/composables), with the same rules. Only a type import from lit, so the pure tests in\n// tests/frontend/test_screen_controllers.ts run without a DOM.\nimport type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { LoadingController, type LoadingOptions, type LoadingState } from \"../../../companyos/frontend/lib/loading\";\nimport { FormSubmissionError, type FieldErrors } from \"../../../companyos/frontend/lib/form-validation\";\n\n/** The host a controller attaches to: a Lit element, or any object with the same three members. */\nexport type ScreenControllerHost = ReactiveControllerHost & Partial<Pick<Element, \"querySelector\">>;\n\n/** One loading lifecycle (200ms delay, 500ms minimum by default); a host that leaves the page cancels it. */\nexport class LoadingStateController implements ReactiveController {\n  #state: LoadingState = { pending: false, visible: false };\n  readonly #controller: LoadingController;\n\n  public constructor(host: ScreenControllerHost, options: Omit<LoadingOptions, \"onChange\"> = {}) {\n    this.#controller = new LoadingController({ ...options, onChange: state => { this.#state = state; host.requestUpdate(); } });\n    host.addController(this);\n  }\n\n  public get pending(): boolean {\n    return this.#state.pending;\n  }\n\n  public get visible(): boolean {\n    return this.#state.visible;\n  }\n\n  public run<T>(operation: (context: { signal: AbortSignal }) => Promise<T>): Promise<T> {\n    return this.#controller.run(operation);\n  }\n\n  public cancel(): void {\n    this.#controller.cancel();\n  }\n\n  public hostDisconnected(): void {\n    this.#controller.cancel();\n  }\n}\n\nexport type CrudDialogMode = \"create\" | \"edit\";\n\nexport interface CrudDialogControllerOptions<Draft extends object> {\n  create: () => Draft;\n  validate: (draft: Draft) => FieldErrors<Extract<keyof Draft, string>>;\n  save: (context: { draft: Draft; mode: CrudDialogMode; signal: AbortSignal }) => Promise<unknown>;\n  /** Default: focus the element with that `name` inside the host, after the host rendered the messages. */\n  focusField?: (field: Extract<keyof Draft, string>) => void;\n  clone?: (draft: Draft) => Draft;\n}\n\nconst SAVE_FAILED = \"Opslaan is niet gelukt. Probeer het opnieuw.\";\n\n/**\n * Draft, validation and submit state for one create/edit dialog, as useCrudDialog: save gets a detached draft, close\n * refuses pending work and a dirty draft unless discard is explicit, a late response after cancel or disconnect is\n * ignored. Dirty compares JSON snapshots, so keep drafts plain JSON. Change the draft with `update`, which also clears\n * the message of each changed field.\n */\nexport class CrudDialogController<Draft extends object> implements ReactiveController {\n  readonly #host: ScreenControllerHost;\n  readonly #options: CrudDialogControllerOptions<Draft>;\n  #draft: Draft;\n  #baseline: string;\n  #open = false;\n  #mode: CrudDialogMode = \"create\";\n  #pending = false;\n  #errors: FieldErrors<Extract<keyof Draft, string>> = {};\n  #formError = \"\";\n  #abort: AbortController | undefined;\n  #revision = 0;\n  #focusRevision = 0;\n\n  public constructor(host: ScreenControllerHost, options: CrudDialogControllerOptions<Draft>) {\n    this.#host = host;\n    this.#options = options;\n    this.#draft = this.#clone(options.create());\n    this.#baseline = JSON.stringify(this.#draft);\n    host.addController(this);\n  }\n\n  public get draft(): Draft {\n    return this.#draft;\n  }\n\n  public get open(): boolean {\n    return this.#open;\n  }\n\n  public get mode(): CrudDialogMode {\n    return this.#mode;\n  }\n\n  public get pending(): boolean {\n    return this.#pending;\n  }\n\n  public get dirty(): boolean {\n    return JSON.stringify(this.#draft) !== this.#baseline;\n  }\n\n  public get errors(): FieldErrors<Extract<keyof Draft, string>> {\n    return this.#errors;\n  }\n\n  public get formError(): string {\n    return this.#formError;\n  }\n\n  public update(patch: Partial<Draft>): void {\n    this.#draft = { ...this.#draft, ...patch };\n    const errors = { ...this.#errors };\n    for (const field of Object.keys(patch))\n      delete errors[field as Extract<keyof Draft, string>];\n    this.#errors = errors;\n    this.#host.requestUpdate();\n  }\n\n  public openCreate(): void {\n    if (this.#pending)\n      return;\n    this.#reset();\n    this.#mode = \"create\";\n    this.#open = true;\n    this.#host.requestUpdate();\n  }\n\n  public openEdit(value: Draft): void {\n    if (this.#pending)\n      return;\n    this.#reset(value);\n    this.#mode = \"edit\";\n    this.#open = true;\n    this.#host.requestUpdate();\n  }\n\n  public close(options: { discard?: boolean } = {}): boolean {\n    if (this.#pending || (this.dirty && !options.discard))\n      return false;\n    this.#open = false;\n    this.#reset();\n    this.#host.requestUpdate();\n    return true;\n  }\n\n  public async submit(): Promise<boolean> {\n    if (!this.#open || this.#pending || !this.#validate())\n      return false;\n    const revision = ++this.#revision;\n    this.#abort = new AbortController();\n    this.#pending = true;\n    this.#host.requestUpdate();\n    try {\n      await this.#options.save({ draft: this.#clone(this.#draft), mode: this.#mode, signal: this.#abort.signal });\n      if (revision !== this.#revision)\n        return false;\n      this.#open = false;\n      this.#reset();\n      return true;\n    } catch (cause) {\n      if (revision === this.#revision)\n        this.#applyError(cause);\n      return false;\n    } finally {\n      if (revision === this.#revision) {\n        this.#pending = false;\n        this.#abort = undefined;\n      }\n      this.#host.requestUpdate();\n    }\n  }\n\n  public cancel(): void {\n    ++this.#revision;\n    this.#abort?.abort();\n    this.#abort = undefined;\n    this.#pending = false;\n    this.#open = false;\n    this.#reset();\n    this.#host.requestUpdate();\n  }\n\n  public hostDisconnected(): void {\n    this.cancel();\n  }\n\n  #clone(value: Draft): Draft {\n    return this.#options.clone ? this.#options.clone(value) : structuredClone(value);\n  }\n\n  #reset(value: Draft = this.#options.create()): void {\n    this.#draft = this.#clone(value);\n    this.#baseline = JSON.stringify(this.#draft);\n    this.#errors = {};\n    this.#formError = \"\";\n    ++this.#focusRevision;\n  }\n\n  #validate(): boolean {\n    this.#formError = \"\";\n    this.#setErrors(this.#options.validate(this.#draft));\n    this.#host.requestUpdate();\n    return Object.keys(this.#errors).length === 0;\n  }\n\n  #setErrors(next: FieldErrors<Extract<keyof Draft, string>>): void {\n    this.#errors = Object.fromEntries(Object.entries(next).filter(([, value]) => Boolean(value))) as FieldErrors<Extract<keyof Draft, string>>;\n    const first = Object.keys(this.#errors)[0] as Extract<keyof Draft, string> | undefined;\n    const revision = ++this.#focusRevision;\n    if (first) // The field only carries its message (and may only be enabled) after the host rendered\n      void this.#host.updateComplete.then(() => {\n        if (revision === this.#focusRevision && this.#errors[first])\n          (this.#options.focusField ?? (field => this.#host.querySelector?.<HTMLElement>(`[name=\"${CSS.escape(field)}\"]`)?.focus()))(first);\n      });\n  }\n\n  #applyError(cause: unknown): void {\n    // Unexpected technical errors are deliberately not copied to an end-user form.\n    if (cause instanceof FormSubmissionError) {\n      this.#setErrors(cause.fieldErrors as FieldErrors<Extract<keyof Draft, string>>);\n      this.#formError = cause.message || (Object.keys(this.#errors).length ? \"\" : SAVE_FAILED);\n    } else\n      this.#formError = SAVE_FAILED;\n  }\n}\n","/** Panel layout of a tab: content reserves space above and below, a list meets the tab baseline directly. */\ntype TabLayout = \"content\" | \"list\";\n\n/** One section of the IP access screen, rendered as a screen Tab. */\nexport interface IPAccessSection { value: string; title: string; disabled: boolean; layout: TabLayout }\n\nexport type IPLoadingKind = \"initial\" | \"refresh\" | \"person\";\nexport type IPSkeletonKind = \"workspace\" | \"person\";\n\n/** Keep the operation kind independent of payload availability and the minimum display interval. */\nexport function getIPSkeletonKind(options: { kind: IPLoadingKind; visible: boolean }): IPSkeletonKind | null {\n  if (!options.visible || options.kind === \"refresh\") return null;\n  return options.kind === \"initial\" ? \"workspace\" : \"person\";\n}\n\n/** What is in flight on the IP access screen. */\nexport interface IPActivity { loading: boolean; loadingPerson: boolean; saving: boolean; skeletonKind: IPSkeletonKind | null; confirming: boolean }\n\n/** Refresh and \"Nieuwe naam\" conflict with writes, confirmations and workspace loads, not with reading one person. */\nexport function getIPHeaderDisabled(activity: IPActivity): boolean {\n  return activity.loading || activity.skeletonKind === \"workspace\" || activity.saving || activity.confirming;\n}\n\n/** A reload reads back the person still being fetched, so a refresh during a row selection does not undo it. */\nexport function getIPReloadPersonId(options: { explicitId?: number; pendingId: number | null; selectedId: number; firstId: number }): number {\n  return options.explicitId ?? (options.pendingId || options.selectedId || options.firstId);\n}\n\n/** Keep the current panel mounted while initial loading prevents switching to empty panels. */\nexport function getIPAccessTabs(options: { activeKey: string; initialLoading: boolean; disabled: boolean }): readonly IPAccessSection[] {\n  // Spreadsheet imports link every IP to a name, so daily management needs no assignment panel.\n  return [{ value: \"people\", title: \"Namen\" }, { value: \"history\", title: \"Historie\" }].map(section => ({\n    ...section,\n    layout: section.value === \"people\" ? \"list\" : \"content\",\n    disabled: options.disabled || (options.initialLoading && section.value !== options.activeKey),\n  }));\n}\n","interface LockableIP { locked?: boolean; allowedTargetIds: readonly number[] }\n\n/** Derives editor restrictions without changing the saved access list. Missing lock metadata is an older response. */\nexport function getIPLockState(options: { ip: LockableIP | null; draftLocked?: boolean }): { locked: boolean; maskReadonly: boolean; protectedTargetIds: number[] } {\n  // A draft unlock releases form restrictions; only the confirmed atomic save may change protection.\n  // Checking a new lock must still allow editing the fields and grants that will be saved with it.\n  const locked = options.ip?.locked === true && options.draftLocked !== false;\n  return {\n    locked,\n    // Saving a new address moves its grants, so only protection freezes the address.\n    maskReadonly: locked,\n    protectedTargetIds: locked ? [...options.ip?.allowedTargetIds ?? []] : [],\n  };\n}\n\n/** Menu actions collect a lock reason or confirm unlocking before any RPC can run. */\nexport function getIPLockChangeIntent(options: { ip: { locked?: boolean }; locked: boolean; confirmed?: boolean }): \"none\" | \"collect-lock-reason\" | \"confirm-unlock\" | \"save\" {\n  if ((options.ip.locked === true) === options.locked) return \"none\";\n  if (options.locked && !options.confirmed) return \"collect-lock-reason\";\n  if (!options.locked && !options.confirmed) return \"confirm-unlock\";\n  return \"save\";\n}\n\nexport interface IPLockDraft { reason: string }\nexport type IPLockErrors = Partial<Record<keyof IPLockDraft, string>>;\n\nexport function validateIPLockDraft(draft: IPLockDraft): IPLockErrors {\n  return draft.reason.trim().length > 10000 ? { reason: \"Gebruik maximaal 10000 tekens voor de reden.\" } : {};\n}\n\n/** Bulk revocation is atomic, so one protected grant blocks revoking this person's entire access. */\nexport function hasProtectedAccess(options: { ips: readonly LockableIP[] }): boolean {\n  return options.ips.some(ip => ip.locked === true && ip.allowedTargetIds.length > 0);\n}\n","import type { IPPersonDetail, SavePersonOptions } from \"../../../../../js/ip-access\";\n\nexport type IPPersonDraft = SavePersonOptions;\nexport type IPPersonField = \"name\" | \"note\";\nexport type IPPersonErrors = Partial<Record<IPPersonField, string>>;\n\n/** Copy form values and legacy metadata so a dialog never mutates the selected person's detail data. */\nexport function createIPPersonDraft(options: { person?: IPPersonDetail | null } = {}): IPPersonDraft {\n  const person = options.person;\n  return {\n    ...(person ? { id: person.id } : {}),\n    name: person?.name ?? \"\",\n    // Preserve legacy organization metadata even though it is no longer editable in this app.\n    organization: person?.organization ?? \"\",\n    note: person?.note ?? \"\",\n  };\n}\n\n/** Validate every field together before submitting to the existing server-side validator. */\nexport function validateIPPersonDraft(draft: IPPersonDraft): IPPersonErrors {\n  const errors: IPPersonErrors = {};\n  if (!draft.name.trim()) errors.name = \"Vul een naam in.\";\n  else if (draft.name.length > 200) errors.name = \"Gebruik maximaal 200 tekens voor de naam.\";\n  if (draft.note.length > 10000) errors.note = \"Gebruik maximaal 10.000 tekens voor de notitie.\";\n  return errors;\n}\n","import type { IPPersonSummary } from \"../../../../../js/ip-access\";\n\n/** What the own-IP confirmation dialog shows. Lives here so the dialog templates can import it without the controller. */\nexport interface OwnIPConfirmation {\n  title: string;\n  confirmLabel: string;\n  description: string;\n  currentIp: string | null;\n  masks: string[];\n}\n\ninterface ParsedAddress {\n  bits: 32 | 128;\n  value: bigint;\n}\n\nfunction parseAddress(input: string): ParsedAddress | null {\n  if (!input.includes(\":\")) {\n    const octets = input.split(\".\");\n    if (octets.length !== 4 || octets.some((part) => !/^\\d{1,3}$/.test(part) || Number(part) > 255))\n      return null;\n    return { bits: 32, value: octets.reduce((value, octet) => (value << 8n) | BigInt(octet), 0n) };\n  }\n\n  let address = input.toLowerCase();\n  if (address.includes(\".\")) {\n    const separator = address.lastIndexOf(\":\");\n    const ipv4 = parseAddress(address.slice(separator + 1));\n    if (!ipv4 || ipv4.bits !== 32)\n      return null;\n    address = `${address.slice(0, separator + 1)}${(ipv4.value >> 16n).toString(16)}:${(ipv4.value & 0xffffn).toString(16)}`;\n  }\n  const halves = address.split(\"::\");\n  if (halves.length > 2)\n    return null;\n  const left = halves[0] ? halves[0].split(\":\") : [];\n  const right = halves.length === 2 && halves[1] ? halves[1].split(\":\") : [];\n  if ([...left, ...right].some((part) => !/^[0-9a-f]{1,4}$/.test(part)))\n    return null;\n  const missing = 8 - left.length - right.length;\n  if (halves.length === 1 ? missing !== 0 : missing < 1)\n    return null;\n  const groups = [...left, ...Array<string>(missing).fill(\"0\"), ...right];\n  return { bits: 128, value: BigInt(`0x${groups.map((group) => group.padStart(4, \"0\")).join(\"\")}`) };\n}\n\nfunction mappedIPv4(address: ParsedAddress): ParsedAddress {\n  return address.bits === 128 && address.value >> 32n === 0xffffn\n    ? { bits: 32, value: address.value & 0xffffffffn }\n    : address;\n}\n\nfunction parseMask(input: string): { network: ParsedAddress; prefix: number } | null {\n  const parts = input.trim().split(\"/\");\n  if (parts.length > 2 || (parts[1] !== undefined && !/^\\d+$/.test(parts[1])))\n    return null;\n  let address = parts[0].replace(/^ipv4:/, \"\");\n  let legacyPrefix: number | undefined;\n  // WebHare still accepts trailing IPv4 wildcards. Keep validation consistent with the native editor.\n  if (parts.length === 1 && address.includes(\"*\")) {\n    const octets = address.split(\".\");\n    const firstWildcard = octets.indexOf(\"*\");\n    if (octets.length !== 4 || firstWildcard < 0 || octets.slice(firstWildcard).some((octet) => octet !== \"*\"))\n      return null;\n    legacyPrefix = firstWildcard * 8;\n    address = octets.map((octet) => octet === \"*\" ? \"0\" : octet).join(\".\");\n  }\n  const network = parseAddress(address);\n  if (!network)\n    return null;\n  const prefix = parts[1] === undefined ? legacyPrefix ?? network.bits : Number(parts[1]);\n  return prefix <= network.bits ? { network, prefix } : null;\n}\n\n/** Validates input on submit without rewriting it. The server remains responsible for canonicalization. */\nexport function validateIPMask(mask: string): string | null {\n  if (!mask.trim())\n    return \"Vul een IP-adres of netwerk in.\";\n  return parseMask(mask) ? null : \"Vul een geldig IPv4- of IPv6-adres in, eventueel met een netwerkprefix. Bijvoorbeeld 192.0.2.10 of 2001:db8::/48.\";\n}\n\n/** Client-side preflight only. The server independently checks every own-IP removal before writing. */\nexport function ipMaskMatches(options: { mask: string; address: string | null }): boolean {\n  if (!options.address)\n    return false;\n  const parsed = parseMask(options.mask);\n  let address = parseAddress(options.address.trim());\n  if (!parsed || !address)\n    return false;\n  let { network, prefix } = parsed;\n  // Webservers can report an IPv4 connection as an IPv4-mapped IPv6 address.\n  if (network.bits === 32) {\n    address = mappedIPv4(address);\n  } else if (mappedIPv4(network).bits === 32 && prefix >= 96) {\n    network = mappedIPv4(network);\n    address = mappedIPv4(address);\n    prefix -= 96;\n  }\n  if (network.bits !== address.bits)\n    return false;\n  const shift = BigInt(network.bits - prefix);\n  return network.value >> shift === address.value >> shift;\n}\n\nexport function isNetworkMask(mask: string): boolean {\n  const parsed = parseMask(mask);\n  return parsed !== null && parsed.prefix < parsed.network.bits;\n}\n\n/** All terms may match the person's name or note. */\nexport function filterPeople(options: { people: readonly IPPersonSummary[]; query: string }): IPPersonSummary[] {\n  const terms = options.query.trim().toLocaleLowerCase(\"nl-NL\").split(/\\s+/).filter(Boolean);\n  return options.people.filter((person) => {\n    const searchable = `${person.name} ${person.note}`.toLocaleLowerCase(\"nl-NL\");\n    return terms.every((term) => searchable.includes(term));\n  });\n}\n\nexport function historyInPeriod<T extends { timestamp: string }>(options: { entries: readonly T[]; days: number | null; now: Date }): T[] {\n  if (options.days === null)\n    return [...options.entries];\n  const since = options.now.getTime() - options.days * 24 * 60 * 60 * 1000;\n  return options.entries.filter((entry) => {\n    const timestamp = Date.parse(entry.timestamp);\n    return Number.isFinite(timestamp) && timestamp >= since && timestamp <= options.now.getTime();\n  });\n}\n\nconst historyLabels: Record<string, string> = {\n  \"person-created\": \"Naam toegevoegd\", \"person-updated\": \"Naam bijgewerkt\", \"person-imported\": \"Naam geïmporteerd\",\n  \"person-merged\": \"Namen samengevoegd\",\n  \"ip-created\": \"IP-adres toegevoegd\", \"ip-updated\": \"IP-adres bijgewerkt\", \"ip-deleted\": \"IP-adres verwijderd\", \"ip-imported\": \"IP-adres geïmporteerd\",\n  \"ip-moved\": \"IP-adres verplaatst\",\n  \"ip-locked\": \"IP-adres vergrendeld\", \"ip-unlocked\": \"IP-adres ontgrendeld\",\n  \"ip-lock-updated\": \"Reden voor vergrendeling bijgewerkt\",\n  \"access-granted\": \"Toegang toegestaan\", \"access-revoked\": \"Toegang ingetrokken\", \"person-revoked\": \"Alle toegang ingetrokken\",\n  \"target-created\": \"Doel toegevoegd\", \"target-updated\": \"Doel bijgewerkt\",\n};\n\n/** Metadata imports do not change native access, so unknown actions also use a neutral label. */\nexport function historyActionLabel(action: string): string {\n  return historyLabels[action] ?? \"Wijziging geregistreerd\";\n}\n\n/** Unlock history retains why the address was protected; older audit entries may omit the reason. */\nexport function historyLockReason(entry: { action: string; details: Record<string, unknown> }): string {\n  const reason = entry.action === \"ip-unlocked\" ? entry.details.previousReason ?? entry.details.reason : entry.details.reason;\n  return typeof reason === \"string\" ? reason : \"\";\n}\n\nfunction mergePerson(value: unknown): { id: number; name: string } | null {\n  if (!value || typeof value !== \"object\" || !(\"id\" in value) || typeof value.id !== \"number\" || !Number.isSafeInteger(value.id) || value.id <= 0)\n    return null;\n  return { id: value.id, name: \"name\" in value && typeof value.name === \"string\" ? value.name : `Naam #${value.id}` };\n}\n\n/** Retains the source's historical access events under the survivor, including successive merges. */\nexport function historyForPerson<T extends { action: string; personId: number | null; details: Record<string, unknown> }>(options: { entries: readonly T[]; personId: number }): T[] {\n  if (!options.personId)\n    return [...options.entries];\n  const personIds = new Set([options.personId]);\n  // Resolve the complete audit before filtering by date; an old merge still links recent source history.\n  let addedSource: boolean;\n  do {\n    addedSource = false;\n    for (const entry of options.entries) {\n      const target = entry.action === \"person-merged\" ? mergePerson(entry.details.target) : null;\n      if (!target || !personIds.has(target.id) || !Array.isArray(entry.details.sources))\n        continue;\n      for (const value of entry.details.sources) {\n        const source = mergePerson(value);\n        if (source && !personIds.has(source.id)) {\n          personIds.add(source.id);\n          addedSource = true;\n        }\n      }\n    }\n  } while (addedSource);\n  return options.entries.filter((entry) => entry.personId !== null && personIds.has(entry.personId));\n}\n\n/** Uses names stored at move time, since either record may have been renamed or merged since. */\nexport function historyMoveSummary(entry: { action: string; details: Record<string, unknown> }): string {\n  const from = entry.action === \"ip-moved\" ? mergePerson(entry.details.from) : null;\n  const to = entry.action === \"ip-moved\" ? mergePerson(entry.details.to) : null;\n  if (!from || !to)\n    return \"\";\n  return [typeof entry.details.mask === \"string\" ? entry.details.mask : \"\", `${from.name} → ${to.name}`].filter(Boolean).join(\" · \");\n}\n\n/** Uses names stored at merge time, since source records may have been closed or renamed. */\nexport function historyMergeSummary(entry: { action: string; details: Record<string, unknown> }): string {\n  if (entry.action !== \"person-merged\" || !Array.isArray(entry.details.sources))\n    return \"\";\n  const target = mergePerson(entry.details.target);\n  const sources = entry.details.sources.map(mergePerson).filter((source) => source !== null);\n  if (!target || !sources.length)\n    return \"\";\n  const names = `${sources.map((source) => source.name).join(\", \")} → ${target.name}`;\n  if (!Array.isArray(entry.details.ips))\n    return names;\n  const count = entry.details.ips.length;\n  return `${names} · ${count} ${count === 1 ? \"IP-adres\" : \"IP-adressen\"}`;\n}\n","import type { IPPersonSummary } from \"../../../../../js/ip-access\";\nimport { filterPeople } from \"./ip-access-model\";\n\nexport type IPPeopleSortKey = \"name\" | \"ipCount\" | \"note\";\nexport type IPSortDirection = \"asc\" | \"desc\";\n\n/** Derive the displayed order without changing the workspace shared with the other tabs. */\nexport function getVisiblePeople(options: { people: readonly IPPersonSummary[]; query: string; key: IPPeopleSortKey; direction: IPSortDirection }): IPPersonSummary[] {\n  const collator = new Intl.Collator(\"nl-NL\", { numeric: true, sensitivity: \"base\" });\n  return filterPeople(options).toSorted((left, right) => {\n    const comparison = options.key === \"ipCount\" ? left.ipCount - right.ipCount : collator.compare(left[options.key], right[options.key]);\n    return (options.direction === \"asc\" ? comparison : -comparison) || collator.compare(left.name, right.name) || left.id - right.id;\n  });\n}\n\n/** Navigation follows the filtered, sorted list and stops at either boundary. Zero means no rows. */\nexport function getAdjacentPersonId(options: { ids: readonly number[]; currentId: number; offset: -1 | 1 }): number {\n  const index = options.ids.indexOf(options.currentId);\n  return options.ids[index < 0 ? 0 : Math.max(0, Math.min(options.ids.length - 1, index + options.offset))] ?? 0;\n}\n\n","import type { IPPersonIP } from \"../../../../../js/ip-access\";\nimport { validateIPMask } from \"./ip-access-model\";\n\nexport interface MaskDraft { mask: string; label: string; allowedTargetIds: number[]; locked: boolean; lockReason: string }\n// Structurally the same as FieldErrors in boot; declared here so the gated screen files do not pull the legacy entry into the typecheck.\ntype FieldErrors<Field extends string = string> = Partial<Record<Field, string>>;\nexport type MaskErrors = FieldErrors<keyof MaskDraft>;\n\n/** Copies grants into local form state so canceling edits cannot change the rendered detail. */\nexport function getMaskDraft(options: { ip: (Pick<IPPersonIP, \"mask\" | \"label\" | \"allowedTargetIds\"> & { locked?: boolean; lockReason?: string }) | null }): MaskDraft {\n  return {\n    mask: options.ip?.mask ?? \"\", label: options.ip?.label ?? \"\", allowedTargetIds: [...options.ip?.allowedTargetIds ?? []],\n    locked: options.ip?.locked === true, lockReason: options.ip?.lockReason ?? \"\",\n  };\n}\nexport function validateMaskDraft(draft: MaskDraft): FieldErrors<keyof MaskDraft> {\n  const errors: FieldErrors<keyof MaskDraft> = {};\n  const maskError = validateIPMask(draft.mask);\n  if (maskError) errors.mask = maskError;\n  if (draft.label.trim().length > 10000) errors.label = \"Gebruik maximaal 10000 tekens voor de omschrijving.\";\n  if (draft.locked && draft.lockReason.trim().length > 10000) errors.lockReason = \"Gebruik maximaal 10000 tekens voor de reden.\";\n  return errors;\n}\n\n/** The existing RPC returns text errors. Only recognized domain messages may reach a field. */\nexport function describeSaveError(cause: unknown): { message?: string; fieldErrors?: FieldErrors } {\n  const message = cause instanceof Error ? cause.message.replace(/^RPC Error: /, \"\") : \"\";\n  if (/^Ongeldig IP-adres of bereik \"/.test(message) || /^IP-adres \".*\" hoort al bij persoon /.test(message) || message === \"Schakel de toegang eerst uit voordat je het IP-adres wijzigt.\")\n    return { fieldErrors: { mask: message } };\n  if (/^Toegangsregel #\\d+ (hoort al bij een doel|bestaat niet meer)\\.$/.test(message) || message === \"De toegangsregel van een bestaand doel kan niet worden verplaatst. Voeg een nieuw doel toe.\")\n    return { fieldErrors: { accessRuleId: message } };\n  const textFields = { naam: \"name\", doelnaam: \"name\", organisatie: \"organization\", notitie: \"note\", omschrijving: \"label\", label: \"label\", \"reden voor vergrendeling\": \"lockReason\" } as const;\n  for (const [label, field] of Object.entries(textFields))\n    if (message === `Ongeldige ${label}.`)\n      return { fieldErrors: { [field]: field === \"name\" ? \"Vul een naam in van maximaal 200 tekens.\" : `Gebruik maximaal ${field === \"note\" || field === \"lockReason\" || label === \"omschrijving\" ? 10000 : 200} tekens.` } };\n  if (message === \"IP-beheer is bezig. Probeer het opnieuw.\" || /^IP-adres \".*\" is vergrendeld\\. Ontgrendel het eerst om het te verwijderen, het adres te wijzigen of toegang in te trekken\\.$/.test(message)) return { message };\n  return { message: \"Opslaan is niet gelukt. Probeer het opnieuw.\" };\n}\n","// Server state of the IP access screen for Lit: a port of the former Vue composable useIPAccess.ts, with the same\n// rules. IP grants always come from the server; every write reloads workspace, detail and audit data.\nimport { FormSubmissionError, LoadingStateController, showToast, type ReactiveController, type ReactiveControllerHost } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport { rpc as createRpcClient, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport type { RPC } from \"../../../../js/rpc\";\nimport type { IPAuditEntry, IPMutationResult, IPPersonDetail, IPPersonIP, IPSaveResult, IPWorkspace, SavePersonOptions, SavePersonIPWithLockOptions } from \"../../../../js/ip-access\";\nimport { ipMaskMatches, type OwnIPConfirmation } from \"../components/ip-access/ip-access-model\";\nimport { getIPLockChangeIntent, hasProtectedAccess, type IPLockDraft } from \"../components/ip-access/ip-lock-model\";\nimport { describeSaveError } from \"../components/ip-access/ip-mask-model\";\nimport { getIPHeaderDisabled, getIPReloadPersonId, getIPSkeletonKind, type IPLoadingKind, type IPSkeletonKind } from \"../components/ip-access/ip-loading-model\";\n\nconst rpc = createRpcClient<OmitRPCContextArgs<typeof RPC>>(\"looping_os:ipaccess\");\n// CompanyOS authentication is still tied to this schema; IP ownership has its own server-side schema.\nconst schema = \"companyos:companyos\";\n\ninterface PendingRemoval {\n  title: string;\n  confirmLabel: string;\n  description: string;\n  masks: string[];\n  message: string;\n  personId: number;\n  operation: (confirmed: boolean) => Promise<IPMutationResult>;\n  alwaysConfirm?: boolean;\n}\n\ntype StateField = \"workspace\" | \"person\" | \"selectedPersonId\" | \"history\" | \"loading\" | \"loadingPerson\" | \"saving\" | \"error\" | \"confirmation\" | \"confirmationError\" | \"unlockConfirmation\" | \"lockRequest\";\n\nexport class IPAccessController implements ReactiveController {\n  public workspace: IPWorkspace | null = null;\n  public person: IPPersonDetail | null = null;\n  public selectedPersonId = 0;\n  public history: IPAuditEntry[] = [];\n  public loading = false;\n  public loadingPerson = false;\n  public saving = false;\n  public error = \"\";\n  /** The own-IP (or always-confirmed) removal waiting for an explicit decision. */\n  public confirmation: OwnIPConfirmation | null = null;\n  public confirmationError = \"\";\n  public unlockConfirmation: IPPersonIP | null = null;\n  public lockRequest: IPPersonIP | null = null;\n  readonly #host: ReactiveControllerHost;\n  // One lifecycle covers initial loading and person selection; nested RPCs do not create more skeleton timers.\n  readonly #lifecycle: LoadingStateController;\n  // Retain the kind after RPC completion so arriving data does not cut a visible skeleton short.\n  #loadingKind: IPLoadingKind = \"initial\";\n  #pendingRemoval: PendingRemoval | null = null;\n  #detailRequest = 0;\n  #pendingPersonId: number | null = null;\n  #disposed = false;\n\n  public constructor(host: ReactiveControllerHost) {\n    this.#host = host;\n    this.#lifecycle = new LoadingStateController(host, { delayMs: 200, minimumMs: 500 });\n    host.addController(this);\n  }\n\n  public get skeletonKind(): IPSkeletonKind | null {\n    return getIPSkeletonKind({ kind: this.#loadingKind, visible: this.#lifecycle.visible });\n  }\n\n  /** An open confirmation or lock dialog blocks every other action until it is decided. */\n  public get confirming(): boolean {\n    return this.confirmation !== null || this.unlockConfirmation !== null || this.lockRequest !== null;\n  }\n\n  /** The header actions and load() share one gate, so an enabled refresh never ignores its click. */\n  public get headerDisabled(): boolean {\n    return getIPHeaderDisabled({ loading: this.loading, loadingPerson: this.loadingPerson, saving: this.saving, skeletonKind: this.skeletonKind, confirming: this.confirming });\n  }\n\n  public hostConnected(): void {\n    this.#disposed = false;\n  }\n\n  public hostDisconnected(): void {\n    this.#disposed = true;\n    ++this.#detailRequest;\n  }\n\n  public async load(): Promise<void> {\n    if (this.headerDisabled)\n      return;\n    this.#loadingKind = this.workspace ? \"refresh\" : \"initial\";\n    this.#set({ loading: true, error: \"\" });\n    try {\n      // A refresh keeps existing content and only the trigger indicates pending work.\n      if (this.#loadingKind === \"refresh\") await this.#reload();\n      else await this.#lifecycle.run(() => this.#reload());\n    } catch (cause) {\n      if (!this.#disposed)\n        this.#report(cause);\n    } finally {\n      if (!this.#disposed)\n        this.#set({ loading: false });\n    }\n  }\n\n  public async selectPerson(id: number): Promise<void> {\n    if (this.saving || this.confirming || this.loading || this.#lifecycle.pending || this.skeletonKind)\n      return;\n    this.#loadingKind = \"person\";\n    this.#set({ error: \"\" });\n    try {\n      // Preserve the old detail while its replacement loads; no empty pane flashes on selection.\n      await this.#lifecycle.run(() => this.#loadDetail(id));\n    } catch (cause) {\n      if (!this.#disposed)\n        this.#report(cause);\n    }\n  }\n\n  public async savePerson(options: SavePersonOptions): Promise<void> {\n    await this.write({ operation: () => rpc.savePerson({ schema, ...options }), message: `Gegevens van \"${options.name}\" opgeslagen.`, personIdForResult: id => id, form: true });\n  }\n\n  /** Runs one write and reads everything back. With `form`, failures become a FormSubmissionError for the dialog. */\n  public async write<T>(options: { operation: () => Promise<T>; message: string; personIdForResult?: (result: T) => number; form?: boolean; unlockConfirmed?: boolean; lockConfirmed?: boolean }): Promise<boolean> {\n    if (this.saving || this.confirmation || (this.unlockConfirmation && !options.unlockConfirmed) || (this.lockRequest && !options.lockConfirmed)) {\n      if (options.form) throw new FormSubmissionError({ message: \"Een andere wijziging wordt nog verwerkt. Probeer het opnieuw.\" });\n      return false;\n    }\n    this.#set({ saving: true, error: \"\" });\n    try {\n      const result = await options.operation();\n      await this.#readBack(options.personIdForResult?.(result) ?? this.selectedPersonId);\n      if (!this.#disposed)\n        showToast({ message: options.message, tone: \"success\" });\n      return true;\n    } catch (cause) {\n      if (options.form) throw new FormSubmissionError(describeSaveError(cause));\n      if (!this.#disposed) {\n        console.dir(cause, { depth: null, colors: true });\n        this.#set({ error: describeSaveError(cause).message ?? \"De wijziging is niet gelukt. Probeer het opnieuw.\" });\n      }\n      return false;\n    } finally {\n      if (!this.#disposed)\n        this.#set({ saving: false });\n    }\n  }\n\n  public async saveIP(options: SavePersonIPWithLockOptions): Promise<IPSaveResult> {\n    if (this.saving || this.confirming)\n      throw new FormSubmissionError({ message: \"Een andere wijziging wordt nog verwerkt. Probeer het opnieuw.\" });\n    this.#set({ saving: true, error: \"\" });\n    try {\n      const result = await rpc.savePersonIpWithLock({ schema, ...options });\n      // A refused own-IP save keeps the editor's draft and requires an explicit second submission.\n      if (result.status === \"confirmation-required\") return result;\n      await this.#readBack(options.personId);\n      if (!this.#disposed) showToast({ message: \"IP-adres opgeslagen.\", tone: \"success\" });\n      return result;\n    } catch (cause) {\n      throw new FormSubmissionError(describeSaveError(cause));\n    } finally {\n      if (!this.#disposed) this.#set({ saving: false });\n    }\n  }\n\n  /** Ownership only: the server keeps the address, protection and access unchanged. */\n  public async moveIP(options: { ip: IPPersonIP; personId: number }): Promise<void> {\n    const name = this.workspace?.people.find(row => row.id === options.personId)?.name ?? `Naam #${options.personId}`;\n    await this.write({ operation: () => rpc.moveIp({ schema, ipId: options.ip.id, personId: options.personId }), message: `IP-adres \"${options.ip.mask}\" verplaatst naar \"${name}\".`, form: true });\n  }\n\n  public setIPLock(options: { ip: IPPersonIP; locked: boolean }): void {\n    if (this.saving || this.confirming) return;\n    const intent = getIPLockChangeIntent(options);\n    if (intent === \"confirm-unlock\")\n      this.#set({ error: \"\", unlockConfirmation: options.ip });\n    else if (intent === \"collect-lock-reason\")\n      this.#set({ error: \"\", lockRequest: options.ip });\n  }\n\n  public async confirmLock(draft: IPLockDraft): Promise<void> {\n    const ip = this.lockRequest;\n    if (!ip) throw new FormSubmissionError({ message: \"Open de vergrendeldialoog opnieuw.\" });\n    // Only submitting this dialog writes protection; failures keep its optional reason available.\n    await this.write({\n      operation: () => rpc.setIpLock({ schema, ipId: ip.id, locked: true, reason: draft.reason }),\n      message: `IP-adres \"${ip.mask}\" vergrendeld.`, form: true, lockConfirmed: true,\n    });\n  }\n\n  public cancelLock(): void {\n    if (!this.saving) this.#set({ lockRequest: null });\n  }\n\n  public async confirmUnlock(): Promise<void> {\n    const ip = this.unlockConfirmation;\n    if (!ip || getIPLockChangeIntent({ ip, locked: false, confirmed: true }) !== \"save\") return;\n    // Cancel never reaches this method; only the explicit confirm action can release protection.\n    const saved = await this.write({ operation: () => rpc.setIpLock({ schema, ipId: ip.id, locked: false }), message: `IP-adres \"${ip.mask}\" ontgrendeld.`, unlockConfirmed: true });\n    if (saved) this.#set({ unlockConfirmation: null });\n  }\n\n  public cancelUnlock(): void {\n    if (!this.saving) this.#set({ unlockConfirmation: null, error: \"\" });\n  }\n\n  public async deleteIP(ip: IPPersonIP): Promise<void> {\n    if (ip.locked) {\n      this.#set({ error: \"Ontgrendel dit IP-adres eerst om het te verwijderen.\" });\n      return;\n    }\n    const own = ip.allowedTargetIds.length > 0 && ipMaskMatches({ mask: ip.mask, address: this.workspace?.currentIp ?? null });\n    await this.#runRemoval({ pending: {\n      title: own ? \"Je eigen IP-adres verwijderen?\" : \"IP-adres verwijderen?\",\n      confirmLabel: \"IP-adres verwijderen\",\n      description: `Je verwijdert \"${ip.mask}\" en trekt de toegang tot CRM, Frontend en Dashboard in.${own ? \" Daardoor kun je jezelf buitensluiten.\" : \"\"}`,\n      alwaysConfirm: true,\n      masks: ip.allowedTargetIds.length ? [ip.mask] : [],\n      message: `IP-adres \"${ip.mask}\" verwijderd.`,\n      personId: this.selectedPersonId,\n      operation: confirmed => rpc.deletePersonIp({ schema, ipId: ip.id, confirmOwnRemoval: confirmed }),\n    } });\n  }\n\n  public async revokePerson(): Promise<void> {\n    const current = this.person;\n    if (!current)\n      return;\n    if (hasProtectedAccess({ ips: current.ips })) {\n      this.#set({ error: \"Ontgrendel eerst de beschermde IP-adressen om alle toegang in te trekken.\" });\n      return;\n    }\n    const masks = current.ips.filter(ip => ip.allowedTargetIds.length).map(ip => ip.mask);\n    const own = masks.some(mask => ipMaskMatches({ mask, address: this.workspace?.currentIp ?? null }));\n    await this.#runRemoval({ pending: {\n      title: \"Alle toegang voor deze naam intrekken?\",\n      confirmLabel: \"Alle toegang intrekken\",\n      alwaysConfirm: true,\n      description: `Je trekt alle toegang voor \"${current.name}\" in.${own ? \" Dit omvat je eigen IP, waardoor je jezelf kunt buitensluiten.\" : \"\"}`,\n      masks,\n      message: `Alle toegang voor \"${current.name}\" ingetrokken.`,\n      personId: current.id,\n      operation: confirmed => rpc.revokePerson({ schema, personId: current.id, confirmOwnRemoval: confirmed }),\n    } });\n  }\n\n  public async confirmRemoval(): Promise<void> {\n    const pending = this.#pendingRemoval;\n    if (pending)\n      await this.#runRemoval({ pending, confirmed: true });\n  }\n\n  public cancelRemoval(): void {\n    this.#pendingRemoval = null;\n    this.#set({ confirmation: null, confirmationError: \"\" });\n  }\n\n  #set(patch: Partial<Pick<IPAccessController, StateField>>): void {\n    Object.assign(this, patch);\n    this.#host.requestUpdate();\n  }\n\n  #report(cause: unknown): void {\n    console.dir(cause, { depth: null, colors: true });\n    this.#set({ error: \"Gegevens ophalen is niet gelukt. Probeer het opnieuw.\" });\n  }\n\n  /** After a committed write: a failed readback must not invite repeating that write. */\n  async #readBack(personId: number): Promise<void> {\n    try {\n      await this.#reload({ personId });\n    } catch (cause) {\n      console.dir(cause, { depth: null, colors: true });\n      if (!this.#disposed) this.#set({ error: \"De wijziging is opgeslagen, maar vernieuwen is niet gelukt. Klik op Vernieuwen.\" });\n    }\n  }\n\n  #showConfirmation(options: { pending: PendingRemoval; currentIp: string | null; masks: string[] }): void {\n    this.#pendingRemoval = options.pending;\n    this.#set({\n      confirmationError: \"\",\n      confirmation: { title: options.pending.title, confirmLabel: options.pending.confirmLabel, description: options.pending.description, currentIp: options.currentIp, masks: options.masks },\n    });\n  }\n\n  async #runRemoval(options: { pending: PendingRemoval; confirmed?: boolean }): Promise<void> {\n    if (this.saving || this.unlockConfirmation || this.lockRequest)\n      return;\n    const currentIp = this.workspace?.currentIp ?? null;\n    if (!options.confirmed && (options.pending.alwaysConfirm || options.pending.masks.some(mask => ipMaskMatches({ mask, address: currentIp })))) {\n      this.#showConfirmation({ pending: options.pending, currentIp, masks: options.pending.masks });\n      return;\n    }\n    this.#set({ saving: true, error: \"\" });\n    try {\n      const result = await options.pending.operation(options.confirmed === true);\n      if (this.#disposed)\n        return;\n      if (result.status === \"confirmation-required\") {\n        // The server catches stale IP data or any mask format the preflight did not recognize.\n        this.#showConfirmation({ pending: options.pending, currentIp: result.currentIp, masks: result.masks });\n        return;\n      }\n      await this.#readBack(options.pending.personId);\n      if (!this.#disposed) {\n        showToast({ message: options.pending.message, tone: \"success\" });\n        this.#pendingRemoval = null;\n        this.#set({ confirmation: null });\n      }\n    } catch (cause) {\n      if (!this.#disposed && this.confirmation) this.#set({ confirmationError: \"De wijziging is niet gelukt. Probeer het opnieuw.\" });\n      else if (!this.#disposed)\n        this.#report(cause);\n    } finally {\n      if (!this.#disposed)\n        this.#set({ saving: false });\n    }\n  }\n\n  async #loadDetail(id: number): Promise<void> {\n    const request = ++this.#detailRequest;\n    this.#pendingPersonId = id;\n    this.#set({ loadingPerson: true });\n    try {\n      const result = id ? await rpc.getPerson({ schema, id }) : null;\n      if (!this.#disposed && request === this.#detailRequest) {\n        this.#set({ person: result, selectedPersonId: result?.id ?? 0 });\n        if (id && !result)\n          throw new Error(`Persoon #${id} bestaat niet meer. Vernieuw de lijst.`);\n      }\n    } finally {\n      if (!this.#disposed && request === this.#detailRequest) {\n        this.#pendingPersonId = null;\n        this.#set({ loadingPerson: false });\n      }\n    }\n  }\n\n  async #reload(options: { personId?: number } = {}): Promise<void> {\n    const [workspace, history] = await Promise.all([rpc.getWorkspace({ schema }), rpc.getHistory({ schema })]);\n    if (this.#disposed)\n      return;\n    this.#set({ workspace, history });\n    await this.#loadDetail(getIPReloadPersonId({ explicitId: options.personId, pendingId: this.#pendingPersonId, selectedId: this.selectedPersonId, firstId: workspace.people[0]?.id ?? 0 }));\n  }\n}\n","// The own-IP confirmation as a Lit template (OwnIPConfirmation.vue): an alert dialog that only an explicit confirm\n// passes; Escape, the backdrop and Annuleren all cancel. Rendered by the screen and by the IP dialog.\nimport { html, type CompanyosDialog } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { OwnIPConfirmation } from \"../components/ip-access/ip-access-model\";\n\nexport function ownIPConfirmationDialog(options: { className: string; confirmation: OwnIPConfirmation | null; disabled: boolean; error?: string; onConfirm: () => void; onCancel: () => void }) {\n  const confirmation = options.confirmation;\n  return html`<companyos-dialog class=\"ip-own-confirmation ${options.className}\" alert heading=${confirmation?.title ?? \"\"} pending-label=\"Wijziging verwerken...\"\n      .open=${confirmation !== null} .pending=${options.disabled} .error=${options.error ?? \"\"} @dialog-submit=${options.onConfirm} @dialog-cancel=${options.onCancel}>\n    <div class=\"ip-confirm-body\">\n      <p class=\"ip-confirm-message\">${confirmation?.description ?? \"\"}</p>\n      ${confirmation?.currentIp ? html`<p class=\"ip-confirm-current tnum\">Je huidige IP: ${confirmation.currentIp}</p>` : \"\"}\n      ${(confirmation?.masks ?? []).map(mask => html`<p class=\"ip-confirm-mask tnum\">${mask}</p>`)}\n    </div>\n    <div slot=\"actions\" class=\"companyos-buttonbar\">\n      <button type=\"button\" class=\"companyos-button\" @click=${(event: Event) => (event.target as Element).closest<CompanyosDialog>(\"companyos-dialog\")?.requestClose()}>Annuleren</button>\n      <button type=\"submit\" class=\"companyos-button companyos-button--danger\" aria-busy=${String(options.disabled)}>${options.disabled ? \"Wijziging verwerken...\" : confirmation?.confirmLabel ?? \"\"}</button>\n    </div>\n  </companyos-dialog>`;\n}\n","// The audit history tab of `<looping-ip-access>`: period and name filters over a read-only list, as IPHistory.vue.\nimport { LitElement, html, type ListColumn } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { IPAuditEntry, IPPersonSummary } from \"../../../../js/ip-access\";\nimport { historyActionLabel, historyForPerson, historyInPeriod, historyLockReason, historyMergeSummary, historyMoveSummary } from \"../components/ip-access/ip-access-model\";\n\ntype Period = \"7\" | \"30\" | \"90\" | \"all\";\n\nconst PERIODS: ReadonlyArray<{ value: Period; label: string }> = [\n  { value: \"7\", label: \"Afgelopen 7 dagen\" }, { value: \"30\", label: \"Afgelopen 30 dagen\" },\n  { value: \"90\", label: \"Afgelopen 90 dagen\" }, { value: \"all\", label: \"Alle wijzigingen\" },\n];\n\nfunction dateLabel(timestamp: string): string {\n  const date = new Date(timestamp);\n  return Number.isFinite(date.getTime()) ? new Intl.DateTimeFormat(\"nl-NL\", { dateStyle: \"short\", timeStyle: \"short\", timeZone: \"Europe/Amsterdam\" }).format(date) : \"Onbekende datum\";\n}\n\nfunction details(entry: IPAuditEntry): string {\n  const summary = historyMergeSummary(entry) || historyMoveSummary(entry);\n  const masks = Array.isArray(entry.details.masks) ? entry.details.masks.filter((mask): mask is string => typeof mask === \"string\") : [];\n  const values = summary ? [summary] : [...[entry.details.mask, entry.details.name, entry.details.targetName].filter((value): value is string => typeof value === \"string\"), ...masks];\n  const reason = historyLockReason(entry);\n  return [values.join(\" · \"), reason ? `Reden: ${reason}` : \"\"].filter(Boolean).join(\" · \");\n}\n\nexport class LoopingIPHistory extends LitElement {\n  public static override properties = { entries: { attribute: false }, people: { attribute: false } };\n  declare public entries: readonly IPAuditEntry[];\n  declare public people: readonly IPPersonSummary[];\n  #period: Period = \"30\";\n  #personId = 0;\n\n  public constructor() {\n    super();\n    this.entries = [];\n    this.people = [];\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override render() {\n    const columns: ReadonlyArray<ListColumn<IPAuditEntry>> = [\n      { key: \"action\", label: \"Actie\", minWidth: 160, defaultWidth: 260, emphasis: true, value: entry => historyActionLabel(entry.action) },\n      { key: \"details\", label: \"Details\", minWidth: 200, defaultWidth: 360, flexible: true, tone: \"secondary\", value: details },\n      { key: \"person\", label: \"Naam\", minWidth: 140, defaultWidth: 200, value: entry => entry.personId ? this.people.find(person => person.id === entry.personId)?.name || `Naam #${entry.personId}` : \"\" },\n      { key: \"actor\", label: \"Gebruiker\", minWidth: 104, defaultWidth: 120, tone: \"secondary\", value: entry => `Gebruiker #${entry.actorId}` },\n      { key: \"date\", label: \"Datum\", minWidth: 136, defaultWidth: 150, align: \"right\", numeric: true, value: entry => dateLabel(entry.timestamp) },\n    ];\n    const entries = historyInPeriod({ entries: historyForPerson({ entries: this.entries, personId: this.#personId }), days: this.#period === \"all\" ? null : Number(this.#period), now: new Date() });\n    return html`<div class=\"ip-history\">\n      <h2 class=\"ip-history__title\">Historie</h2>\n      <div class=\"ip-history__panel\">\n        <div class=\"ip-history__filters companyos-form\">\n          <div class=\"companyos-field\"><label class=\"companyos-field__label\" for=\"ip-history-period\">Periode</label>\n            <select id=\"ip-history-period\" name=\"period\" @change=${(event: Event) => { this.#period = (event.target as HTMLSelectElement).value as Period; this.requestUpdate(); }}>\n              ${PERIODS.map(period => html`<option value=${period.value} ?selected=${period.value === this.#period}>${period.label}</option>`)}\n            </select></div>\n          <div class=\"companyos-field\"><label class=\"companyos-field__label\" for=\"ip-history-person\">Naam</label>\n            <select id=\"ip-history-person\" name=\"personId\" @change=${(event: Event) => { this.#personId = Number((event.target as HTMLSelectElement).value); this.requestUpdate(); }}>\n              <option value=\"0\" ?selected=${!this.#personId}>Alle namen</option>\n              ${this.people.map(person => html`<option value=${person.id} ?selected=${person.id === this.#personId}>${person.name}</option>`)}\n            </select></div>\n        </div>\n        <companyos-list class=\"ip-history__list\" label=\"Historie\" .items=${entries} .itemKey=${(entry: IPAuditEntry) => entry.id} .itemLabel=${(entry: IPAuditEntry) => historyActionLabel(entry.action)}\n            .columns=${columns} .selectable=${false}>\n          <div class=\"companyos-list__empty\"><p>Geen wijzigingen in deze periode.</p></div>\n        </companyos-list>\n      </div>\n    </div>`;\n  }\n}\n\nif (!customElements.get(\"looping-ip-history\"))\n  customElements.define(\"looping-ip-history\", LoopingIPHistory);\n","// Add or edit one IP address of a person: `<looping-ip-mask-dialog>`, the Lit counterpart of IPMaskDialog.vue. Unlocking\n// and removing access from your own IP each need their own confirmation before the one atomic save may run.\nimport { LitElement, html, nothing, type PropertyValues, CrudDialogController, FormSubmissionError, LoadingStateController, type CompanyosDialog } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { IPPersonIP, IPSaveResult, IPTarget, SavePersonIPWithLockOptions } from \"../../../../js/ip-access\";\nimport { isNetworkMask, type OwnIPConfirmation } from \"../components/ip-access/ip-access-model\";\nimport { getIPLockChangeIntent, getIPLockState } from \"../components/ip-access/ip-lock-model\";\nimport { getMaskDraft, validateMaskDraft, type MaskDraft } from \"../components/ip-access/ip-mask-model\";\nimport { ownIPConfirmationDialog } from \"./ip-confirmations\";\n\ntype TextField = \"mask\" | \"label\" | \"lockReason\";\n\nexport class LoopingIPMaskDialog extends LitElement {\n  public static override properties = {\n    open: { type: Boolean }, personId: { attribute: false }, ip: { attribute: false }, targets: { attribute: false }, save: { attribute: false },\n  };\n  declare public open: boolean;\n  declare public personId: number;\n  declare public ip: IPPersonIP | null;\n  declare public targets: readonly IPTarget[];\n  declare public save: (options: SavePersonIPWithLockOptions) => Promise<IPSaveResult>;\n  readonly #loading = new LoadingStateController(this);\n  readonly #editor = new CrudDialogController<MaskDraft>(this, {\n    create: () => getMaskDraft({ ip: null }),\n    validate: validateMaskDraft,\n    save: async ({ draft }) => {\n      const result = await this.#loading.run(() => this.save({\n        personId: this.personId, ...(this.ip ? { id: this.ip.id } : {}),\n        mask: draft.mask.trim(), label: draft.label.trim(), allowedTargetIds: draft.allowedTargetIds,\n        locked: draft.locked, lockReason: draft.locked ? draft.lockReason.trim() : \"\", confirmUnlock: this.#confirmedUnlock,\n        confirmOwnRemoval: this.#confirmedOwnRemoval,\n      }));\n      if (result.status === \"confirmation-required\") {\n        this.#pendingConfirmation = result;\n        // Keeps the controller from completing or discarding a draft that has not been saved.\n        throw new FormSubmissionError({ message: \"Bevestig het intrekken van je eigen toegang.\" });\n      }\n    },\n  });\n  #ownConfirmation: OwnIPConfirmation | null = null;\n  #unlockConfirmation = false;\n  #pendingConfirmation: Extract<IPSaveResult, { status: \"confirmation-required\" }> | null = null;\n  #confirmedOwnRemoval = false;\n  #confirmedUnlock = false;\n  // The refusal's message only kept the draft open; the confirmation dialog explains it instead.\n  #hideRefusal = false;\n\n  public constructor() {\n    super();\n    this.open = false;\n    this.personId = 0;\n    this.ip = null;\n    this.targets = [];\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  protected override willUpdate(changed: PropertyValues<this>) {\n    if (!changed.has(\"open\"))\n      return;\n    this.#ownConfirmation = null;\n    this.#pendingConfirmation = null;\n    this.#confirmedOwnRemoval = false;\n    this.#unlockConfirmation = false;\n    this.#confirmedUnlock = false;\n    this.#hideRefusal = false;\n    if (this.open) {\n      if (this.ip) this.#editor.openEdit(getMaskDraft({ ip: this.ip }));\n      else this.#editor.openCreate();\n    } else if (changed.get(\"open\") !== undefined)\n      this.#editor.close({ discard: true });\n  }\n\n  public override render() {\n    const editor = this.#editor;\n    const draft = editor.draft;\n    const lockState = getIPLockState({ ip: this.ip, draftLocked: draft.locked });\n    // Existing dealer and broker sign-in checks do not expand network ranges.\n    const loginHint = isNetworkMask(draft.mask) && this.targets.some(target => target.loginWhitelist && draft.allowedTargetIds.includes(target.id));\n    const maskHint = lockState.locked\n      ? \"Dit IP-adres is vergrendeld. Het adres en bestaande toegang blijven behouden; de omschrijving kun je wel aanpassen.\"\n      : \"Bijvoorbeeld 192.0.2.10 of 2001:db8::/48.\";\n    return html`<companyos-dialog class=\"ip-mask-dialog\" heading=${editor.mode === \"create\" ? \"IP-adres toevoegen\" : \"IP-adres bewerken\"} pending-label=\"IP-adres opslaan...\"\n        .open=${editor.open && !this.#ownConfirmation && !this.#unlockConfirmation} .pending=${editor.pending} .loadingVisible=${this.#loading.visible} .dirty=${editor.dirty}\n        .error=${this.#hideRefusal ? \"\" : editor.formError} @dialog-submit=${() => void this.#submit()} @dialog-cancel=${(event: CustomEvent<{ discard: boolean }>) => this.#cancel(event.detail)}>\n      ${this.#textField({ field: \"mask\", id: \"ip-mask\", label: \"IP-adres of netwerk\", hint: maskHint, readonly: lockState.maskReadonly })}\n      ${this.#textField({ field: \"label\", id: \"ip-mask-label\", label: \"Omschrijving\", hint: \"Bijvoorbeeld kantoor of thuis.\", rows: 4 })}\n      <div class=\"companyos-field ip-check\">\n        <input type=\"checkbox\" id=\"ip-mask-locked\" name=\"locked\" aria-describedby=\"ip-mask-locked-hint\" .checked=${draft.locked}\n          @change=${(event: Event) => editor.update({ locked: (event.target as HTMLInputElement).checked })}>\n        <div><label for=\"ip-mask-locked\">IP-adres vergrendelen</label>\n          <span id=\"ip-mask-locked-hint\" class=\"companyos-field__hint\">Beschermt het IP-adres tegen verwijderen, wijzigen en intrekken van bestaande toegang.</span></div>\n      </div>\n      <div>${draft.locked ? this.#textField({ field: \"lockReason\", id: \"ip-mask-lock-reason\", label: \"Reden voor vergrendeling\", hint: \"Optioneel. Leg vast waarom dit IP-adres behouden moet blijven.\", rows: 3 }) : nothing}</div>\n      <fieldset class=\"companyos-field ip-targets\" aria-describedby=${loginHint ? \"ip-mask-targets-hint\" : nothing}>\n        <legend class=\"companyos-field__label\">Toegang</legend>\n        ${this.targets.map(target => {\n          const protectedTarget = lockState.protectedTargetIds.includes(target.id);\n          const reason = protectedTarget ? \"Ontgrendel dit IP-adres eerst om de toegang in te trekken\" : !target.accessRuleId ? \"Toegang momenteel niet beschikbaar\" : \"\";\n          return html`<div class=\"ip-check\">\n            <input type=\"checkbox\" id=\"ip-mask-target-${target.id}\" name=\"allowedTargetIds\" value=${target.id} ?disabled=${Boolean(reason)} aria-describedby=${reason ? `ip-mask-target-${target.id}-reason` : nothing}\n              .checked=${draft.allowedTargetIds.includes(target.id)} @change=${(event: Event) => this.#toggleTarget({ id: target.id, checked: (event.target as HTMLInputElement).checked })}>\n            <div><label for=\"ip-mask-target-${target.id}\">${target.name}</label>${reason ? html`<span id=\"ip-mask-target-${target.id}-reason\" class=\"companyos-field__hint\">${reason}</span>` : nothing}</div>\n          </div>`;\n        })}\n        ${loginHint ? html`<span id=\"ip-mask-targets-hint\" class=\"companyos-field__hint\">Om ook in te loggen als dealer of makelaar, voeg je het IP-adres van die werkplek apart toe.</span>` : nothing}\n      </fieldset>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${() => this.querySelector<CompanyosDialog>(\"companyos-dialog.ip-mask-dialog\")?.requestClose()}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(editor.pending)}>${editor.pending ? \"IP-adres opslaan...\" : \"IP-adres opslaan\"}</button>\n      </div>\n    </companyos-dialog>\n    <companyos-dialog class=\"ip-mask-unlock\" alert heading=\"IP-adres ontgrendelen?\" .open=${this.#unlockConfirmation} .pending=${editor.pending}\n        @dialog-submit=${() => void this.#confirmUnlock()} @dialog-cancel=${() => this.#cancelUnlock()}>\n      <p class=\"ip-confirm-message\">Je ontgrendelt \"${this.ip?.mask ?? \"\"}\". Daarna kan dit IP-adres worden verwijderd of gewijzigd en kan bestaande toegang worden ingetrokken.</p>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${() => this.querySelector<CompanyosDialog>(\"companyos-dialog.ip-mask-unlock\")?.requestClose()}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(editor.pending)}>${editor.pending ? \"Opslaan...\" : \"Ontgrendelen en opslaan\"}</button>\n      </div>\n    </companyos-dialog>\n    ${ownIPConfirmationDialog({ className: \"ip-mask-own\", confirmation: this.#ownConfirmation, disabled: editor.pending, onConfirm: () => void this.#confirmOwnRemoval(), onCancel: () => this.#cancelOwnRemoval() })}`;\n  }\n\n  #textField(options: { field: TextField; id: string; label: string; hint: string; rows?: number; readonly?: boolean }) {\n    const editor = this.#editor;\n    const error = editor.errors[options.field];\n    const describedBy = `${options.id}-hint${error ? ` ${options.id}-error` : \"\"}`;\n    const input = (event: Event) => editor.update({ [options.field]: (event.target as HTMLInputElement | HTMLTextAreaElement).value });\n    return html`<div class=\"companyos-field\">\n      <label class=\"companyos-field__label\" for=${options.id}>${options.label}</label>\n      ${options.rows\n        ? html`<textarea id=${options.id} name=${options.field} rows=${options.rows} maxlength=\"10000\" .value=${editor.draft[options.field]} aria-invalid=${error ? \"true\" : \"false\"} aria-describedby=${describedBy} @input=${input}></textarea>`\n        : html`<input id=${options.id} name=${options.field} required autocomplete=\"off\" spellcheck=\"false\" ?readonly=${options.readonly} .value=${editor.draft[options.field]}\n            aria-invalid=${error ? \"true\" : \"false\"} aria-describedby=${describedBy} @input=${input}>`}\n      <span id=\"${options.id}-hint\" class=\"companyos-field__hint\">${options.hint}</span>\n      ${error ? html`<span id=\"${options.id}-error\" class=\"companyos-field__error\">${error}</span>` : nothing}\n    </div>`;\n  }\n\n  #toggleTarget(options: { id: number; checked: boolean }): void {\n    const ids = this.#editor.draft.allowedTargetIds.filter(id => id !== options.id);\n    this.#editor.update({ allowedTargetIds: options.checked ? [...ids, options.id].toSorted((left, right) => left - right) : ids });\n  }\n\n  async #submit(): Promise<void> {\n    const editor = this.#editor;\n    if (editor.pending)\n      return;\n    this.#hideRefusal = false;\n    // An invalid draft goes straight to submit(), which shows the errors without saving.\n    const valid = Object.keys(validateMaskDraft(editor.draft)).length === 0;\n    if (valid && this.ip && getIPLockChangeIntent({ ip: this.ip, locked: editor.draft.locked, confirmed: this.#confirmedUnlock }) === \"confirm-unlock\") {\n      this.#unlockConfirmation = true;\n      this.requestUpdate();\n      return;\n    }\n    if (await editor.submit()) this.#close();\n    if (this.#pendingConfirmation) {\n      const refusal = this.#pendingConfirmation;\n      this.#pendingConfirmation = null;\n      this.#loading.cancel();\n      this.#hideRefusal = true;\n      // Present one dialog at a time while retaining the unsaved form underneath.\n      this.#ownConfirmation = {\n        title: \"Toegang vanaf je eigen IP intrekken?\", confirmLabel: \"Opslaan en toegang intrekken\",\n        description: \"Je trekt toegang vanaf je huidige IP-adres in. Daardoor kun je jezelf buitensluiten.\",\n        currentIp: refusal.currentIp, masks: refusal.masks,\n      };\n      this.requestUpdate();\n    }\n  }\n\n  async #confirmUnlock(): Promise<void> {\n    this.#unlockConfirmation = false;\n    this.#confirmedUnlock = true;\n    try { await this.#submit(); } finally {\n      // Keep the unlock approval only while the own-IP confirmation blocks this same save.\n      if (!this.#ownConfirmation) this.#confirmedUnlock = false;\n    }\n  }\n\n  #cancelUnlock(): void {\n    this.#unlockConfirmation = false;\n    this.#confirmedUnlock = false;\n    this.requestUpdate();\n  }\n\n  async #confirmOwnRemoval(): Promise<void> {\n    this.#ownConfirmation = null;\n    this.#confirmedOwnRemoval = true;\n    try { await this.#submit(); } finally {\n      this.#confirmedOwnRemoval = false;\n      this.#confirmedUnlock = false;\n    }\n  }\n\n  #cancelOwnRemoval(): void {\n    this.#ownConfirmation = null;\n    this.#confirmedUnlock = false;\n    this.requestUpdate();\n  }\n\n  #cancel(options: { discard: boolean }): void {\n    if (this.#editor.close(options)) {\n      // Confirmed cancellation ends any remaining failed-save indicator immediately.\n      this.#loading.cancel();\n      this.#close();\n    }\n  }\n\n  #close(): void {\n    this.dispatchEvent(new CustomEvent(\"mask-dialog-close\", { bubbles: true }));\n  }\n}\n\nif (!customElements.get(\"looping-ip-mask-dialog\"))\n  customElements.define(\"looping-ip-mask-dialog\", LoopingIPMaskDialog);\n","// The Looping OS IP access screen as a Lit element on a regular CompanyOS page: `<looping-ip-access>`. Same RPC and\n// pure models as the Vue app (components/ip-access), built on the CompanyOS screen parts in light DOM.\nimport { LitElement, html, nothing, CrudDialogController, LoadingStateController, icon, type CompanyosDialog, type CompanyosList, type ListColumn, type ListRowAction, type ListSort } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { IPPersonDetail, IPPersonIP, IPPersonSummary, IPTarget } from \"../../../../js/ip-access\";\nimport { getIPAccessTabs } from \"../components/ip-access/ip-loading-model\";\nimport { getIPLockState, hasProtectedAccess, validateIPLockDraft, type IPLockDraft } from \"../components/ip-access/ip-lock-model\";\nimport { createIPPersonDraft, validateIPPersonDraft, type IPPersonDraft } from \"../components/ip-access/ip-person-model\";\nimport { getAdjacentPersonId, getVisiblePeople, type IPPeopleSortKey } from \"../components/ip-access/ip-table-model\";\nimport { IPAccessController } from \"./ip-access-controller\";\nimport { ownIPConfirmationDialog } from \"./ip-confirmations\";\nimport \"./ip-history\";\nimport \"./ip-mask-dialog\";\nimport \"../components/ip-access/ip-access.css\";\nimport \"./ip-access.css\";\n\nconst PEOPLE_COLUMNS: ReadonlyArray<ListColumn<IPPersonSummary, IPPeopleSortKey>> = [\n  { key: \"name\", label: \"Naam\", minWidth: 160, defaultWidth: 230, sortable: true, emphasis: true },\n  { key: \"ipCount\", label: \"IP-adressen\", minWidth: 112, defaultWidth: 120, sortable: true, align: \"right\", numeric: true },\n  { key: \"note\", label: \"Notitie\", minWidth: 140, defaultWidth: 300, flexible: true, sortable: true, tone: \"secondary\" },\n];\nconst PEOPLE_ACTIONS: readonly ListRowAction[] = [{ id: \"edit\", kind: \"edit\" }];\n\n/** Read-only cells keep the stored state visible; changes are submitted through the IP dialog. */\nfunction matrixColumns(targets: readonly IPTarget[]): ReadonlyArray<ListColumn<IPPersonIP>> {\n  return [\n    { key: \"mask\", label: \"IP-adres\", minWidth: 160, defaultWidth: 220, flexible: true, numeric: true, badge: ip => ip.locked ? { label: \"Vergrendeld\", description: ip.lockReason || \"verwijderen en toegang intrekken zijn beschermd\" } : undefined },\n    ...targets.map(target => ({\n      kind: \"check\" as const, key: `target-${target.id}`, label: target.name, minWidth: 104, defaultWidth: 104,\n      checked: (ip: IPPersonIP) => ip.allowedTargetIds.includes(target.id), checkLabel: (ip: IPPersonIP) => `${ip.mask}: toegang tot ${target.name}`,\n    })),\n  ];\n}\n\nfunction ipActions(ip: IPPersonIP): readonly ListRowAction[] {\n  const locked = getIPLockState({ ip }).locked;\n  return [\n    { id: \"edit\", kind: \"edit\" },\n    { id: \"move\", label: \"Verplaatsen naar andere naam\" },\n    { id: \"remove\", kind: \"delete\", disabled: locked },\n    { id: \"lock\", label: locked ? \"Ontgrendelen\" : \"Vergrendelen\" },\n  ];\n}\n\ninterface MoveDraft { personId: number }\n\nfunction iconButton(options: { icon: Parameters<typeof icon>[0]; label: string; disabled?: boolean; pressed?: boolean; title?: string; className?: string; onClick: () => void }) {\n  return html`<button type=\"button\" class=\"companyos-button ip-iconbutton ${options.className ?? \"\"}\" aria-label=${options.label} title=${options.title ?? options.label}\n    aria-pressed=${options.pressed === undefined ? nothing : String(options.pressed)} ?disabled=${options.disabled} @click=${options.onClick}>${icon(options.icon, 16)}</button>`;\n}\n\nfunction skeleton(kind: \"workspace\" | \"person\") {\n  const bar = html`<div class=\"ip-panel__bar\"><span class=\"ip-skeleton__block ip-skeleton__title\"></span><span class=\"ip-skeleton__block ip-skeleton__button\"></span></div>`;\n  return html`<div class=\"ip-loading-skeleton ip-stack\" data-kind=${kind} aria-hidden=\"true\">\n    ${kind === \"workspace\" ? html`<section class=\"ip-panel\">${bar}\n      <div class=\"ip-panel__body ip-skeleton__intro\"><span class=\"ip-skeleton__block ip-skeleton__description\"></span><span class=\"ip-skeleton__block ip-skeleton__search\"></span></div>\n      ${[1, 2, 3].map(() => html`<div class=\"ip-skeleton__row\"><span class=\"ip-skeleton__block ip-skeleton__name\"></span><span class=\"ip-skeleton__block ip-skeleton__count\"></span><span class=\"ip-skeleton__block ip-skeleton__note\"></span></div>`)}\n    </section>` : nothing}\n    <section class=\"ip-panel\">${bar}<div class=\"ip-panel__body\"><span class=\"ip-skeleton__block ip-skeleton__description\"></span></div></section>\n    <section class=\"ip-panel\">${bar}<div class=\"ip-skeleton__matrix\">${[1, 2, 3].map(() => html`<div class=\"ip-skeleton__matrix-row\"><span class=\"ip-skeleton__block\"></span><span class=\"ip-skeleton__block\"></span><span class=\"ip-skeleton__block\"></span></div>`)}</div></section>\n  </div>`;\n}\n\nexport class LoopingIPAccess extends LitElement {\n  readonly #state = new IPAccessController(this);\n  readonly #dialogLoading = new LoadingStateController(this);\n  readonly #editor = new CrudDialogController<IPPersonDraft>(this, {\n    create: () => createIPPersonDraft(),\n    validate: validateIPPersonDraft,\n    // Only the editable snapshot is submitted. Detail refreshes cannot overwrite an unsaved draft.\n    save: async ({ draft }) => {\n      await this.#state.savePerson({ ...draft, name: draft.name.trim(), note: draft.note.trim() });\n      this.#panelOpen = true;\n    },\n  });\n  readonly #moveLoading = new LoadingStateController(this);\n  readonly #mover = new CrudDialogController<MoveDraft>(this, {\n    create: () => ({ personId: 0 }),\n    validate: draft => draft.personId ? {} : { personId: \"Kies de naam waar dit IP-adres naartoe gaat.\" },\n    save: async ({ draft }) => {\n      const ip = this.#movingIP;\n      if (ip) await this.#moveLoading.run(() => this.#state.moveIP({ ip, personId: draft.personId }));\n    },\n  });\n  readonly #lockLoading = new LoadingStateController(this);\n  readonly #locker = new CrudDialogController<IPLockDraft>(this, {\n    create: () => ({ reason: \"\" }),\n    validate: validateIPLockDraft,\n    save: async ({ draft }) => await this.#lockLoading.run(() => this.#state.confirmLock({ reason: draft.reason.trim() })),\n  });\n  #view = \"people\";\n  #query = \"\";\n  #sort: ListSort<IPPeopleSortKey> = { key: \"name\", direction: \"asc\" };\n  #panelOpen = false;\n  #expanded = false;\n  #pendingSelection: Promise<void> | null = null;\n  // Held apart from reloads, so a failed save keeps the record the dialog was opened for.\n  #maskOpen = false;\n  #editedIP: IPPersonIP | null = null;\n  #movingIP: IPPersonIP | null = null;\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    void this.#state.load();\n  }\n\n  /** Writes and workspace loads block everything; reading one person leaves row gestures available. */\n  get #busy(): boolean {\n    const state = this.#state;\n    return state.loading || state.loadingPerson || state.skeletonKind !== null || state.saving || state.confirming;\n  }\n\n  get #peopleBusy(): boolean {\n    return this.#state.loading || this.#state.skeletonKind === \"workspace\" || this.#state.saving || this.#state.confirming;\n  }\n\n  get #visiblePeople(): IPPersonSummary[] {\n    return getVisiblePeople({ people: this.#state.workspace?.people ?? [], query: this.#query, key: this.#sort.key, direction: this.#sort.direction });\n  }\n\n  public override render() {\n    const state = this.#state;\n    const sections = getIPAccessTabs({ activeKey: this.#view, initialLoading: state.skeletonKind === \"workspace\" || (!state.workspace && state.loading), disabled: state.saving || state.confirming });\n    return html`<div class=\"ip-access\" @keydown=${this.#onKeydown}>\n      <header class=\"ip-header\"><div class=\"ip-header__title\">\n        <div><h1 class=\"page-title\">IP-toegangsbeheer</h1><p>Beheer IP-adressen per naam en bepaal toegang tot CRM, Frontend en Dashboard.</p></div>\n        <div class=\"companyos-buttonbar ip-header__actions\">\n          <button type=\"button\" class=\"companyos-button ip-button--ghost\" ?disabled=${state.headerDisabled} aria-busy=${String(state.loading)} @click=${() => void state.load()}>${icon(\"renew\")}${state.loading ? \"Vernieuwen...\" : \"Vernieuwen\"}</button>\n          ${this.#view === \"people\" ? html`<button type=\"button\" class=\"companyos-button companyos-button--primary\" ?disabled=${state.headerDisabled} @click=${() => this.#editor.openCreate()}>${icon(\"add\")}Nieuwe naam</button>` : nothing}\n        </div>\n      </div></header>\n      <span class=\"ip-loading-status\" role=\"status\" aria-live=\"polite\">${state.loading ? \"IP-toegangsbeheer laden...\" : state.loadingPerson ? \"Naamgegevens laden...\" : \"\"}</span>\n      <div class=\"ip-body\" aria-busy=${String(state.loading || state.loadingPerson || state.skeletonKind !== null)}>\n        <div class=\"ip-feedback\">${state.error ? html`<div class=\"ip-error\" role=\"alert\"><p>${state.error}</p><div class=\"companyos-buttonbar\"><button type=\"button\" class=\"companyos-button\" ?disabled=${this.#busy} @click=${() => void state.load()}>Opnieuw laden</button></div></div>` : nothing}</div>\n        <companyos-tabs label=\"IP-toegangsbeheer onderdelen\" .selected=${this.#view} @tab-change=${(event: CustomEvent<string>) => { this.#view = event.detail; this.requestUpdate(); }}>\n          ${sections.map(section => html`<section data-tab=${section.value} data-tab-title=${section.title} ?data-tab-disabled=${section.disabled} class=\"ip-tabpanel ip-tabpanel--${section.layout}\">\n            ${section.value === \"people\" ? this.#people() : state.workspace ? html`<looping-ip-history .entries=${state.history} .people=${state.workspace.people}></looping-ip-history>` : nothing}\n          </section>`)}\n        </companyos-tabs>\n      </div>\n      ${this.#personDialog()}\n      ${this.#ipDialogs()}\n    </div>`;\n  }\n\n  #people() {\n    const state = this.#state;\n    if (state.skeletonKind === \"workspace\")\n      return html`<div class=\"ip-people-layout\">${skeleton(\"workspace\")}</div>`;\n    if (!state.workspace)\n      return nothing;\n    const rows = this.#visiblePeople;\n    const total = state.workspace.people.length;\n    return html`<div class=\"ip-people-layout ${this.#panelOpen ? \"ip-people-layout--open\" : \"\"} ${this.#expanded ? \"ip-people-layout--expanded\" : \"\"}\">\n      <div class=\"ip-people\" aria-busy=${String(this.#peopleBusy)}>\n        <div class=\"ip-people__tools\">\n          <input type=\"search\" class=\"ip-table-search\" aria-label=\"Zoek op naam of notitie\" placeholder=\"Zoek op naam of notitie...\" .value=${this.#query}\n            @input=${(event: InputEvent) => { this.#query = (event.target as HTMLInputElement).value; this.requestUpdate(); }}>\n        </div>\n        <companyos-list class=\"ip-people__list\" label=\"Namen en IP-adressen\" .items=${rows} .itemKey=${(row: IPPersonSummary) => row.id} .itemLabel=${(row: IPPersonSummary) => row.name}\n            .columns=${PEOPLE_COLUMNS} .rowActions=${PEOPLE_ACTIONS} .selected=${this.#panelOpen && state.selectedPersonId ? state.selectedPersonId : undefined} .sort=${this.#sort} .disabled=${this.#peopleBusy}\n            @select-row=${(event: CustomEvent<number>) => void this.#openPerson(event.detail)}\n            @sort-change=${(event: CustomEvent<ListSort<IPPeopleSortKey>>) => { this.#sort = event.detail; this.requestUpdate(); }}\n            @open-row=${(event: CustomEvent<IPPersonSummary>) => void this.#editPerson(event.detail.id)}\n            @row-action=${(event: CustomEvent<{ item: IPPersonSummary; actionId: string }>) => { if (event.detail.actionId === \"edit\") void this.#editPerson(event.detail.item.id); }}\n            @search-request=${() => this.querySelector<HTMLInputElement>(\".ip-table-search\")?.focus()}>\n          <div class=\"companyos-list__empty\">\n            <h3>${this.#query ? \"Geen namen gevonden\" : \"Nog geen namen\"}</h3>\n            <p>${this.#query ? \"Pas je zoekopdracht aan.\" : \"Voeg een naam toe om IP-adressen te beheren.\"}</p>\n          </div>\n        </companyos-list>\n        <footer class=\"ip-table-footer\"><span class=\"tnum\">${rows.length} ${rows.length === 1 ? \"naam\" : \"namen\"}${rows.length !== total ? ` van ${total}` : \"\"}</span><span class=\"ip-table-footer__hint\"><kbd>↑ ↓</kbd> navigeren <kbd>↵</kbd> openen</span></footer>\n      </div>\n      ${this.#panelOpen ? this.#detailPanel(rows.map(row => row.id)) : nothing}\n    </div>`;\n  }\n\n  #detailPanel(ids: number[]) {\n    const state = this.#state;\n    const index = ids.indexOf(state.selectedPersonId);\n    const personSkeleton = state.skeletonKind === \"person\";\n    return html`<aside class=\"ip-detail-panel\" aria-label=\"Naam en toegang\">\n      <header class=\"ip-detail-panel__toolbar\">\n        <div class=\"ip-detail-panel__navigation\">\n          ${iconButton({ icon: \"chevron--left\", label: \"Vorige naam\", disabled: this.#busy || index <= 0, onClick: () => this.#navigate({ ids, offset: -1 }) })}\n          ${iconButton({ icon: \"chevron--right\", label: \"Volgende naam\", disabled: this.#busy || !ids.length || index === ids.length - 1, onClick: () => this.#navigate({ ids, offset: 1 }) })}\n          ${index >= 0 ? html`<span class=\"ip-detail-panel__position tnum\">${index + 1} van ${ids.length}</span>` : nothing}\n        </div>\n        <div class=\"ip-detail-panel__controls\">\n          ${iconButton({ icon: \"fit-to-screen\", label: this.#expanded ? \"Detailpaneel verkleinen\" : \"Detailpaneel vergroten\", pressed: this.#expanded, className: \"ip-detail-panel__expand\", onClick: () => { this.#expanded = !this.#expanded; this.requestUpdate(); } })}\n          ${iconButton({ icon: \"close\", label: \"Detailpaneel sluiten\", title: \"Sluiten (Escape)\", onClick: () => void this.#closePanel() })}\n        </div>\n      </header>\n      <div class=\"ip-details-region\">\n        ${personSkeleton ? skeleton(\"person\") : nothing}\n        <!-- Hidden detail keeps its geometry while its replacement loads. -->\n        ${state.person ? html`<div class=\"ip-details-content\" aria-hidden=${personSkeleton ? \"true\" : nothing} ?inert=${personSkeleton}>${this.#details(state.person)}</div>` : nothing}\n      </div>\n    </aside>`;\n  }\n\n  #details(person: IPPersonDetail) {\n    const targets = this.#state.workspace?.targets ?? [];\n    const protectedAccess = hasProtectedAccess({ ips: person.ips });\n    const canRevoke = !protectedAccess && person.ips.some(ip => ip.allowedTargetIds.length);\n    return html`<div class=\"ip-person-details\">\n      <section class=\"ip-person-hero\" aria-label=\"Naamdetails\">\n        <div class=\"ip-person-hero__heading\"><div class=\"ip-person-hero__avatar\">${icon(\"user--avatar\", 24)}</div><div class=\"ip-person-hero__identity\"><h2 class=\"ip-person-hero__name\">${person.name}</h2></div>\n          ${iconButton({ icon: \"edit\", label: \"Naam bewerken\", disabled: this.#busy, onClick: () => void this.#editPerson(person.id) })}</div>\n        <div class=\"ip-person-meta\"><span class=\"ip-person-meta__count tnum\">${icon(\"connect\", 16)}${person.ips.length} ${person.ips.length === 1 ? \"IP-adres\" : \"IP-adressen\"}</span></div>\n        ${person.note ? html`<p class=\"ip-person-note\">${person.note}</p>` : nothing}\n      </section>\n      <section class=\"ip-person-access\" aria-label=\"IP-adressen en toegang\">\n        <div class=\"ip-person-access__bar\"><h3>IP-adressen en toegang</h3><div class=\"companyos-buttonbar\">\n          <button type=\"button\" class=\"companyos-button ip-button--ghost\" ?disabled=${this.#busy} @click=${() => this.#editIP(null)}>${icon(\"add\")}Toevoegen</button></div></div>\n        ${person.ips.length\n          ? html`<companyos-list class=\"ip-matrix\" label=\"IP-adressen en toegang tot CRM, Frontend en Dashboard\" .items=${person.ips} .itemKey=${(ip: IPPersonIP) => ip.id} .itemLabel=${(ip: IPPersonIP) => ip.mask}\n              .columns=${matrixColumns(targets)} .rowActions=${ipActions} .selectable=${false} .disabled=${this.#busy}\n              @open-row=${(event: CustomEvent<IPPersonIP>) => this.#editIP(event.detail)}\n              @row-action=${(event: CustomEvent<{ item: IPPersonIP; actionId: string }>) => this.#ipAction(event.detail)}></companyos-list>`\n          : html`<div class=\"ip-person-empty\">${icon(\"search\", 24)}<h3 class=\"ip-person-empty__title\">Nog geen IP-adressen</h3><p class=\"ip-person-empty__body\">Voeg een IP-adres of netwerk toe om de toegang te beheren.</p></div>`}\n      </section>\n      <footer class=\"ip-person-footer\">${protectedAccess ? html`<p class=\"ip-person-lock-hint\" role=\"note\">Ontgrendel eerst de beschermde IP-adressen om alle toegang in te trekken.</p>` : nothing}\n        <div class=\"companyos-buttonbar\"><button type=\"button\" class=\"companyos-button ip-button--ghost ip-revoke\" ?disabled=${this.#busy || !canRevoke} @click=${() => void this.#state.revokePerson()}>${icon(\"stop--filled\")}Alle toegang intrekken</button></div></footer>\n    </div>`;\n  }\n\n  #ipDialogs() {\n    const state = this.#state;\n    const person = state.person;\n    const mover = this.#mover;\n    const locker = this.#locker;\n    const moveError = mover.errors.personId;\n    const closeDialog = (event: Event) => (event.target as Element).closest<CompanyosDialog>(\"companyos-dialog\")?.requestClose();\n    return html`<looping-ip-mask-dialog .open=${this.#maskOpen && person !== null} .personId=${person?.id ?? 0} .ip=${this.#editedIP} .targets=${state.workspace?.targets ?? []}\n        .save=${(options: Parameters<IPAccessController[\"saveIP\"]>[0]) => state.saveIP(options)} @mask-dialog-close=${() => { this.#maskOpen = false; this.requestUpdate(); }}></looping-ip-mask-dialog>\n    <companyos-dialog class=\"ip-move-dialog\" heading=\"IP-adres verplaatsen\" description=${`Je verplaatst \"${this.#movingIP?.mask ?? \"\"}\" naar een andere naam. Toegang en vergrendeling blijven ongewijzigd.`}\n        pending-label=\"Verplaatsen...\" .open=${mover.open} .pending=${mover.pending} .loadingVisible=${this.#moveLoading.visible} .dirty=${mover.dirty} .error=${mover.formError}\n        @dialog-submit=${() => void this.#submitMove()}\n        @dialog-cancel=${(event: CustomEvent<{ discard: boolean }>) => { if (mover.close(event.detail)) { this.#moveLoading.cancel(); this.#movingIP = null; } }}>\n      <div class=\"companyos-field\">\n        <label class=\"companyos-field__label\" for=\"ip-move-person\">Naar naam</label>\n        <select id=\"ip-move-person\" name=\"personId\" required aria-invalid=${moveError ? \"true\" : \"false\"} aria-describedby=${moveError ? \"ip-move-person-error\" : nothing}\n            @change=${(event: Event) => mover.update({ personId: Number((event.target as HTMLSelectElement).value) })}>\n          <option value=\"0\" ?selected=${mover.draft.personId === 0}>Kies een naam</option>\n          ${(state.workspace?.people ?? []).filter(row => row.id !== person?.id).map(row => html`<option value=${row.id} ?selected=${mover.draft.personId === row.id}>${row.name}</option>`)}\n        </select>\n        ${moveError ? html`<span id=\"ip-move-person-error\" class=\"companyos-field__error\">${moveError}</span>` : nothing}\n      </div>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${closeDialog}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(mover.pending)}>${mover.pending ? \"Verplaatsen...\" : \"Verplaatsen\"}</button>\n      </div>\n    </companyos-dialog>\n    <companyos-dialog class=\"ip-lock-dialog\" heading=\"IP-adres vergrendelen\" description=${`Je vergrendelt \"${state.lockRequest?.mask ?? \"\"}\". Dit beschermt het IP-adres tegen verwijderen, wijzigen en intrekken van bestaande toegang.`}\n        pending-label=\"Vergrendelen...\" .open=${locker.open} .pending=${locker.pending} .loadingVisible=${this.#lockLoading.visible} .dirty=${locker.dirty} .error=${locker.formError}\n        @dialog-submit=${() => void this.#submitLock()}\n        @dialog-cancel=${(event: CustomEvent<{ discard: boolean }>) => { if (locker.close(event.detail)) { this.#lockLoading.cancel(); state.cancelLock(); } }}>\n      <div class=\"companyos-field\">\n        <label class=\"companyos-field__label\" for=\"ip-lock-reason\">Reden voor vergrendeling</label>\n        <textarea id=\"ip-lock-reason\" name=\"reason\" rows=\"3\" maxlength=\"10000\" .value=${locker.draft.reason} aria-invalid=${locker.errors.reason ? \"true\" : \"false\"}\n          aria-describedby=\"ip-lock-reason-hint${locker.errors.reason ? \" ip-lock-reason-error\" : \"\"}\" @input=${(event: Event) => locker.update({ reason: (event.target as HTMLTextAreaElement).value })}></textarea>\n        <span id=\"ip-lock-reason-hint\" class=\"companyos-field__hint\">Optioneel. Leg vast waarom dit IP-adres behouden moet blijven.</span>\n        ${locker.errors.reason ? html`<span id=\"ip-lock-reason-error\" class=\"companyos-field__error\">${locker.errors.reason}</span>` : nothing}\n      </div>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${closeDialog}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(locker.pending)}>${locker.pending ? \"Vergrendelen...\" : \"Vergrendelen\"}</button>\n      </div>\n    </companyos-dialog>\n    <companyos-dialog class=\"ip-unlock-dialog\" alert heading=\"IP-adres ontgrendelen?\" pending-label=\"Ontgrendelen...\" .open=${state.unlockConfirmation !== null} .pending=${state.saving} .error=${state.error}\n        @dialog-submit=${() => void state.confirmUnlock()} @dialog-cancel=${() => state.cancelUnlock()}>\n      <p class=\"ip-confirm-message\">Je ontgrendelt \"${state.unlockConfirmation?.mask ?? \"\"}\". Daarna kan dit IP-adres worden verwijderd of gewijzigd en kan bestaande toegang worden ingetrokken.</p>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${closeDialog}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(state.saving)}>${state.saving ? \"Ontgrendelen...\" : \"Ontgrendelen\"}</button>\n      </div>\n    </companyos-dialog>\n    ${ownIPConfirmationDialog({ className: \"ip-removal-confirmation\", confirmation: state.confirmation, disabled: state.saving, error: state.confirmationError, onConfirm: () => void state.confirmRemoval(), onCancel: () => state.cancelRemoval() })}`;\n  }\n\n  #editIP(ip: IPPersonIP | null): void {\n    if (this.#busy) return;\n    this.#editedIP = ip;\n    this.#maskOpen = true;\n    this.requestUpdate();\n  }\n\n  #ipAction(options: { item: IPPersonIP; actionId: string }): void {\n    const ip = options.item;\n    const locked = getIPLockState({ ip }).locked;\n    if (options.actionId === \"edit\") this.#editIP(ip);\n    else if (options.actionId === \"move\") {\n      this.#movingIP = ip;\n      this.#mover.openCreate();\n    } else if (options.actionId === \"remove\" && !locked) void this.#state.deleteIP(ip);\n    else if (options.actionId === \"lock\") {\n      this.#state.setIPLock({ ip, locked: !locked });\n      if (this.#state.lockRequest) this.#locker.openCreate();\n    }\n  }\n\n  async #submitMove(): Promise<void> {\n    if (await this.#mover.submit()) this.#movingIP = null;\n  }\n\n  async #submitLock(): Promise<void> {\n    if (await this.#locker.submit()) this.#state.cancelLock();\n  }\n\n  #personDialog() {\n    const editor = this.#editor;\n    const label = editor.mode === \"create\" ? \"Aanmaken\" : \"Opslaan\";\n    const field = (name: \"name\" | \"note\") => {\n      const error = editor.errors[name];\n      return { invalid: error ? \"true\" : \"false\", describedBy: error ? `ip-person-${name}-error` : name === \"name\" ? \"ip-person-name-hint\" : nothing, error: error ? html`<span id=\"ip-person-${name}-error\" class=\"companyos-field__error\">${error}</span>` : nothing };\n    };\n    const name = field(\"name\");\n    const note = field(\"note\");\n    return html`<companyos-dialog class=\"ip-person-dialog\" heading=${editor.mode === \"create\" ? \"Naam toevoegen\" : \"Naam bewerken\"} description=\"Bewaar de naam van een persoon, kantoor of dienst bij de IP-adressen.\"\n        pending-label=\"${label}...\" .open=${editor.open} .pending=${editor.pending} .loadingVisible=${this.#dialogLoading.visible} .dirty=${editor.dirty} .error=${editor.formError}\n        @dialog-submit=${() => void this.#dialogLoading.run(() => editor.submit())}\n        @dialog-cancel=${(event: CustomEvent<{ discard: boolean }>) => { if (editor.close({ discard: event.detail.discard })) this.#dialogLoading.cancel(); }}>\n      <div class=\"companyos-field\">\n        <label class=\"companyos-field__label\" for=\"ip-person-name\">Naam</label>\n        <input id=\"ip-person-name\" name=\"name\" autocomplete=\"off\" required .value=${editor.draft.name} aria-invalid=${name.invalid} aria-describedby=${name.describedBy}\n          @input=${(event: InputEvent) => editor.update({ name: (event.target as HTMLInputElement).value })}>\n        <span id=\"ip-person-name-hint\" class=\"companyos-field__hint\">Persoon, kantoor of dienst.</span>\n        ${name.error}\n      </div>\n      <div class=\"companyos-field\">\n        <label class=\"companyos-field__label\" for=\"ip-person-note\">Notitie</label>\n        <textarea id=\"ip-person-note\" name=\"note\" rows=\"3\" .value=${editor.draft.note} aria-invalid=${note.invalid} aria-describedby=${note.describedBy}\n          @input=${(event: InputEvent) => editor.update({ note: (event.target as HTMLTextAreaElement).value })}></textarea>\n        ${note.error}\n      </div>\n      <div slot=\"actions\" class=\"companyos-buttonbar\">\n        <button type=\"button\" class=\"companyos-button\" @click=${() => this.querySelector<CompanyosDialog>(\"companyos-dialog.ip-person-dialog\")?.requestClose()}>Annuleren</button>\n        <button type=\"submit\" class=\"companyos-button companyos-button--primary\" aria-busy=${String(editor.pending)}>${editor.pending ? `${label}...` : label}</button>\n      </div>\n    </companyos-dialog>`;\n  }\n\n  async #openPerson(id: number): Promise<void> {\n    this.#panelOpen = true;\n    this.requestUpdate();\n    if (id !== this.#state.selectedPersonId && !this.#pendingSelection) {\n      this.#pendingSelection = this.#state.selectPerson(id);\n      try { await this.#pendingSelection; } finally { this.#pendingSelection = null; }\n    }\n  }\n\n  async #editPerson(id: number): Promise<void> {\n    // A double-click can arrive before the first click has finished loading the selected record.\n    if (this.#pendingSelection) await this.#pendingSelection;\n    if (id !== this.#state.selectedPersonId) await this.#state.selectPerson(id);\n    const person = this.#state.person;\n    if (person?.id !== id) return;\n    this.#editor.openEdit(createIPPersonDraft({ person }));\n  }\n\n  #navigate(options: { ids: number[]; offset: -1 | 1 }): void {\n    const id = getAdjacentPersonId({ ids: options.ids, currentId: this.#state.selectedPersonId, offset: options.offset });\n    if (id && !this.#busy) void this.#openPerson(id);\n  }\n\n  async #closePanel(): Promise<void> {\n    this.#expanded = false;\n    this.#panelOpen = false;\n    this.requestUpdate();\n    await this.updateComplete;\n    await this.querySelector<CompanyosList>(\".ip-people__list\")?.focusRow(this.#state.selectedPersonId);\n  }\n\n  #onKeydown(event: KeyboardEvent): void {\n    // An open dialog or row menu handles its own Escape; this closes the detail panel step by step.\n    if (event.key !== \"Escape\" || !this.#panelOpen || this.querySelector(\"dialog[open]\") || (event.target as Element).closest(\".companyos-list__menu\") || event.defaultPrevented) return;\n    event.preventDefault();\n    if (this.#expanded) {\n      this.#expanded = false;\n      this.requestUpdate();\n    } else void this.#closePanel();\n  }\n}\n\nif (!customElements.get(\"looping-ip-access\"))\n  customElements.define(\"looping-ip-access\", LoopingIPAccess);\n","// Looping OS on regular CompanyOS pages: the page base, the Looping design system and the Lit IP access element.\n// Lit comes from the CompanyOS screen entry, so the bundle has one copy; no Vue.\nimport \"@mod-companyos/webdesigns/pages/frontend/pages\";\nimport \"./design-system/looping.css\";\nimport \"./ip-access/ip-access\";\nimport { setupWRDAuth } from \"@webhare/frontend\";\n\n// The site's own WRDAuth: logout and the logged-in class need it.\nsetupWRDAuth();\n","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/looping_os.20261102T113007.077Z/webdesigns/loopingos/frontend/frontend\";const aps = globalThis.whAssetPacks ||= {}; aps[\"looping_os:loopingos\"]=\"2026-11-02T11:30:09.088Z\";"],"mapp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lags","localDebugFlags","debugFlagsOverridesCB","DebugFlagsProxyHandler","debugFlagsOverridesCB","localDebugFlags","globalDebugFlags","target","p","record","keys","key","newValue","toModify","runSettingsCallbacks","value","debugFlags","formatForConsoleLogs","cb","settingschangedcallbacks","dtapStage","isLive","backendBase","dtapstage","islive","initEnv","setDtapStage","setBackendBase","getBrowserDebugFlags","varname","flags","urldebugvar","debugcookie","debugcookievalue","flag","config","siteroot","dtapStage","whconfigel","initEnv","flag","getBrowserDebugFlags","debugFlags","frontendConfig","getFrontendData","dataObject","allowMissing","retval","resolve","reject","_resolve","_reject","items","callbackfn","retval","idx","item","key","list","IteratorPrototype","ArrayIteratorPrototype","OriginalIteratorPrototype","callback","it","value","next_value","real_value","max_count","values","limit","remaining","index","mapper","mapped","reducer","initial_value","acc","count","string","final","first","iterables","others","it_array","e","finished","partition1","partition2","i","max","min","isObject","t","GetIteratorFlattenable","obj","method","iterator","Iterator","WrappedIterator","#iterator","args","returnMethod","Iterator_from","submitForm","action","values","method","form","item","input","navigateTo","navigation","getWHType","obj","isCrossRealm","value","isMoney","isTemporalInstant","isTemporalPlainDateTime","isTemporalPlainDate","isTemporalZonedDateTime","isDate","isBlob","isFile","stdTypeOf","value","t","isMoney","isBlob","isFile","isDate","isTemporalInstant","isTemporalPlainDate","isTemporalPlainDateTime","isTemporalZonedDateTime","stripUnneededDecimals","num","decimals","isneg","toText","amount","decimalpoint","mindecimals","isnegative","astext","splitValue","money","split","sign","joinPrice","parts","adjustDecimals","requiredecimals","toadd","multiplier","idx","__add","lhs","rhs","requiredecimals","adjustDecimals","add","amount1","amount2","joinPrice","splitValue","subtract","amount","tosubtract","__multiply","multiply","cmp","diff","getPercentageOfAmount","perc","result","normalize","__roundIntegerToMultiple","value","roundunit","mode","roundToMultiple","unit","split_value","splitValue","split_unit","requiredecimals","adjustDecimals","result","joinPrice","min","amount","amounts","val","cmp","max","getNonNegativePowerOf10","exp","retval","running_exp","divide","divisor","lhs","rhs","mul10exp","mulfactor","test","lhs","relation","rhs","compareresult","cmp","stripUnneededDecimals","num","decimals","isneg","splitValue","money","split","sign","toText","amount","decimalpoint","mindecimals","thousandpoint","isnegative","astext","beforepoint","afterpoint","Money","_Money","value","intvalue","param","isMoney","left","right","sum","item","add","subtract","roundto","mode","roundToMultiple","lhs","rhs","cmp","relation","test","multiply","percentage","getPercentageOfAmount","numerator","divisor","divide","amounts","min","max","format","escapeRegExp","text","options","mask","isHTMLUnrepresentableChar","curch","encodeEntities","str","html","s","char","stringify","arg","options","usereplacer","key","value","origvalue","type","stdTypeOf","lhs","rhs","result","encodeEntities","parseTyped","input","Money","omit","value","keys","elt","ret","key","val","unlock","LocalMutex","defer","LocalLock","mutex","CustomEvent","dispatchCustomEvent","node","event","params","prop","evt","CustomEvent","defaultaction","stop","event","addDocEventListener","node","type","listener","options","locallocks","modallocked","uiwatcher","installedanticancelhandler","currentbusymodaldialog","currentbusymodaluserdialog","busymodalcontent","mylockmgr","getLockmgr","getParentLockManager","LockManager","anyModalLocks","l","scheduleCheckUIFree","checkUIFree","toggleBusyModal","lockmgr","isDialogElement","el","checkCancelEvent","evt","show","dispatchCustomEvent","dialog","toembed","lock","pos","debugFlags","BusyLock","options","lockmgr","getLockmgr","locallocks","modallocked","toggleBusyModal","debugFlags","lockpos","scheduleCheckUIFree","flagUIBusy","options","BusyLock","getParentLockManager","debugFlags","locallocks","l","lockmgr","getLockmgr","locallockmgr","LockManager","lock","mylockmgr","qR","node_or_selector","selector","matches","qSA","isElement","node","isHTMLElement","isDomReady","onDomReady","callback","components","map","isNodeCompletelyInDom","node","processRegistration","item","reg","domready","list","applyRegistration","startnode","isDomReady","items","e","register","selector","handler","options","newreg","components","isDomReady","onDomReady","registerMissed","applyRegistration","startnode","item","getCookie","key","value","escapeRegExp","parseUserAgent","ua","UA","platform","name","version","device","browser","parseUserAgent","getBrowser","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","e","VERTEX","FRAGMENT","hexToRgb","color","i","start","el","gl","compile","type","source","shader","program","position","resolution","time","still","startedAt","frame","draw","now","loop","resize","ratio","onVisibility","visible","canvas","MESSAGES","event","form","error","input","button","register","node","event","UNKNOWN_FUNCTION","parse","stackString","lines","stack","line","parseResult","parseChrome","parseWinjs","parseGecko","parseNode","parseJSC","chromeRe","chromeEvalRe","parts","isNative","isEval","submatch","winjsRe","geckoRe","geckoEvalRe","javaScriptCoreRe","nodeRe","parseTrace","e","parse","i","formatTrace","trace","prependStackTrace","error","stacklines","tracelines","isAbsolute","url","getBaseURL","backendBase","ControlledCall","client","method","stack","options","callurl","fetchoptions","fetchpromise","requestStack","response","exception","retryafter","resolve","jsonresponse","parseTyped","logitem","omit","err","prependStackTrace","RPCClient","debugFlags","error","params","stringify","parseTrace","ServiceProxy","target","prop","receiver","newoptions","rpc","args","service","servicematch","rpcclient","PublicCookieSuffix","authOptions","getCookieName","getFrontendData","getAuthLocalData","c","parseTyped","getCookie","PublicCookieSuffix","submitLoginForm","node","event","_stack","stop","username","password","site","returnto","persistentlogin","login","lock","__using","flagUIBusy","loginresult","refreshLoginStatus","navigateTo","failLogin","_","_error","_hasError","__callDispose","loggedIn","isLoggedIn","setupWRDAuth","options","register","addDocEventListener","evt","handleLogoutClick","doLogout","logout","onDomReady","message","response","form","evtdetail","dispatchCustomEvent","loginfield","qR","getUserInfo","getLoginTweaks","tweaks","urlvars","lang","cookieName","result","rpc","getBrowser","postRenderChecks","log","logtext","onDomReady","DEFAULT_SCHEMA","client","rpc","useRpc","APPS_STATE_ATTRIBUTE","revealApps","root","items","isLoggedIn","visibleAppIds","canManageApps","useRpc","DEFAULT_SCHEMA","isVisible","appId","item","error","trimSlashes","path","followSpaBookmark","dashboard","wanted","target","link","a","b","start","ThemeController","#environment","#theme","#fixedTheme","environment","options","next","createPageTheme","storageKey","onApply","root","controller","ThemeController","next","start","button","theme","displayName","info","combined","setupAccount","account","isLoggedIn","getUserInfo","name","email","button","popover","items","theme","createPageTheme","next","item","candidate","isOpen","open","focus","close","restoreFocus","event","index","move","start","global","globalThis","supportsAdoptingStyleSheets","ShadowRoot","ShadyCSS","nativeShadow","Document","prototype","CSSStyleSheet","constructionToken","Symbol","cssTagCache","WeakMap","CSSResult","cssText","strings","safeToken","this","Error","_strings","styleSheet","_styleSheet","cacheable","length","get","replaceSync","set","toString","unsafeCSS","value","String","adoptStyles","renderRoot","styles","supportsAdoptingStyleSheets","adoptedStyleSheets","map","s","CSSStyleSheet","styleSheet","style","document","createElement","nonce","global","setAttribute","textContent","cssText","appendChild","getCompatibleStyle","sheet","rule","cssRules","unsafeCSS","is","defineProperty","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","Object","global","globalThis","trustedTypes","emptyStringForBooleanAttribute","emptyScript","polyfillSupport","reactiveElementPolyfillSupport","JSCompiler_renameProperty","prop","_obj","defaultConverter","value","type","Boolean","Array","JSON","stringify","fromValue","Number","parse","e","notEqual","old","defaultPropertyDeclaration","attribute","String","converter","reflect","useDefault","hasChanged","Symbol","metadata","litPropertyMetadata","WeakMap","ReactiveElement","HTMLElement","initializer","this","__prepare","_initializers","push","observedAttributes","finalize","__attributeToPropertyMap","keys","name","options","state","prototype","hasOwnProperty","create","wrapped","elementProperties","set","noAccessor","key","descriptor","getPropertyDescriptor","get","v","oldValue","call","requestUpdate","configurable","enumerable","superCtor","Map","finalized","props","properties","propKeys","p","createProperty","attr","__attributeNameForProperty","elementStyles","finalizeStyles","styles","isArray","Set","flat","Infinity","reverse","s","unshift","getCompatibleStyle","toLowerCase","constructor","super","__instanceProperties","isUpdatePending","hasUpdated","__reflectingProperty","__initialize","__updatePromise","Promise","res","enableUpdating","_$changedProperties","__saveInstanceProperties","forEach","i","controller","__controllers","add","renderRoot","isConnected","hostConnected","delete","instanceProperties","size","createRenderRoot","shadowRoot","attachShadow","shadowRootOptions","adoptStyles","connectedCallback","c","_requestedUpdate","disconnectedCallback","hostDisconnected","_old","_$attributeToProperty","attrValue","toAttribute","removeAttribute","setAttribute","ctor","propName","getPropertyOptions","fromAttribute","convertedValue","__defaultValues","useNewValue","newValue","hasAttribute","_$changeProperty","__enqueueUpdate","initializeValue","has","__reflectingProperties","reject","result","scheduleUpdate","performUpdate","shouldUpdate","changedProperties","willUpdate","hostUpdate","update","__markUpdated","_$didUpdate","_changedProperties","hostUpdated","firstUpdated","updated","updateComplete","getUpdateComplete","__propertyToAttribute","mode","reactiveElementVersions","global","globalThis","wrap","node","trustedTypes","policy","createPolicy","createHTML","s","boundAttributeSuffix","marker","Math","random","toFixed","slice","markerMatch","nodeMarker","d","document","createMarker","createComment","isPrimitive","value","isArray","Array","isIterable","Symbol","iterator","SPACE_CHAR","textEndRegex","commentEndRegex","comment2EndRegex","tagEndRegex","RegExp","singleQuoteAttrEndRegex","doubleQuoteAttrEndRegex","rawTextElement","tag","type","strings","values","_$litType$","html","svg","mathml","noChange","for","nothing","templateCache","WeakMap","walker","createTreeWalker","trustFromTemplateString","tsa","stringFromTSA","hasOwnProperty","Error","getTemplateHtml","l","length","attrNames","rawTextEndRegex","regex","i","attrName","match","attrNameEndIndex","lastIndex","exec","test","end","startsWith","push","Template","constructor","options","this","parts","nodeIndex","attrNameIndex","partCount","el","createElement","currentNode","content","wrapper","firstChild","replaceWith","childNodes","nextNode","nodeType","hasAttributes","name","getAttributeNames","endsWith","realName","statics","getAttribute","split","m","index","ctor","PropertyPart","BooleanAttributePart","EventPart","AttributePart","removeAttribute","tagName","textContent","emptyScript","append","data","indexOf","_options","innerHTML","resolveDirective","part","parent","attributeIndex","currentDirective","__directives","__directive","nextDirectiveConstructor","_$initialize","_$resolve","TemplateInstance","template","_$parts","_$disconnectableChildren","_$template","_$parent","parentNode","_$isConnected","fragment","creationScope","importNode","partIndex","templatePart","ChildPart","nextSibling","ElementPart","_$setValue","__isConnected","startNode","endNode","_$committedValue","_$startNode","_$endNode","isConnected","directiveParent","_$clear","_commitText","_commitTemplateResult","_commitNode","_commitIterable","insertBefore","_insert","createTextNode","result","_$getTemplate","h","_update","instance","_clone","get","set","itemParts","itemPart","item","start","from","_$notifyConnectionChanged","n","remove","element","fill","String","valueIndex","noCommit","change","v","_commitValue","setAttribute","toggleAttribute","super","newListener","oldListener","shouldRemoveListener","capture","once","passive","shouldAddListener","removeEventListener","addEventListener","event","call","host","handleEvent","polyfillSupport","global","litHtmlPolyfillSupport","Template","ChildPart","litHtmlVersions","push","render","value","container","options","partOwnerNode","renderBefore","part","endNode","insertBefore","createMarker","_$setValue","global","globalThis","LitElement","ReactiveElement","constructor","this","renderOptions","host","__childPart","createRenderRoot","renderRoot","super","renderBefore","firstChild","changedProperties","value","render","hasUpdated","isConnected","update","connectedCallback","setConnected","disconnectedCallback","noChange","litElementHydrateSupport","polyfillSupport","litElementPolyfillSupport","global","litElementVersions","push","UNSAVED_ATTRIBUTE","GUARD","SCOPE","submittedScopes","leaving","scopeOf","node","form","scope","hasUnsavedChanges","root","markUnsaved","event","REGISTERED","register","CompanyosSections","i","#sections","#label","#active","#adopt","b","section","label","#select","isUnsaved","nav","hostId","host","link","UNSAVED_ATTRIBUTE","event","#revealError","selected","name","error","field","target","focus","entry","heading","actionKind","action","actionRank","kind","getMenuActions","options","ordered","left","right","firstOtherAction","index","normalized","getMenuPosition","nextListSort","options","ifDefined","value","nothing","ICON_DATA","icon","name","size","b","ICON_DATA","tag","attrs","w","o","CONTROL","FIELD","CompanyosList","i","#cursor","#menu","item","root","key","#keys","row","element","changed","keys","actions","b","#onKeydown","column","A","#heading","#row","#renderMenu","menu","trigger","anchor","position","getMenuPosition","sortable","sorted","align","#onSort","icon","selected","#select","event","#onDoubleClick","#onContextMenu","#checkCell","#textCell","#openMenu","raw","text","badge","checked","getMenuActions","#onMenuToggle","#onMenuKeydown","action","#onAction","#emit","type","detail","nextListSort","index","target","#closeMenu","focusTrigger","active","items","next","actionId","lastId","CompanyosDialog","i","#id","#content","#opener","#discardOrigin","#confirmingDiscard","#actionsDisabled","active","#dialog","disabled","b","A","#onCancel","#onClose","#onBackdrop","#onSubmit","#keepEditing","#discard","changed","fields","actions","node","dialog","shown","wasReady","#ready","#focusAfterSave","invalid","event","rect","origin","activeTabKey","options","item","nextTabKey","enabled","index","lastId","CompanyosTabs","i","#id","#observer","root","records","record","items","#items","active","#active","b","event","#onKey","item","#tabId","#panelId","#select","changed","panel","#panels","value","child","activeTabKey","target","nextTabKey","browserClock","callback","delayMs","timer","ToastController","#clock","#onChange","#entries","#nextId","options","entry","id","oldest","#schedule","#publish","REGION_CLASS","controller","ensure","region","created","ToastController","messages","D","message","toast","owner","id","tone","b","icon","showToast","options","ensure","browserClock","callback","delayMs","timer","LoadingController","#clock","#delayMs","#minimumMs","#onChange","#operations","#visible","#visibleSince","#cancelShow","#cancelHide","#disposed","#revision","options","operation","revision","abort","#publish","#finishPresentation","remaining","FormSubmissionError","options","LoadingStateController","#state","#controller","host","options","LoadingController","state","operation","SAVE_FAILED","CrudDialogController","#host","#options","#draft","#baseline","#open","#mode","#pending","#errors","#formError","#abort","#revision","#focusRevision","#clone","patch","errors","field","#reset","value","#validate","revision","cause","#applyError","#setErrors","next","first","FormSubmissionError","getIPSkeletonKind","options","getIPHeaderDisabled","activity","getIPReloadPersonId","getIPAccessTabs","section","getIPLockState","options","locked","getIPLockChangeIntent","validateIPLockDraft","draft","hasProtectedAccess","ip","createIPPersonDraft","options","person","validateIPPersonDraft","draft","errors","parseAddress","input","octets","part","value","octet","address","separator","ipv4","halves","left","right","missing","groups","group","mappedIPv4","parseMask","parts","legacyPrefix","firstWildcard","network","prefix","validateIPMask","mask","ipMaskMatches","options","parsed","shift","isNetworkMask","filterPeople","terms","person","searchable","term","historyInPeriod","since","entry","timestamp","historyLabels","historyActionLabel","action","historyLockReason","reason","mergePerson","historyForPerson","personIds","addedSource","target","source","historyMoveSummary","from","to","historyMergeSummary","sources","names","count","getVisiblePeople","options","collator","filterPeople","left","right","comparison","getAdjacentPersonId","index","getMaskDraft","options","validateMaskDraft","draft","errors","maskError","validateIPMask","describeSaveError","cause","message","textFields","label","field","rpc","schema","IPAccessController","#host","#lifecycle","#loadingKind","#pendingRemoval","#detailRequest","#pendingPersonId","#disposed","host","LoadingStateController","getIPSkeletonKind","getIPHeaderDisabled","#set","#reload","cause","#report","id","#loadDetail","options","FormSubmissionError","result","#readBack","showToast","describeSaveError","name","row","intent","getIPLockChangeIntent","draft","ip","own","ipMaskMatches","#runRemoval","confirmed","current","hasProtectedAccess","masks","mask","pending","patch","personId","#showConfirmation","currentIp","request","workspace","history","getIPReloadPersonId","ownIPConfirmationDialog","options","confirmation","b","mask","event","PERIODS","dateLabel","timestamp","date","details","entry","summary","historyMergeSummary","historyMoveSummary","masks","mask","values","value","reason","historyLockReason","LoopingIPHistory","i","#period","#personId","columns","historyActionLabel","person","entries","historyInPeriod","historyForPerson","b","event","period","LoopingIPMaskDialog","i","#loading","LoadingStateController","#editor","CrudDialogController","getMaskDraft","validateMaskDraft","draft","result","#confirmedUnlock","#confirmedOwnRemoval","#pendingConfirmation","FormSubmissionError","#ownConfirmation","#unlockConfirmation","#hideRefusal","changed","editor","lockState","getIPLockState","loginHint","isNetworkMask","target","maskHint","b","#submit","event","#cancel","#textField","A","reason","#toggleTarget","#confirmUnlock","#cancelUnlock","ownIPConfirmationDialog","#confirmOwnRemoval","#cancelOwnRemoval","options","error","describedBy","input","ids","id","left","right","getIPLockChangeIntent","#close","refusal","PEOPLE_COLUMNS","PEOPLE_ACTIONS","matrixColumns","targets","ip","target","ipActions","locked","getIPLockState","iconButton","options","b","A","icon","skeleton","kind","bar","LoopingIPAccess","i","#state","IPAccessController","#dialogLoading","LoadingStateController","#editor","CrudDialogController","createIPPersonDraft","validateIPPersonDraft","draft","#panelOpen","#moveLoading","#mover","#movingIP","#lockLoading","#locker","validateIPLockDraft","#view","#query","#sort","#expanded","#pendingSelection","#maskOpen","#editedIP","#busy","state","#peopleBusy","#visiblePeople","getVisiblePeople","sections","getIPAccessTabs","#onKeydown","event","section","#people","#personDialog","#ipDialogs","rows","total","row","#openPerson","#editPerson","#detailPanel","ids","index","personSkeleton","#navigate","#closePanel","#details","person","protectedAccess","hasProtectedAccess","canRevoke","#editIP","#ipAction","mover","locker","moveError","closeDialog","#submitMove","#submitLock","ownIPConfirmationDialog","editor","label","field","name","error","note","id","getAdjacentPersonId","setupWRDAuth","aps"]}