{"version":3,"sources":["@webhare/env/src/envbackend.ts","@webhare/dompack/src/tree.ts","@webhare/std/src/quacks.ts","@webhare/std/src/datetime.ts","@webhare/std/src/promises.ts","@webhare/std/src/finmath.ts","@webhare/std/src/money.ts","@webhare/std/src/types.ts","@webhare/std/src/strings.ts","@webhare/std/src/platformbased.ts","@webhare/std/src/collections.ts","@webhare/std/src/utils.ts","@webhare/std/src/localmutex.ts","@webhare/std/src/std.ts","@webhare/env/src/navigation.ts","@webhare/env/src/fetchdebug.ts","@webhare/env/src/whglobal.ts","@webhare/env/src/env.ts","@webhare/gettid/src/hooks.ts","@webhare/gettid/src/internal.ts","@webhare/frontend/src/init.ts","@webhare/env/src/init-browser.ts","@webhare/tsrun/src/polyfills.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","@webhare/dompack/src/busy.ts","mod::system/js/dompack/src/events.ts","@webhare/dompack/src/dompack.ts","mod::system/js/dompack/src/tree.ts","@webhare/dompack/src/storage.ts","@webhare/dompack/src/browser.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::paswerk/api/interest-validation.ts","@webhare/gettid/src/gettid.ts","mod::paswerk/web/widgets/widgets.lang.json","mod::paswerk/web/offer-calendar.ts","mod::paswerk/web/widgets/logic.ts","mod::paswerk/web/widgets/booking-logic.ts","mod::paswerk/web/widgets/widgets.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\n/// Empty or no parameter lang is get, otherwise it's a set\nexport type GetSetAssetBase = (assetBase?: string | null) => string | null;\n\nexport type EnvHooks = {\n  currentAssetBase: GetSetAssetBase;\n};\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\nexport function updateLocalDebugFlags(mode: \"enable\" | \"disable\" | \"clear\", flags: string[]): DebugFlags {\n  switch (mode) {\n    case \"enable\":\n    case \"disable\":\n      for (const flag of flags)\n        localDebugFlags[flag] = mode === \"enable\";\n      break;\n    case \"clear\":\n      for (const flag of Object.keys(localDebugFlags))\n        delete localDebugFlags[flag];\n  }\n  runSettingsCallbacks();\n  return { ...globalDebugFlags, ...localDebugFlags };\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/** The global assetbase */\nlet assetBase: string | null = null;\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\nlet hooks: EnvHooks | undefined;\nlet hookFactory: (() => EnvHooks) | undefined;\nlet gotHooks = false;\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 function setEnvHooksFactory(newHookFactory: () => EnvHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setEnvHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getEnvHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n\nfunction ensureHooks(): EnvHooks {\n  return hooks ??= getEnvHooks?.() ?? {\n    currentAssetBase: (newAssetBase) => {\n      if (newAssetBase !== undefined)\n        assetBase = newAssetBase;\n      return assetBase;\n    }\n  };\n}\n\n/** Get the base url for assets. This may point towards eg. a CDN\n * @returns The base url for assets, ending with a '/'. null if not set\n */\nexport function getAssetBase(): string | null {\n  return ensureHooks().currentAssetBase();\n}\n\n/** Get the base url for a module's public assets (those located in the module's `public` folder)\n */\nexport function getModulePublicAssetBase(module: string) {\n  return `${getAssetBase() || \"/\"}.wh/mod/${encodeURIComponent(module)}/public/`;\n}\n\n/** Set the base url for assets */\nexport function setAssetBase(base: string | null): void {\n  if (base && !base.endsWith(\"/\"))\n    throw new Error(`Asset base must end with a '/'`);\n\n  ensureHooks().currentAssetBase(base);\n}\n\nexport { dtapStage, isLive, backendBase, localDebugFlags };\nexport { dtapstage, islive }; //deprecated variants\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\nexport type ParsedLanguageTag = {\n  /** The full tag, eg en-US */\n  tag: string;\n  /** The language code, eg 'en' */\n  language: string;\n  region?: string;\n  /** The script, eg 'Hant' */\n  script?: string;\n};\n\n/** Parse a BCP47 language tag */\nexport function parseLanguageTag(languageTag: string): ParsedLanguageTag {\n  /* https://datatracker.ietf.org/doc/html/rfc5646#section-2.1\n     langtag       = language\n                 [\"-\" script]\n                 [\"-\" region]\n                 *(\"-\" variant)\n                 *(\"-\" extension)\n                 [\"-\" privateuse]\n     BUT: we're limiting ourselves to language, script and region for now\n\n     language      = 2*3ALPHA           ; shortest ISO 639 code\n                    [\"-\" extlang]       ; sometimes followed by\n                                          extended language subtags\n\n                                           extlang       = 3ALPHA              ; selected ISO 639 codes\n                 *2(\"-\" 3ALPHA)      ; permanently reserved\n\n      script        = 4ALPHA              ; ISO 15924 code\n\n      region        = 2ALPHA              ; ISO 3166-1 code\n                    / 3DIGIT              ; UN M.49 code\n\n     Note that we're not yet fully implementing the spec, just the parts we expect to encounter in practice\n  */\n  const match = languageTag.match(/^([a-z]{2,}(-[a-z]{3})?)(-[A-Za-z]{4,})?(-[A-Z]{2}|-\\d{3})?$/);\n  if (!match)\n    throw new Error(`Invalid language tag: ${languageTag}`);\n\n  return {\n    tag: languageTag,\n    language: match[1],\n    ...(match[3] ? { script: match[3].substring(1) } : {}),\n    ...(match[4] ? { region: match[4].substring(1) } : {})\n  };\n}\n\n/** Get the effective language for an element (or the document)\n * @param node - The element for which to get the effective language. If not specified, the documentElement and finally the browser is used\n * @returns The language code, eg. \"nl\" or \"en-GB\"\n */\nexport function getLang(node?: Element): ParsedLanguageTag {\n  if (!node && typeof document !== \"undefined\")\n    node = document.documentElement;\n  const tag = (node?.closest('[lang]')?.getAttribute(\"lang\") || navigator.language || \"en\");\n  return parseLanguageTag(tag);\n}\n","//TODO can we replace ourselves with nodejs util.types in a pure NodeJS environment?\n\nimport type { Money } from \"./money.ts\";\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.PlainTime */\nexport function isTemporalPlainTime(value: unknown): value is Temporal.PlainTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainTime');\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: T | Promise<T>): e is Promise<Awaited<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\" | \"PlainTime\" | \"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 (isTemporalPlainTime(value))\n      return \"PlainTime\";\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","import { isDate, isTemporalInstant } from \"./quacks.ts\";\n\n/** A tolerant JS date parameter */\nexport type FlexibleInstant = Date | Temporal.Instant | Temporal.ZonedDateTime;\n\n/** A relative (up to a week) or absolute wait period. Use 0 for 'polling' and Infinity to indicate an endless waits. Numbers are interpreted to be in milliseconds, a string is interpreted as a ISO8601 duration */\nexport type WaitPeriod = 0 | number | string | FlexibleInstant;\nexport interface Duration {\n  sign: \"+\" | \"-\";\n  years: number;\n  months: number;\n  weeks: number;\n  days: number;\n  hours: number;\n  minutes: number;\n  seconds: number;\n  milliseconds: number;\n}\n\nfunction parseMS(ms: string): number {\n  if (ms.length === 2) //.5\n    return parseInt(ms.substring(1)) * 100;\n  if (ms.length === 3) //.54\n    return parseInt(ms.substring(1)) * 10;\n  return parseInt(ms.substring(1, 4));\n}\n\n/** Parse an ISO8601 duration\n * @param duration - ISO8601 duration string (e.g. \"P1Y2M3DT4H5M6S\")\n */\nexport function parseDuration(duration: string): Duration {\n  // const matches = duration.match(/(-)?P(?:([.,\\d]+)Y)?(?:([.,\\d]+)M)?(?:([.,\\d]+)W)?(?:([.,\\d]+)D)?T(?:([.,\\d]+)H)?(?:([.,\\d]+)M)?(?:([.,\\d]+)S)?/);\n  const matches = duration.match(/^(-)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(\\.\\d+)?S)?)?$/);\n  if (!matches ||\n    (matches[4] && (matches[2] || matches[3] || matches[5])) || //can't have weeks and years/months/days\n    !(matches[2] || matches[3] || matches[4] || matches[5] || matches[6] || matches[7] || matches[8])) //one component must be present\n    throw new Error(`Invalid ISO8601 duration '${duration}'`);\n\n  return {\n    sign: matches[1] ? '-' : '+',\n    years: parseInt(matches[2]) || 0,\n    months: parseInt(matches[3]) || 0,\n    weeks: parseInt(matches[4]) || 0,\n    days: parseInt(matches[5]) || 0,\n    hours: parseInt(matches[6]) || 0,\n    minutes: parseInt(matches[7]) || 0,\n    seconds: parseInt(matches[8]) || 0,\n    milliseconds: matches[9] ? parseMS(matches[9]) : 0\n  };\n}\n\n/** Add a duration (time) to a date\n * @param startingdate - Date to start from\n * @param duration - Duration to add (as object or as ISO8601 duration string, eg \"P1Y2M3DT4H5M6S\")\n */\nexport function addDuration(startingdate: Date, duration: Partial<Duration> | string): Date;\nexport function addDuration(startingdate: Temporal.Instant, duration: Partial<Duration> | string): Temporal.Instant;\n\nexport function addDuration(startingdate: Date | Temporal.Instant, duration: Partial<Duration> | string): Date | Temporal.Instant {\n  if (isTemporalInstant(startingdate))\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(addDuration(new Date(startingdate.epochMilliseconds), duration).getTime());\n\n  //we cannot take timezones (flexible instant) yet? as we do not timezone correct day/week/month calculations\n  if (typeof duration === \"string\")\n    duration = parseDuration(duration);\n\n  const direction = duration.sign === \"-\" ? -1 : 1;\n  const date = new Date(startingdate.getTime());\n  if (duration.years)\n    date.setUTCFullYear(date.getUTCFullYear() + direction * duration.years);\n  if (duration.months)\n    date.setUTCMonth(date.getUTCMonth() + direction * duration.months);\n\n  const modifydays = (duration.days ?? 0) + (duration.weeks ?? 0) * 7;\n  if (modifydays)\n    date.setUTCDate(date.getUTCDate() + direction * modifydays);\n\n  const timeoffset = (duration.hours ?? 0) * 60 * 60 * 1000 + (duration.minutes ?? 0) * 60 * 1000 + (duration.seconds ?? 0) * 1000 + (duration.milliseconds ?? 0);\n  date.setTime(date.getTime() + direction * timeoffset);\n\n  return date;\n}\n\n/** Subtract a duration (time) from a date\n * @param startingdate - Date to start from\n * @param duration - Duration to subtract (as object or as ISO8601 duration string, eg \"P1Y2M3DT4H5M6S\")\n */\nexport function subtractDuration(startingdate: Date, duration: Partial<Duration> | string): Date;\nexport function subtractDuration(startingdate: Temporal.Instant, duration: Partial<Duration> | string): Temporal.Instant;\n\nexport function subtractDuration(startingdate: Date | Temporal.Instant, duration: Partial<Duration> | string): Date | Temporal.Instant {\n  if (isTemporalInstant(startingdate))\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(subtractDuration(new Date(startingdate.epochMilliseconds), duration).getTime());\n\n  if (typeof duration === \"string\")\n    duration = parseDuration(duration);\n\n  return addDuration(startingdate, { ...duration, sign: duration?.sign === \"-\" ? \"+\" : \"-\" });\n}\n\n/** Convert a flexible instant to a date\n * @param input - Date, Temporal.Instant or Temporal.ZonedDateTime value to convert\n * @returns The converted date (or null if the input is null)\n */\nexport function convertFlexibleInstantToDate(input: FlexibleInstant): Date;\nexport function convertFlexibleInstantToDate(input: null | undefined): null;\nexport function convertFlexibleInstantToDate(input: FlexibleInstant | null | undefined): Date | null;\n\nexport function convertFlexibleInstantToDate(input: FlexibleInstant | null | undefined): Date | null {\n  return input ? \"epochMilliseconds\" in input ? new Date(input.epochMilliseconds) : input : null;\n}\n\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options: { relativeTo: Temporal.Instant }): Temporal.Instant;\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options?: { relativeTo?: Date }): Date;\n\n/** Convert a WaitPeriod parameter to a Date\n * @param wait - Wait time as milliseconds or a Date\n * @param options - Options for conversion\n * @param options.relativeTo - Date to use as a reference for relative waits\n*/\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options?: { relativeTo?: Date | Temporal.Instant }): Date | Temporal.Instant {\n  if (options?.relativeTo && isTemporalInstant(options?.relativeTo)) { //then our caller expects a Temporal.Instant\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(\n      convertWaitPeriodToDate(wait, { relativeTo: new Date(options?.relativeTo.epochMilliseconds) }).getTime()\n    );\n  }\n\n  if (isDate(wait)) {\n    return wait;\n  } else if (typeof wait === \"string\") {\n    return addDuration(convertFlexibleInstantToDate(options?.relativeTo) ?? new Date(), wait); //NOTE that \"P1D\" here adds \"24 hours\" which is *not* correct for a TimeZonedDate - which is why convertWaitPeriodToDate cannot yet accept these\n  } else if (typeof wait === \"number\") {\n    if (wait === 0)\n      return new Date(-864000 * 1000 * 10000000);\n    if (wait === Infinity)\n      return new Date(864000 * 1000 * 10000000);\n    if (wait > 0) //note: options?.relativeTo can't be instant, we already eliminated that above\n      return new Date(((options?.relativeTo as Date | undefined)?.getTime() ?? Date.now()) + wait);\n  } else if (wait && \"epochMilliseconds\" in wait) { //Instant or ZonedDateTime\n    return new Date(wait.epochMilliseconds);\n  }\n\n  throw new Error(\"Invalid wait duration - it must either be an absolute date, 0, a number of milliseconds or Infinity\");\n}\n\n/** Check whether the specified parts make a valid and reasonable (usually 1600+) date */\nexport function isValidDate(year: number, month: number, day: number, { minYear = 1601 } = {}) {\n  if (!(year >= minYear && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= 31\n    && Number.isSafeInteger(year) && Number.isSafeInteger(month) && Number.isSafeInteger(day)))\n    return false;\n  if ([4, 6, 9, 11].includes(month) && day > 30) //handle april, june, sep, nov\n    return false;\n  const isleapyear = (year % 400) === 0 || ((year % 100) !== 0 && (year % 4) === 0);\n  if (month === 2 && day > (isleapyear ? 29 : 28))\n    return false;\n  return true;\n}\n\n/** Check whether the specified parts make a reasonable time (does not consider the leap second a valid time) */\nexport function isValidTime(hour: number, minute: number, second: number, msec: number) {\n  return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59 && msec >= 0 && msec <= 999\n    && Number.isSafeInteger(hour) && Number.isSafeInteger(minute) && Number.isSafeInteger(second) && Number.isSafeInteger(msec);\n}\n\n/** Returns a string containing a formatted date and time.\n * @param format  A string that specifies the format of the output string. The string can contain the following:\n%%  Character %\n%a  Abbreviated weekday name\n%A  Full weekday name\n%b  Abbreviated month name\n%B  Full month name\n%d  Two-digit day of month (01 - 31)\n%#d Two-digit day of month, remove any leading zeros\n%H  Hour of the day, 24 hour day\n%#H Hour of the day, 24 hour day, remove any leading zeros\n%I  Two-digit hour, 12 hour day (01 - 12)\n%#I Two-digit hour, 12 hour day, remove any leading zeros\n%j  Three-digit day of year (001 - 366)\n%#j Three-digit day of year, remove any leading zeros\n%m  Two-digit month number (01 - 12)\n%#m Two-digit month number, remove any leading zeros\n%M  2-digit minute (00 - 59)\n%#M 2-digit minute, remove leading any zeros\n%Q  Three-digit millisecond (000-999)\n%#Q Three-digit millisecond, remove any leading zeros\n%p  AM or PM\n%S  Two-digit second (00 - 59)\n%#S Two-digit second, remove leading any zeros\n%V  Two-digot week number (00 - 52)\n%#V One-digit week number (0 - 52)\n%y  Two-digit year without century (00 to 99)\n%#y Two-digit year without century, remove any leading zeros\n%Y  Year with century\n%#Y Year with century, remove any leading zeros\n   @param zdt          The date/time value to format.\n   @example\n// The current date and time in German in the format: 01 Januar 2005\nconst example1 = formatDateTime(\"%d %B %Y\", Temporal.Instant.now(), { locale: \"de-DE\" });\n\n// The current day of the week in the Dutch language, using the\n// parameter datetexts as language switch.\n// The date format is <abbreviated> - <full>.\nconst example2 = formatDateTime(\"%a - %B \", new Date, { locale: \"nl-NL\" });\n*/\n\nexport function formatDateTime(format: string, zdt: Temporal.ZonedDateTime, options?: { locale: string }): string {\n  //TODO consider allowing Date & Instant too? might avoid users going for things like toString().replace(\"T\", \" \").replace(\"Z\", \"\")\n  //const zdt: Temporal.ZonedDateTime = date instanceof Date ? date.toTemporalInstant().toZonedDateTimeISO('UTC') : \"year\" in date ? date : date.toZonedDateTimeISO('UTC');\n  const locale = options?.locale || 'en-US';\n  let stripZeroes = false;\n\n  function formatNumber(num: number, length: number): string {\n    return stripZeroes ? num.toString() : num.toString().padStart(length, '0');\n  }\n\n  function formatPart(spec: string): string {\n    switch (spec) {\n      case 'a': //dayofweek name, abbreviated\n        return zdt.toLocaleString(locale, { weekday: 'short' });\n      case 'A': //dayofweek name, full\n        return zdt.toLocaleString(locale, { weekday: 'long' });\n      case 'b':  //month name, abbreviated\n        return zdt.toLocaleString(locale, { month: 'short' });\n      case 'B': //month name, abbreviated\n        return zdt.toLocaleString(locale, { month: 'long' });\n      case 'C': //century number\n        return formatNumber(Math.floor(zdt.year / 100), 2);\n      case 'd':  //day of month\n        return formatNumber(zdt.day, 2);\n      case 'H':  //hour of the day (24 hours format)\n        return formatNumber(zdt.hour, 2);\n      case 'I'://hour of the day (12 hours format)\n        return formatNumber((zdt.hour % 12) || 12, 2);\n      case 'j'://day of the year (three-digit)\n        return formatNumber(zdt.dayOfYear, 3);\n      case 'M'://two digit minute\n        return formatNumber(zdt.minute, 2);\n      case 'm'://two digit month\n        return formatNumber(zdt.month, 2);\n      case 'p'://am/pm\n        //Unfortunately this doesn't return am/pm: return zdt.toLocaleString(locale, { dayPeriod: 'narrow', hourCycle: \"h12\" });\n        return zdt.hour < 12 ? \"am\" : \"pm\";\n      case 'Q'://three digit millisecond\n        return formatNumber(Math.floor(zdt.millisecond), 3);\n      case 'S'://two digit second\n        return formatNumber(zdt.second, 2);\n      case 'V'://week number\n        if (zdt.weekOfYear === undefined)\n          throw new Error(\"Week of year is not defined for this calendar\");\n        return formatNumber(zdt.weekOfYear, 2);\n      case 'Y'://year, with century\n        return formatNumber(zdt.year, 4);\n      case 'y'://year, without century\n        return formatNumber(zdt.year % 100, 2);\n      default:\n        throw new Error(`Invalid date format specifier '%${spec}'`);\n    }\n  }\n\n  let out = '', inSpecifier = false;\n  for (const spec of [...format]) {\n    if (inSpecifier) {\n      if (spec === '#') {\n        stripZeroes = true;\n        continue; //get the next char\n      }\n\n      inSpecifier = false;\n      if (spec === '%') {\n        out += '%';\n        continue;\n      }\n      out += formatPart(spec);\n    } else {\n      if (spec === '%') {\n        inSpecifier = true;\n        stripZeroes = false; //reset it\n        continue;\n      }\n      out += spec;\n    }\n  }\n  if (inSpecifier)\n    throw new Error(\"Invalid date format string, ends with single %\");\n\n  return out;\n}\n","import { type WaitPeriod, convertWaitPeriodToDate } from \"./datetime.ts\";\nimport { isPromise } from \"./quacks.ts\";\n\n//TODO Deprecate once everyone is WH5.5+\nexport type DeferredPromise<T> = PromiseWithResolvers<T>;\n\n/** A promise that sleeps for the specified number of milliseconds\n *  @param duration - Relative (milliseconds, but not Infinity) or absolute (Date) wait duration. May not be Infinity\n *  @param options - Options - `signal` to set an AbortSignal which will canel this sleep\n*/\nexport function sleep(duration: WaitPeriod, options?: { signal?: AbortSignal }): Promise<void> {\n  if (duration === Infinity)\n    throw new Error(`A sleep may not be infinite`);\n\n  const until = convertWaitPeriodToDate(duration);\n  return new Promise(resolve => {\n    const timeoutid = setTimeout(resolve, Math.max(0, until.getTime() - Date.now()));\n    if (options?.signal)\n      options.signal.addEventListener(\"abort\", () => clearTimeout(timeoutid));\n  });\n}\n\n/** @deprecated Use Promise.withResolvers instead */\nexport function createDeferred<T>(): PromiseWithResolvers<T> {\n  return Promise.withResolvers<T>();\n}\n\n/** Wrap a promise in a timeout\n * @param promise - Promise to wrap\n * @param timeout - Timeout in milliseconds or as a Date\n * @param rejectWith - Error to reject with if the timeout expires (string, Error, or a callback returning one)\n*/\nexport function wrapInTimeout<T>(promise: Promise<T>, timeout: WaitPeriod, rejectWith: string | Error | (() => string | Error)): Promise<T> {\n  if (timeout === Infinity)\n    return promise;\n\n  const until = convertWaitPeriodToDate(timeout);\n  const timeoutpromise = new Promise<T>((resolve, reject) => {\n    const timer = setTimeout(() => {\n      //this approach allows to delay actual Error object construction\n      const error: string | Error = typeof rejectWith === \"function\" ? rejectWith() : rejectWith;\n      reject(typeof error === \"object\" ? error : new Error(error));\n    }, until.getTime() - Date.now());\n\n    //ensure timer cancellation. No need to wait on this promise\n    promise = promise.finally(() => clearTimeout(timer));\n  });\n\n  return Promise.race([promise, timeoutpromise]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we need to accept any callback.\ntype CallbackFunctionVariadic<RetType> = (...args: any[]) => Promise<RetType>;\n\nexport interface SerializeOptions {\n  ///Coalescing will ignore intermediate calls if the original call has not completed yet. Eg when invoking functions 1,2,3 in succession, only 3 will run, calls 1 and 2 will be merged into that call\n  coalesce?: boolean;\n}\n\nclass Coalescer<RetVal> {\n  private queue: Array<PromiseWithResolvers<RetVal>> = [];\n  private call: CallbackFunctionVariadic<RetVal> | null = null;\n  private readonly fn: CallbackFunctionVariadic<RetVal>;\n\n  //invoke is the actual entry point for incoming calls (ie C++'s operator() )\n  readonly invoke: CallbackFunctionVariadic<RetVal>;\n\n  constructor(fn: CallbackFunctionVariadic<RetVal>) {\n    this.invoke = this.onInvoke.bind(this);\n    this.fn = fn;\n  }\n  private onInvoke(...args: unknown[]): Promise<RetVal> {\n    //overwrite the call to execute\n    this.call = () => this.fn(...args); //TODO just queueing the parameters might do?\n\n    if (!this.queue.length) //schedule a flush of the queue\n      setTimeout(() => void this.flush(), 0);\n\n    this.queue.push(Promise.withResolvers<RetVal>());\n    return this.queue[this.queue.length - 1].promise;\n  }\n\n  private async flush() {\n    for (let startpos = 0; this.queue && startpos < this.queue?.length;) {\n      const currentpos = this.queue?.length;\n\n      try {\n        //invoke the last known call. *NOTE* new calls may be added to the queue now\n        const result = await this.call!();\n        for (let i = startpos; i < currentpos; i++)\n          this.queue[i].resolve(result);\n      } catch (e) {\n        for (let i = startpos; i < currentpos; i++)\n          this.queue[i].reject(e as Error);\n      }\n      startpos = currentpos;\n    }\n    //empty the queue\n    this.queue.splice(0, this.queue.length);\n  }\n}\n\n// export function<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, options?: SerializeOptions): Fn {\n// type RetVal = ReturnType<Fn>;\n\n/** Wrap a function in a serializer */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we need to accept any callback.\nexport function wrapSerialized<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, options?: SerializeOptions): Fn {\n  type RetVal = ReturnType<Fn>;\n  if (options?.coalesce)\n    return (new Coalescer<RetVal>(fn)).invoke as Fn;\n\n  let queue = Promise.resolve() as Promise<unknown>;\n  return ((...args: unknown[]): Promise<RetVal> => {\n    const res = queue.then(() => fn(...args));\n    queue = res.catch(() => { /* ignore errors */ });\n    return res;\n  }) as Fn;\n}\n\n//TODO abandon the name 'serialize' for now so it's free and safe to use once JS Decorators land (so we can use @serialize there)\n/** @deprecated Use wrapSerialized instead */\nexport function serialize<RetVal>(fn: (...args: unknown[]) => Promise<RetVal>, context: unknown) {\n  return wrapSerialized(fn, undefined);\n}\n\n/** Attempt to run code that may throw. If it throws anything, the fallback is returned\n\n   This allows you to replace:\n   ```\n   let url;\n     try {\n    url = new URL(inurl);\n  } catch (e) {\n    return null;\n  }```\n\n  with\n\n  ```\n  const url = attempt(() => new URL(inurl));\n  ```\n*/\nexport function attempt<T>(toTry: Promise<T> | (() => Promise<T>)): Promise<T | undefined>;\nexport function attempt<T, F>(toTry: Promise<T> | (() => Promise<T>), fallback: F): Promise<T | F>;\nexport function attempt<T>(toTry: () => T): T | undefined;\nexport function attempt<T, F>(toTry: () => T, fallback: F): T | F;\n\nexport function attempt<T, F>(toTry: (() => T) | Promise<T> | (() => Promise<T>), fallback?: F): T | F | Promise<T | F> {\n  try {\n    const retval = typeof toTry === \"function\" ? toTry() : toTry;\n    if (isPromise(retval))\n      return (retval as Promise<T>).catch(() => fallback as F);\n    return retval as T;\n  } catch (e) {\n    return fallback as F;\n  }\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.ts\"; //TODO absorb into us as soon as noone externally depends on finmath anymore\nimport { isMoney } from \"./quacks.ts\";\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 { Money } from \"./money.ts\";\nimport { isBlob, isDate, isMoney, isPromise, isTemporalInstant, isTemporalPlainDate, isTemporalPlainDateTime, isTemporalPlainTime, isTemporalZonedDateTime, stdTypeOf } from \"./quacks.ts\";\n\n/// Returns T or a promise resolving to T\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport type ComparableType = number | null | bigint | string | Date | Money | boolean | Uint8Array | Temporal.Instant | Temporal.PlainDate | Temporal.PlainTime | Temporal.ZonedDateTime;\n\ntype CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`\n  ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`\n  : Lowercase<S>;\n\ntype KeysToCamelCase<T> = {\n  [K in keyof T as CamelCase<string & K>]: ToCamelCase<T[K]>;\n};\n\ntype CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ?\n  `${T extends Capitalize<T> ? \"_\" : \"\"}${Lowercase<T>}${CamelToSnakeCase<U>}` :\n  S;\n\ntype KeysToSnakeCase<T> = {\n  [K in keyof T as CamelToSnakeCase<string & K>]: ToSnakeCase<T[K]>\n};\n\ntype NonRecordTypes = Date | Money | Blob | Temporal.Instant | Temporal.PlainDate | Temporal.PlainDateTime | Temporal.ZonedDateTime;\n\nexport type ToSnakeCase<T> =\n  T extends unknown[] ? Array<ToSnakeCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToSnakeCase<T> :\n  T;\n\nexport type ToCamelCase<T> =\n  T extends unknown[] ? Array<ToCamelCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToCamelCase<T> :\n  T;\n\n/** Convert a snake_case_name to its corresponding camelCaseName\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToCamelCase(name: string) {\n  return name.replaceAll(/_[a-z]/g, c => c[1].toUpperCase());\n}\n\n/** Convert a camelCaseName to corresponding snake_case_name\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToSnakeCase(name: string) {\n  return name.replaceAll(/[A-Z]/g, c => '_' + c.toLowerCase());\n}\n\n/// Should we rewrite the key/values in this object?\nfunction recodeObject(inp: object) {\n  return !isDate(inp) && !isMoney(inp) && !isBlob(inp) && !isTemporalInstant(inp) && !isTemporalPlainDate(inp) && !isTemporalPlainDateTime(inp) && !isTemporalZonedDateTime(inp);\n}\n\nfunction recursiveToSnakeCase<T>(inp: T): ToSnakeCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toSnakeCase) as ToSnakeCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToSnakeCase(key), recursiveToSnakeCase(value)])) as ToSnakeCase<T>;\n  return inp as ToSnakeCase<T>;\n}\n\nfunction recursiveToCamelCase<T>(inp: T): ToCamelCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toCamelCase) as ToCamelCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToCamelCase(key), recursiveToCamelCase(value)])) as ToCamelCase<T>;\n  return inp as ToCamelCase<T>;\n}\n\n/** Convert all keys to camel case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toSnakeCase<T extends object | object[] | null | undefined>(inp: T): ToSnakeCase<T> {\n  return recursiveToSnakeCase(inp);\n}\n\n/** Convert all keys to snake case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toCamelCase<T extends object | object[] | null | undefined>(inp: T): ToCamelCase<T> {\n  return recursiveToCamelCase(inp);\n}\n\n// TODO make this a quack if we're sure Uint8array is what we want to support - this is here basically to give Buffer support to be compatible with hscompat' compare\nfunction isUInt8Array(value: unknown): value is Uint8Array {\n  return value !== null && typeof value === \"object\" && \"length\" in value && (value as Uint8Array).BYTES_PER_ELEMENT === 1;\n}\n\ntype AwaitedValues<T extends readonly unknown[]> = { -readonly [K in keyof T]: Awaited<T[K]> };\n\n/** Resolve an array of potential promises, returning an array with resolved results\n * @param array - Array of values or promises\n * @returns An array of resolved values, or a promise resolving to that array if any input was a promise\n*/\nexport function maybePromiseAll<const T extends readonly unknown[]>(array: T): MaybePromise<AwaitedValues<T>> {\n  const resolved: Array<Awaited<T[number]>> = [];\n  for (const item of array) {\n    if (isPromise(item))\n      return Promise.all(array) as Promise<AwaitedValues<T>>;\n    resolved.push(item as Awaited<T[number]>);\n  }\n  return resolved as AwaitedValues<T>;\n}\n\n/** Call a function on the value of a potential promise, return the result\n * @param value - Value or promise\n * @param cb - Callback to call on the value\n * @returns The result of the callback, or a promise resolving to that result if the input was a promise\n*/\nexport function mapMaybePromise<T, U>(value: T, cb: (arg: Awaited<T>) => U): U | Promise<U> {\n  return isPromise(value) ? value.then(t => cb(t as Awaited<T>)) : cb(value as Awaited<T>);\n}\n\n/** Compare two values of std-supported types\n * @param left - First value\n * @param right - Second value\n * @returns -1 if left \\< right, 0 if equal, 1 if left \\> right\n */\nexport function compare(left: ComparableType, right: ComparableType): -1 | 0 | 1 {\n  if (left === null)\n    return right === null ? 0 : -1;\n  else if (right === null)\n    return 1;\n\n  switch (typeof left) {\n    case \"boolean\": {\n      if (typeof right === \"boolean\")\n        return left !== right ? left < right ? -1 : 1 : 0;\n    } break;\n    case \"number\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          const right_number = Number(right);\n          return left !== right_number ? left < right_number ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right))\n            return Money.cmp(left.toString(), right);\n        }\n      }\n    } break;\n    case \"bigint\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          const left_number = Number(left);\n          return left_number !== right ? left_number < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right)) {\n            return Money.cmp(left.toString(), right);\n          }\n        }\n      }\n    } break;\n    case \"string\": {\n      if (typeof right === \"string\")\n        return left === right ? 0 : left < right ? -1 : 1;\n    } break;\n    case \"object\": {\n      if (Money.isMoney(left)) {\n        switch (typeof right) {\n          case \"number\":\n          case \"bigint\":\n            return Money.cmp(left, right.toString());\n          case \"object\": {\n            if (right === null) {\n              return 1;\n            } else if (Money.isMoney(right))\n              return Money.cmp(left, right);\n          }\n        }\n      } else if (isDate(left)) {\n        if (isTemporalInstant(right)) {\n          const left_value = Number(left);\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isDate(right)) {\n          const left_value = Number(left);\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isUInt8Array(left) && isUInt8Array(right)) {\n        const compareLength = Math.min(left.length, right.length);\n        for (let i = 0; i < compareLength; i++) {\n          if (left[i] !== right[i])\n            return left[i] < right[i] ? -1 : 1;\n        }\n        return left.length !== right.length ? left.length < right.length ? -1 : 1 : 0;\n      } else if (isTemporalInstant(left)) {\n        if (isDate(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isTemporalInstant(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isTemporalPlainDate(left) && isTemporalPlainDate(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainDate.compare(left, right);\n      } else if (isTemporalPlainTime(left) && isTemporalPlainTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainTime.compare(left, right);\n      } else if (isTemporalZonedDateTime(left) && isTemporalZonedDateTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.ZonedDateTime.compare(left, right);\n      }\n    } break;\n  }\n  throw new Error(`Cannot compare a ${stdTypeOf(left)} with a ${stdTypeOf(right)}`);\n}\n\n/** Returns all property keys of an object type whose value is comparable */\ntype ComparableFields<E extends object, K extends keyof E = keyof E> = K extends keyof E ? E[K] extends ComparableType ? K : never : never;\n\n/** Type of array elements for keys in `compareProperties` */\ntype ComparePropertiesArrayElement<E extends object> = ComparableFields<E> | [ComparableFields<E>, \"asc\" | \"desc\"];\n\n/** All possible types of object keys */\ntype AnyKey = string | symbol | number;\n\n/** Extracts the property name from an array element of CompareProperties */\ntype GetPropertyFromComparePropertiesArrayElement<T> = T extends AnyKey ? T : T extends [infer A, \"asc\" | \"desc\"] ? A : never;\n\n/** Get the list of properties referenced in the `compareProperties` keys list */\ntype GetPropertiesFromComparePropertiesKeys<K extends AnyKey | Array<AnyKey | [AnyKey, \"asc\" | \"desc\"]>> = K extends AnyKey ? K : K extends Array<infer T> ? GetPropertyFromComparePropertiesArrayElement<T> : never;\n\n/** Get all proper prefixes of a tuple, excluding the empty tuple and the source tuple */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TuplePrefixes<K extends AnyKey | [...any[]]> = K extends [any] ? never : K extends [infer A, ...infer B] ? [A] | [A, ...TuplePrefixes<B>] : never;\n\n/** Template for possible keys value (needed to make TS understand that a tuple prefix of the keys is also a valid keys list */\ntype PossibleFields<E extends object> = ComparableFields<E> | [ComparePropertiesArrayElement<E>, ...Array<ComparePropertiesArrayElement<E>>];\n\n\nexport function compareProperties<const K extends ComparableFields<E> | [...Array<ComparePropertiesArrayElement<E>>], E extends object = Record<GetPropertiesFromComparePropertiesKeys<K>, ComparableType>>(fields: K) {\n  const compareList = (Array.isArray(fields) ? fields : [fields]).map((field): [keyof E, 1 | -1] => Array.isArray(field) ? [field[0], field[1] === \"desc\" ? -1 : 1] : [field, 1]);\n  const retval: (lhs: E, rhs: E) => number = (a, b) => {\n    for (const [field, negate] of compareList) {\n      if (a[field] === undefined || b[field] === undefined)\n        throw new Error(`Property '${String(field)}' does not exist`);\n      const res = negate * compare(a[field] as ComparableType, b[field] as ComparableType);\n      if (res)\n        return res;\n    }\n    return 0;\n  };\n  return Object.assign(retval, {\n    partialCompare: <T extends TuplePrefixes<K> & PossibleFields<E>>(partialFields: T) => compareProperties<T, E>(partialFields)\n  });\n}\n","import { stdTypeOf } from \"./quacks.ts\";\nimport { Money } from \"./money.ts\";\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 \"PlainTime\":\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 \"PlainTime\":\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/** 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\n/** Update the search parameters in a URL\n * @param inUrl - URL to update\n * @param updates - Updates to apply, use 'null' to delete a variable\n * @returns Updated URL\n */\nexport function updateURL(inUrl: string | URL, updates: Record<string, string | null>): URL {\n  const u = new URL(inUrl);\n  for (const [k, v] of Object.entries(updates)) {\n    if (v === null) {\n      u.searchParams.delete(k);\n    } else {\n      u.searchParams.set(k, v);\n    }\n  }\n  return u;\n}\n","/** Test whether a string looks like a valid random id */\nexport function isLikeRandomId(input: string): boolean { //TODO add encoding parameter/bytes support ?\n  return Boolean(input.match(/^[A-Za-z0-9_-]{22}$/));\n}\n\n/** Test whether a string is a valid hex UUID\n * @param input - uuid in hex format to verify. you may need to lowercase the uuid first\n * @param format - optional, if set to \"v4\" it will only accept UUIDv4 format\n*/\nexport function isValidUUID(input: string, format?: \"v4\"): boolean {\n  //we'll require you to lowercase the uuid first to increase the chance that you'll actually be storing/matching it in lowercase too\n\n  if (format === \"v4\")\n    return Boolean(input.match(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/));\n  else if (format !== undefined)\n    throw new Error(`Unsupported format '${format}'`);\n  else\n    return Boolean(input.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/));\n}\n\n/** Generate a configurable random id (the default settings, base64url and 16 bytes, match HareScript's GenerateUFS128BitId)\n * @param encoding - Encoding to use, base64url, hex or uuidv4. Default is base64url\n * @param bytes - Number of bytes to generate. Default is 16\n * @returns An encoded ID. With the default settings it will be a url (and filename) safe string of 22 characters in length\n */\nexport function generateRandomId(encoding: \"base64url\" | \"hex\" | \"uuidv4\" = \"base64url\", bytes: number = 16): string {\n  if (encoding === \"uuidv4\") {\n    if (bytes !== 16)\n      throw new Error(\"UUIDv4 encoding only supports 16 bytes\");\n\n    if (crypto.randomUUID) //NOTE: not available in non-secure contexts so the fallback can never go away\n      return crypto.randomUUID();\n  }\n\n  const u8array = new Uint8Array(bytes);\n  crypto.getRandomValues(u8array);\n\n  if (encoding === \"uuidv4\") {\n    u8array[6] = (u8array[6] & 0x0f) | 0x40;\n    u8array[8] = (u8array[8] & 0x3f) | 0x80;\n    return [...u8array.values()].map(x => x.toString(16).padStart(2, \"0\")).join(\"\").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, \"$1-$2-$3-$4-$5\");\n  }\n\n  if (encoding === \"base64url\")\n    return btoa(String.fromCharCode.apply(null, u8array as unknown as number[])).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n\n  if (encoding === \"hex\")\n    return [...u8array.values()].map(x => x.toString(16).padStart(2, \"0\")).join(\"\");\n\n  throw new Error(`Invalid encoding '${encoding}'`);\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  private compareFn;\n\n  constructor(compareFn: (lhs: V, rhs: V) => number, contents?: V[]) {\n    this.compareFn = compareFn;\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","import { isPromise } from \"./quacks\";\n\nfunction propagateAbort(signal: AbortSignal, cb: ((reason: typeof signal[\"reason\"]) => void) | AbortController) {\n  if (signal.aborted) {\n    if (\"abort\" in cb)\n      cb.abort(signal.reason);\n    else\n      cb(signal.reason);\n  } else signal.addEventListener(\"abort\", () => {\n    if (\"abort\" in cb)\n      cb.abort(signal.reason);\n    else\n      cb(signal.reason);\n  });\n}\n\nexport type AbortSignals = Iterable<AbortSignal | Promise<AbortSignal> | undefined | null> | AbortSignal | Promise<AbortSignal> | null | undefined;\n\n/** Calls the callback when any of the passed abort signals is (or already was) aborted. Use\n * this instead of addEventListener when it is possible that any of the abortsignals was already aborted.\n*/\nexport function whenAborted(signals: AbortSignals, cb: ((reason: AbortSignal[\"reason\"]) => void) | AbortController): void {\n  propagateAbort(combineAbortSignals(signals), cb);\n}\n\n/** Combines abort signals (or promises for abort signals) into one abort signal. More generic version of AbortSignal.any() */\nexport function combineAbortSignals(signals: AbortSignals): AbortSignal {\n  if (!signals || !(Symbol.iterator in signals))\n    signals = [signals];\n  const abortController = new AbortController;\n  for (const signal of signals) {\n    if (signal) {\n      if (\"then\" in signal) {\n        // Convert promise errors to abort\n        void signal.then(s => propagateAbort(s, abortController), e => abortController.abort(e));\n      } else\n        propagateAbort(signal, abortController);\n    }\n  }\n  return abortController.signal;\n}\n\n/** Returns a signal that can be used like `using signal = getScopeSignal()` and will be aborted when going out of scope */\nexport function getScopeSignal(): AbortSignal & { [Symbol.dispose](): void } {\n  const ctrl = new AbortController();\n  const signal = ctrl.signal as AbortSignal & { [Symbol.dispose](): void };\n  signal[Symbol.dispose] = () => ctrl.abort();\n  return signal;\n}\n\ntype PipeReturn<PFinal, PAll extends readonly unknown[]> = Extract<PAll[number], Promise<unknown>> extends never ? PFinal : Promise<Awaited<PFinal>>;\n\n/** @hidden */\nexport function pipe<P1>(f1: P1 | ((a: void) => P1)): PipeReturn<P1, [P1]>;\nexport function pipe<P1, P2>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2): PipeReturn<P2, [P1, P2]>;\nexport function pipe<P1, P2, P3>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3): PipeReturn<P3, [P1, P2, P3]>;\nexport function pipe<P1, P2, P3, P4>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4): PipeReturn<P4, [P1, P2, P3, P4]>;\nexport function pipe<P1, P2, P3, P4, P5>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5): PipeReturn<P5, [P1, P2, P3, P4, P5]>;\nexport function pipe<P1, P2, P3, P4, P5, P6>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6): PipeReturn<P6, [P1, P2, P3, P4, P5, P6]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7): PipeReturn<P7, [P1, P2, P3, P4, P5, P6, P7]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8): PipeReturn<P8, [P1, P2, P3, P4, P5, P6, P7, P8]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9): PipeReturn<P9, [P1, P2, P3, P4, P5, P6, P7, P8, P9]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10): PipeReturn<P10, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11): PipeReturn<P11, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12): PipeReturn<P12, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13): PipeReturn<P13, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14): PipeReturn<P14, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14, f15: (o: Awaited<P14>) => P15): PipeReturn<P15, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14, f15: (o: Awaited<P14>) => P15, f16: (p: Awaited<P15>) => P16): PipeReturn<P16, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16]>;\n\n/** Chain together (possibly async) function calls, each receiving the resolved (awaited) output of the previous one. The first parameter may be a value, all further parameters must be functions.\n *  Type safe up to 16 parameters\n */\nexport function pipe(fn0: unknown, ...fns: Array<(x: unknown) => unknown>): unknown;\n\nexport function pipe(fn0: unknown, ...fns: Array<(x: unknown) => unknown>): unknown {\n  let result = typeof fn0 === \"function\" ? fn0() : fn0;\n\n  if (isPromise(result)) { //switch to full async handling immediately\n    return (async () => {\n      let asyncResult = await result;\n      for (const fn of fns)\n        asyncResult = await fn(asyncResult);\n      return asyncResult;\n    })();\n  }\n\n  for (let idx = 0; idx < fns.length; ++idx) {\n    const next = fns[idx](result);\n    if (isPromise(next)) { //switch to async as soon as we hit a promise\n      return (async () => {\n        let asyncResult = await next;\n        for (let asyncIdx = idx + 1; asyncIdx < fns.length; ++asyncIdx)\n          asyncResult = await fns[asyncIdx](asyncResult);\n        return asyncResult;\n      })();\n    }\n    result = next;\n  }\n\n  return result;\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","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/std\" {\n}\n\n// Adding APIs may also require an update to https://www.webhare.dev/manuals/typescript/harescript-conversion-guide/\nexport { attempt, sleep, createDeferred, wrapInTimeout, serialize, wrapSerialized, type DeferredPromise, type SerializeOptions } from \"./promises.ts\";\n\nexport { compare, compareProperties, nameToCamelCase, nameToSnakeCase, toSnakeCase, toCamelCase, maybePromiseAll, mapMaybePromise } from \"./types.ts\";\nexport type { ToSnakeCase, ToCamelCase, ComparableType, MaybePromise } from \"./types.ts\";\n\nexport { encodeString, decodeString, escapeRegExp, regExpFromWildcards, stringify, parseTyped, slugify, isValidEmail, type StringEncodings, toCLocaleLowercase, toCLocaleUppercase, levenshteinDistance, getUTF8Length, limitUTF8Length, updateURL } from \"./strings.ts\";\nexport { generateRandomId, isLikeRandomId, isValidUUID } from \"./platformbased.ts\";\n\nexport { shuffle, emplace, pick, omit, isTruthy, appendToArray, typedEntries, typedFromEntries, typedKeys, SortedMultiSet, SortedMultiMap, type TypedEntries, type TypedFromEntries } from \"./collections.ts\";\nexport type { EmplaceHandler, DistributedKeys, DistributedOmit, DistributedPick } from \"./collections.ts\";\n\nexport { Money, type MoneyRoundingMode, type MoneyFormatOptions } from \"./money.ts\";\n\nexport { addDuration, parseDuration, subtractDuration, convertWaitPeriodToDate, isValidDate, isValidTime, convertFlexibleInstantToDate, formatDateTime } from \"./datetime.ts\";\nexport type { Duration, WaitPeriod, FlexibleInstant } from \"./datetime.ts\";\n\nexport { stdTypeOf, isDate, isBlob, isFile, isError, isPromise, isMoney, isTemporalInstant, isTemporalPlainDate, isTemporalPlainDateTime, isTemporalZonedDateTime, isTemporalPlainTime } from \"./quacks.ts\";\n\nexport { combineAbortSignals, getScopeSignal, whenAborted, pipe } from \"./utils.ts\";\n\nexport { LocalMutex, type LocalLock } from \"./localmutex.ts\";\n\n/** Throw an error with the specified message. This function allows you to throw inside expressions\n * @param err - The error message\n * @returns This function never returns\n * @throws An error with the specified message\n */\nexport function throwError(err: Error | string): never {\n  //TODO remove ourselves from the stack ?\n  throw err instanceof Error ? err : new Error(err);\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","import { debugFlags, registerDebugConfigChangedCallback } from \"./envbackend\";\nimport { generateRandomId } from \"@webhare/std\";\n\nlet hookedfetch = false;\n\nfunction sanitizeBody(body: unknown) {\n  if (body instanceof ArrayBuffer) {\n    const view = new Uint8Array(body.slice(0, 5000)); //show the bytes but filter unprintable as '.'\n    return Array.from(view).map(v => v >= 32 && v < 127 ? String.fromCharCode(v) : \".\").join(\"\");\n  }\n  if (body instanceof URLSearchParams)\n    return body.toString();\n  if (typeof body !== 'string') {\n    return `[${typeof body}]`;\n  }\n  body = body.substring(0, 5000).replaceAll(\"\\r\", \" \").replaceAll(\"\\n\", \" \");\n  return body;\n}\n\nfunction getResponseSummary(response: Pick<Response, \"headers\">) {\n  const toks = [];\n  if (response.headers.get(\"Content-Type\"))\n    toks.push(response.headers.get(\"Content-Type\"));\n  if (response.headers.get(\"Content-Length\"))\n    toks.push(response.headers.get(\"Content-Length\") + \" bytes\");\n  if (response.headers.get(\"Transfer-Encoding\"))\n    toks.push(response.headers.get(\"Transfer-Encoding\"));\n  if (response.headers.get(\"Content-Encoding\"))\n    toks.push(response.headers.get(\"Content-Encoding\"));\n\n  return toks.length ? `(${toks.join(\", \")})` : \"\";\n}\n\nfunction headersToString(headers: Headers) {\n  return JSON.stringify(Object.fromEntries(headers.entries()));\n}\n\nexport function extractRequestInfo(input: RequestInfo | URL, init?: RequestInit) {\n  const method = (init?.method || (input as Request)?.method || \"GET\");\n  const url = input instanceof URL ? input.toString() : typeof input === \"string\" ? input : input.url;\n  const headers = new Headers(typeof input === \"object\" && !(input instanceof URL) ? input.headers : init?.headers);\n  const body = typeof input === \"object\" && !(input instanceof URL) ? input.body : init?.body;\n  return { method, url, headers, body };\n}\n\nexport async function extractRequestBody(body: BodyInit): Promise<XMLHttpRequestBodyInit> {\n  if (!(body instanceof ReadableStream))\n    return body;\n\n  //convert the ReadableStream to ArrayBuffer so we can print AND send it (TODO ideally 'tee' the stream and just grab the first 5K bytes)\n  const reader = body.getReader();\n  const chunks = [];\n  for (; ;) {\n    const { done, value } = await reader.read();\n    if (done)\n      break;\n    chunks.push(value);\n  }\n  return await new Blob(chunks).arrayBuffer();\n}\n\nexport function logWrqRequest(method: string, url: string, headers: Headers, body: XMLHttpRequestBodyInit | undefined | null) {\n  const debugrequestid = generateRandomId();\n\n  console.log(`[wrq] ${debugrequestid} ${method.padEnd(7)} ${url}`);\n  console.log(`[wrq] ${debugrequestid} headers ${headersToString(headers)}`);\n  if (body) {\n    console.log(`[wrq] ${debugrequestid} body    ${sanitizeBody(body)}`);\n  }\n\n  return debugrequestid;\n}\n\nexport async function logWrqResponse(debugrequestid: string, fetchresult: Pick<Response, \"ok\" | \"status\" | \"statusText\" | \"headers\" | \"json\" | \"text\" | \"arrayBuffer\" | \"clone\">) {\n  console.log(`[wrq] ${debugrequestid} result  ${fetchresult.status} ${fetchresult.statusText} ${getResponseSummary(fetchresult)}`);\n  console.log(`[wrq] ${debugrequestid} headers ${headersToString(fetchresult.headers)}`);\n\n  const ct = fetchresult.headers.get(\"Content-Type\");\n  if (ct && [\"text/html\", \"text/plain\", \"application/json\"].includes(ct?.split(';')[0])) {\n    const responsebody = await fetchresult.clone().text();\n    console.log(`[wrq] ${debugrequestid} body    ${sanitizeBody(responsebody)}`);\n  }\n}\n\nasync function debuggableFetch(originalfetch: typeof fetch, input: RequestInfo | URL, init?: RequestInit) {\n  if (!debugFlags.wrq)\n    return originalfetch(input, init);\n\n  let { method, url, headers, body } = extractRequestInfo(input, init);\n  if (body) {\n    body = await extractRequestBody(body);\n    init = { ...init, body };\n  }\n\n  const debugrequestid = logWrqRequest(method, url, headers, body);\n\n  const fetchresult = await originalfetch(input, init); //TODO log responses as well (if safe/applicable, eg not binary or Very Long... and we probably should wait for the first json()/text()/body() call? but at least log the status and time!)\n  await logWrqResponse(debugrequestid, fetchresult);\n\n  return fetchresult;\n}\n\nexport function hookFetch() {\n  if (hookedfetch)\n    return;\n\n  globalThis.fetch = debuggableFetch.bind(null, globalThis.fetch);\n  hookedfetch = true;\n}\n\nexport function enableFetchDebugging() {\n  // Hook global fetch if requested\n  if (globalThis[\"fetch\"]) {\n    if (debugFlags.wrq)\n      hookFetch();\n\n    registerDebugConfigChangedCallback(() => {\n      if (debugFlags.wrq)\n        hookFetch();\n    });\n  }\n}\n","/* Manages the $wh global, an API for just-in-time debugging */\nimport type { DebugRegistry } from \"@webhare/env\";\nimport { debugFlags } from \"./envbackend\";\n\nlet debugRegFinalizer: FinalizationRegistry<{ type: keyof DebugRegistry; key: string }> | undefined;\n\nexport type WHGlobal = DebugRegistry & {\n  debugFlags: typeof debugFlags;\n  /** Global counter to avoid HMRs from duplicating IDs */\n  nextId: number;\n};\n\ndeclare global {\n  var $wh: WHGlobal;\n}\n\nglobalThis.$wh = {\n  debugFlags,\n  nextId: 1\n} satisfies WHGlobal;\n\nexport function addToDebugRegistry<T extends keyof DebugRegistry>(type: T, key: string, value: NonNullable<ReturnType<NonNullable<DebugRegistry[T]>[string][\"deref\"]>>) {\n  const debugRegistry = globalThis.$wh as unknown as DebugRegistry;\n  //@ts-ignore prevents '>   Type '{}' is not assignable to type 'never'. in jssdk builds, probably because noone yet extends DebugRegistry there\n  debugRegistry[type] ||= {};\n  debugRegFinalizer ||= new FinalizationRegistry(({ type: t, key: k }) => {\n    delete debugRegistry![t]?.[k];\n  });\n\n  if (debugRegistry[type][key])\n    console.error(`Debug registry key ${key} already exists, overwriting it`);\n\n  (debugRegistry[type] as Record<string, unknown>)[key] = new WeakRef(value);\n  debugRegFinalizer.register(value, { type, key });\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/env\" {\n  interface DebugRegistry {\n  }\n}\n\nimport { debugFlags, dtapStage, isLive, backendBase, getAssetBase, setAssetBase, getModulePublicAssetBase } from \"./envbackend\";\nimport type { DTAPStage } from \"./concepts\";\n\nexport { type NavigateInstruction, navigateTo } from \"./navigation\";\nexport { enableFetchDebugging } from \"./fetchdebug\";\nexport { addToDebugRegistry } from \"./whglobal\";\nexport { type DTAPStage, dtapStage, debugFlags, isLive, backendBase, getAssetBase, setAssetBase, getModulePublicAssetBase };\n\n//user locale *which Tollium and sites should start to use to define localization, and perhaps gettid too?)\nexport type UserLocale = {\n  /** The language code, eg 'en' including optional country, eg en-US */\n  lang: string;\n  //TODO regional settings\n};\n\n//export deprecated variants\nexport { dtapstage, islive } from \"./envbackend\";\n\n/** @deprecated For WH5.4 and up use 'debugFlags' */\nexport const flags = debugFlags;\n","import type { GetTidHooks } from \"./types.js\";\n\nlet hookFactory: (() => GetTidHooks) | undefined;\nlet gotHooks = false;\n\nexport function setGetTidHooksFactory(newHookFactory: () => GetTidHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setGetTidHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getGetTidHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n","import { decodeString, encodeString } from '@webhare/std';\nimport type { CompiledLanguageFile, GetTidHooks, LanguagePart, LanguageText, RecursiveLanguageTexts, TidAllowedHTMLTags, TidParam } from './types';\nimport { getGetTidHooks } from './hooks';\nimport { debugFlags, dtapStage } from '@webhare/env';\nimport { getLang } from '@webhare/dompack/src/tree';\n\n\n\nlet hooks: GetTidHooks | undefined;\nlet browserSetLanguage = getLang().language;\nconst defaultLanguage = \"en\";\n\nfunction ensureHooks(): GetTidHooks {\n  return hooks ??= getGetTidHooks?.() ?? {\n    loader: null,\n    currentLanguage: (lang) => {\n      if (lang)\n        browserSetLanguage = lang;\n      return browserSetLanguage;\n    }\n  };\n}\n\nexport function getTidLanguage(): string {\n  return ensureHooks().currentLanguage() || defaultLanguage;\n}\n\nexport function setTidLanguage(newLanguage: string): void {\n  ensureHooks().currentLanguage(newLanguage.toLowerCase());\n}\n\nconst langFileCache: Record<string, CompiledLanguageFile> = {};\n\nfunction getLanguageFile(module: string, langCode: string): CompiledLanguageFile | undefined {\n  const langkey = `${module}:${langCode}`;\n  let compiled = langFileCache[langkey];\n  if (!compiled || !compiled.resource) {\n    const loader = ensureHooks().loader;\n    if (loader) {\n      try {\n        compiled = loader(module, langCode, compiled?.registered ?? new Map);\n      } catch (e) {\n        // loading failed, erase the loaded texts (keep the registered texts, though)\n        if (dtapStage !== \"production\" || debugFlags.gtd) {\n          console.error(e);\n        }\n        const texts = compiled?.registered ?? new Map;\n        compiled = { resource: \"\", fallbackLanguage: \"\", langCode, texts, registered: texts };\n      }\n      langFileCache[langkey] = compiled;\n    }\n  }\n  if (!compiled && (dtapStage !== \"production\" || debugFlags.gtd)) {\n    console.warn(`No language texts found for module '${module}' and language '${langCode}'`);\n  }\n  return compiled;\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- needed for generics\nexport type GetTidRenderFunc<Result extends object = object> = ((tag: TidAllowedHTMLTags, props: { children?: any[]; href?: string }, ...childNodes: any[]) => Result);\nexport type GetTidOptions = { langCode?: string; render?: GetTidRenderFunc | \"fragment\" };\n\ntype GetTidArgumentTypes = [GetTidOptions?] | [TidParam[], GetTidOptions?] | [TidParam?, TidParam?, TidParam?, TidParam?];\n\nfunction toHTMLNode(tag: string, props: { href?: string; children?: Array<string | Node> }): Node {\n  const node = document.createElement(tag);\n  if (props.href)\n    node.setAttribute(\"href\", props.href);\n  if (props.children)\n    node.append(...props.children);\n  return node;\n}\n\nfunction wrapInFragment(children: Array<string | Node>): DocumentFragment {\n  const fragment = document.createDocumentFragment();\n  fragment.append(...children);\n  return fragment;\n}\n\n\nfunction getTidInternal(tid: string, params: TidParam[], options?: GetTidOptions): string | Array<string | object> | DocumentFragment {\n  if (tid === \"\") {\n    return \"\";\n  }\n\n  if (tid.startsWith(\":\")) {\n    return tid.substring(1);\n  } else if (tid.startsWith(\"<>\")) {\n    return decodeString(tid.substring(2), \"html\");\n  }\n\n  const langCode = options?.langCode?.toLowerCase() || getTidLanguage();\n  if (options?.render) {\n    if (options.render === \"fragment\") {\n      const nodes = calcTIDForLanguage(langCode, tid, params, true, toHTMLNode) as Array<string | Node>;\n      return wrapInFragment(nodes);\n    }\n    return calcTIDForLanguage(langCode, tid, params, true, options.render);\n  } else\n    return calcTIDForLanguage(langCode, tid, params, false, null).join(\"\");\n}\n\nexport function getTid(tid: string, options?: GetTidOptions & { render?: undefined }): string;\nexport function getTid<VNode extends object>(tid: string, options?: GetTidOptions & { render?: GetTidRenderFunc<VNode> }): string | Array<string | VNode>;\nexport function getTid(tid: string, options?: GetTidOptions & { render?: \"fragment\" }): DocumentFragment;\nexport function getTid(tid: string, param: TidParam[], options?: GetTidOptions & { render?: undefined }): string;\nexport function getTid<VNode extends object>(tid: string, param: TidParam[], options?: GetTidOptions & { render?: GetTidRenderFunc<VNode> }): string | Array<string | VNode>;\nexport function getTid(tid: string, param: TidParam[], options?: GetTidOptions & { render?: \"fragment\" }): DocumentFragment;\nexport function getTid(tid: string, p1?: TidParam, p2?: TidParam, p3?: TidParam, p4?: TidParam): string;\n\nexport function getTid(tid: string, ...p: GetTidArgumentTypes): string | Array<string | object> | DocumentFragment {\n  if (Array.isArray(p[0])) // case: param: TidParam[], options?: GetTidOptions)\n    return getTidInternal(tid, p[0], p[1] as GetTidOptions);\n  if (p[0] && typeof p[0] === \"object\") // case: options: GetTidOptions\n    return getTidInternal(tid, [], p[0]);\n  return getTidInternal(tid, p as Array<TidParam | undefined>, {});\n}\n\nexport function getTidForLanguage(langCode: string, tid: string, p1: TidParam = null, p2: TidParam = null, p3: TidParam = null, p4: TidParam = null): string {\n  return getTid(tid, [p1, p2, p3, p4], { langCode });\n}\n\nexport function getHTMLTid(tid: string, ...params: TidParam[]): string {\n  return getHTMLTidForLanguage(getTidLanguage(), tid, ...params);\n}\n\nexport function getHTMLTidForLanguage(langCode: string, tid: string, ...params: TidParam[]): string {\n  if (tid === \"\") {\n    return \"\";\n  }\n\n  if (tid.startsWith(\":\")) {\n    return encodeString(tid.substring(1), \"html\");\n  } else if (tid.startsWith(\"<>\")) {\n    return tid.substring(2);\n  }\n\n  return calcTIDForLanguage(langCode, tid, params, true, null).join(\"\");\n}\n\nexport function getTIDListForLanguage(langcode: string, gid: string) {\n  gid = getCanonicalTid(gid.toLowerCase());\n  langcode = langcode.toLowerCase();\n\n  const modsep = gid.indexOf(':');\n  if (modsep === -1) {\n    if (dtapStage !== \"production\" || debugFlags.gtd)\n      console.warn(`Missing module name in call for gid '${gid}'`);\n    return `(cannot find textnode: ${gid})`;\n  }\n\n  const module = gid.substring(0, modsep);\n  const lookup = gid.substring(modsep + 1).replace(/ /g, \"_\") + \".\";\n\n  const compiled = getLanguageFile(module, langcode);\n  const result: string[] = [];\n  if (compiled) {\n    for (const key of compiled.texts.keys()) {\n      if (key.startsWith(lookup) && key.indexOf(\".\", lookup.length) === -1)\n        result.push(`${module}:${key}`);\n    }\n    if (compiled.fallbackLanguage) {\n      const fallback = getLanguageFile(module, compiled.fallbackLanguage);\n      if (fallback) {\n        for (const key of fallback.texts.keys()) {\n          if (key.startsWith(lookup) && key.indexOf(\".\", lookup.length) === -1 && !result.includes(`${module}:${key}`))\n            result.push(`${module}:${key}`);\n        }\n      }\n    }\n  }\n\n  return result;\n}\n\nfunction cannotFind(tid: string) {\n  if (debugFlags.sut)\n    return [tid.substring(tid.lastIndexOf(\".\"))];\n\n  return [`(cannot find text: ${tid})`];\n}\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: null): string[];\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: GetTidRenderFunc): Array<string | object>;\n\n\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: GetTidRenderFunc | null): Array<string | object> {\n  tid = getCanonicalTid(tid.toLowerCase());\n  if (langcode.match(/^[a-z]{2}-/)) //truncate country codes from language identifiers (eg en-GB) until we have actual support for those, so we don't break when en-GB is passed straight from eg. document.documentElement.lang\n    langcode = langcode.substring(0, 2);\n\n  if (tid === \"tollium:tilde.locale.datetimestrings\") {\n    return [getLanguageDatetimeStrings(langcode)];\n  }\n\n  // convert null to \"\", numbers to strings\n  const params = rawParams.map(p => (typeof p === \"number\" ? p.toString() : (p ?? \"\")));\n\n  const modsep = tid.indexOf(':');\n  if (modsep === -1) {\n    if (dtapStage !== \"production\" || debugFlags.gtd)\n      console.warn(`Missing module name in call for tid '${tid}'`);\n    return [`(missing module name in tid: ${tid})`];\n  }\n\n  const module = tid.substring(0, modsep);\n  const lookup = tid.substring(modsep + 1).replace(/ /g, \"_\");\n  tid = `${module}:${lookup}`;\n\n  if (langcode === \"debug\") {\n    const debugtid = `{${[tid, ...params].join(\"|\")}}`;\n    return [rich ? encodeString(debugtid, \"html\") : debugtid];\n  }\n\n  const compiled = getLanguageFile(module, langcode);\n  const match = compiled?.texts.get(lookup);\n  if (!match && compiled?.fallbackLanguage) {\n    const fallback = getLanguageFile(module, compiled.fallbackLanguage);\n    const fallbackMatch = fallback?.texts.get(lookup);\n    if (!fallbackMatch && (dtapStage !== \"production\" || debugFlags.gtd)) {\n      console.warn(`Cannot find text ${tid} for language ${langcode}, also tried fallback language '${compiled.fallbackLanguage}'`);\n    }\n    return fallbackMatch ? executeCompiledTidText(fallbackMatch, params, rich, render) : cannotFind(tid);\n  }\n\n  if (!match && (dtapStage !== \"production\" || debugFlags.gtd)) {\n    console.warn(`Cannot find text ${tid} for language ${langcode}, no fallback language`);\n  }\n  return match ? executeCompiledTidText(match, params, rich, render) : cannotFind(tid);\n}\n\nfunction getCanonicalTid(tid: string) {\n  if (tid.startsWith(\"tollium:common.buttons.\") || tid.startsWith(\"tollium:common.actions.\") || tid.startsWith(\"tollium:common.labels.\")) {\n    return `tollium:tilde.${tid.substring(tid.indexOf(\".\") + 1)}`;\n  } else if (tid.startsWith(\"~\")) {\n    return `tollium:tilde.${tid.substring(1)}`;\n  }\n\n  return tid;\n}\n\nfunction renderString(tok: string, rich: boolean, render: GetTidRenderFunc | null) {\n  return rich ?\n    render ?\n      tok.split(/(\\n)/).map(part => part !== \"\\n\" ? part : render(\"br\", {})).filter(_ => _) :\n      [encodeString(tok, \"html\")] :\n    [tok];\n}\n\nfunction executeCompiledTidText(text: string | LanguagePart[], params: string[], rich: boolean, render: GetTidRenderFunc | null): Array<object | string> {\n  if (typeof text === \"string\")\n    return renderString(text, rich, render);\n\n  const parts = new Array<object | string>;\n  for (const tok of text) {\n    if (typeof tok === \"string\") {\n      parts.push(...renderString(tok, rich, render));\n    } else if (typeof tok === \"number\") {\n      if (tok >= 1) {\n        const get_param = params[tok - 1];\n        if (get_param) {\n          parts.push(...renderString(get_param, rich, render));\n        }\n      }\n    } else if (tok.t === \"tag\") {\n      const sub = executeCompiledTidText(tok.subs, params, rich, render);\n      if (rich && render)\n        parts.push(render(tok.tag, { children: sub }));\n      else\n        parts.push(...(rich ? [`<${tok.tag}>`, ...sub, `</${tok.tag}>`] : sub));\n    } else if (tok.t === \"ifparam\") {\n      const get_param = params[tok.p - 1] || \"\";\n      parts.push(...executeCompiledTidText(get_param.toUpperCase() === tok.value.toUpperCase() ? tok.subs : tok.subselse, params, rich, render));\n    } else if (tok.t === \"a\") {\n      const sub = executeCompiledTidText(tok.subs, params, rich, render);\n      if (rich) {\n        let link = tok.link;\n        if (tok.linkparam > 0 && tok.linkparam <= params.length) {\n          link = params[tok.linkparam - 1] || link;\n        }\n        if (link) {\n          if (render)\n            parts.push(render(\"a\", { href: link, children: sub }));\n          else\n            parts.push(`<a href=\"${encodeString(link, \"attribute\")}\">`, ...sub, `</a>`);\n        } else {\n          parts.push(...sub);\n        }\n      } else {\n        parts.push(...sub);\n      }\n    }\n  }\n  return parts;\n}\n\nfunction flattenRecursiveLanguageTexts(text: RecursiveLanguageTexts, pathsofar: string, result: Map<string, LanguageText>): void {\n  if (typeof text === \"string\" || Array.isArray(text))\n    result.set(pathsofar, text);\n  else\n    for (const [name, value] of Object.entries(text))\n      flattenRecursiveLanguageTexts(value, `${pathsofar}${pathsofar && name ? \".\" : \"\"}${name}`, result);\n}\n\nexport function registerTexts(module: string, langCode: string, tids: RecursiveLanguageTexts) {\n  const langkey = `${module}:${langCode}`;\n  let compiledFile = langFileCache[langkey];\n  if (!compiledFile) {\n    const texts = new Map;\n    langFileCache[langkey] = compiledFile = { resource: \"\", fallbackLanguage: \"\", langCode, texts, registered: texts };\n  }\n  flattenRecursiveLanguageTexts(tids, \"\", compiledFile.registered);\n  if (compiledFile.texts !== compiledFile.registered) {\n    for (const [key, value] of compiledFile.registered)\n      compiledFile.texts.set(key, value);\n  }\n}\n\nfunction getLanguageDatetimeStrings(langCode: string) {\n  switch (langCode.substring(0, 2)) {\n    case \"nl\": return \"am;pm;januari;februari;maart;april;mei;juni;juli;augustus;september;oktober;november;december;maandag;dinsdag;woensdag;donderdag;vrijdag;zaterdag;zondag;jan;feb;mrt;apr;mei;jun;jul;aug;sep;okt;nov;dec;ma;di;wo;do;vr;za;zo\";\n    case \"de\": return \"am;pm;Januar;Februar;März;April;Mai;Juni;Juli;August;September;Oktober;November;Dezember;Montag;Dienstag;Mittwoch;Donnerstag;Freitag;Samstag;Sonntag;Jan.;Febr.;März;Apr.;Mai;Juni;Juli;Aug.;Sept.;Okt.;Nov.;Dez.;Mo;Di;Mi;Do;Fr;Sa;So\";\n    case \"fr\": return \"am;pm;Janvier;Février;Mars;Avril;Mai;Juin;Juillet;Août;Septembre;Octobre;Novembre;Décembre;Lundi;Mardi;Mercredi;Jeudi;Vendredi;Samedi;Dimanche;Janv;Févr;Mars;Avril;Mai;Juin;Juil;Août;Sept;Oct;Nov;Déc;Lun;Mar;Mer;Jeu;Ven;Sam;Dim\";\n    case \"jp\": {\n      return Buffer.from(\"5Y2I5YmNO+WNiOW+jDvvvJHmnIg777yS5pyIO++8k+aciDvvvJTmnIg777yV5pyIO++8luaciDvvvJfmnIg777yY5pyIO++8meaciDvvvJHvvJDmnIg777yR77yR5pyIO++8ke+8kuaciDvmnIjmm5zml6U754Gr5puc5pelO+awtOabnOaXpTvmnKjmm5zml6U76YeR5puc5pelO+Wcn+abnOaXpTvml6Xmm5zml6U777yR5pyIO++8kuaciDvvvJPmnIg777yU5pyIO++8leaciDvvvJbmnIg777yX5pyIO++8mOaciDvvvJnmnIg777yR77yQ5pyIO++8ke+8keaciDvvvJHvvJLmnIg75pyIO+eBqzvmsLQ75pyoO+mHkTvlnJ875pel\", \"base64\").toString();\n    }\n  }\n\n  // \"en\" is the default\n  return \"am;pm;January;February;March;April;May;June;July;August;September;October;November;December;Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday;Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec;Mon;Tue;Wed;Thu;Fri;Sat;Sun\";\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 PageBuildRequest'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 { getLang } from \"@webhare/dompack/src/tree\";\nimport type { FrontendDataTypes } from \"@webhare/frontend\";\nimport { omit } from \"@webhare/std\";\n\n\n/** The format of the <script id=\"wh-config\"> object  */\nexport type WHConfigScriptData = {\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   *  @deprecated Use setFrontendData for type-safe settings\n  */\n  obj: { [key: string]: unknown };\n  /** Site specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n   */\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} & {\n  ///Plugins may add keys at this level\n  [key in keyof FrontendDataTypes]?: FrontendDataTypes[key];\n};\n\nexport type WHConfigScriptData_FromServer = WHConfigScriptData & { dtapStage: DTAPStage };\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\nlet config: WHConfigScriptData_FromServer | 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  const parsedConfig: WHConfigScriptData_FromServer & WHConfigScriptData_OldPublishFields = JSON.parse(whconfigel.textContent);\n  config = omit(parsedConfig, [\"siteroot\", \"dtapstage\", \"islive\"]);\n\n  //Fallbacks for pages last published with WH5.3 *and* pages published from HareScript which still emit lowercase props\n  siteroot = parsedConfig.siteRoot ?? parsedConfig.siteroot!;\n  dtapStage = parsedConfig.dtapStage ?? parsedConfig.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: WHConfigScriptData & WHConfigScriptData_LegacyFields = {\n  server: 0,\n  ...config,\n  obj: config?.obj || {},\n  site: config?.site || {},\n  siteRoot: siteroot || \"\",\n  dtapstage: dtapStage,\n  islive: dtapStage === \"production\" || dtapStage === \"acceptance\",\n  siteroot: siteroot || \"\",\n};\n\nif (typeof document !== \"undefined\") {\n  //@ts-expect-error -- locale isn't supposed to exist - but some old code is still referring to it\n  frontendConfig.locale = getLang().tag;\n}\n\nif (dtapStage === \"development\") { //WH6.0: it's time to hard phase-out the old fields\n  for (const prop of [\"islive\", \"dtapstage\", \"siteroot\", \"locale\"] as const)\n    Object.defineProperty(frontendConfig, prop, {\n      get() { throw new Error(`frontendConfig.${prop} will be removed`); }\n    });\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","\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  if (typeof sessionStorage !== \"undefined\") {\n    const sessionDebug = sessionStorage.getItem(varname);\n    if (sessionDebug)\n      flags.push(...sessionDebug.split(','));\n  }\n\n  return flags;\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-expect-error -- It's marked readonly\nSymbol.dispose ||= Symbol.for('Symbol.dispose');\n//@ts-expect-error -- 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-expect-error `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/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            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","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","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-expect-error IScroll is a custom Window property set by IScroll\n  if (eventtype === 'click' && window.IScroll)\n    // @ts-expect-error _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","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/dompack\" {\n}\n\n/* This is our public api */\nexport { flagUIBusy, setupBusyModal } from './busy';\nexport type { UIBusyLock, BusyModalEvent } from './busy';\nexport { dispatchCustomEvent, dispatchDomEvent, fireModifiedEvents, changeValue, stop, addDocEventListener } from '../../../modules/system/js/dompack/src/events';\nexport type { DocEvent, DomEventOptions } from '../../../modules/system/js/dompack/src/events';\nexport { qS, qR, qSA, isFormControl, isEditControl, isElement, isHTMLElement, getRelativeBounds, getLang } from './tree';\nexport type { FormControlElement, Rect } from './tree';\nexport { isDomReady, onDomReady } from '../../../modules/system/js/dompack/src/tree';\nexport { create, jsxcreate, jsxfragment } from '../../../modules/system/js/dompack/src/create';\nexport { focus, register, registerMissed } from '../../../modules/system/js/dompack/src/components';\nexport type { TakeFocusEvent } from '../../../modules/system/js/dompack/src/components';\nexport { getLocal, setLocal, getSession, setSession, listCookies, getCookie, setCookie, deleteCookie, listLocalKeys, listSessionKeys } from './storage';\nexport { loadImage, loadScript, loadCSS } from \"./preload\";\nexport { browser, getBrowser, isMultiSelectKey, isCopyKey } from './browser';\nexport type { KeyAttributeValue, UserAgentInfo, Platform, Device } from './browser';\n\n/** @deprecated As 'Lock' conflicts, in WH5.4+ you can safely switch to UIBusyLock */\nimport type { UIBusyLock } from './busy';\nexport type Lock = UIBusyLock;\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 { 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}\nexport function listSessionKeys() {\n  try {\n    return Object.keys(window.sessionStorage);\n  } catch (e) {\n    return Object.keys(backup.sessionStorage || {});\n  }\n}\nexport function listLocalKeys() {\n  try {\n    return Object.keys(window.localStorage);\n  } catch (e) {\n    return Object.keys(backup.localStorage || {});\n  }\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","export function interestErrors(input:{name?:unknown;email?:unknown;message?:unknown;language?:unknown}) {\n return {\n  name:typeof input.name!=='string'||!input.name.trim()||input.name.trim().length>120?'Vul je naam in (maximaal 120 tekens).':'',\n  email:typeof input.email!=='string'||input.email.length>254||!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(input.email.trim())?'Vul een geldig e-mailadres in.':'',\n  message:typeof input.message!=='string'||!input.message.trim()||input.message.trim().length>2000?'Vertel welke datum of periode je zoekt (maximaal 2000 tekens).':'',\n  language:!['nl','de','en'].includes(String(input.language))?'Kies Nederlands, Duits of Engels.':''\n };\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/gettid\" {\n}\n\nexport {\n  getTidLanguage,\n  setTidLanguage,\n  getTid,\n  getTidForLanguage,\n  getHTMLTid,\n  getHTMLTidForLanguage,\n  getTIDListForLanguage\n} from \"./internal\";\n","// Auto-generated language file from /opt/whdata/installedmodules/paswerk/web/widgets/widgets.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"paswerk\",\"nl\",{\"widgets\":{\"preview-sent\":\"Demonstratie: je aanvraag is gecontroleerd. Er is niets opgeslagen of verstuurd.\",\"courses-title\":\"Onze cursussen\",\"choose-course\":\"Kiezen\",\"chosen-course\":\"Gekozen\",\"equipment-included\":\"Uitrusting inbegrepen\",\"notice-days\":[\"Minstens \",1,\" dagen vooraf boeken\"],\"group-size\":[1,\" tot \",2,\" deelnemers\"],\"participants\":\"Deelnemers\",\"rental\":\"Huursets\",\"masks\":\"Losse maskers\",\"show\":\"Toon data\",\"first-available\":\"Eerste passende datum\",\"previous-month\":\"Vorige maand\",\"next-month\":\"Volgende maand\",\"legend-all\":\"Alle tijden beschikbaar\",\"legend-some\":\"Een deel\",\"legend-none\":\"Geen passend tijdstip\",\"no-sessions-month\":\"Geen data deze maand.\",\"choose-course-first\":\"Kies eerst een cursus.\",\"choose-day\":\"Kies een dag om de tijden te zien.\",\"times-on\":[\"Tijden op \",1],\"places-left\":[\"Nog \",1,\" plaatsen\"],\"full\":\"Vol\",\"not-for-group\":\"Niet voor deze groep\",\"book\":\"Dit tijdstip boeken\",\"selected\":[\"Gekozen: \",1],\"none-found\":\"Geen passende datum gevonden in de komende maanden.\",\"loading\":\"Laden…\",\"error\":\"Er ging iets mis. Probeer het opnieuw.\",\"unavailable\":\"Deze cursus is niet online te boeken.\",\"error-participants\":[\"Kies 1 tot en met \",1,\" deelnemers.\"],\"error-rental\":\"Niet meer huursets dan deelnemers.\",\"error-masks\":[\"Kies 0 tot en met \",1,\" maskers.\"],\"interest-open\":\"Geen passende datum?\",\"interest-title\":\"Welke datum zou je passen?\",\"interest-intro\":\"Laat weten welke periode je zoekt. Hiermee reserveer je nog niets.\",\"name\":\"Naam\",\"email\":\"E-mail\",\"contact-language\":\"Contacttaal\",\"message\":\"Gewenste datum of periode\",\"send\":\"Versturen\",\"sent\":\"Bedankt. We nemen contact met je op.\",\"error-name\":\"Vul je naam in.\",\"error-email\":\"Vul een geldig e-mailadres in.\",\"error-message\":\"Vertel welke datum of periode je zoekt.\",\"places-left-one\":\"Nog 1 plaats\",\"notice-days-one\":\"Minstens 1 dag vooraf boeken\",\"booking-title\":\"Boeken\",\"booking-choose-first\":\"Kies eerst een datum en een tijd.\",\"booking-when\":[1,\", \",2],\"booking-counts\":[1,\" deelnemer(s), \",2,\" huurset(s)\"],\"booking-masks\":[1,\" los(se) masker(s)\"],\"booking-hold\":\"Plaats vasthouden\",\"booking-held\":[\"We houden je plaats nog \",1,\" vast. Rond binnen die tijd af.\"],\"booking-details\":\"Jouw gegevens\",\"booking-pay\":\"Bestellen en betalen\",\"booking-release\":\"Plaats vrijgeven\",\"booking-paying\":\"Je betaling wordt verwerkt. Zodra de betaalprovider de uitkomst doorgeeft, zie je die hier.\",\"booking-check-again\":\"Opnieuw controleren\",\"booking-confirmed\":\"Je boeking is bevestigd. Tot ziens bij DiveWorld!\",\"booking-confirmed-late\":\"Je betaling kwam binnen nadat de reservering was verlopen. De plaats was nog vrij en is voor je geboekt.\",\"booking-rejected\":[\"De betaling is geweigerd. We houden je plaats vast tot \",1,\"; je kunt het opnieuw proberen.\"],\"booking-aborted\":[\"Je hebt het betalen afgebroken. We houden je plaats vast tot \",1,\".\"],\"booking-expired\":\"Je reservering is verlopen. Kies opnieuw een tijd.\",\"booking-released\":\"Je hebt de plaats vrijgegeven.\",\"booking-refund\":\"We hebben je betaling ontvangen, maar de plaats was niet meer vrij. We nemen contact met je op en betalen het bedrag terug.\",\"booking-mismatch\":\"Er klopt iets niet met je bestelling. Er is niets geboekt; we nemen contact met je op.\",\"booking-start-over\":\"Opnieuw kiezen\",\"booking-unavailable\":\"Deze tijd is niet meer beschikbaar. Kies een andere tijd.\",\"booking-busy\":\"Er loopt al een betaling voor deze plaats. Wacht op de uitkomst.\",\"booking-price\":\"Wat je bestelt\",\"booking-price-line\":[1,\" × \",2],\"booking-total\":\"Totaal (incl. btw)\",\"booking-seller\":\"Verkoper\",\"booking-kvk\":[\"KvK \",1],\"booking-vat\":[\"btw \",1],\"booking-cancellation\":\"Annuleren\",\"booking-withdrawal\":\"Herroepingsrecht\",\"booking-terms\":\"Algemene voorwaarden\",\"booking-privacy\":\"Privacyverklaring\",\"booking-minutes-left\":[\"Nog \",1,\" minuten om af te ronden.\"],\"booking-minute-left\":\"Nog 1 minuut om af te ronden.\",\"booking-too-many\":\"Je houdt al te veel plaatsen tegelijk vast. Rond die eerst af of wacht tot er een verloopt.\",\"booking-not-configured\":\"Online boeken is nog niet beschikbaar. Neem contact op met DiveWorld.\",\"booking-cart\":\"Je plaats wordt vastgehouden. Voeg de cursus toe aan je winkelwagen om af te rekenen.\"}});\nregisterTexts(\"paswerk\",\"de\",{\"widgets\":{\"preview-sent\":\"Demonstration: Ihre Anfrage wurde geprüft. Es wurde nichts gespeichert oder versendet.\",\"courses-title\":\"Unsere Kurse\",\"choose-course\":\"Auswählen\",\"chosen-course\":\"Ausgewählt\",\"equipment-included\":\"Ausrüstung inklusive\",\"notice-days\":[\"Mindestens \",1,\" Tage im Voraus buchen\"],\"group-size\":[1,\" bis \",2,\" Teilnehmer\"],\"participants\":\"Teilnehmer\",\"rental\":\"Leihsets\",\"masks\":\"Einzelne Masken\",\"show\":\"Termine anzeigen\",\"first-available\":\"Erster passender Termin\",\"previous-month\":\"Vorheriger Monat\",\"next-month\":\"Nächster Monat\",\"legend-all\":\"Alle Zeiten verfügbar\",\"legend-some\":\"Einige Zeiten\",\"legend-none\":\"Kein passender Termin\",\"no-sessions-month\":\"Keine Termine in diesem Monat.\",\"choose-course-first\":\"Wählen Sie zuerst einen Kurs.\",\"choose-day\":\"Wählen Sie einen Tag, um die Zeiten zu sehen.\",\"times-on\":[\"Zeiten am \",1],\"places-left\":[\"Noch \",1,\" Plätze\"],\"full\":\"Ausgebucht\",\"not-for-group\":\"Nicht für diese Gruppe\",\"book\":\"Diesen Termin buchen\",\"selected\":[\"Ausgewählt: \",1],\"none-found\":\"In den nächsten Monaten kein passender Termin gefunden.\",\"loading\":\"Wird geladen…\",\"error\":\"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.\",\"unavailable\":\"Dieser Kurs ist online nicht buchbar.\",\"error-participants\":[\"Wählen Sie 1 bis \",1,\" Teilnehmer.\"],\"error-rental\":\"Nicht mehr Leihsets als Teilnehmer.\",\"error-masks\":[\"Wählen Sie 0 bis \",1,\" Masken.\"],\"interest-open\":\"Kein passender Termin?\",\"interest-title\":\"Welcher Termin würde Ihnen passen?\",\"interest-intro\":\"Teilen Sie uns mit, welchen Zeitraum Sie suchen. Damit wird noch nichts reserviert.\",\"name\":\"Name\",\"email\":\"E-Mail\",\"contact-language\":\"Kontaktsprache\",\"message\":\"Gewünschtes Datum oder Zeitraum\",\"send\":\"Senden\",\"sent\":\"Vielen Dank. Wir melden uns bei Ihnen.\",\"error-name\":\"Bitte geben Sie Ihren Namen ein.\",\"error-email\":\"Bitte geben Sie eine gültige E-Mail-Adresse ein.\",\"error-message\":\"Teilen Sie uns mit, welchen Termin oder Zeitraum Sie suchen.\",\"places-left-one\":\"Noch 1 Platz\",\"notice-days-one\":\"Mindestens 1 Tag im Voraus buchen\",\"booking-title\":\"Buchen\",\"booking-choose-first\":\"Wählen Sie zuerst ein Datum und eine Uhrzeit.\",\"booking-when\":[1,\", \",2],\"booking-counts\":[1,\" Teilnehmer, \",2,\" Leihset(s)\"],\"booking-masks\":[1,\" einzelne Maske(n)\"],\"booking-hold\":\"Platz reservieren\",\"booking-held\":[\"Wir halten Ihren Platz noch \",1,\" frei. Bitte schließen Sie die Buchung in dieser Zeit ab.\"],\"booking-details\":\"Ihre Angaben\",\"booking-pay\":\"Kostenpflichtig bestellen\",\"booking-release\":\"Platz freigeben\",\"booking-paying\":\"Ihre Zahlung wird verarbeitet. Sobald der Zahlungsanbieter das Ergebnis meldet, sehen Sie es hier.\",\"booking-check-again\":\"Erneut prüfen\",\"booking-confirmed\":\"Ihre Buchung ist bestätigt. Bis bald bei DiveWorld!\",\"booking-confirmed-late\":\"Ihre Zahlung kam nach Ablauf der Reservierung an. Der Platz war noch frei und ist für Sie gebucht.\",\"booking-rejected\":[\"Die Zahlung wurde abgelehnt. Wir halten Ihren Platz bis \",1,\" frei; Sie können es erneut versuchen.\"],\"booking-aborted\":[\"Sie haben die Zahlung abgebrochen. Wir halten Ihren Platz bis \",1,\" frei.\"],\"booking-expired\":\"Ihre Reservierung ist abgelaufen. Bitte wählen Sie erneut eine Uhrzeit.\",\"booking-released\":\"Sie haben den Platz freigegeben.\",\"booking-refund\":\"Wir haben Ihre Zahlung erhalten, aber der Platz war nicht mehr frei. Wir melden uns bei Ihnen und erstatten den Betrag.\",\"booking-mismatch\":\"Mit Ihrer Bestellung stimmt etwas nicht. Es wurde nichts gebucht; wir melden uns bei Ihnen.\",\"booking-start-over\":\"Neu wählen\",\"booking-unavailable\":\"Diese Uhrzeit ist nicht mehr verfügbar. Bitte wählen Sie eine andere Uhrzeit.\",\"booking-busy\":\"Für diesen Platz läuft bereits eine Zahlung. Bitte warten Sie auf das Ergebnis.\",\"booking-price\":\"Ihre Bestellung\",\"booking-price-line\":[1,\" × \",2],\"booking-total\":\"Gesamt (inkl. MwSt.)\",\"booking-seller\":\"Verkäufer\",\"booking-kvk\":[\"Handelsregister (KvK) \",1],\"booking-vat\":[\"USt-IdNr. \",1],\"booking-cancellation\":\"Stornierung\",\"booking-withdrawal\":\"Widerrufsrecht\",\"booking-terms\":\"Allgemeine Geschäftsbedingungen\",\"booking-privacy\":\"Datenschutzerklärung\",\"booking-minutes-left\":[\"Noch \",1,\" Minuten, um die Buchung abzuschließen.\"],\"booking-minute-left\":\"Noch 1 Minute, um die Buchung abzuschließen.\",\"booking-too-many\":\"Sie halten bereits zu viele Plätze gleichzeitig. Bitte schließen Sie diese zuerst ab oder warten Sie, bis eine Reservierung abläuft.\",\"booking-not-configured\":\"Online-Buchungen sind noch nicht verfügbar. Bitte wenden Sie sich an DiveWorld.\",\"booking-cart\":\"Ihr Platz wird freigehalten. Legen Sie den Kurs in den Warenkorb, um zu bezahlen.\"}});\nregisterTexts(\"paswerk\",\"en\",{\"widgets\":{\"preview-sent\":\"Demo: your request has been checked. Nothing was saved or sent.\",\"courses-title\":\"Our courses\",\"choose-course\":\"Choose\",\"chosen-course\":\"Chosen\",\"equipment-included\":\"Equipment included\",\"notice-days\":[\"Book at least \",1,\" days ahead\"],\"group-size\":[1,\" to \",2,\" participants\"],\"participants\":\"Participants\",\"rental\":\"Rental sets\",\"masks\":\"Extra masks\",\"show\":\"Show dates\",\"first-available\":\"First available date\",\"previous-month\":\"Previous month\",\"next-month\":\"Next month\",\"legend-all\":\"All times available\",\"legend-some\":\"Some times\",\"legend-none\":\"No suitable time\",\"no-sessions-month\":\"No dates this month.\",\"choose-course-first\":\"Choose a course first.\",\"choose-day\":\"Choose a day to see the times.\",\"times-on\":[\"Times on \",1],\"places-left\":[1,\" places left\"],\"full\":\"Full\",\"not-for-group\":\"Not for this group\",\"book\":\"Book this time\",\"selected\":[\"Selected: \",1],\"none-found\":\"No suitable date found in the coming months.\",\"loading\":\"Loading…\",\"error\":\"Something went wrong. Please try again.\",\"unavailable\":\"This course cannot be booked online.\",\"error-participants\":[\"Choose 1 to \",1,\" participants.\"],\"error-rental\":\"No more rental sets than participants.\",\"error-masks\":[\"Choose 0 to \",1,\" masks.\"],\"interest-open\":\"No suitable date?\",\"interest-title\":\"Which date would suit you?\",\"interest-intro\":\"Tell us which period you are looking for. This does not reserve anything.\",\"name\":\"Name\",\"email\":\"E-mail\",\"contact-language\":\"Contact language\",\"message\":\"Preferred date or period\",\"send\":\"Send\",\"sent\":\"Thank you. We will contact you.\",\"error-name\":\"Please enter your name.\",\"error-email\":\"Please enter a valid e-mail address.\",\"error-message\":\"Tell us which date or period you are looking for.\",\"places-left-one\":\"1 place left\",\"notice-days-one\":\"Book at least 1 day ahead\",\"booking-title\":\"Book\",\"booking-choose-first\":\"Choose a date and a time first.\",\"booking-when\":[1,\", \",2],\"booking-counts\":[1,\" participant(s), \",2,\" rental set(s)\"],\"booking-masks\":[1,\" separate mask(s)\"],\"booking-hold\":\"Hold this place\",\"booking-held\":[\"We are holding your place for another \",1,\". Please finish within that time.\"],\"booking-details\":\"Your details\",\"booking-pay\":\"Order and pay\",\"booking-release\":\"Release this place\",\"booking-paying\":\"Your payment is being processed. As soon as the payment provider reports the result, you will see it here.\",\"booking-check-again\":\"Check again\",\"booking-confirmed\":\"Your booking is confirmed. See you at DiveWorld!\",\"booking-confirmed-late\":\"Your payment arrived after the reservation had expired. The place was still free and has been booked for you.\",\"booking-rejected\":[\"The payment was declined. We are holding your place until \",1,\"; you can try again.\"],\"booking-aborted\":[\"You cancelled the payment. We are holding your place until \",1,\".\"],\"booking-expired\":\"Your reservation has expired. Please choose a time again.\",\"booking-released\":\"You released the place.\",\"booking-refund\":\"We received your payment, but the place was no longer available. We will contact you and refund the amount.\",\"booking-mismatch\":\"Something is wrong with your order. Nothing has been booked; we will contact you.\",\"booking-start-over\":\"Choose again\",\"booking-unavailable\":\"This time is no longer available. Please choose another time.\",\"booking-busy\":\"A payment for this place is already in progress. Please wait for the result.\",\"booking-price\":\"Your order\",\"booking-price-line\":[1,\" × \",2],\"booking-total\":\"Total (incl. VAT)\",\"booking-seller\":\"Seller\",\"booking-kvk\":[\"Chamber of Commerce (KvK) \",1],\"booking-vat\":[\"VAT \",1],\"booking-cancellation\":\"Cancellation\",\"booking-withdrawal\":\"Right of withdrawal\",\"booking-terms\":\"Terms and conditions\",\"booking-privacy\":\"Privacy statement\",\"booking-minutes-left\":[1,\" minutes left to finish.\"],\"booking-minute-left\":\"1 minute left to finish.\",\"booking-too-many\":\"You are already holding too many places at once. Please finish those first or wait until one expires.\",\"booking-not-configured\":\"Online booking is not available yet. Please contact DiveWorld.\",\"booking-cart\":\"Your place is being held. Add the course to your shopping cart to pay.\"}});\n// Adding dependency: /opt/whdata/installedmodules/paswerk/language/nl.xml\n// Adding dependency: /opt/whdata/installedmodules/paswerk/language/de.xml\n// Adding dependency: /opt/whdata/installedmodules/paswerk/language/default.xml\n","import type { OfferSlot } from '../api/public-offer';\n\n/** Group public slots by their venue date, never by the visitor's time zone.\n * Keep capacity per slot: adding remaining places across times would mislead.\n * Self-contained so the same function can be included in the widget client.\n */\nexport function offerCalendar(slots: OfferSlot[], timeZone = 'Europe/Amsterdam') {\n  const format = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' });\n  const grouped = new Map<string, OfferSlot[]>();\n  for (const slot of slots) {\n    const parts = format.formatToParts(new Date(slot.starts));\n    const part = (name: string) => parts.find(p => p.type === name)!.value;\n    const date = `${part('year')}-${part('month')}-${part('day')}`;\n    const day = grouped.get(date) ?? [];\n    day.push(slot);\n    grouped.set(date, day);\n  }\n  return [...grouped].sort(([a], [b]) => a.localeCompare(b)).map(([date, day]) => {\n    const available = day.filter(slot => slot.available).length;\n    return {\n      date,\n      state: available === 0 ? 'unavailable' : available === day.length ? 'available' : 'partial',\n      available,\n      slots: day.sort((a, b) => Date.parse(a.starts) - Date.parse(b.starts) || a.session - b.session)\n    };\n  });\n}\n","/**\n * Pure logic of the public widgets (docs/publieke-widgets.md), without DOM: testable in node and in the browser.\n * Dates are the venue's (Europe/Amsterdam) calendar dates, never the visitor's time zone.\n */\nimport { offerCalendar } from '../offer-calendar';\nimport type { OfferSlot } from '../../api/public-offer';\n\nexport type Lang = 'nl' | 'de' | 'en';\nexport type Counts = { participants: number; rental: number; masks: number };\nexport type Course = { id: number; title: string; category: string; minimum: number; maximum: number; noticeDays: number; equipmentIncluded: boolean; masks: boolean };\n\n/** What one widget tells the others in its group. A selection never reserves anything. */\nexport type WidgetEvent =\n  | { type: 'course'; course: Course }\n  | { type: 'counts'; course: number; counts: Counts }\n  | { type: 'day'; course: number; counts: Counts; date: string; slots: OfferSlot[] }\n  | { type: 'slot'; course: number; counts: Counts; slot: OfferSlot };\nexport const eventName = (group: string) => `paswerk:${group}`;\n\n/** The widget's language: its own `lang`, else the page's, else Dutch. Only the three supported ones. */\nexport function widgetLang(own: string | null, page: string | null): Lang {\n  for (const value of [own, page]) {\n    const code = value?.toLowerCase().split('-')[0];\n    if (code === 'nl' || code === 'de' || code === 'en') return code;\n  }\n  return 'nl';\n}\n\nconst locale = (lang: Lang) => ({ nl: 'nl-NL', de: 'de-DE', en: 'en-GB' })[lang];\nconst zone = 'Europe/Amsterdam';\n\n/** A month grid (Monday first) with each day's state from the offer, and empty cells before the 1st. */\nexport function monthGrid(month: string, slots: OfferSlot[]) {\n  const [year, number] = month.split('-').map(Number) as [number, number];\n  const days = new Date(Date.UTC(year, number, 0)).getUTCDate();\n  const firstWeekday = (new Date(Date.UTC(year, number - 1, 1)).getUTCDay() + 6) % 7;\n  const byDate = new Map(offerCalendar(slots, zone).map(d => [d.date, d]));\n  const cells: Array<null | { date: string; day: number; state: '' | 'available' | 'partial' | 'unavailable'; slots: OfferSlot[] }> = Array(firstWeekday).fill(null);\n  for (let day = 1; day <= days; day++) {\n    const date = `${month}-${String(day).padStart(2, '0')}`;\n    const entry = byDate.get(date);\n    cells.push({ date, day, state: entry ? entry.state as 'available' | 'partial' | 'unavailable' : '', slots: entry?.slots ?? [] });\n  }\n  return cells;\n}\n\nexport function shiftMonth(month: string, delta: number) {\n  const [year, number] = month.split('-').map(Number) as [number, number];\n  return new Date(Date.UTC(year, number - 1 + delta, 1)).toISOString().slice(0, 7);\n}\n\nexport function monthTitle(month: string, lang: Lang) {\n  return new Intl.DateTimeFormat(locale(lang), { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(new Date(`${month}-01T12:00:00Z`));\n}\nexport function weekdayNames(lang: Lang) {\n  return Array.from({ length: 7 }, (_, i) => new Intl.DateTimeFormat(locale(lang), { weekday: 'short', timeZone: 'UTC' }).format(new Date(Date.UTC(2024, 0, 1 + i))));\n}\nexport function dayTitle(date: string, lang: Lang) {\n  return new Intl.DateTimeFormat(locale(lang), { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }).format(new Date(`${date}T12:00:00Z`));\n}\nexport function timeRange(slot: { starts: string; ends: string }, lang: Lang) {\n  const f = new Intl.DateTimeFormat(locale(lang), { hour: '2-digit', minute: '2-digit', timeZone: zone });\n  return `${f.format(new Date(slot.starts))}–${f.format(new Date(slot.ends))}`;\n}\n\n/** Client-side count check, the same rules as the server's (booking-counts.ts), reported per field as a tid. */\nexport function countProblems(c: Counts, masksAllowed: boolean, maximum = 6) {\n  return {\n    participants: !Number.isSafeInteger(c.participants) || c.participants < 1 || c.participants > maximum ? 'error-participants' : '',\n    rental: !Number.isSafeInteger(c.rental) || c.rental < 0 || c.rental > c.participants ? 'error-rental' : '',\n    masks: !Number.isSafeInteger(c.masks) || c.masks < 0 || c.masks > maximum || c.masks > 0 && !masksAllowed ? 'error-masks' : '',\n  };\n}\n\n/** Map the server's interest field problems to tids (the server speaks Dutch; the widget speaks the visitor's language). */\nexport function interestProblemTids(fields: Record<string, string> | undefined) {\n  const map: Record<string, string> = { name: 'error-name', email: 'error-email', message: 'error-message', language: 'error' };\n  return Object.fromEntries(Object.entries(fields ?? {}).filter(([, v]) => v).map(([k]) => [k, map[k] ?? 'error']));\n}\n","/**\n * Pure logic of <paswerk-booking> (docs/publieke-widgets.md, Boekingsstraat), without DOM: testable in node.\n * What the visitor sees comes from the server's progress of their own claim, never from a payment redirect.\n */\nimport type { Counts } from './logic';\n\n/** The server's answer for a claim (api/payment-port.ts#claimProgress). */\nexport type Progress =\n  | { status: 'missing' }\n  | { status: 'active' | 'paying' | 'confirmed' | 'released' | 'expired' | 'attention'; outcome: { state: string; status: string } | null;\n    expires: string; starts: string; ends: string; course: string; participants: number; rental: number; masks: number; };\n\n/** A chosen time, from the group's slot event or from a booking page's URL. Reserves nothing. */\nexport type Selection = { course: number; session: number; counts: Counts; starts?: string; ends?: string };\n\nexport type View =\n  | { view: 'empty' }\n  | { view: 'chosen' }\n  | { view: 'held'; notice: '' | 'booking-rejected' | 'booking-aborted' }\n  | { view: 'paying' }\n  | { view: 'done'; tid: 'booking-confirmed' | 'booking-confirmed-late' }\n  | { view: 'ended'; tid: 'booking-expired' | 'booking-released' | 'booking-refund' | 'booking-mismatch' };\n\n/** From the server's progress (or none yet) to what the widget shows. */\nexport function viewOf(progress: Progress | null, selection: Selection | null): View {\n  if (!progress || progress.status === 'missing') return selection ? { view: 'chosen' } : { view: 'empty' };\n  switch (progress.status) {\n    case 'confirmed': return { view: 'done', tid: progress.outcome?.state === 'confirmedLate' ? 'booking-confirmed-late' : 'booking-confirmed' };\n    case 'paying': return { view: 'paying' };\n    case 'attention': return { view: 'ended', tid: progress.outcome?.state === 'refund' ? 'booking-refund' : 'booking-mismatch' };\n    case 'expired': return { view: 'ended', tid: 'booking-expired' };\n    case 'released': return { view: 'ended', tid: 'booking-released' };\n    case 'active': {\n      const last = progress.outcome?.state === 'released' ? progress.outcome.status : '';\n      return { view: 'held', notice: last === 'cancelled' ? 'booking-aborted' : last === 'failed' ? 'booking-rejected' : '' };\n    }\n  }\n}\n\n/** Remaining time as m:ss, or null once expired. */\nexport function remaining(expires: string, now: number) {\n  const ms = Date.parse(expires) - now;\n  if (!(ms > 0)) return null;\n  const s = Math.ceil(ms / 1000);\n  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;\n}\n\n/** A booking page's URL as written by <paswerk-slots booking-url>: ?session=&participants=&rental= (and course). */\nexport function selectionFromUrl(search: string, course: number): Selection | null {\n  const p = new URLSearchParams(search);\n  const n = (name: string, fallback = 0) => p.has(name) ? Number(p.get(name)) : fallback;\n  const session = n('session'), participants = n('participants', 1), rental = n('rental'), masks = n('masks');\n  const chosenCourse = n('course', course);\n  if (![session, participants, rental, masks, chosenCourse].every(Number.isSafeInteger) || session <= 0 || chosenCourse <= 0 || participants < 1 || rental < 0 || masks < 0) return null;\n  return { course: chosenCourse, session, counts: { participants, rental, masks } };\n}\n\n/** The claim's browser secret: 32 random bytes as hex, kept only in this tab's sessionStorage. */\nexport function newSecret() {\n  return Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, '0')).join('');\n}\n","import { interestErrors } from '../../api/interest-validation';\n/**\n * Paswerk's public widgets (docs/publieke-widgets.md), one assetpack that registers four elements once:\n *   <paswerk-offer>     the published courses; choosing one tells the group\n *   <paswerk-calendar>  counts, a month with coloured days (with words, not colour alone); choosing a day tells the group\n *   <paswerk-slots>     the times of the chosen day with the places left; choosing a time tells the group\n *   <paswerk-interest>  \"no suitable date?\": a request that reserves nothing\n * Attributes: `group` (widgets with the same group work together; default \"default\"), `course` (preselect),\n * `lang` (nl/de/en; else the page's), `endpoint` (Paswerk's widget API; default this site's /.paswerk-widgets/).\n * Nothing here reserves, pays or shows a customer. The server decides what is bookable.\n * The fifth element, <paswerk-booking>, is the booking street: it claims a chosen time, takes the customer's details\n * and hands over to the payment port; what it shows afterwards comes only from the server.\n */\nimport { getTid } from '@webhare/gettid';\n// The widgets' texts (language/*.xml, group `widgets`) compiled into this assetpack for every supported language.\nimport './widgets.lang.json';\nimport { countProblems, dayTitle, eventName, interestProblemTids, monthGrid, monthTitle, shiftMonth, timeRange, weekdayNames, widgetLang, type Counts, type Course, type Lang, type WidgetEvent } from './logic';\nimport type { OfferSlot } from '../../api/public-offer';\nimport { newSecret, remaining, selectionFromUrl, viewOf, type Progress, type Selection } from './booking-logic';\n\nconst css = `:host{display:block;font:inherit;color:var(--paswerk-text,#17313c);--accent:var(--paswerk-accent,#086a78)}\n*{box-sizing:border-box}h2{font-size:1.15em;margin:0 0 .6em}button{font:inherit;cursor:pointer;border:1px solid #91aeb9;border-radius:8px;background:#fff;color:inherit;padding:.5em .9em}\nbutton:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid var(--paswerk-focus,#edaa46);outline-offset:2px}\nbutton[aria-pressed=true]{border:2px solid var(--accent);background:#e5f5f6}button:disabled{opacity:.55;cursor:default}.primary{background:var(--accent);color:#fff;border-color:var(--accent)}\nlabel{display:block;font-weight:600;margin:.4em 0}input,select,textarea{display:block;font:inherit;padding:.45em;border:1px solid #a4bbc4;border-radius:7px;margin-top:.25em}textarea{width:100%;min-height:6em}\n.row{display:flex;gap:1em;flex-wrap:wrap;align-items:end}.row input{width:6em}.error{color:#9b302c;font-size:.9em;font-weight:400}.muted{color:#5c7078;font-size:.9em}.status{min-height:1.4em}\n.courses{list-style:none;padding:0;margin:0;display:grid;gap:.6em}.courses li{display:flex;justify-content:space-between;gap:1em;align-items:center;border:1px solid #d6e2e7;border-radius:10px;padding:.7em}\n.nav{display:flex;justify-content:space-between;align-items:center;margin:.8em 0}.days{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:4px}.wd{text-align:center;font-size:.75em;color:#61747b}\n.day{padding:.45em 0;min-height:2.6em;border-color:transparent;background:#f1f4f5;color:#8c9da4}.day[data-state=available]{background:#def2e9;color:#176044}.day[data-state=partial]{background:#fff0ce;color:#765309}.day[data-state=unavailable]{background:#f7e2df;color:#8f3c32}\n.legend{display:flex;gap:1em;flex-wrap:wrap;font-size:.8em;color:#526d77;margin-top:.6em}.slots{display:grid;grid-template-columns:repeat(auto-fit,minmax(11em,1fr));gap:.5em}.slot{text-align:left;white-space:pre-line}[hidden]{display:none!important}\n.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}.price{border-collapse:collapse;width:100%}.price td,.price th{padding:.25em 0;text-align:left;vertical-align:top}.price td+td,.price th+th{text-align:right;white-space:nowrap}h3{font-size:1em;margin:1em 0 .3em}a{color:var(--accent)}input,select{max-width:100%}`;\n\nlet shared: CSSStyleSheet | null = null;\n/** One stylesheet for every widget on the page. */\nfunction sheet() {\n  if (!shared) { shared = new CSSStyleSheet(); shared.replaceSync(css); }\n  return shared;\n}\n\ntype Fields = Record<string, string>;\nclass ApiError extends Error {\n  readonly status: number;\n  readonly body: { error?: string; fields?: Fields; interestFields?: Fields };\n  constructor(status: number, body: ApiError['body']) { super(body.error ?? 'error'); this.status = status; this.body = body; }\n}\n\nabstract class PaswerkWidget extends HTMLElement {\n  protected root!: ShadowRoot;\n  protected language: Lang = 'nl';\n  private listener = (e: Event) => this.onGroup((e as CustomEvent<WidgetEvent>).detail);\n\n  connectedCallback() {\n    this.language = widgetLang(this.getAttribute('lang'), document.documentElement.getAttribute('lang'));\n    if (!this.root) {\n      this.root = this.attachShadow({ mode: 'open' });\n      // A constructed stylesheet, not a <style> element: a site's Content-Security-Policy may forbid inline styles\n      // (WebHare's own default does), and CSSOM sheets are not subject to that.\n      this.root.adoptedStyleSheets = [sheet()];\n      this.root.innerHTML = `<div part=\"body\"></div>`;\n    }\n    document.addEventListener(eventName(this.group), this.listener);\n    void this.start();\n  }\n  disconnectedCallback() { document.removeEventListener(eventName(this.group), this.listener); }\n\n  protected get group() { return `${new URL(this.getAttribute('endpoint') || '/.paswerk-widgets/', location.href).href}#${this.getAttribute('group') || 'default'}`; }\n  protected get body() { return this.root.querySelector('[part=body]') as HTMLElement; }\n  protected t(tid: string, params: Array<string | number> = []) { return getTid(`paswerk:widgets.${tid}`, params.map(String), { langCode: this.language }); }\n  protected tell(detail: WidgetEvent) { document.dispatchEvent(new CustomEvent(eventName(this.group), { detail })); }\n  /** A small element factory: properties are assigned as-is (textContent, value, disabled, type, …). */\n  protected el(tag: string, props: Record<string, unknown> = {}, ...children: Array<Node | string>): HTMLElement {\n    const node = Object.assign(document.createElement(tag), props);\n    node.append(...children);\n    return node;\n  }\n  protected async api<T>(action: string, body?: object): Promise<T> {\n    const endpoint = new URL(this.getAttribute('endpoint') || '/.paswerk-widgets/', location.href);\n    endpoint.searchParams.set('action', action);\n    endpoint.searchParams.set('lang', this.language); // course names in the visitor's language\n    const response = await fetch(endpoint, body ? { method: 'POST', headers: { 'content-type': 'application/vnd.paswerk+json' }, body: JSON.stringify(body), credentials: 'omit' } : { credentials: 'omit' });\n    const json = await response.json().catch(() => ({}));\n    if (!response.ok) throw new ApiError(response.status, json);\n    return json as T;\n  }\n  protected abstract start(): Promise<void>;\n  protected onGroup(_event: WidgetEvent) { /* widgets that listen override this */ }\n}\n\n/** Remembered per group, so a widget added later starts from what the group already chose. */\nconst lastCourse = new Map<string, Course>();\n\nclass PaswerkOffer extends PaswerkWidget {\n  private courses: Course[] = [];\n  protected async start() {\n    this.body.replaceChildren(this.el('p', { className: 'status', textContent: this.t('loading') }));\n    try { this.courses = (await this.api<{ courses: Course[] }>('catalog')).courses; } catch { this.body.replaceChildren(this.el('p', { className: 'error', textContent: this.t('error') })); return; }\n    this.render(Number(this.getAttribute('course')) || 0);\n    const preset = this.courses.find(c => c.id === Number(this.getAttribute('course')));\n    if (preset) this.choose(preset);\n  }\n  private render(chosen: number) {\n    const list = this.el('ul', { className: 'courses' });\n    for (const c of this.courses) {\n      const info = [c.category, c.maximum ? this.t('group-size', [Math.max(1, c.minimum), c.maximum]) : '', c.equipmentIncluded ? this.t('equipment-included') : '', c.noticeDays ? (c.noticeDays === 1 ? this.t('notice-days-one') : this.t('notice-days', [c.noticeDays])) : ''].filter(Boolean).join(' · ');\n      const button = this.el('button', { textContent: c.id === chosen ? this.t('chosen-course') : this.t('choose-course') });\n      button.setAttribute('aria-pressed', String(c.id === chosen));\n      button.setAttribute('aria-label', `${this.t('choose-course')}: ${c.title}`);\n      button.onclick = () => this.choose(c);\n      list.append(this.el('li', {}, this.el('div', {}, this.el('strong', { textContent: c.title }), this.el('div', { className: 'muted', textContent: info })), button));\n    }\n    this.body.replaceChildren(this.el('h2', { textContent: this.t('courses-title') }), list);\n  }\n  private choose(course: Course) { lastCourse.set(this.group, course); this.render(course.id); this.tell({ type: 'course', course }); }\n}\n\nclass PaswerkCalendar extends PaswerkWidget {\n  private course: Course | null = null;\n  private month = new Date().toISOString().slice(0, 7);\n  private slots: OfferSlot[] = [];\n  private chosenDate = '';\n  private counts: Counts = { participants: 1, rental: 0, masks: 0 };\n  private status = '';\n  protected async start() {\n    const id = Number(this.getAttribute('course'));\n    this.course = lastCourse.get(this.group) ?? null;\n    if (id && this.course?.id !== id) {\n      try { this.course = (await this.api<{ courses: Course[] }>('catalog')).courses.find(c => c.id === id) ?? null; } catch { this.course = null; }\n      if (!this.course) { this.status = this.t('unavailable'); }\n    }\n    this.render();\n    if (this.course) await this.load();\n  }\n  protected onGroup(e: WidgetEvent) {\n    if (e.type === 'course') { this.course = e.course; this.chosenDate = ''; this.render(); void this.load(); }\n  }\n  private readCounts(): Counts {\n    const v = (name: string) => Number((this.root.querySelector(`[name=${name}]`) as HTMLInputElement | null)?.value ?? 0);\n    return { participants: v('participants'), rental: this.course?.equipmentIncluded ? v('participants') : v('rental'), masks: this.course?.masks ? v('masks') : 0 };\n  }\n  private async load(month = this.month) {\n    if (!this.course) return;\n    const counts = this.readCounts();\n    this.counts = counts; // kept as typed, also when invalid, so the visitor sees what to correct\n    const problems = countProblems(counts, this.course.masks, this.course.maximum);\n    if (Object.values(problems).some(Boolean)) { this.slots = []; this.chosenDate = ''; this.tell({ type: 'counts', course: this.course.id, counts }); this.render(problems); return; }\n    this.status = this.t('loading'); this.render();\n    try {\n      const offer = await this.api<{ slots: OfferSlot[]; month: string }>('offer', { activity: this.course.id, month, ...counts });\n      this.month = offer.month; this.slots = offer.slots; this.status = this.slots.length ? '' : this.t('no-sessions-month');\n      this.tell({ type: 'counts', course: this.course.id, counts });\n    } catch (error) {\n      this.status = error instanceof ApiError && error.status === 404 ? this.t('unavailable') : this.t('error');\n    }\n    this.render();\n  }\n  private async first() {\n    if (!this.course) return;\n    const counts = this.readCounts();\n    this.counts = counts;\n    const problems = countProblems(counts, this.course.masks, this.course.maximum);\n    if (Object.values(problems).some(Boolean)) { this.slots = []; this.chosenDate = ''; this.tell({ type: 'counts', course: this.course.id, counts }); this.render(problems); return; }\n    try {\n      const { slot } = await this.api<{ slot: OfferSlot | null }>('first', { activity: this.course.id, ...counts });\n      if (!slot) { this.status = this.t('none-found'); this.render(); return; }\n      await this.load(new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Amsterdam', year: 'numeric', month: '2-digit' }).format(new Date(slot.starts)));\n      const date = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Amsterdam', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(slot.starts));\n      this.pick(date);\n    } catch { this.status = this.t('error'); this.render(); }\n  }\n  private pick(date: string) {\n    const cell = monthGrid(this.month, this.slots).find(c => c?.date === date);\n    if (!cell || !this.course) return;\n    this.chosenDate = date; this.render();\n    this.tell({ type: 'day', course: this.course.id, counts: this.counts, date, slots: cell.slots });\n  }\n  private render(problems: Record<string, string> = {}) {\n    if (!this.course) { this.body.replaceChildren(this.el('p', { className: 'muted', textContent: this.status || this.t('choose-course-first') })); return; }\n    const field = (name: keyof Counts, value: number, max: number) => {\n      const input = this.el('input', { type: 'number', name, min: name === 'participants' ? '1' : '0', max: String(max), value: String(value) });\n      const error = this.el('span', { className: 'error', textContent: problems[name] ? this.t(problems[name]!, [this.course!.maximum]) : '' });\n      input.setAttribute('aria-invalid', String(Boolean(problems[name])));\n      return this.el('label', {}, this.t(name), input, error);\n    };\n    const counts = this.el('div', { className: 'row' }, field('participants', this.counts.participants, this.course.maximum), this.course.equipmentIncluded ? this.el('p', { className: 'muted', textContent: this.t('equipment-included') }) : field('rental', this.counts.rental, this.course.maximum), ...(this.course.masks ? [field('masks', this.counts.masks, this.course.maximum)] : []));\n    const show = this.el('button', { textContent: this.t('show') }); show.onclick = () => void this.load();\n    const first = this.el('button', { textContent: this.t('first-available') }); first.onclick = () => void this.first();\n    const prev = this.el('button', { textContent: '←' }); prev.setAttribute('aria-label', this.t('previous-month')); prev.onclick = () => void this.load(shiftMonth(this.month, -1));\n    const next = this.el('button', { textContent: '→' }); next.setAttribute('aria-label', this.t('next-month')); next.onclick = () => void this.load(shiftMonth(this.month, 1));\n    const days = this.el('div', { className: 'days' }, ...weekdayNames(this.language).map(n => this.el('div', { className: 'wd', textContent: n })));\n    const words = { available: this.t('legend-all'), partial: this.t('legend-some'), unavailable: this.t('legend-none'), '': '' };\n    for (const cell of monthGrid(this.month, this.slots)) {\n      if (!cell) { days.append(this.el('div')); continue; }\n      const b = this.el('button', { className: 'day', textContent: String(cell.day), disabled: !cell.state });\n      b.dataset.state = cell.state;\n      b.setAttribute('aria-pressed', String(cell.date === this.chosenDate));\n      b.setAttribute('aria-label', [dayTitle(cell.date, this.language), words[cell.state]].filter(Boolean).join(': '));\n      b.onclick = () => this.pick(cell.date);\n      days.append(b);\n    }\n    const legend = this.el('div', { className: 'legend' }, this.el('span', { textContent: `● ${words.available}` }), this.el('span', { textContent: `◐ ${words.partial}` }), this.el('span', { textContent: `○ ${words.unavailable}` }));\n    const status = this.el('p', { className: 'status', textContent: this.status }); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');\n    this.body.replaceChildren(this.el('h2', { textContent: this.course.title }), ...(this.course.noticeDays ? [this.el('p', { className: 'muted', textContent: this.course.noticeDays === 1 ? this.t('notice-days-one') : this.t('notice-days', [this.course.noticeDays]) })] : []), counts, this.el('div', { className: 'row' }, show, first),\n      this.el('div', { className: 'nav' }, prev, this.el('strong', { textContent: monthTitle(this.month, this.language) }), next), days, legend, status);\n  }\n}\n\nclass PaswerkSlots extends PaswerkWidget {\n  private day: Extract<WidgetEvent, { type: 'day' }> | null = null;\n  private chosen = 0;\n  protected async start() { this.render(); }\n  protected onGroup(e: WidgetEvent) {\n    if (e.type === 'day') { this.day = e; this.chosen = 0; this.render(); }\n    if (e.type === 'course' || e.type === 'counts') { this.day = null; this.render(); }\n  }\n  private render() {\n    if (!this.day) { this.body.replaceChildren(this.el('p', { className: 'muted', textContent: this.t('choose-day') })); return; }\n    const day = this.day;\n    const list = this.el('div', { className: 'slots' });\n    for (const slot of day.slots) {\n      const label = `${timeRange(slot, this.language)}\\n${slot.available ? (slot.remaining === 1 ? this.t('places-left-one') : this.t('places-left', [slot.remaining])) : slot.remaining > 0 ? this.t('not-for-group') : this.t('full')}`;\n      const b = this.el('button', { className: 'slot', textContent: label, disabled: !slot.available });\n      b.setAttribute('aria-pressed', String(slot.session === this.chosen));\n      b.onclick = () => { this.chosen = slot.session; this.render(); this.tell({ type: 'slot', course: day.course, counts: day.counts, slot }); };\n      list.append(b);\n    }\n    const chosen = day.slots.find(s => s.session === this.chosen);\n    const status = this.el('p', { className: 'status', textContent: chosen ? this.t('selected', [`${dayTitle(day.date, this.language)}, ${timeRange(chosen, this.language)}`]) : '' });\n    status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');\n    const parts: Node[] = [this.el('h2', { textContent: this.t('times-on', [dayTitle(day.date, this.language)]) }), list, status];\n    const booking = this.getAttribute('booking-url');\n    if (chosen && booking) {\n      const url = new URL(booking, location.href);\n      url.searchParams.set('session', String(chosen.session));\n      url.searchParams.set('participants', String(day.counts.participants));\n      url.searchParams.set('rental', String(day.counts.rental));\n      parts.push(this.el('a', { className: 'primary', href: url.href, textContent: this.t('book') }));\n    }\n    this.body.replaceChildren(...parts);\n  }\n}\n\nclass PaswerkInterest extends PaswerkWidget {\n  private course = 0;\n  private counts: Counts = { participants: 1, rental: 0, masks: 0 };\n  private open = false;\n  private sent = false;\n  // The server's idempotency key: 32 random bytes as hex (interests.ts), so a resend is the same request.\n  private requestKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, '0')).join('');\n  protected async start() { this.course = Number(this.getAttribute('course')) || lastCourse.get(this.group)?.id || 0; this.render(); }\n  protected onGroup(e: WidgetEvent) {\n    if (e.type === 'course') { this.course = e.course.id; this.render(); }\n    if (e.type === 'counts' || e.type === 'day') { this.counts = e.counts; }\n  }\n  private render(problems: Record<string, string> = {}, status = '') {\n    if (!this.course) { this.body.replaceChildren(); return; }\n    const toggle = this.el('button', { textContent: this.t('interest-open') });\n    toggle.setAttribute('aria-expanded', String(this.open));\n    toggle.onclick = () => { this.open = !this.open; this.render(); };\n    if (!this.open) { this.body.replaceChildren(toggle); return; }\n    if (this.sent) { this.body.replaceChildren(this.el('p', { className: 'status', textContent: this.t(this.hasAttribute('preview') ? 'preview-sent' : 'sent') })); return; }\n    const input = (name: string, props: Partial<HTMLInputElement>) => {\n      const el = this.el('input', { name, ...props }); el.setAttribute('aria-invalid', String(Boolean(problems[name])));\n      return this.el('label', {}, this.t(name), el, this.el('span', { className: 'error', textContent: problems[name] ? this.t(problems[name]!) : '' }));\n    };\n    const language = this.el('select', { name: 'language' }, ...(['nl', 'de', 'en'] as const).map(code => this.el('option', { value: code, textContent: { nl: 'Nederlands', de: 'Deutsch', en: 'English' }[code], selected: code === this.language })));\n    const message = this.el('textarea', { name: 'message', maxLength: 2000 }); message.setAttribute('aria-invalid', String(Boolean(problems.message)));\n    const send = this.el('button', { className: 'primary', textContent: this.t('send') });\n    send.onclick = () => void this.send();\n    const statusLine = this.el('p', { className: 'status', textContent: status }); statusLine.setAttribute('role', 'status');\n    this.body.replaceChildren(toggle, this.el('h2', { textContent: this.t('interest-title') }), this.el('p', { className: 'muted', textContent: this.t('interest-intro') }),\n      input('name', { maxLength: 120, autocomplete: 'name' }), input('email', { type: 'email', maxLength: 254, autocomplete: 'email' }),\n      this.el('label', {}, this.t('contact-language'), language), this.el('label', {}, this.t('message'), message, this.el('span', { className: 'error', textContent: problems.message ? this.t(problems.message) : '' })), send, statusLine);\n  }\n  private async send() {\n    const value = (name: string) => (this.root.querySelector(`[name=${name}]`) as HTMLInputElement).value;\n    const form = { name: value('name'), email: value('email'), language: value('language'), message: value('message') };\n    try {\n      if (this.hasAttribute('preview')) {\n        const problems = interestProblemTids(interestErrors(form));\n        if (Object.values(problems).some(Boolean)) { this.render(problems); for (const [k, v] of Object.entries(form)) { const el = this.root.querySelector(`[name=${k}]`) as HTMLInputElement | null; if (el) el.value = v; } return; }\n      } else await this.api('interest', { activity: this.course, ...this.counts, ...form, requestKey: this.requestKey });\n      this.sent = true; this.render();\n    } catch (error) {\n      const problems = error instanceof ApiError ? interestProblemTids(error.body.interestFields) : {};\n      this.render(problems, Object.keys(problems).length ? '' : this.t('error'));\n      for (const [k, v] of Object.entries(form)) { const el = this.root.querySelector(`[name=${k}]`) as HTMLInputElement | null; if (el) el.value = v; }\n    }\n  }\n}\n\n/** The booking street. Attributes as the others, plus `instance` to keep two streets on one page apart.\n *  The claim's secret lives only in this tab's sessionStorage, so a shared URL never reaches someone's booking.\n *  Before paying it shows the pre-contract information from the server (seller, items and price incl. VAT,\n *  conditions); the legal rules it follows are listed in docs/regels-boekingsstraat.md. */\ntype Quote = { lines: Array<{ title: string; quantity: number; unitCents: number; totalCents: number }>; totalCents: number };\ntype Legal = { companyName: string; address: string; kvk: string; vatNumber: string; email: string; phone: string; termsUrl: string; privacyUrl: string; cancellationText: string; withdrawalText: string };\ntype Stored = { token: string; requestKey: string; customer?: Record<string, string> };\nclass PaswerkBooking extends PaswerkWidget {\n  private selection: Selection | null = null;\n  private progress: Progress | null = null;\n  private offer: { quote: Quote; legal: Legal } | null = null;\n  private problems: Record<string, string> = {};\n  private notice = '';\n  private timer = 0;\n  private polls = 0;\n  private announced = -1;\n  private get storageKey() { return `paswerk-booking:${this.group}:${this.getAttribute('instance') ?? ''}`; }\n  private stored(): Stored | null {\n    try { return JSON.parse(sessionStorage.getItem(this.storageKey) ?? 'null'); } catch { return null; }\n  }\n  private store(value: Stored | null) {\n    try { if (value) sessionStorage.setItem(this.storageKey, JSON.stringify(value)); else sessionStorage.removeItem(this.storageKey); } catch { /* private mode: the claim then lasts this page view only */ }\n  }\n  protected async start() {\n    this.selection = selectionFromUrl(location.search, Number(this.getAttribute('course')) || lastCourse.get(this.group)?.id || 0);\n    if (this.stored()) await this.refresh(); else this.render();\n  }\n  disconnectedCallback() { super.disconnectedCallback(); clearInterval(this.timer); }\n  protected onGroup(e: WidgetEvent) {\n    if (e.type !== 'slot') return;\n    const held = this.progress && this.progress.status !== 'missing' && ['active', 'paying'].includes(this.progress.status);\n    if (held) return; // a held claim is released explicitly, never by browsing the calendar\n    this.selection = { course: e.course, session: e.slot.session, counts: e.counts, starts: e.slot.starts, ends: e.slot.ends };\n    this.progress = null; this.notice = ''; this.render();\n  }\n  private codeNotice(error: unknown) {\n    const code = error instanceof ApiError ? (error.body as { code?: string }).code : '';\n    return this.t({ paying: 'booking-busy', unavailable: 'booking-unavailable', 'too-many': 'booking-too-many', 'not-configured': 'booking-not-configured' }[code ?? ''] ?? (error instanceof ApiError && error.status === 404 ? 'booking-unavailable' : 'error'));\n  }\n  private async refresh() {\n    const own = this.stored();\n    if (!own) { this.progress = null; this.render(); return; }\n    try { this.progress = await this.api<Progress>('progress', { token: own.token }); } catch { this.notice = this.t('error'); }\n    if (this.progress?.status === 'missing') { this.store(null); this.progress = null; }\n    if (this.progress?.status === 'active' && !this.offer) await this.loadOffer();\n    this.render();\n  }\n  /** The price and the seller's conditions come from the server, never from this page. */\n  private async loadOffer() {\n    const own = this.stored();\n    if (!own) return;\n    try { this.offer = await this.api<{ quote: Quote; legal: Legal }>('quote', { token: own.token, lang: this.language }); } catch (error) { this.offer = null; this.notice = this.codeNotice(error); }\n  }\n  private async hold() {\n    if (!this.selection) return;\n    // Always a fresh secret: a token is bound to one claim and never reused.\n    const own = { token: newSecret(), requestKey: newSecret().slice(0, 40) };\n    this.store(own);\n    try {\n      this.progress = await this.api<Progress>('claim', { token: own.token, requestKey: own.requestKey, revision: 0, activity: this.selection.course, session: this.selection.session, ...this.selection.counts });\n      this.notice = '';\n      await this.loadOffer();\n    } catch (error) {\n      this.store(null);\n      this.notice = this.codeNotice(error);\n    }\n    this.render();\n  }\n  private async release() {\n    const own = this.stored();\n    if (!own) return;\n    try { this.progress = await this.api<Progress>('release', { token: own.token }); } catch (error) { this.notice = this.codeNotice(error); }\n    this.render();\n  }\n  private startOver() { this.store(null); this.progress = null; this.offer = null; this.notice = ''; this.render(); }\n  private async pay() {\n    const own = this.stored();\n    if (!own) return;\n    const value = (name: string) => (this.root.querySelector(`[name=${name}]`) as HTMLInputElement).value;\n    const customer = { name: value('name'), email: value('email'), language: value('language') };\n    // Kept in this tab only, so a declined or aborted payment does not mean typing everything again.\n    this.store({ ...own, customer });\n    try {\n      const { next } = await this.api<{ next: { type: 'redirect'; url: string } | { type: 'cart'; lines: unknown[] } }>('pay', { token: own.token, customer, returnUrl: location.href, lang: this.language });\n      if (next.type === 'redirect') { location.assign(next.url); return; }\n      // Webshop route: the product page's handler puts these lines in the shop's own cart (docs/webshop-koppeling.md).\n      this.dispatchEvent(new CustomEvent('paswerk:booking-cart', { detail: next, bubbles: true, composed: true }));\n      this.notice = this.t('booking-cart');\n      await this.refresh();\n    } catch (error) {\n      const fields = error instanceof ApiError ? (error.body as { customerFields?: Record<string, string> }).customerFields : undefined;\n      this.problems = Object.fromEntries(Object.keys(fields ?? {}).map(k => [k, k === 'language' ? 'error' : `error-${k}`]));\n      this.notice = Object.keys(this.problems).length ? '' : this.codeNotice(error);\n      this.render();\n      // WCAG 3.3.1: the first field with an error gets focus; its message is linked with aria-describedby.\n      (this.root.querySelector('[aria-invalid=true]') as HTMLElement | null)?.focus();\n    }\n  }\n  private money(cents: number) { return new Intl.NumberFormat(this.language, { style: 'currency', currency: 'EUR' }).format(cents / 100); }\n  private summary() {\n    const p = this.progress && this.progress.status !== 'missing' ? this.progress : null;\n    const slot = p ? { starts: p.starts, ends: p.ends } : this.selection?.starts && this.selection.ends ? { starts: this.selection.starts, ends: this.selection.ends } : null;\n    const date = slot ? new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Amsterdam', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(slot.starts)) : '';\n    const counts = p ? { participants: p.participants, rental: p.rental, masks: p.masks } : this.selection?.counts;\n    const lines = [p?.course ?? '', slot ? this.t('booking-when', [dayTitle(date, this.language), timeRange(slot, this.language)]) : '',\n      counts ? this.t('booking-counts', [counts.participants, counts.rental]) + (counts.masks ? `, ${this.t('booking-masks', [counts.masks])}` : '') : ''];\n    return this.el('p', {}, ...lines.filter(Boolean).flatMap((l, i) => i ? [this.el('br'), l] : [l]));\n  }\n  /** Pre-contract information (BW 6:230m): what is bought for how much incl. VAT, from whom, on which terms. */\n  private contract() {\n    if (!this.offer) return [this.el('p', { className: 'muted', textContent: this.t('loading') })];\n    const { quote, legal } = this.offer;\n    const table = this.el('table', { className: 'price' });\n    for (const l of quote.lines) table.append(this.el('tr', {}, this.el('td', { textContent: this.t('booking-price-line', [l.quantity, l.title]) }), this.el('td', { textContent: this.money(l.totalCents) })));\n    table.append(this.el('tr', {}, this.el('th', { textContent: this.t('booking-total') }), this.el('th', { textContent: this.money(quote.totalCents) })));\n    const link = (href: string, tid: string) => href ? this.el('a', { href, textContent: this.t(tid), target: '_blank', rel: 'noopener noreferrer' }) : this.el('span', { textContent: `${this.t(tid)}: [—]` });\n    const seller = [legal.companyName, legal.address, [legal.kvk && this.t('booking-kvk', [legal.kvk]), legal.vatNumber && this.t('booking-vat', [legal.vatNumber])].filter(Boolean).join(' · '), [legal.email, legal.phone].filter(Boolean).join(' · ')].filter(Boolean);\n    return [this.el('h3', { textContent: this.t('booking-price') }), table,\n      this.el('h3', { textContent: this.t('booking-seller') }), this.el('p', {}, ...seller.flatMap((l, i) => i ? [this.el('br'), l] : [l])),\n      this.el('h3', { textContent: this.t('booking-cancellation') }), this.el('p', { textContent: legal.cancellationText }),\n      this.el('h3', { textContent: this.t('booking-withdrawal') }), this.el('p', { textContent: legal.withdrawalText }),\n      this.el('p', {}, link(legal.termsUrl, 'booking-terms'), ' · ', link(legal.privacyUrl, 'booking-privacy'))];\n  }\n  private render() {\n    clearInterval(this.timer);\n    const view = viewOf(this.progress, this.selection);\n    if (view.view !== 'paying') this.polls = 0;\n    const status = this.el('p', { className: 'status', textContent: this.notice }); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');\n    const button = (tid: string, action: () => void, primary = false) => { const b = this.el('button', { type: 'button', textContent: this.t(tid), className: primary ? 'primary' : '' }); b.onclick = action; return b; };\n    const parts: Node[] = [this.el('h2', { textContent: this.t('booking-title') })];\n    if (view.view === 'empty') parts.push(this.el('p', { className: 'muted', textContent: this.t('booking-choose-first') }));\n    if (view.view === 'chosen') parts.push(this.summary(), button('booking-hold', () => void this.hold(), true));\n    if (view.view === 'held' && this.progress && this.progress.status !== 'missing') {\n      const expires = this.progress.expires;\n      // The visible clock ticks every second but is not announced; a polite live region speaks once a minute.\n      const clock = this.el('p', { className: 'muted' }); clock.setAttribute('aria-hidden', 'true');\n      const spoken = this.el('p', { className: 'sr' }); spoken.setAttribute('aria-live', 'polite');\n      const tick = () => {\n        const left = remaining(expires, Date.now());\n        if (left === null) { void this.refresh(); return; }\n        clock.textContent = this.t('booking-held', [left]);\n        const minutes = Math.ceil((Date.parse(expires) - Date.now()) / 60000);\n        if (minutes !== this.announced) { this.announced = minutes; spoken.textContent = this.t(minutes === 1 ? 'booking-minute-left' : 'booking-minutes-left', [minutes]); }\n      };\n      this.announced = -1; tick(); this.timer = window.setInterval(tick, 1000);\n      const time = new Intl.DateTimeFormat(this.language, { hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Amsterdam' }).format(new Date(expires));\n      if (view.notice) parts.push(this.el('p', { className: 'error', textContent: this.t(view.notice, [time]) }));\n      const typed = this.stored()?.customer ?? {};\n      const field = (name: string, props: Partial<HTMLInputElement>) => {\n        const id = `${name}-${this.group}`;\n        const el = this.el('input', { name, id, value: typed[name] ?? '', ...props }); el.setAttribute('aria-invalid', String(Boolean(this.problems[name])));\n        const error = this.el('span', { className: 'error', id: `${id}-error`, textContent: this.problems[name] ? this.t(this.problems[name]!) : '' });\n        if (this.problems[name]) el.setAttribute('aria-describedby', error.id);\n        return this.el('label', {}, this.t(name), el, error);\n      };\n      const language = this.el('select', { name: 'language' }, ...(['nl', 'de', 'en'] as const).map(code => this.el('option', { value: code, textContent: { nl: 'Nederlands', de: 'Deutsch', en: 'English' }[code], selected: code === (typed.language || this.language) })));\n      parts.push(this.summary(), clock, spoken, ...this.contract(), this.el('h3', { textContent: this.t('booking-details') }),\n        field('name', { maxLength: 120, autocomplete: 'name', required: true }), field('email', { type: 'email', maxLength: 254, autocomplete: 'email', required: true }),\n        this.el('label', {}, this.t('contact-language'), language),\n        this.el('div', { className: 'row' }, button('booking-pay', () => void this.pay(), true), button('booking-release', () => void this.release())));\n    }\n    if (view.view === 'paying') {\n      parts.push(this.summary(), this.el('p', { textContent: this.t('booking-paying') }), button('booking-check-again', () => void this.refresh()));\n      // The outcome arrives server-side from the provider; look again for a while, then leave it to the button.\n      if (this.polls++ < 24) this.timer = window.setInterval(() => void this.refresh(), 5000);\n    }\n    if (view.view === 'done') parts.push(this.summary(), this.el('p', { className: 'status', textContent: this.t(view.tid) }));\n    if (view.view === 'ended') parts.push(this.el('p', { className: view.tid === 'booking-released' ? 'muted' : 'error', textContent: this.t(view.tid) }), button('booking-start-over', () => this.startOver()));\n    parts.push(status);\n    this.body.replaceChildren(...parts);\n  }\n}\n\n// Registered once, however many widgets (or copies of this script) a page has.\nif (!customElements.get('paswerk-offer')) customElements.define('paswerk-offer', PaswerkOffer);\nif (!customElements.get('paswerk-calendar')) customElements.define('paswerk-calendar', PaswerkCalendar);\nif (!customElements.get('paswerk-slots')) customElements.define('paswerk-slots', PaswerkSlots);\nif (!customElements.get('paswerk-interest')) customElements.define('paswerk-interest', PaswerkInterest);\nif (!customElements.get('paswerk-booking')) customElements.define('paswerk-booking', PaswerkBooking);\n","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/paswerk/web/widgets/widgets.ts\";const aps = globalThis.whAssetPacks ||= {}; aps[\"paswerk:widgets\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M,KAAK,KAAK,QAAQ,EAAG,KAAK,GAAG,IAAK,CAAE,UAAW,SAAU,YAAa,KAAK,EAAE+B,EAAK,GAAG,CAAE,CAAC,CAAC,EACrHA,EAAK,OAAS,SAAS/B,EAAM,KAAK,KAAK,GAAG,IAAK,CAAE,UAAW+B,EAAK,MAAQ,mBAAqB,QAAU,QAAS,YAAa,KAAK,EAAEA,EAAK,GAAG,CAAE,CAAC,EAAGrE,EAAO,qBAAsB,IAAM,KAAK,UAAU,CAAC,CAAC,EAC3MsC,EAAM,KAAK/D,CAAM,EACjB,KAAK,KAAK,gBAAgB,GAAG+D,CAAK,CACpC,CACF,EAGK,eAAe,IAAI,eAAe,GAAG,eAAe,OAAO,gBAAiB5C,EAAY,EACxF,eAAe,IAAI,kBAAkB,GAAG,eAAe,OAAO,mBAAoBQ,EAAe,EACjG,eAAe,IAAI,eAAe,GAAG,eAAe,OAAO,gBAAiB+B,EAAY,EACxF,eAAe,IAAI,kBAAkB,GAAG,eAAe,OAAO,mBAAoBQ,EAAe,EACjG,eAAe,IAAI,iBAAiB,GAAG,eAAe,OAAO,kBAAmBY,EAAc,ECnd9B,IAAM4B,GAAM,WAAW,eAAiB,CAAC,EAAGA,GAAI,iBAAiB,EAAE","names":["formatForConsoleLogs","debugFlags","key","runSettingsCallbacks","cb","settingschangedcallbacks","initEnv","setDtapStage","setBackendBase","dtapStage","isLive","backendBase","dtapstage","islive","globalDebugFlags","localDebugFlags","debugFlagsOverridesCB","DebugFlagsProxyHandler","init_envbackend","__esmMin","target","p","record","keys","newValue","toModify","value","isElement","node","isHTMLElement","parseLanguageTag","languageTag","match","getLang","tag","init_tree","__esmMin","init_quacks","__esmMin","init_datetime","__esmMin","init_quacks","init_promises","__esmMin","init_datetime","init_quacks","init_finmath","__esmMin","init_money","__esmMin","init_finmath","init_quacks","init_types","__esmMin","init_money","init_quacks","isHTMLUnrepresentableChar","curch","encodeEntities","str","html","s","char","decodeEntities","_","dec","encodeString","encoding","decodeString","init_strings","__esmMin","init_quacks","init_money","init_platformbased","__esmMin","omit","value","keys","elt","ret","key","val","init_collections","__esmMin","init_utils","__esmMin","init_quacks","unlock","LocalMutex","LocalLock","init_localmutex","__esmMin","defer","mutex","init_std","__esmMin","init_promises","init_types","init_strings","init_platformbased","init_collections","init_money","init_datetime","init_quacks","init_utils","init_localmutex","init_navigation","__esmMin","init_fetchdebug","__esmMin","init_envbackend","init_std","init_whglobal","__esmMin","init_envbackend","debugFlags","init_env","__esmMin","init_envbackend","init_navigation","init_fetchdebug","init_whglobal","getGetTidHooks","gotHooks","hookFactory","init_hooks","__esmMin","internal_exports","__export","getHTMLTid","getHTMLTidForLanguage","getTIDListForLanguage","getTid","getTidForLanguage","getTidLanguage","registerTexts","setTidLanguage","ensureHooks","hooks","getGetTidHooks","lang","browserSetLanguage","defaultLanguage","newLanguage","getLanguageFile","module","langCode","langkey","compiled","langFileCache","loader","e","dtapStage","debugFlags","texts","toHTMLNode","tag","props","node","wrapInFragment","children","fragment","getTidInternal","tid","params","options","decodeString","nodes","calcTIDForLanguage","p","p1","p2","p3","p4","encodeString","langcode","gid","getCanonicalTid","modsep","lookup","result","key","fallback","cannotFind","rawParams","rich","render","getLanguageDatetimeStrings","debugtid","match","fallbackMatch","executeCompiledTidText","renderString","tok","part","_","text","parts","get_param","sub","link","flattenRecursiveLanguageTexts","pathsofar","name","value","tids","compiledFile","init_internal","__esmMin","init_std","init_hooks","init_env","init_tree","getLang","init_envbackend","getBrowserDebugFlags","varname","flags","urldebugvar","debugcookie","debugcookievalue","flag","sessionDebug","init_tree","init_std","config","siteroot","dtapStage","whconfigel","parsedConfig","omit","initEnv","flag","getBrowserDebugFlags","debugFlags","frontendConfig","getLang","prop","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","init_env","CustomEvent","init_tree","init_tree","init_std","parseUserAgent","ua","UA","platform","name","version","device","browser","parseUserAgent","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","e","interestErrors","input","init_internal","registerTexts","offerCalendar","slots","timeZone","format","grouped","slot","parts","part","name","p","date","day","a","b","available","eventName","group","widgetLang","own","page","value","code","locale","lang","zone","monthGrid","month","slots","year","number","days","firstWeekday","byDate","offerCalendar","d","cells","day","date","entry","shiftMonth","delta","monthTitle","weekdayNames","_","i","dayTitle","timeRange","slot","f","countProblems","c","masksAllowed","maximum","interestProblemTids","fields","map","v","k","viewOf","progress","selection","last","remaining","expires","now","ms","s","selectionFromUrl","search","course","p","n","name","fallback","session","participants","rental","masks","chosenCourse","newSecret","b","css","shared","sheet","ApiError","status","body","PaswerkWidget","widgetLang","eventName","tid","params","getTid","detail","tag","props","children","node","action","endpoint","response","json","_event","lastCourse","PaswerkOffer","preset","c","chosen","list","info","button","course","PaswerkCalendar","id","v","name","month","counts","problems","countProblems","offer","error","slot","date","cell","monthGrid","field","value","max","input","show","first","prev","shiftMonth","next","days","weekdayNames","n","words","b","dayTitle","legend","monthTitle","PaswerkSlots","day","label","timeRange","s","parts","booking","url","PaswerkInterest","toggle","el","language","code","message","send","statusLine","form","interestProblemTids","interestErrors","k","PaswerkBooking","selectionFromUrl","own","newSecret","customer","fields","cents","p","lines","l","quote","legal","table","link","href","seller","view","viewOf","primary","expires","clock","spoken","tick","left","remaining","minutes","time","typed","aps"]}