{"version":3,"sources":["@webhare/frontend/src/init.ts","@webhare/env/src/init-browser.ts","mod::publisher/js/internal/polyfills/all.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::system/js/wh/integration.ts","@webhare/frontend/src/linkhandler.ts","mod::alsikindehemelcom/webdesigns/alsikindehemelcom/shared/forms/forms.es","mod::system/js/dompack/extra/merge.ts","mod::publisher/js/forms/internal/customvalidation.ts","mod::publisher/js/forms/internal/webharefields.tsx","mod::system/js/dompack/types/datetime.ts","mod::publisher/js/forms/fields/addressfield.ts","mod::publisher/js/forms/formbase.ts","mod::system/js/dompack/browserfix/focus.ts","@webhare/forms/src/registeredfield.ts","mod::publisher/js/forms/fields/arrayfield.ts","@webhare/forms/src/fieldmap.ts","@webhare/forms/src/address.ts","mod::publisher/js/forms/internal/datehelpers.ts","@webhare/forms/src/domsupport.ts","@webhare/forms/src/jsformelement.ts","mod::publisher/js/forms/rpc.ts","mod::publisher/js/forms/internal/emailvalidation.tsx","mod::system/js/dompack/api/dialog.ts","mod::publisher/js/forms/fields/captchafield.ts","mod::publisher/js/captcha/api.ts","mod::publisher/js/captcha/__captcha.lang.json","mod::publisher/js/forms/fields/upload.tsx","mod::publisher/js/forms/fields/fileeditbase.ts","mod::publisher/js/forms/internal/form.lang.json","mod::publisher/js/forms/fields/imgedit.ts","@webhare/forms/src/registration.ts","@webhare/forms/src/forms.ts","mod::publisher/js/forms/fields/datetime.tsx","mod::publisher/js/forms/internal/datepicker.tsx","mod::publisher/js/captcha/google-recaptcha.tsx","@webhare/forms/src/friendly-captcha.ts","mod::publisher/js/forms/index.ts","mod::consilio/js/pxl.ts","@webhare/frontend/src/pxl.ts","mod::publisher/js/forms/fields/splitdatetime.tsx","mod::publisher/js/forms/fields/rtd/index.ts","mod::publisher/js/richcontent/video.ts","mod::publisher/js/internal/rtd.lang.json","mod::publisher/js/analytics/consenthandler.ts","mod::alsikindehemelcom/webdesigns/alsikindehemelcom/pages/home/home.es","mod::alsikindehemelcom/webdesigns/alsikindehemelcom/pages/about/about.es","mod::alsikindehemelcom/webdesigns/alsikindehemelcom/alsikindehemelcom.es","/entrypoint.js"],"sourcesContent":["/* 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","import \"@webhare/tsrun/src/polyfills\";\nimport \"./iterator-helpers\";\nimport \"./publisher-integration\";\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 { 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","import * as dompack from '@webhare/dompack';\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { navigateTo, type NavigateInstruction } from \"@webhare/env\";\nexport { frontendConfig as config } from '@webhare/frontend/src/init';\n\nexport function executeSubmitInstruction(instr: NavigateInstruction, options?: {\n  ismodal?: boolean;\n  iframe?: HTMLIFrameElement;\n}) {\n  if (!instr)\n    throw Error(\"Unknown instruction received\");\n\n  options = { ismodal: true, ...options };\n  //Are there any cirumstances where you would want to reelase this lock?\n  dompack.flagUIBusy({ modal: options.ismodal || false });\n  navigateTo(instr);\n}\n","/** Link handler options */\nexport interface LinkOpenOptions {\n  /** List of internal hosts (do not open in a new window) */\n  internalhosts?: string[];\n  /** List of extensions to open in a new window, even if they are internal */\n  extensions?: string[];\n}\n\nlet linkopenoptions: LinkOpenOptions | undefined;\nlet isattached: true | undefined;\n\nfunction onLinkClick(event: MouseEvent) {\n  const link = (event.target as HTMLElement)?.closest?.('a');\n  if (!link || link.download)\n    return;\n\n  const url = new URL(link.href);\n  if (!['http:', 'https:'].includes(url.protocol))\n    return; //not a browser protocol, skip\n\n  if (link.target) //never overwrite an explicit target\n    return;\n\n  const destdomain = url.host.toLowerCase();\n  if (!linkopenoptions?.internalhosts?.includes(destdomain)) {\n    link.target = \"_blank\";\n    return;\n  }\n\n  if (linkopenoptions.extensions) {\n    const ext = url.pathname.split('.').at(-1);\n    if (ext && linkopenoptions.extensions.find(match => match.toUpperCase() === ext.toUpperCase())) {\n      link.target = \"_blank\";\n      return;\n    }\n  }\n}\n\n\n/** Open external links in a new window */\nexport function setupLinksInNewWindow(options?: LinkOpenOptions) {\n  if (!isattached) {\n    isattached = true;\n    window.addEventListener(\"click\", onLinkClick);\n  }\n  linkopenoptions = { ...linkopenoptions, ...options };\n\n  if (!linkopenoptions.internalhosts) {\n    const ourdomain = (new URL(location.href)).host.toLowerCase();\n    if (ourdomain.startsWith('www.'))\n      linkopenoptions.internalhosts = [ourdomain, ourdomain.substring(4)];\n    else\n      linkopenoptions.internalhosts = [ourdomain, 'www.' + ourdomain];\n  }\n}\n","import * as dompack from 'dompack';\nimport * as forms from '@mod-publisher/js/forms';\nimport UploadField from '@mod-publisher/js/forms/fields/upload';\nimport { SplitDateField, SplitTimeField } from '@mod-publisher/js/forms/fields/splitdatetime';\nimport ImgEditField from '@mod-publisher/js/forms/fields/imgedit';\nimport RTDField from '@mod-publisher/js/forms/fields/rtd';\n\n//import * as googleRecaptcha from '@mod-publisher/js/captcha/google-recaptcha';\n\n// Styling\nimport '@mod-publisher/js/forms/themes/neutral';\nimport './forms.scss';\n\n// Enable forms and our builtin validation\nforms.setup({validate:true});\n\n// Replaces upload fields with a nicer and edit-supporting version\ndompack.register('.wh-form__upload', node => new UploadField(node));\n\n// Replaces date fields with a split version\ndompack.register('.wh-form__date', node => new SplitDateField(node));\ndompack.register('.wh-form__time', node => new SplitTimeField(node));\n\n// Enable the imgedit and/or rtd fields:\ndompack.register('.wh-form__imgedit', node => new ImgEditField(node));\ndompack.register('.wh-form__rtd', node => new RTDField(node));\n\n// Enable the line below AND the googleRecaptcha import if you want to use this recaptcha. you'll also need to enable it in the site profile\n//googleRecaptcha.setupGoogleRecaptcha();\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\ntype FormatFunction = (value: any) => string | number;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\ntype UpdateFunction = (node: HTMLElement, value: any) => void;\nconst formatters: { [key: string]: FormatFunction } = {};\nconst updaters: { [key: string]: UpdateFunction } = {};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\nfunction mergeNode(node: HTMLElement, set: string, data: any) {\n  const parts = set.split(\":\");\n  const isNodeFunc = parts.length === 1;\n  if (parts.length > 2) {\n    console.error(`Illegal merge expression: '${set}'`, node);\n    return;\n  }\n\n  let func = \"\";\n  let exprpath = (isNodeFunc ? parts[0] : parts[1]).trim();\n\n  const callparts = exprpath.split(\"(\");\n  if (callparts.length > 1) {\n    if (callparts.length !== 2) {\n      console.error(`Illegal merge value: '${set}'`, node);\n      return;\n    }\n\n    func = callparts[0].trim();\n    const funcrest = callparts[1].split(\")\");\n    if (funcrest.length !== 2 || funcrest[1] !== \"\") {\n      console.error(`Illegal merge value: '${set}'`, node);\n      return;\n    }\n    exprpath = funcrest[0].trim();\n  }\n\n  let value = data;\n  if (exprpath !== \"*\") {\n    const exprpathparts = exprpath.split(\".\");\n    for (let i = 0; i < exprpathparts.length; ++i) {\n      value = value[exprpathparts[i].trim()];\n      if (typeof value === \"undefined\")\n        return;\n    }\n  }\n\n  if (isNodeFunc) {\n    if (func && updaters[func])\n      updaters[func](node, value);\n    else if (func)\n      console.error(`Unknown updating function '${func}' in '${set}'`, node);\n    else\n      console.error(`A function is required for merges without a property (in '${set}')`, node);\n    return;\n  }\n\n  const prop = parts[0].trim();\n  if (func) {\n    if (formatters[func])\n      value = formatters[func](value);\n    else {\n      console.error(`Unknown formatting function '${func}' in '${set}'`, node);\n      return;\n    }\n  }\n\n  if (typeof value !== \"string\" && typeof value !== \"number\") {\n    console.error(`Got a value of type ${typeof value} in '${set}'`, node);\n    return;\n  }\n\n  switch (prop) {\n    case 'events':\n    case 'styles':\n    case 'children':\n    case 'on':\n    case \"className\":\n    case \"class\":\n    case 'style':\n    case 'dataset':\n    case 'childNodes':\n      {\n        console.error(`Cannot modify '${prop}' with merge`, node);\n        return;\n      }\n    default:\n      {\n        // 1-to-1 name to property mapping\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n        (node as any)[prop] = value;\n        return;\n      }\n  }\n}\n\n/**\n     Apply all merge fields within a node, recursively\n *\n    @param mergenode - Root node to start merging\n    @param data - Merge data\n    @param options - filter: If set, a function that will be called for every node with merge functions. If it returns a falsy value, the node will be skipped.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\nexport async function run(mergenode: ParentNode, data: any, { filter }: { filter?: (node: Element) => boolean } = {}) {\n  const nodes = mergenode.querySelectorAll('*[data-merge],*[data-wh-merge]') as NodeListOf<HTMLElement>;\n  for (const node of Array.from(nodes)) { //FIXME drop support for data-wh-merge as soon as we've completed the phase out\n    if (node.nodeType !== 1 || (filter && !filter(node)))\n      continue;\n\n    // Parse 'a=b;c=d(e)'\n    const sets = ((node as HTMLElement).dataset.merge || (node as HTMLElement).dataset.whMerge)?.split(\";\");\n    if (sets)\n      for (const set of sets)\n        mergeNode(node, set, data);\n  }\n}\n\n/**\n     Register a formatter function.\n *\n    @param name - Name of the formatter function\n    @param callback - Formatter function. Called with parameter (value), must return a formatted value to write to the property.\n */\nexport function registerFormatter(name: string, callback: FormatFunction) {\n  formatters[name] = callback;\n}\n\n/**\n     Register an updater function (used to update multiple properties of a node at once)\n *\n    @param name - Name of the updater function\n    @param callback - Updater function. Called with parameters (node: HTMLElement, value: Any).\n */\nexport function registerUpdater(name: string, callback: UpdateFunction) {\n  updaters[name] = callback;\n}\n","import * as dompack from '@webhare/dompack';\nimport type { FieldErrorOptions, FormFrontendMessage } from '../formbase';\nimport { debugFlags } from '@webhare/env';\nimport { getFieldDisplayName, getFieldNativeError } from '@webhare/forms/src/domsupport';\n\n///Fired at nodes to apply error\nexport type SetFieldErrorData = {\n  error: FormFrontendMessage;\n  reportimmediately: boolean;\n  serverside: boolean;\n  metadata: unknown;\n};\n\nexport type FieldValidator<E extends HTMLElement = HTMLElement> = (node: E) => Promise<FormFrontendMessage | undefined> | FormFrontendMessage | undefined;\n\nfunction setupServerErrorClear(field: HTMLElement) {\n  const group = field.closest<HTMLElement>('.wh-form__fieldgroup') || field;\n  field.propWhCleanupFunction = () => {\n    group.removeEventListener(\"change\", field.propWhCleanupFunction!, true);\n    group.removeEventListener(\"input\", field.propWhCleanupFunction!, true);\n    group.removeEventListener(\"blur\", field.propWhCleanupFunction!, true);\n    setFieldError(field, '', { serverside: true });\n    field.propWhCleanupFunction = undefined;\n  };\n\n  // to be rightly paranoid (plugins and JS directly editing other fields) we'll blur when anything anywhere seems to change\n  // eg wrd.testwrdauth-emailchange would fail on Chrome without this if the browser window was not currently focused\n  group.addEventListener(\"change\", field.propWhCleanupFunction, true);\n  group.addEventListener(\"input\", field.propWhCleanupFunction, true);\n  if (!field.closest('form[novalidate]')) //if we're doing html5 validation, errors will block submit, so let's already clear on blur\n    group.addEventListener(\"blur\", field.propWhCleanupFunction, true);\n}\n\nclass ComponentValidationState {\n  el: HTMLElement;\n\n  /** Explicitly set error */\n  explicit: {\n    error: FormFrontendMessage;\n    serverside: boolean;\n    reportimmediately: boolean;\n    metadata?: unknown;\n\n  } | null = null;\n\n  /** Dynamic errors (generated by the validation steps, refreshable instead of waiting for explciit errors) */\n  dynamicError: FormFrontendMessage | null = null;\n\n  validators: FieldValidator[] = [];\n\n  constructor(el: HTMLElement) {\n    this.el = el;\n  }\n\n  getState(): { error: FormFrontendMessage; suggested?: never } | { error?: never; suggested: FormFrontendMessage } | null {\n    const err = this.getError();\n    if (err)\n      return { error: err };\n\n    if (this.el.propWhValidationSuggestion)\n      return { suggested: this.el.propWhValidationSuggestion };\n\n    return null;\n  }\n\n  getError(): FormFrontendMessage | null {\n    return this.explicit?.error || this.dynamicError || getFieldNativeError(this.el) || null;\n  }\n\n  hasError(): boolean {\n    return Boolean(this.getError());\n  }\n}\n\nconst validations = new WeakMap<HTMLElement, ComponentValidationState>();\n\nexport function getValidationState(field: HTMLElement) {\n\n  const state = validations.get(field);\n  if (state)\n    return state;\n\n  const newstate = new ComponentValidationState(field);\n  validations.set(field, newstate);\n  return newstate;\n}\n\n/* TODO Are we sure we should expose this API? A form-level setupValidator might be better as we can then re-validate at the proper point in time\n   instead of relying on an external user to enable and shutdown the error. We're mixing two completely different systems with setupValidator (which\n   works nicely with our focusout hadling) and setFieldError (which is extremely stateful and relies on the error-setter managing all the edge cases)\n\n   Oh and serverside errors float somewhere halfway that spectrum.. as we setup explicit clearing callbacks to remove the state we created ourselves.\n*/\nexport function setFieldError(field: Element, error: FormFrontendMessage, options?: Partial<FieldErrorOptions>) {\n  if (!dompack.isHTMLElement(field))\n    throw new Error(`Field is not a valid target for handling errors`);\n\n  const state = getValidationState(field);\n  if (!error) {  //clearing\n    if (!state.explicit)\n      return; //no change\n\n    state.explicit = null;\n    if (debugFlags.fhv)\n      console.log(`[fhv] Clearing error state for ${getFieldDisplayName(field)}`, field, error, options);\n  } else { //changing ?\n    if (debugFlags.fhv)\n      console.log(`[fhv] ${state.explicit ? 'Updating' : 'Setting'} error state for ${getFieldDisplayName(field)}`, field, error, options);\n\n    state.explicit = {\n      error,\n      serverside: options?.serverside || false,\n      reportimmediately: options?.reportimmediately || false,\n      metadata: options?.metadata\n    };\n\n    if (options?.serverside)\n      setupServerErrorClear(field);\n  }\n\n  updateFieldError(field);\n}\n\nexport function updateFieldError(field: HTMLElement) {\n  const state = getValidationState(field);\n\n  dompack.dispatchCustomEvent(field, 'wh:form-setfielderror', //this is where parsley hooks in and cancels to handle the rendering of faults itself\n    {\n      bubbles: true,\n      cancelable: true,\n      detail: {\n        error: state.explicit?.error || getFieldNativeError(field) || '',\n        reportimmediately: state.explicit?.reportimmediately || false,\n        serverside: state.explicit?.serverside || false,\n        metadata: state.explicit?.metadata\n      }\n    });\n}\n\n/** Set up a custom validator\n * @param node - Form element to validate\n * @param checker - Sync or async function that returns a string with an error message or undefined if the field is valid.\n*/\nexport function setupValidator<NodeType extends HTMLElement>(node: NodeType, checker: FieldValidator<NodeType>): void {\n  getValidationState(node).validators.push(checker as FieldValidator);\n\n  //if the checker as a name, we'll add it. otherwise we'll ensure that data-wh-form-custom-validator is set so we can scan for it (and it's probably nice to see it in the dom)\n  node.dataset.whFormCustomValidator = ((node.dataset.whFormCustomValidator || \"\") + \" \" + (checker.name || \"?\")).trim();\n}\n","import * as dompack from 'dompack';\nimport { qSA } from 'dompack';\nimport * as datetime from 'dompack/types/datetime';\nimport AddressField from '@mod-publisher/js/forms/fields/addressfield';\nimport { setupValidator } from './customvalidation';\n\nimport { getTid } from \"@webhare/gettid\";\nimport { formatDate, parseISODate } from './datehelpers';\nimport { isValidDate } from '@webhare/std';\n\nfunction validateCheckboxGroup(groupnode: HTMLElement) {\n  const nodes = dompack.qSA<HTMLInputElement>(groupnode, \"input[type='checkbox']\");\n  const min = Number(groupnode.dataset.whMin) || 0;\n  const max = Number(groupnode.dataset.whMax) || 0;\n\n  const anyenabled = nodes.some(node => !node.disabled);\n  const numChecked = nodes.filter(node => node.checked).length;\n\n  if (anyenabled) {\n    if (numChecked < min)\n      return getTid(\"publisher:site.forms.commonerrors.mincheck\", min);\n    else if (max > 0 && numChecked > max)\n      return getTid(\"publisher:site.forms.commonerrors.maxcheck\", max);\n  }\n}\n\nfunction validateRadioGroup(groupnode: HTMLElement) {\n  const nodes = dompack.qSA<HTMLInputElement>(groupnode, \"input[type='radio']\");\n  const isrequired = nodes.some(node => node.required);\n\n  if (isrequired) {\n    const isanychecked = nodes.some(node => node.checked && !node.disabled);\n    if (!isanychecked)\n      return getTid(\"publisher:site.forms.commonerrors.required\");\n  }\n}\n\nexport function reformatDate(datestr: string): string {\n  const parsed = parseISODate(datestr);\n  return parsed ? formatDate(\"D-M-Y\", parsed.year, parsed.month, parsed.day) : \"\";\n}\n\nfunction validateDate(date: HTMLInputElement) {\n  if (date.getAttribute('type') !== 'date') //it's no longer a date field\n    return '';\n  if (!date.value) //any required checks should be handled by the HTML5 compat layer, nothing for us to check\n    return '';\n\n  const dateparts = date.value.match(/^([0-9]+)-([0-9]+)-([0-9]+)$/) || [];\n  const year = parseInt(dateparts[1]), month = parseInt(dateparts[2]), day = parseInt(dateparts[3]);\n  if (!isValidDate(year, month, day))\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n\n  const normalizeddate = ('0000' + year).substr(-4) + '-' + ('00' + month).substr(-2) + '-' + ('00' + day).substr(-2);\n  const min = date.getAttribute(\"min\"), max = date.getAttribute(\"max\");\n  if (min && normalizeddate < min)\n    return getTid(\"publisher:site.forms.commonerrors.min\", reformatDate(min));\n  if (max && normalizeddate > max)\n    return getTid(\"publisher:site.forms.commonerrors.max\", reformatDate(max));\n\n  return '';\n}\n\nfunction validateTime(time: HTMLInputElement) {\n  if (time.getAttribute('type') !== 'time') //it's no longer a time field\n    return '';\n  if (!time.value) //any required checks should be handled by the HTML5 compat layer, nothing for us to check\n    return '';\n\n  const timeparts = time.value.match(/^([0-9]+):([0-9]+)(:([0-9]+))?$/) || [];\n  const hours = parseInt(timeparts[1]), minutes = parseInt(timeparts[2]), seconds = parseInt(timeparts[3]);\n  if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || (!isNaN(seconds) && (seconds < 0 || seconds > 59)))\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n\n  return '';\n}\n\nexport function setup(form: HTMLElement) {\n  for (const datecontrol of qSA<HTMLInputElement>(form, 'input[type=date]')) {\n    for (const field of ['whMin', 'whMax', 'whValue'])\n      if (datecontrol.dataset[field]) {\n        //parse 'now' or 'now+5d'. be able to extract '+5d'\n        const datematch = datecontrol.dataset[field]!.match(/^now((\\+|-)\\d+d)?$/);\n\n        if (datematch) {\n          const propname = field.substr(2).toLowerCase();\n          let thedate;\n          if (datematch[1])\n            thedate = new Date(Date.now() + parseInt(datematch[1]) * 86400 * 1000);\n          else\n            thedate = new Date;\n\n          (datecontrol as unknown as Record<string, string>)[propname] = datetime.getISOLocalDate(thedate);\n        }\n      }\n\n    if (datecontrol.type !== 'date' && !datecontrol.whValidationPolyfilled) { //this browser doesn't natively support date fields\n      datecontrol.whValidationPolyfilled = true;\n      //ADDME some sort of global validator would be better so we don't get confused by fields that change their type\n      setupValidator(datecontrol, validateDate);\n    }\n  }\n\n  for (const timecontrol of qSA<HTMLInputElement>(form, 'input[type=time][data-wh-value]')) {\n    //parse 'now'\n    //ADDME: Support for stuff like 'now + 15 minutes' 'next whole hour + 2.5 hours'?\n    const timematch = timecontrol.dataset.whValue!.match(/^now$/);\n\n    if (timematch) {\n      const thedate = new Date;\n\n      let propvalue = ('0' + thedate.getHours()).substr(-2) + '-' + ('0' + thedate.getMinutes()).substr(-2);\n      if (parseInt(timecontrol.getAttribute(\"step\") || '0') % 60) //step not multiple of 60? seconds\n        propvalue += '-' + ('0' + thedate.getSeconds()).substr(-2);\n      timecontrol.value = propvalue;\n    }\n\n    if (timecontrol.type !== 'time' && !timecontrol.whValidationPolyfilled) { //this browser doesn't natively support time fields\n      timecontrol.whValidationPolyfilled = true;\n      //ADDME some sort of global validator would be better so we don't get confused by fields that change their type\n      setupValidator(timecontrol, validateTime);\n    }\n  }\n\n  // Setup checkbox group (min/max checked) validation\n  for (const checkboxgroup of qSA(form, \".wh-form__fieldgroup--checkboxgroup\"))\n    setupValidator(checkboxgroup, validateCheckboxGroup);\n\n  // Setup radio group (hidden/disabled) validation\n  for (const radiogroup of qSA(form, \".wh-form__fieldgroup--radiogroup\")) {\n    setupValidator(radiogroup, validateRadioGroup);\n\n    //we should probably disable by name (or form.elements[name] but validate() and form isn't really tracking name either...\n    dompack.qSA<HTMLInputElement>(radiogroup, `input[type='radio']`).forEach(\n      node => node.dataset.whFormSkipnativevalidation = \"true\"); //don't handle by both RadioGroupField *and* native validation\n\n  }\n\n  // Setup address field validation\n  for (const addresscontrol of qSA(form, \".wh-form__fieldgroup--addressfield\"))\n    new AddressField(addresscontrol);\n}\n","/**\n * Get ISO-formatted local date from a date (getISOString returns an UTC datetime)\n *\n * @param date - Date to return\n * @returns Date as a YYYY-MM-DD string\n */\nexport function getISOLocalDate(date: Date) {\n  return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from \"@webhare/dompack\";\nimport FormBase from \"../formbase\";\nimport { debugFlags } from \"@webhare/env\";\nimport { verifyHareScriptAddress, type HareScriptAddressValidationResult, type AddressChecks, type HareScriptAddressValue } from \"@webhare/forms/src/address\";\nimport { setFieldError } from \"../internal/customvalidation\";\nimport { throwError } from \"@webhare/std\";\n\nclass SubField {\n  node;\n  fieldgroup: HTMLElement;\n  pos: number;\n\n  constructor(node: dompack.FormControlElement, pos: number) {\n    this.node = node;\n    this.pos = pos;\n    this.fieldgroup = node.closest(\".wh-form__fieldgroup\") ?? throwError(\"Could not find fieldgroup for field\");\n  }\n}\n\ninterface OrderingData {\n  countries: string[];\n  fieldorder: string[];\n}\n\nexport default class AddressField {\n  numvaliditycalls = 0;\n  node: HTMLElement;\n  formnode: HTMLFormElement;\n  countryNode: HTMLSelectElement;\n  currentcountry: string;\n  fieldName: string;\n  orderingData: OrderingData[];\n  allFields = new Map<string, SubField>;\n  _updatingFields = false;\n\n  constructor(node: HTMLElement) {\n    this.node = node;\n    //We won't FormBase.getForNode yet here so we're not too dependent on registration ordering\n    this.formnode = node.closest(\"form\") ?? throwError(\"Could not find form for addressfield\");\n\n    // AddressField is initialized for the address's country field, so first find the other fields\n    this.countryNode = dompack.qR(this.node, \"select.wh-form__pulldown\"); //TODO why aren't we targetting by ID ? this will work but seems ambiguous\n    if (!this.countryNode)\n      throw new Error(\"Could not find country select node\");\n    if (!this.countryNode.dataset.orderingdata)\n      throw new Error(\"Addressfield not properly configured\");\n\n    this.currentcountry = this.countryNode.value;\n    this.fieldName = this.countryNode.name.substr(0, this.countryNode.name.lastIndexOf(\".\"));\n    this.orderingData = JSON.parse(this.countryNode.dataset.orderingdata) as OrderingData[];\n    const prefixLength = this.fieldName.length + 1; // fieldName + \".\"\n    this.allFields = new Map();\n    let fieldpos = 0;\n    this.allFields.set(this.countryNode.name.substr(prefixLength), new SubField(this.countryNode, ++fieldpos));\n\n    for (const field of dompack.qSA<HTMLInputElement | HTMLTextAreaElement>(this.formnode, `[name^='${this.fieldName}.']`)) {\n      this.allFields.set(field.name.substring(prefixLength), new SubField(field, ++fieldpos));\n\n      field.addEventListener(\"change\", event => this._gotFieldChange(event));\n    }\n\n    if (this.orderingData) {\n      this.countryNode.addEventListener(\"change\", () => this._reconfigureFieldOrdering());\n      this._reconfigureFieldOrdering();\n    }\n  }\n\n  _gotFieldChange(event: Event) {\n    if (this._updatingFields)\n      return; // We're updating our own fields\n\n    if (event.target === this.countryNode && this.currentcountry !== this.countryNode.value) {\n      //country changed. clear errors on all fields before revalidating.. otherwise the errors will just seem to 'linger' for a while after switching\n      this._clearErrors();\n      this.currentcountry = this.countryNode.value;\n    }\n\n    if (this._getFieldValue(\"country\") === \"NL\") {\n      if (!this._getFieldValue(\"zip\") || !this._getFieldValue(\"nr_detail\"))\n        return;\n    }\n    this._checkValidity(event);\n  }\n\n  _getFieldValue(fieldname: string) {\n    const data = this.allFields.get(fieldname);\n    if (data)\n      return data.node.value;\n    return \"\";\n  }\n\n  _getFirstCountrySpecificField() {\n    let firstfield = null;\n    for (const [key, field] of this.allFields.entries())\n      if (key !== \"country\" && !field.fieldgroup.classList.contains(\"wh-form__fieldgroup--hidden\") && (!firstfield || firstfield.pos > field.pos))\n        firstfield = field;\n\n    return firstfield ?? throwError(\"Cannot find field for error\");\n  }\n\n  _reconfigureFieldOrdering() {\n    const country = this.countryNode.value;\n    if (country) {\n      const ordering = this.orderingData.find(e => e.countries.length === 0 || e.countries.includes(country));\n      if (ordering) {\n        let prevgroup;\n        for (let idx = 0; idx < ordering.fieldorder.length; ++idx) {\n          const item = this.allFields.get(ordering.fieldorder[idx]);\n          if (!item)\n            continue; //ordering may appear to fields that have not been rendered, eg 'state'\n\n          item.pos = idx + 1;\n          const fieldgroup = item.fieldgroup;\n          if (prevgroup) {\n            const compareres = prevgroup!.compareDocumentPosition(fieldgroup);\n            if (compareres & Node.DOCUMENT_POSITION_PRECEDING)\n              prevgroup!.parentNode!.insertBefore(fieldgroup, prevgroup!.nextSibling);\n          }\n          prevgroup = fieldgroup;\n        }\n      }\n    }\n\n    //street + city should skip client side validation for NL, we will be looking it up server side (FIXME we should consider overwriting our validation to delay validation until address lookups are complete)\n    for (const fieldname of ['street', 'city']) {\n      const field = this.allFields.get(fieldname);\n      if (field)\n        if (country.toUpperCase() === 'NL')\n          field.node.setAttribute(\"data-wh-form-skipnativevalidation\", \"\");\n        else\n          field.node.removeAttribute(\"data-wh-form-skipnativevalidation\");\n    }\n  }\n\n  _clearErrors() {\n    this.allFields.forEach(field => setFieldError(field.node, \"\", { reportimmediately: true }));\n  }\n\n  _getCurState() {\n    const value: HareScriptAddressValue = { country: \"\" };\n    const visiblefields: HTMLElement[] = [];\n    let anyset = false, allrequiredset = true;\n    this.allFields.forEach((field, key) => {\n      if (!field.fieldgroup.classList.contains(\"wh-form__fieldgroup--hidden\")) {\n        visiblefields.push(field.node.closest(\".wh-form__fieldgroup\")!);\n        value[key as keyof HareScriptAddressValue] = field.node.value;\n\n        if (!anyset && key !== 'country' && field.node.value)\n          anyset = true;\n        if (field.node.required && !field.node.value && !field.node.hasAttribute(\"data-wh-form-skipnativevalidation\"))\n          allrequiredset = false;\n      }\n    });\n\n    return { value, visiblefields, anyset, allrequiredset, lookupkey: JSON.stringify(value) };\n  }\n\n  async _checkValidity(event: Event) {\n    const form = FormBase.getForNode(this.formnode) ?? throwError(\"Parent form for address field not yet initialized\");\n    /* we used to clear fields that are no longer visible after a country change, add visible fields to the value we're checking\n       but not sure why. ignoring those fields should be okay? and this is a very eager trigger, so if we really do this, do\n       this on base of the country actually changing, not an external checkbox controlling visibility of the whole country field\n       and a stray update event\n       */\n    const curstate = this._getCurState();\n    if (!curstate.anyset) { //fields are empty..\n      this._clearErrors();\n      return; //then don't validate\n    }\n    if (!curstate.allrequiredset)\n      return; //no need to validate if we don't even have the required fields in place\n\n    let result: HareScriptAddressValidationResult;\n    const lock = dompack.flagUIBusy();\n    try {\n      curstate.visiblefields.forEach(el => el.classList.add(\"wh-form__fieldgroup--addresslookup\"));\n      ++this.numvaliditycalls;\n      result = await verifyHareScriptAddress(curstate.value as HareScriptAddressValue, {\n        lang: form.getLangCode(),\n        checks: (this.node.dataset.checks?.split(' ') ?? []) as AddressChecks[]\n      });\n    } catch (e) {\n      console.error(`Error while validating value: ${e}`);\n      return;\n    } finally {\n      if (--this.numvaliditycalls === 0) //we're the last call\n        curstate.visiblefields.forEach(el => el.classList.remove(\"wh-form__fieldgroup--addresslookup\"));\n\n      lock.release();\n    }\n    if (this._getCurState().lookupkey !== curstate.lookupkey)\n      return; //abandon this _checkValidity call, the field has already changed.\n\n    if (debugFlags.fhv)\n      console.log(`[fhv] Validation result for address '${this.fieldName}': ${result.status}`);\n\n    if (debugFlags.fdv) {\n      if ([\"different_citystreet\", \"incomplete\"].includes(result.status))\n        console.warn(`[fdv] Address validation was performed, processing incomplete address (status: '${result.status}')`);\n      else {\n        console.warn(`[fdv] Ignoring return status '${result.status}' of address validation`);\n        result.status = \"ok\";\n      }\n    }\n\n    this._clearErrors();\n\n    for (const err of result.errors) {\n      const field = this.allFields.get(err.fields[0]) ?? this._getFirstCountrySpecificField();\n      if (field)\n        form.setFieldError(field.node, err.message, { reportimmediately: true });\n    }\n\n    if (result.corrections) {\n      let anychanges = false;\n      this._updatingFields = true;\n\n      for (const [key, newvalue] of Object.entries(result.corrections)) {\n        const field = this.allFields.get(key);\n        if (field && field.node.value !== newvalue) {\n          dompack.changeValue(field.node, newvalue);\n          anychanges = true;\n        }\n      }\n\n      this._updatingFields = false;\n      if (anychanges)\n        form.refreshConditions();\n    }\n  }\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from '@webhare/dompack';\nimport { type DocEvent, type FormControlElement, type TakeFocusEvent, addDocEventListener, isFormControl } from '@webhare/dompack';\nimport * as domfocus from 'dompack/browserfix/focus';\nimport * as webharefields from './internal/webharefields';\nimport * as merge from './internal/merge';\nimport './internal/requiredstyles.css';\nimport { type SetFieldErrorData, getValidationState, setFieldError, setupValidator, updateFieldError } from './internal/customvalidation';\nimport { generateRandomId, isPromise, wrapSerialized } from '@webhare/std';\nimport { debugFlags, isLive, navigateTo, type NavigateInstruction } from '@webhare/env';\nimport { getFieldDisplayName, isFieldNativeErrored, isRadioOrCheckbox, isRadioNodeList, type ConstrainedRadioNodeList, parseCondition, getFormElementCandidates, isFormFieldLike, queryFormFieldLike, getFieldName } from '@webhare/forms/src/domsupport';\nimport { rfSymbol } from '@webhare/forms/src/registeredfield';\nimport type { FormAnalyticsEventData, FormAnalyticsSubEvents, FormCondition, FormFileValue, RPCFormMessage } from '@webhare/forms/src/types';\nimport { FieldMapDataProxy, FormFieldMap } from '@webhare/forms/src/fieldmap';\nimport { submitselector, type SubmitSelectorType } from '@webhare/dompack/src/browser';\nimport type { FormSubmitDetails } from './rpc';\nimport type { FormConfiguration } from '@webhare/forms';\n\n//Suggestion or error messages\nexport type FormFrontendMessage = HTMLElement | string;\n\ndeclare global {\n  interface HTMLElement {\n    //TODO Clean this up, these are internal. Move to a dataset, safer against DOM manipulation eg as done by slimselect\n    //Used by formgroups:\n    propWhFormInitialRequired?: boolean;\n    propWhFormCurrentEnabled?: boolean;\n    propWhFormCurrentRequired?: boolean;\n    propWhFormCurrentVisible?: boolean;\n    //Used by formlines:\n    propWhFormlineCurrentVisible?: boolean;\n    propWhValidationSuggestion?: FormFrontendMessage | null;\n    propWhCleanupFunction?: () => void;\n    /** @deprecated Use `getFormHandler` or `getFormData` from `@webhare/forms` to access the form's API */\n    propWhFormhandler?: FormBase<object>;\n    whFormsApiChecker?: () => Promise<void> | void;\n    whUseFormGetValue?: boolean;\n    whValidationPolyfilled?: boolean;\n    __didPlaceholderWarning?: boolean;\n  }\n\n  interface GlobalEventHandlersEventMap {\n    \"wh:form-enable\": CustomEvent<{ enabled: boolean }>;\n    \"wh:form-require\": CustomEvent<{ required: boolean }>;\n    \"wh:form-getvalue\": CustomEvent<{ deferred: PromiseWithResolvers<unknown> }>;\n    \"wh:form-setfielderror\": CustomEvent<SetFieldErrorData>; //TODO can we phase this out? it's a too deep integration\n    \"wh:form-configure\": CustomEvent<FormConfiguration>;\n    \"wh:form-pagechange\": CustomEvent<{\n      formHandler: FormBase<object>;\n      /** TODO Add numPages and currentPage, but we'd need to figure out how to properly account for Captcha pages (you don't want either numPages or currentPage to count that one)\n      numPages: number;\n      currentPage: number;\n      */\n    }>;\n    \"wh:form-preparesubmit\": CustomEvent<{ extrasubmit: Record<string, unknown> }>;\n    \"wh:form-response\": CustomEvent<FormSubmitResult>;\n    \"wh:form-submitted\": CustomEvent<FormSubmitDetails>;\n  }\n}\n\ntype ExtraData = unknown;\n\ntype FormControlDescription = {\n  name: string;\n  multi: false;\n  node: HTMLElement;\n} | {\n  name: string;\n  multi: true;\n  nodes: HTMLInputElement[];\n};\n\nexport type FormResultValue = Record<string, unknown>;\n\n/** The result returned to onSubmitSuccess */\nexport type FormSubmitEmbeddedResult<UserResult = { [key: string]: unknown }> = UserResult & {\n  //webtool submit additions. TODO a future API shouldn't mix these at the same level but allow them in the FormSubmitResult\n  submittype?: string;\n  richvalues?: RichValues;\n  resultsguid?: string;\n  submitinstruction?: NavigateInstruction;\n};\n\nexport interface FormSubmitMessage {\n  name: string;\n  message: string;\n  metadata: unknown;\n}\n\nexport interface FormSubmitResult {\n  success: boolean;\n  //TODO a next form iteration should not mix all these additional props into the form user's 'result'\n  result: FormSubmitEmbeddedResult;\n  errors: FormSubmitMessage[];\n  warnings: FormSubmitMessage[];\n  messages: RPCFormMessage[];\n}\n\ntype RichValues = Array<{ field: string; value: string }>;\n\nexport interface FieldErrorOptions {\n  serverside: boolean;\n  reportimmediately: boolean;\n  metadata?: unknown;\n}\n\ntype LimitSet = undefined | HTMLElement | HTMLElement[];\n\ninterface ValidationOptions {\n  // focusfailed Focus the first invalid element (defaults to true)\n  focusfailed?: boolean;\n  iffailedbefore?: boolean;\n}\n\ninterface FormValidationResult {\n  /// True if the fields successfuly validated\n  valid: boolean;\n  failed: HTMLElement[];\n  firstfailed: HTMLElement | null;\n}\n\ninterface ValidationQueueElement {\n  limitset?: LimitSet;\n  options?: ValidationOptions;\n  defer: PromiseWithResolvers<FormValidationResult>;\n}\n\ninterface PageState {\n  pages: HTMLElement[];\n  curpage: number;\n}\n\nlet delayvalidation = false, validationpendingfor: EventTarget | null = null;\nlet didGlobalHandlers: true | undefined;\n\n/** Convert linefeeds to BR tags */\nfunction lineFeedsToBreaks(text: string): DocumentFragment {\n  const frag = new DocumentFragment;\n  for (const part of text.split(/\\r?\\n/)) {\n    if (frag.childNodes.length)\n      frag.appendChild(document.createElement(\"br\"));\n    frag.append(part);\n  }\n  return frag;\n}\n\nfunction getPageIdx(state: PageState, page: number | HTMLElement) {\n  if (typeof page === 'number') {\n    if (page < 0 || page >= state.pages.length)\n      throw new Error(`Cannot navigate to nonexisting page #${page}`);\n    return page;\n  }\n\n  const idx = state.pages.indexOf(page);\n  if (idx === -1) {\n    console.error(`Cannot find page by element`, page);\n    throw new Error(`Cannot find page`);\n  }\n\n  return idx;\n}\n\nfunction getErrorFields(validationresult: FormValidationResult) {\n  return validationresult.failed.map(field => getFieldName(field) || field.dataset.whFormGroupFor || \"?\")\n    .sort()\n    .filter((value, index, self) => self.indexOf(value) === index) //unique filter\n    .join(\" \");\n}\nfunction hasEverFailed(field: HTMLElement) {\n  if (field.matches(\"input[type=radio],input[type=checkbox]\")) //these are handled by their group, so do the failed check there\n    return field.closest(\".wh-form__fieldgroup\")?.classList.contains('wh-form__field--everfailed');\n\n  return field.classList.contains('wh-form__field--everfailed');\n}\nfunction doValidation(field: EventTarget | null, iffailedbefore: boolean) {\n  if (iffailedbefore || validationpendingfor)\n    releasePendingValidations(); //release any earlier validation. this also cancels 'delayvalidation' but better safe than sorry if we double-run here\n\n  if (delayvalidation) { //Can't be \"iffailedbefore\" as that would have been cleared above\n    if (debugFlags.fhv)\n      console.log(\"[fhv] doValidation: validations are delayed. now pending: \", field);\n    validationpendingfor = field;\n    return;\n  }\n\n  const form = (field as HTMLElement).closest?.('form');\n  if (!form || !form.propWhFormhandler)\n    return;\n\n  const formhandler = form.propWhFormhandler;\n  formhandler.validate([field as HTMLElement], { focusfailed: false, iffailedbefore: iffailedbefore });\n}\n\n\nfunction doDelayValidation() {\n  if (delayvalidation)\n    releasePendingValidations();\n\n  delayvalidation = true;\n}\n\nfunction releasePendingValidations() {\n  if (!delayvalidation)\n    return;\n\n  delayvalidation = false;\n\n  if (validationpendingfor) {\n    const tovalidate = validationpendingfor;\n    if (debugFlags.fhv)\n      console.log(\"[fhv] releasePendingValidations: \", tovalidate);\n    validationpendingfor = null;\n    doValidation(tovalidate, false);\n  }\n}\n\n/* Browser extensions such as 1Password interfere with the event model and may\n   cause focusout to not fire for email and password fields. They don't seem\n   to break focusin so we'll watch focusin to detect missed focusout events */\nlet lastfocusout: EventTarget | null = null;\nfunction handleFocusOutEvent(event: FocusEvent) {\n  lastfocusout = event.target;\n  doValidation(event.target, false);\n}\nfunction handleFocusInEvent(event: FocusEvent) {\n  if (event.relatedTarget && lastfocusout !== event.relatedTarget)\n    doValidation(event.relatedTarget, false);\n}\n\nfunction handleValidateAfterEvent(event: Event) {\n  doValidation(event.target, true);\n}\n\nexport default class FormBase<DataShape extends object = Record<string, unknown>> extends FormFieldMap<DataShape> {\n  /** @deprecated Use node.elements if you want a true HTMLFormControlsCollection, use getElementByName since WH5.4+ for properly typed elements */\n  readonly elements: HTMLFormControlsCollection;\n  private _formsessionid = generateRandomId();\n  private _firstinteraction: number | undefined;\n  protected _submitstart: number | undefined;\n  private validationqueue = new Array<ValidationQueueElement>;\n  private _submitter: SubmitSelectorType | null = null;\n  private _submittimeout: NodeJS.Timeout | undefined;\n  /** Is the form currently interactive? Used to ignore changes done by code/setFieldValue */\n  private isInteractive = true;\n  /** Did we warn about old style form controls? */\n  private didLegacyWarning = false;\n  /** Are we currently in the _submit handler? (prevent duplicate submit attemps while eg. inside onBeforeSubmit) */\n  private inSubmit = false;\n  /** Where should the exitButton navigate to? */\n  private exitButtonNavigateTo?: NavigateInstruction;\n  /** Name of last focused element */\n  #lastFocused = \"\";\n\n  readonly data = new Proxy<DataShape>({} as DataShape, new FieldMapDataProxy(this));\n\n  readonly node: HTMLFormElement;\n\n  constructor(node: HTMLFormElement) {\n    if (node.nodeName !== 'FORM')\n      throw new Error(\"Specified node is not a <form>\"); //we want our clients to be able to assume 'this.node.elements' works\n\n    super(\"\", getFormElementCandidates(node, ''));\n\n    this.node = node;\n\n    this.elements = node.elements;\n    if (this.node.propWhFormhandler)\n      throw new Error(\"Specified node already has an attached form handler\");\n    this.node.propWhFormhandler = this;\n\n    //TODO Can we scope these handlers to the form ? Or register only once needed?\n    if (!didGlobalHandlers) {\n      didGlobalHandlers = true;\n      window.addEventListener(\"mouseup\", releasePendingValidations, true);\n      window.addEventListener(\"focusin\", handleFocusInEvent, true);\n    }\n\n    //Implement webhare fields extensions, eg 'now' for date fields or 'enablecomponents'\n    webharefields.setup(this.node);\n    //Implement page navigation\n    addDocEventListener(this.node, \"click\", evt => this._checkClick(evt));\n    addDocEventListener(this.node, \"dompack:takefocus\", evt => this._onTakeFocus(evt));\n    addDocEventListener(this.node, \"input\", evt => this._onInputChange(), { capture: true });\n    addDocEventListener(this.node, \"change\", evt => this._onInputChange(), { capture: true });\n    addDocEventListener(this.node, 'submit', evt => this._submit(evt, null));\n    addDocEventListener(this.node, 'wh:form-dosubmit', evt => { throw new Error(`wh:form-dosubmit is no longer supported`); });\n    addDocEventListener(this.node, \"wh:form-setfielderror\", evt => this._doSetFieldError(evt));\n    addDocEventListener(this.node, \"mousedown\", doDelayValidation);\n    addDocEventListener(this.node, \"focusout\", handleFocusOutEvent, { capture: true });\n    addDocEventListener(this.node, \"input\", handleValidateAfterEvent, { capture: true });\n    addDocEventListener(this.node, \"change\", handleValidateAfterEvent, { capture: true });\n    addDocEventListener(this.node, \"focusin\", this.#recordLastFocus, { capture: true });\n    this.node.noValidate = true;\n\n    this._rewriteEnableOn();\n    this._updateConditions(true); //Update required etc handlers\n    this._applyPrefills();\n\n    //Update page navigation\n    const pagestate = this._getPageState();\n    this._updatePageVisibility(pagestate.pages, 0);\n    this._updatePageNavigation();\n  }\n\n  static getForNode<DataShape extends object = Record<string, unknown>>(node: HTMLElement): FormBase<DataShape> | null {\n    return (node.propWhFormhandler as FormBase<DataShape>) || null;\n  }\n\n  ///like namedItem but improves on the types returned. does *not* lookup by data-wh-form-name!\n  getElementByName(name: string): FormControlElement | ConstrainedRadioNodeList | null {\n    return this.node.elements.namedItem(name) as FormControlElement | ConstrainedRadioNodeList | null;\n  }\n\n  /** Get language for this form */\n  getLangCode() {\n    return this.node.closest<HTMLElement>('[lang]')?.lang ?? 'en';\n  }\n\n  #recordLastFocus = (evt: dompack.DocEvent<FocusEvent>) => {\n    if (this.node.contains(evt.target)) {\n      const name = getFieldName(evt.target) || evt.target.dataset.whFormGroupFor;\n      if (name)\n        this.#lastFocused = name;\n    }\n  };\n\n  #onUnload = () => {\n    this.sendFormEvent({\n      event: 'abandoned',\n      lastfocused: this.#lastFocused,\n      pagenum: this.getCurrentPageNumber()\n    });\n  };\n\n  protected __formStarted() {\n  }\n\n  protected sendFormEvent(event?: FormAnalyticsSubEvents) {\n    const now = Date.now();\n    if (event?.event === 'submitted')\n      removeEventListener(\"pagehide\", this.#onUnload);\n\n    if (!this._firstinteraction) {   //The user hasn't interacted with the form yet\n      if (!this.isInteractive) { //ignore events triggered by code, eg a form prefill\n        if (event?.event && debugFlags.anl)\n          console.log(`[anl] Form is supressing broadcast of '${event?.event}' because it hasn't been interacted with yet`);\n        return;\n      }\n\n      //The user has interacted, start the clock!\n      this._firstinteraction = now; //set for calculation base *and* to prevent endless loops\n      this.sendFormEvent({ event: \"started\" });\n      addEventListener(\"pagehide\", this.#onUnload);\n    }\n\n    if (!event)\n      return; //we were only triggered to signal First Interaction\n    this._firstinteraction ||= now;\n\n    const pagestate = this._getPageState();\n    const eventdata: FormAnalyticsEventData = {\n      ...event,\n      id: this.node.dataset.whFormId || '',\n      session: this._formsessionid,\n      pagetitle: this._getPageTitle(pagestate.curpage),\n      pagenum: pagestate.curpage + 1,\n      time: now - this._firstinteraction,\n      objref: this.node.dataset.whFormObjref || ''\n    };\n\n    if (this._submitstart) //is set during a pending submission\n      eventdata.waittime = Date.now() - this._submitstart;\n\n    dompack.dispatchCustomEvent(this.node, \"wh:form-analytics\", { bubbles: true, cancelable: false, detail: eventdata });\n  }\n\n  _rewriteEnableOn() { //ADDME move this to webhare server\n    // EnablingComponents may set data-wh-form-enable. input(radio/checkbox) and option qualify\n    type EnablingComponent = HTMLInputElement | HTMLOptionElement;\n\n    // This is the initialization, check the enable components for all elements within the form\n    for (const control of dompack.qSA<EnablingComponent>(this.node, \"*[data-wh-form-enable]\"))\n      for (const element of control.dataset.whFormEnable!.split(\" \")) {\n        const target = this.getElementByName(element);\n        if (target && target instanceof HTMLElement) {\n          const name = (control instanceof HTMLOptionElement ? control.closest<HTMLSelectElement>(\"select\") : control)?.name;\n          if (!name) //duplicated node?\n            continue;\n\n          let ourcondition: FormCondition = { field: name, matchtype: \"IN\", value: control.value };\n          if (target.dataset.whFormEnabledIf) //append to existing criterium\n            ourcondition = { conditions: [parseCondition(target.dataset.whFormEnabledIf), ourcondition], matchtype: \"AND\" };\n          target.dataset.whFormEnabledIf = JSON.stringify({ c: ourcondition });\n        }\n      }\n  }\n\n  _applyPrefills() {\n    //Apply prefills. Set in field order, so controls-enabling-controls things will generally work\n    const searchparams = new URL(location.href).searchParams;\n    for (const field of this._queryAllFields()) {\n      const allvalues = searchparams.getAll(field.name);\n      if (!allvalues.length)\n        continue;\n\n      if (field.multi && field.nodes[0].type === 'checkbox') {\n        for (const node of field.nodes) {\n          const shouldbechecked = allvalues.includes(node.value);\n          if (shouldbechecked !== node.checked) //NOTE: used to read 'field.checked' which doesn't exist so this if() would always evaluate to true\n            this.setFieldValue(node, shouldbechecked);\n        }\n      } else if (field.multi) { //implies radio\n        const tocheck = field.nodes.filter(_ => _.value === allvalues[allvalues.length - 1])[0];\n        if (tocheck && !tocheck.checked)\n          this.setFieldValue(tocheck, true);\n        if (!tocheck)\n          field.nodes.filter(_ => _.checked).forEach(_ => this.setFieldValue(_, false));\n      } else if (field.node.matches(\"input:not([type=file]),select,textarea\")) { //Limit URL prefills to simple elements - TODO allow custom components to decide on this themselves OR *explicitly* require fields to opt-in to being prefillable\n        if (!this._isNowSettable(field.node))\n          continue;\n        this.setFieldValue(field.node, allvalues[allvalues.length - 1]); //last value wins\n      }\n    }\n  }\n\n  /**\n   * Set or update the message for the specified field\n   * @param field - node on which the validation triggered\n   * @param type - type of the message (\"error\" or \"suggestion\") - a field or group can have both an \"error\" and \"suggestion\" visible\n   * @param getError - function which returns a reference to the error node (or DocumentFragment) or a text\n   *\n   * .wh-form__field--error      - Used to indicate this element has an error\n   * .wh-form__field--suggestion - Used to indicate this element has an suggestion\n   * .wh-form__error             - The error message container\n   * .wh-form_suggestion         - The suggestion message container\n   */\n  _updateFieldGroupMessageState(field: HTMLElement, type: \"error\" | \"suggestion\", getError: (field: HTMLElement) => FormFrontendMessage | null) {\n    //Please note that _updateFieldGroupMessageState doesn't *validate* anything - it takes the current error/suggestion status and updates the DOM accordingly\n\n    /*\n    ADDME: ability to show multiple messages in case both the toplevel and a subfield have an error/suggestion.\n           Example: a checkboxgroup in which too many options are selected AND the required textfield of a selected option is empty.\n\n    ADDME: how should an error message reference a required nested textfield?\n\n    ADDME: Support progressive enhancements such as splitdatetime which use a native form element\n           to store the value. (it's probably confusing that aria-described by ends up on an\n           element which needs receives focus and cannot be used to influence/fix the value).\n           (such as the splitdatetime)\n\n           Suggestion for possible solution:\n           - have the progressive enchancement code add an attribute to the native form element\n             with the ID of the (group)element.\n    */\n    const fieldgroup = field.closest<HTMLElement>(\".wh-form__fieldgroup\");\n    //console.log(\"_updateFieldGroupMessageState\", field, fieldgroup);\n    if (!fieldgroup)\n      return;\n\n    /* Within the group this field belongs to we lookup the first node we can find which is marked as having the\n       type of message we want (\"error\" or \"suggestion\").\n       First we'll see if the fieldgroup wants to report something (radio & checkboxes handle their errors at the group level)\n       otherwise whe'll look for the first node which has a message.\n    */\n    const field_with_message = fieldgroup.classList.contains(\"wh-form__field--\" + type) ? fieldgroup : fieldgroup.querySelector<HTMLElement>(\".wh-form__field--\" + type);\n    //Do not pick up errors from deeper groups (array rows)\n    const error = (field_with_message && field_with_message.closest(\".wh-form__fieldgroup\") === fieldgroup ? getError(field_with_message) : null) || null;\n\n    // Now mark the whole .wh-form__fieldgroup as having an error/suggestion\n    fieldgroup.classList.toggle(\"wh-form__fieldgroup--\" + type, Boolean(error));\n\n    // Lookup the error message from the field metadata\n    if (error) { //mark the field has having failed at one point. we will now switch to faster updating error state\n      if (!field.classList.contains('wh-form__field--everfailed')) {\n        if (debugFlags.fhv)\n          console.log('[fhv] marking as everfailed', field, 'because of error', error);\n        field.classList.add('wh-form__field--everfailed');\n      }\n    }\n\n    // Determine the contextnode to set ARIA attributes on\n\n    // ADDME: before looking up a group, check if there an attribute specifying\n    //        another element with role=\"group\" handled the input.\n\n    // Find the first role=\"group\" we can find\n    // (ineither the .wh-form__subfield or .wh-form__field)\n    const potentialgroupnode = field.closest<HTMLElement>(\"[role=group],.wh-form__subfield,wh-form__fieldgroup\");\n    const group = potentialgroupnode?.role === \"group\" ? potentialgroupnode : null;\n    const contextnode = group ?? field;\n\n    let messageid = \"\";\n    let messagenode = fieldgroup.querySelector(\".wh-form__\" + type); //either wh-form__error or wh-form__suggestion\n\n    // Create a container for the suggestion or error\n    if (messagenode) {\n      messageid = messagenode.id; // reuse the existing messagenode\n    } else {\n      if (!error)\n        return; //nothing to do\n\n      // Generate a temporary id for the message which we can use in\n      // the aria-describedby to point to the message.\n      const random = Math.floor((1 + Math.random()) * 0x10000000).toString(16);\n      messageid = \"whform-msg-\" + random; // `${fieldname}-${random}`;\n\n      const suggestionholder = field.closest('.wh-form__fields') || fieldgroup.querySelector('.wh-form__fields') || fieldgroup;\n      messagenode = dompack.create(\"div\", { className: \"wh-form__\" + type }); // add a wh-form__error or wh-form__suggestion message container\n      messagenode.id = messageid; // id to reference to in the aria-describedby\n      suggestionholder.appendChild(messagenode);\n    }\n\n    if (error) { // Do we show a message?\n      messagenode.replaceChildren(typeof error === \"string\" ? lineFeedsToBreaks(error) : error);\n      this._addDescribedBy(contextnode, messageid);\n\n      if (type === \"error\")\n        contextnode.setAttribute(\"aria-invalid\", \"true\");\n    } else {\n      messagenode.replaceChildren(); // remove previous errors/suggestions texts from the errornode\n      this._removeDescribedBy(contextnode, messageid);\n      contextnode.removeAttribute(\"aria-invalid\");\n    }\n\n  }\n\n  // add the specified id of the message element to the list of elements in aria-describedby\n  _addDescribedBy(contextnode: HTMLElement, messageid: string) {\n    const describedby = contextnode.getAttribute(\"aria-describedby\") ?? \"\";\n    const describedby_fields = describedby !== \"\" ? describedby.split(\" \") : [];\n\n    if (describedby_fields.indexOf(messageid) === -1) {\n\n      describedby_fields.push(messageid);\n      contextnode.setAttribute(\"aria-describedby\", describedby_fields.join(\" \"));\n    }\n  }\n\n  // remove the specified id of the message element from the list of elements in aria-describedby\n  _removeDescribedBy(contextnode: HTMLElement, messageid: string) {\n    const describedby = contextnode.getAttribute(\"aria-describedby\") ?? \"\";\n    const describedby_fields = describedby !== \"\" ? describedby.split(\" \") : [];\n\n    for (let idx = 0; idx < describedby_fields.length; idx++) {\n      if (describedby_fields[idx] === messageid) {\n        describedby_fields.splice(idx, 1); // remove that item\n        break;\n      }\n    }\n\n    if (describedby_fields.length > 0)\n      contextnode.setAttribute(\"aria-describedby\", describedby_fields.join(\" \"));\n    else\n      contextnode.removeAttribute(\"aria-describedby\");\n  }\n\n  _updateFieldGroupErrorState(field: HTMLElement) {\n    this._updateFieldGroupMessageState(field, 'error', failedfield => getValidationState(failedfield).getError());\n  }\n\n  _updateFieldGroupSuggestionState(field: HTMLElement) {\n    this._updateFieldGroupMessageState(field, 'suggestion', failedfield => failedfield.propWhValidationSuggestion || '');\n  }\n\n  _doSetFieldError(evt: DocEvent<CustomEvent<SetFieldErrorData>>) {\n    //FIXME properly handle multiple fields in this group reporting errors\n    dompack.stop(evt);\n\n\n    this._reportFieldValidity(evt.target);\n  }\n\n  /** @returns false on error */\n  _reportFieldValidity(node: HTMLElement): boolean {\n    const state = getValidationState(node).getState();\n    node.classList.toggle(\"wh-form__field--error\", Boolean(state?.error));\n    node.classList.toggle(\"wh-form__field--suggestion\", Boolean(state?.suggested));\n\n    this._updateFieldGroupErrorState(node);\n    this._updateFieldGroupSuggestionState(node);\n    return !(state && \"error\" in state);\n  }\n\n  //validate and submit. normal submissions should use this function, directly calling submit() skips validation and busy locking\n  async validateAndSubmit(extradata: ExtraData) {\n    await this._submit(null, extradata);\n  }\n\n  /** Override beforeSubmit to have a last chance to block/confirm actual form submission\n   * @returns true to continue submitting\n  */\n  beforeSubmit(extradata: ExtraData): boolean | Promise<boolean> {\n    return true;\n  }\n\n  async _submit(evt: SubmitEvent | null, extradata: ExtraData) {\n    if (this.node.classList.contains('wh-form--submitting') || this.inSubmit) { //already submitting\n      evt?.preventDefault(); //avoid 'No RPC handler installed' noise during 429 errors\n      return;\n    }\n\n    //A form element's default button is the first submit button in tree order whose form owner is that form element.\n    const submitter = this._submitter || this.node.querySelector(submitselector);\n    this._submitter = null;\n\n    if (debugFlags.fhv)\n      console.log('[fhv] received submit event, submitter:', submitter);\n\n    let tempbutton = null;\n    if (submitter) { //temporarily add a hidden field representing the selected button\n      tempbutton = document.createElement('input');\n      tempbutton.name = submitter.name;\n      tempbutton.value = submitter.value;\n      tempbutton.type = \"hidden\";\n      this.node.appendChild(tempbutton);\n    }\n\n    try {\n      this.inSubmit = true;\n      const beforeResult = this.beforeSubmit(extradata);\n      if (!beforeResult || (isPromise(beforeResult) && !await beforeResult))\n        return;\n\n      /* DEPRECATED - Switch to onBeforeSubmit in 5.7+ */\n      if (!dompack.dispatchCustomEvent(this.node, 'wh:form-beforesubmit', { bubbles: true, cancelable: true })) { //allow parsley to hook into us\n        console.error(\"The use of wh:form-beforesubmit is deprecated and will be removed in a future version. Use onBeforeSubmit instead\");\n        return;\n      }\n\n      await this._doSubmit(evt, extradata);\n    } finally {\n      tempbutton?.remove();\n      this.inSubmit = false;\n    }\n  }\n\n  private _shouldValidateField(el: HTMLElement) {\n    //TODO maybe we can get rid of the data attributes by checking for explicit symbols like whFormsApiChecker\n    return (el.whFormsApiChecker || el.matches(`${queryFormFieldLike},*[data-wh-form-name],*[data-wh-form-custom-validator`)) &&\n      this._isPartOfForm(el);\n  }\n\n  _getFieldsToValidate(startingpoint?: HTMLElement) {\n    return dompack.qSA<HTMLElement>(startingpoint ?? this.node, \"*\").filter(el => this._shouldValidateField(el));\n  }\n\n  //reset any serverside generated errors (generally done when preparing a new submission)\n  resetServerSideErrors() {\n    for (const field of this._getFieldsToValidate()) {\n      const state = getValidationState(field);\n      if (state?.explicit?.serverside && field.propWhCleanupFunction)\n        field.propWhCleanupFunction();\n    }\n  }\n\n  async _doSubmit(evt: SubmitEvent | null, extradata: ExtraData) {\n    if (evt)\n      evt.preventDefault();\n\n    const lock = dompack.flagUIBusy({ modal: true });\n    this._submitstart = Date.now();\n    this._submittimeout = setTimeout(() => this._submitHasTimedOut(), 5000);\n    this.node.classList.add('wh-form--submitting');\n\n    try {\n      this.resetServerSideErrors();\n\n      const validationresult = await this.validate();\n      if (validationresult.valid) {\n        const result = await this.submit(extradata);\n        if (result.result && result.result.submittype && result.result.submittype !== this._getVariableValueForConditions(\"formsubmittype\")) {\n          this.node.setAttribute(\"data-wh-form-var-formsubmittype\", result.result.submittype);\n          this._updateConditions(false);\n        }\n      } else {\n        this.sendFormEvent({ event: \"failed\", errorfields: getErrorFields(validationresult), errorsource: 'client' });\n      }\n    } finally {\n      lock.release();\n      this.node.classList.remove('wh-form--submitting');\n      if (this._submittimeout) {\n        clearTimeout(this._submittimeout);\n        this._submittimeout = undefined;\n      }\n      this._submitstart = undefined;\n    }\n  }\n\n  _submitHasTimedOut() { //TODO extend this to (background) RPCs too, and make waitfor more specific. also check whether we're stuck on client or server side\n    this.sendFormEvent({ event: \"slow\", waitfor: \"submit\" });\n  }\n\n  //default submission function. eg. RPC will override this\n  async submit(extradata?: ExtraData): Promise<{ result?: FormSubmitEmbeddedResult }> {\n    this.node.submit();\n    return {};\n  }\n\n  _onTakeFocus(evt: DocEvent<TakeFocusEvent>) {\n    const containingpage = evt.target.closest('.wh-form__page');\n    if (containingpage && containingpage.classList.contains('wh-form__page--hidden')) {\n      //make sure the page containing the errored component is visible\n      const pagenum = dompack.qSA(this.node, '.wh-form__page').findIndex(page => page === containingpage);\n      if (pagenum >= 0)\n        this.gotoPage(pagenum);\n    }\n  }\n\n  _checkClick(evt: DocEvent<MouseEvent>) {\n    const actionnode = evt.target?.closest<HTMLElement>(\"*[data-wh-form-action]\");\n    if (!actionnode) {\n      const submitter = evt.target.closest<SubmitSelectorType>(submitselector);\n      if (submitter?.form === this.node) { //if we found the submit buton AND it's for *this* form. don't intercept otherwise\n        if (!this.node.classList.contains('wh-form--allowsubmit')) { //we're not allowed to submit yet (not on a final page)\n          dompack.stop(evt);\n          if (this.node.classList.contains('wh-form--allownext'))  //but we can convert your action to a NextPage! which is likely what you intended\n            this.executeFormAction('next');\n          return;\n        }\n\n        this._submitter = submitter; //store as submitter in case a submit event actually occurs\n        setTimeout(() => this._submitter = null); //but clear it as soon as event processing ends\n      }\n      return;\n    }\n\n    dompack.stop(evt);\n    this.executeFormAction(actionnode.dataset.whFormAction!);\n  }\n\n  private _getPageState(): PageState {\n    const pages = dompack.qSA<HTMLElement>(this.node, '.wh-form__page');\n    const curpage = pages.findIndex(page => !page.classList.contains('wh-form__page--hidden'));\n    return { pages, curpage };\n  }\n\n  _updatePageVisibility(pagelist: HTMLElement[], currentpage: number) {\n    pagelist.forEach((page, idx) => {\n      page.classList.toggle('wh-form__page--hidden', idx !== currentpage);\n      page.classList.toggle('wh-form__page--visible', idx === currentpage);\n    });\n  }\n\n  ///Get the currently opened page (page node)\n  getCurrentPage() {\n    const state = this._getPageState();\n    return state.curpage >= 0 ? state.pages[state.curpage] : null;\n  }\n\n  /** Position the specified element's group or the form itself into view, using `.wh-anchor` nodes to correct for fixed headers\n      @param scrollto -  Element to position into view. If not set, the form it scrolled into view */\n  scrollIntoView(scrollto?: HTMLElement) {\n    const origscrollto = scrollto;\n    scrollto = (scrollto ? scrollto.closest<HTMLElement>('.wh-form__fieldgroup') : undefined) || this.node;\n    scrollto = scrollto.querySelector<HTMLElement>('.wh-anchor') || scrollto;\n    if (origscrollto && scrollto !== origscrollto && debugFlags.fhv)\n      console.log('[fhv] Modified scroll target from ', origscrollto, ' to anchor ', scrollto);\n    else if (debugFlags.fhv)\n      console.log('[fhv] Scroll to ', scrollto);\n\n    scrollto.scrollIntoView();\n  }\n\n  /** Get the current page number\n      @returns 0-based index of page to jump to */\n  getCurrentPageNumber() {\n    return this._getPageState().curpage;\n  }\n\n  /** Goto a specific page\n      @param page - 0-based index of page or the HTML element of the page to jump to */\n  async gotoPage(page: number | HTMLElement, { __isSubmit = false } = {}): Promise<void> {\n    const state = this._getPageState();\n    const pageidx = getPageIdx(state, page);\n    if (state.curpage === pageidx)\n      return;\n\n    const goingforward = pageidx > state.curpage;\n    if (!__isSubmit)\n      this.sendFormEvent({\n        event: goingforward ? __isSubmit ? 'submitted' : 'nextpage' : 'previouspage',\n        targetpagenum: pageidx + 1,\n        targetpagetitle: this._getPageTitle(pageidx)\n      });\n\n    this._updatePageVisibility(state.pages, pageidx);\n    if (goingforward) //only makes sense to update if we're making progress\n      merge.run(state.pages[pageidx], { form: await this.getFormValue() });\n\n    this._updatePageNavigation();\n\n    //scroll back up\n    this.scrollIntoView();\n\n    /* tell the page it's now visible - note that we specifically don't fire this on init, as it's very likely\n       users would 'miss' the event anyway - registerHandler usually executes faster than your wh:form-pagechange\n       registrations, if you wrapped those in a dompack.register */\n    dompack.dispatchCustomEvent(state.pages[pageidx], \"wh:form-pagechange\", { bubbles: true, cancelable: false, detail: { formHandler: this } });\n  }\n\n  private _getDestinationPage(pagestate: PageState, direction: number) {\n    let pagenum = pagestate.curpage + direction;\n    //TODO \"captcha\" should no longer exist since WH5.9 - unless there are still some static published forms around, so keep skipping them for a while\n    while (pagenum >= 0 && pagenum < pagestate.pages.length && (pagestate.pages[pagenum].propWhFormCurrentVisible === false || pagestate.pages[pagenum].dataset.whFormPagerole === \"captcha\"))\n      pagenum = pagenum + direction;\n    if (pagenum < 0 || pagenum >= pagestate.pages.length)\n      return -1;\n    return pagenum;\n  }\n\n  _getPageTitle(pagenum: number) {\n    const pagenode = this._getPageState().pages[pagenum];\n    if (!pagenode)\n      return \"\";\n    return pagenode.dataset.whFormPagetitle || (\"#\" + (pagenum + 1));\n  }\n\n  async executeFormAction(action: string) {\n    switch (action) {\n      case 'previous':\n        {\n          if (this.node.classList.contains('wh-form--allowprevious')) {\n            const pagestate = this._getPageState();\n            if (pagestate.curpage > 0)\n              this.gotoPage(this._getDestinationPage(pagestate, -1));\n            else if (this.node.dataset.whFormBacklink)\n              navigateTo({ type: \"redirect\", url: this.node.dataset.whFormBacklink });\n          }\n          return;\n        }\n      case 'next':\n        {\n          const pagestate = this._getPageState();\n          if (this.node.classList.contains('wh-form--allownext')) {\n            this.resetServerSideErrors();\n\n            const validationstatus = await this.validate(pagestate.pages[pagestate.curpage]);\n            if (validationstatus.valid) {\n              this.gotoPage(this._getDestinationPage(pagestate, +1));\n            } else {\n              this.sendFormEvent({ event: \"failed\", errorfields: getErrorFields(validationstatus), errorsource: 'nextpage' });\n            }\n          }\n          return;\n        }\n      case 'exit': {\n        if (!this.exitButtonNavigateTo)\n          throw new Error(\"No exit navigation target set for this form\");\n\n        navigateTo(this.exitButtonNavigateTo);\n        return;\n      }\n      default: {\n        console.error(`Unknown form action '${action}'`);\n      }\n    }\n  }\n\n  async refreshConditions() {\n    await this._updateConditions(false);\n  }\n\n  _onInputChange() {\n    this.sendFormEvent(); //only trigger implicit _firstinteraction event\n    this._updateConditions(false);\n  }\n\n  async _updateConditions(isinit: boolean) {\n    // Check pages visibility\n    const hiddenPages = [];\n    const mergeNodes = [];\n    let anychanges = false;\n\n    for (const formpage of dompack.qSA(this.node, \".wh-form__page\")) {\n      let visible = true;\n      if (formpage.dataset.whFormVisibleIf) {\n        visible = this._matchesCondition(formpage.dataset.whFormVisibleIf);\n        if (!visible)\n          hiddenPages.push(formpage); // We don't have to check fields on this page any further\n\n        if (visible !== formpage.propWhFormCurrentVisible) {\n          anychanges = true;\n          formpage.propWhFormCurrentVisible = visible;\n          mergeNodes.push(formpage);\n        }\n      }\n    }\n    if (anychanges)\n      this._updatePageNavigation();\n\n    const tovalidate = new Array<HTMLElement>;\n    const hiddengroups = [], enabledgroups = [], requiredgroups = [];\n    for (const formgroup of dompack.qSA(this.node, \".wh-form__fieldgroup\")) {\n      const groupPage = formgroup.closest<HTMLElement>(\".wh-form__page\");\n      const visible = (!groupPage || !hiddenPages.includes(groupPage)) && this._matchesCondition(formgroup.dataset.whFormVisibleIf);\n      if (!visible)\n        hiddengroups.push(formgroup);\n\n      const enabled = visible\n        && this._matchesCondition(formgroup.dataset.whFormEnabledIf);\n\n      if (enabled)\n        enabledgroups.push(formgroup);\n\n      //load initial status?\n      if (formgroup.propWhFormInitialRequired === undefined)\n        formgroup.propWhFormInitialRequired = formgroup.classList.contains(\"wh-form__fieldgroup--required\");\n\n      const required = enabled\n        && (formgroup.dataset.whFormRequiredIf ? this._matchesCondition(formgroup.dataset.whFormRequiredIf) : formgroup.propWhFormInitialRequired);\n\n      if (required)\n        requiredgroups.push(formgroup);\n\n      if (visible !== formgroup.propWhFormCurrentVisible // These are initially undefined, so this code will always run first time\n        || enabled !== formgroup.propWhFormCurrentEnabled\n        || required !== formgroup.propWhFormCurrentRequired) {\n        formgroup.propWhFormCurrentVisible = visible;\n        formgroup.propWhFormCurrentEnabled = enabled;\n        formgroup.propWhFormCurrentRequired = required;\n\n        formgroup.classList.toggle(\"wh-form__fieldgroup--disabled\", !enabled);\n        formgroup.classList.toggle(\"wh-form__fieldgroup--hidden\", !visible);\n        formgroup.classList.toggle(\"wh-form__fieldgroup--required\", required);\n\n        mergeNodes.push(formgroup);\n      }\n    }\n\n    for (const formline of dompack.qSA(this.node, \".wh-form__fieldline\")) {\n      const formgroup = formline.closest<HTMLElement>(\".wh-form__fieldgroup\");\n      if (!formgroup)\n        continue;\n      const visible = !hiddengroups.includes(formgroup) && this._matchesCondition(formline.dataset.whFormVisibleIf);\n      const enabled = visible && enabledgroups.includes(formgroup) && this._matchesCondition(formline.dataset.whFormEnabledIf);\n      const required = enabled && requiredgroups.includes(formgroup);\n\n      if (visible !== formline.propWhFormlineCurrentVisible) {  // These are initially undefined, so this code will always run first time\n        formline.propWhFormlineCurrentVisible = visible;\n        formline.classList.toggle(\"wh-form__fieldline--hidden\", !visible);\n      }\n\n      // Look for nodes that are explicit enable state (enablee/require) listeners, or that need to do so because they're real input controls\n      const inputtargets = dompack.qSA(formline, `${queryFormFieldLike},[data-wh-form-state-listener='true']`);\n\n      for (const node of inputtargets) {\n        //Record initial states\n        if (!node.dataset.whFormSavedEnabled)\n          node.dataset.whFormSavedEnabled = (\"disabled\" in node ? !node.disabled : !(\"whFormDisabled\" in node.dataset)).toString();\n\n        if (!node.dataset.whFormSavedRequired)\n          node.dataset.whFormSavedRequired = Boolean(\"required\" in node && node.required).toString();\n\n        // The field is enabled if all of these are matched:\n        // - we're setting it to enabled now\n        // - it hasn't been disabled explicitly (set initially on the node)\n        // - it hasn't been disabled through enablecomponents\n        const node_enabled = enabled && node.dataset.whFormSavedEnabled === \"true\" && this._matchesCondition(node.dataset.whFormEnabledIf);\n\n        /* TODO ideally we'd eliminate 'current enabled/required' states, but we need them as long as some components intercept wh:form-enable and wh:form-require events\n                to know the state we told them to put the component in. we may be able to eliminate those events */\n        //if node.dataset.whFormCurrentEnabled is unset, we may still need to apply disabled state to a fresh field\n        if (!node.dataset.whFormCurrentEnabled || node_enabled !== (node.dataset.whFormCurrentEnabled === \"true\")) {\n          node.dataset.whFormCurrentEnabled = node_enabled ? \"true\" : \"false\";\n\n          // Give the formgroup a chance to handle it\n          if (dompack.dispatchCustomEvent(node, \"wh:form-enable\", { bubbles: true, cancelable: true, detail: { enabled: node_enabled } })) {\n            // Not cancelled, so run our default handler\n            if (isFormFieldLike(node)) //For true html5 inputs we'll use the native attributes. formstatelisteners: we use data attributes\n              node.disabled = !node_enabled;\n            else if (node_enabled)\n              node.removeAttribute(\"data-wh-form-disabled\");\n            else\n              node.setAttribute(\"data-wh-form-disabled\", \"\");\n          }\n\n          if (!isinit && !node_enabled && !tovalidate.includes(node))\n            tovalidate.push(node); // to clear errors for this disabled field\n        }\n\n        const node_required = (node.dataset.whFormSavedRequired === \"true\" || required) && node_enabled && visible;\n        //if node.dataset.whFormCurrentEnabled is unset, we may still need to apply disabled state to a fresh field\n        //if node.dataset.whFormCurrentRequired is unset, we may still need to apply required state to a fresh field\n        if (!node.dataset.whFormCurrentRequired || node.dataset.whFormCurrentRequired !== (node_required ? \"true\" : \"false\")) {\n          node.dataset.whFormCurrentRequired = node_required ? \"true\" : \"false\";\n\n          // Give the formgroup a chance to handle it\n          if (dompack.dispatchCustomEvent(node, \"wh:form-require\", { bubbles: true, cancelable: true, detail: { required: node_required } })) {\n            // Not cancelled, so run our default handler\n            if (isFormFieldLike(node)) { //For true html5 inputs we'll use the native attributes. formstatelisteners: we use data attributes\n              if (!isFormControl(node) || node.type !== 'checkbox') //don't set required on checkboxes, that doesn't do what you want\n                node.required = node_required;\n            } else if (node_required)\n              node.setAttribute(\"data-wh-form-required\", \"\");\n            else\n              node.removeAttribute(\"data-wh-form-required\");\n          }\n\n          if (!isinit && !node_required && formgroup.classList.contains(\"wh-form__fieldgroup--error\") && !tovalidate.includes(node))\n            tovalidate.push(node); // to clear errors for this now optional field\n        }\n      }\n    }\n\n    for (const option of dompack.qSA<HTMLOptionElement>(this.node, \".wh-form__fieldgroup select option\")) {\n      const visible = this._matchesCondition(option.dataset.whFormVisibleIf);\n\n      //Record initial states\n      if (!option.dataset.whFormSavedEnabled)\n        option.dataset.whFormSavedEnabled = (!option.disabled).toString();\n      if (!option.dataset.whFormSavedHidden)\n        option.dataset.whFormSavedHidden = option.hidden.toString();\n\n      const option_enabled = visible && option.dataset.whFormSavedEnabled === \"true\";\n      const option_hidden = !visible || option.dataset.whFormSavedHidden === \"true\";\n\n      if (option_enabled !== (option.dataset.whFormCurrentEnabled === \"true\") || option_hidden !== (option.dataset.whFormCurrentHidden === \"true\")) {\n        option.dataset.whFormCurrentEnabled = option_enabled ? \"true\" : \"false\";\n        option.dataset.whFormCurrentHidden = option_hidden ? \"true\" : \"false\";\n        option.disabled = !option_enabled;\n        option.hidden = option_hidden;\n\n        // If this option was the selected option, but is now disabled (but not the placeholder), reset the select's value\n        const selectnode = option.closest<HTMLSelectElement>(\"select\");\n        if (selectnode && option.selected && (!option_enabled || option_hidden) && option.dataset.placeholder === undefined) {\n          if (selectnode.options[0].dataset.placeholder !== undefined) { //we have a placeholder...\n            selectnode.selectedIndex = 0;\n          } else {\n            selectnode.selectedIndex = -1;\n            if (!selectnode.__didPlaceholderWarning) {\n              selectnode.__didPlaceholderWarning = true;\n              console.warn(\"This <select> lacks an explicit placeholder so we had to set selectedIndex to -1\", selectnode);\n            }\n          }\n        }\n\n        if (selectnode && !isinit && !tovalidate.includes(selectnode))\n          tovalidate.push(selectnode); // to clear errors for this option's select field\n      }\n    }\n\n    if (tovalidate.length)\n      await this.validate(tovalidate, { focusfailed: false, iffailedbefore: true });\n\n    this.fixupMergeFields(mergeNodes);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-misused-promises -- FIXME: needs API rework\n  __scheduleUpdateConditions = wrapSerialized(() => this._updateConditions(false), { coalesce: true });\n\n  async fixupMergeFields(nodes: HTMLElement[]) {\n    // Rename the data-wh-merge attribute to data-wh-dont-merge on hidden pages and within hidden formgroups to prevent\n    // merging invisible nodes\n    // FIXME 'merge' has a filter option now - convert to that!\n    const formvalue = await this.getFormValue();\n    for (const node of nodes) {\n      if (node.propWhFormCurrentVisible) {\n        for (const mergeNode of dompack.qSA(node, '*[data-wh-dont-merge]')) {\n          mergeNode.dataset.merge = mergeNode.dataset.whDontMerge;\n          mergeNode.removeAttribute(\"data-wh-dont-merge\");\n        }\n        merge.run(node, { form: formvalue });\n      } else {\n        for (const mergeNode of dompack.qSA(node, '*[data-merge]')) {\n          mergeNode.dataset.whDontMerge = mergeNode.dataset.merge;\n          mergeNode.removeAttribute(\"data-merge\");\n        }\n      }\n    }\n  }\n\n  _matchesCondition(conditiontext: string | undefined) {\n    if (!conditiontext)\n      return true;\n\n    return this._matchesConditionRecursive(parseCondition(conditiontext));\n  }\n\n  _getConditionRawValue(fieldname: string, options?: { checkdisabled?: boolean }) {\n    if (this.node.hasAttribute(\"data-wh-form-var-\" + fieldname))\n      return this.node.getAttribute(\"data-wh-form-var-\" + fieldname);\n\n    const matchfield = this.getElementByName(fieldname);\n    if (!matchfield) {\n      console.error(`No match for conditional required field '${fieldname}'`);\n      return null;\n    }\n\n    if (isRadioNodeList(matchfield)) {\n      let currentvalue = null;\n\n      for (const field of matchfield)\n        if (((options && options.checkdisabled) || this._isNowSettable(field)) && field.checked) {\n          if (field.type !== \"checkbox\")\n            return field.value;\n\n          if (!currentvalue)\n            currentvalue = [];\n          currentvalue.push(field.value);\n        }\n      return currentvalue;\n    } else {\n      //Can we set this field?\n      if ((!options || !options.checkdisabled) && !this._isNowSettable(matchfield))\n        return null;\n    }\n\n    if (matchfield.type === \"checkbox\")\n      return (matchfield as HTMLInputElement).checked ? [matchfield.value] : null;\n\n    if (matchfield.type === \"radio\")\n      return (matchfield as HTMLInputElement).checked ? matchfield.value : null;\n\n    return matchfield.value;\n  }\n\n  _getVariableValueForConditions(conditionfield: string, options?: { matchcase?: boolean; checkdisabled?: boolean }) {\n    if (this.node.hasAttribute(\"data-wh-form-var-\" + conditionfield))\n      return this.node.getAttribute(\"data-wh-form-var-\" + conditionfield);\n\n    const fields = conditionfield.split(\"$\");\n\n    if (fields.length > 1) {\n      // If the condition field has a subfield, check if it's available through a form var\n      // The '$' in the attribute name is replaced with '.' to make the attribute name valid\n      const attrname = fields.join(\".\");\n      if (this.node.hasAttribute(\"data-wh-form-var-\" + attrname))\n        return this.node.getAttribute(\"data-wh-form-var-\" + attrname);\n    }\n\n    let currentvalue = this._getConditionRawValue(fields[0], options);\n    if (fields.length === 1 || currentvalue === null) //no subs to process\n      return currentvalue;\n\n    // Look for an extrafield match\n    const matchfield = this.getElementByName(fields[0]);\n    if (!matchfield) {\n      console.error(`No match for conditional required field '${conditionfield}'`);\n      return null;\n    }\n\n    if (matchfield instanceof HTMLSelectElement) {\n      if (Array.isArray(currentvalue)) {\n        const selectedvalue = currentvalue;\n        currentvalue = [];\n        for (const val of selectedvalue) {\n          const selected = dompack.qS<HTMLOptionElement>(matchfield, `option[value=\"${CSS.escape(val)}\"]`);\n          if (!selected?.dataset.__extrafields)\n            return null;\n          const extrafields = JSON.parse(selected.dataset.__extrafields);\n          currentvalue.push(extrafields[fields[1]]);\n        }\n      } else {\n        const selected = dompack.qS<HTMLOptionElement>(matchfield, `option[value=\"${CSS.escape(currentvalue)}\"]`);\n        if (!selected?.dataset.__extrafields)\n          return null;\n        const extrafields = JSON.parse(selected.dataset.__extrafields);\n        currentvalue = extrafields[fields[1]];\n      }\n      return currentvalue;\n    } else {\n      console.error(\"Subfield matching not supported for non-select fields\");\n      return null;\n    }\n  }\n\n\n  _matchesConditionRecursive(condition: FormCondition): boolean {\n    switch (condition.matchtype) {\n      case \"AND\":\n        for (const subcondition of condition.conditions)\n          if (!this._matchesConditionRecursive(subcondition))\n            return false;\n        return true;\n\n      case \"OR\":\n        for (const subcondition of condition.conditions)\n          if (this._matchesConditionRecursive(subcondition))\n            return true;\n        return false;\n\n      case \"NOT\":\n        return !this._matchesConditionRecursive(condition.condition);\n\n      case \"AGE<\":\n      case \"AGE>=\": {\n        const currentvalue = this._getVariableValueForConditions(condition.field);\n        if (!currentvalue)\n          return false;\n\n        const now = new Date, birthdate = new Date(Array.isArray(currentvalue) ? currentvalue[0] : currentvalue); //should never be an array, but _getVariableValueForConditions is generic\n        let age = now.getFullYear() - birthdate.getFullYear();\n        //birthdate not hit yet this year? then you lose a year\n        if (now.getMonth() < birthdate.getMonth()\n          || (now.getMonth() === birthdate.getMonth() && now.getDate() < birthdate.getDate())) {\n          --age;\n        }\n\n        return (condition.matchtype === 'AGE<' ? age < condition.value : age >= condition.value);\n      }\n    }\n\n    const currentvalue = this._getVariableValueForConditions(condition.field, condition.options);\n\n    if (condition.matchtype === \"HASVALUE\")\n      return Boolean(currentvalue) === Boolean(condition.value);\n\n    if ([\"IN\", \"HAS\", \"IS\"].includes(condition.matchtype)) {\n      const matchcase = condition.options?.matchcase !== false; // Defaults to true\n      const compareagainst = Array.isArray(condition.value) ? condition.value : condition.value ? [condition.value] : [];\n      const currentValArray: string[] = Array.isArray(currentvalue) ? currentvalue : currentvalue ? [currentvalue] : [];\n\n      // If the match is not case-sensitive, the condition value is already uppercased, so we only have to uppercase the\n      // current value(s) when checking\n      if (!matchcase)\n        currentValArray.forEach((_, idx) => currentValArray[idx] = currentValArray[idx].toUpperCase());\n\n      // The current value and the condition value should (at least) overlap\n      if (!currentValArray.some(value => compareagainst.includes(value)))\n        return false;\n\n      // For \"HAS\" and \"IS\" conditions, all of the required values should be selected (there shouldn't be required values\n      // that are not selected)\n      if ((condition.matchtype === \"HAS\" || condition.matchtype === \"IS\") && compareagainst.some(value => !currentValArray.includes(value)))\n        return false;\n\n      // For an \"IS\" condition, all of the selected values should be required (there shouldn't be selected values that are\n      // not required)\n      if (condition.matchtype === \"IS\" && currentValArray.some(value => !compareagainst.includes(value)))\n        return false;\n\n      return true;\n    }\n\n    return console.error(`No support for conditional type '${condition.matchtype}'`), false;\n  }\n\n  _updatePageNavigation() {\n    const pagestate = this._getPageState();\n    const nextpage = this._getDestinationPage(pagestate, +1);\n    const morepages = nextpage !== -1;\n    const curpagerole = pagestate.pages[pagestate.curpage] ? pagestate.pages[pagestate.curpage].dataset.whFormPagerole : '';\n    const nextpagerole = morepages ? pagestate.pages[nextpage].dataset.whFormPagerole : \"\";\n\n    this.node.classList.toggle(\"wh-form--allowprevious\", Boolean((pagestate.curpage > 0 && curpagerole !== 'thankyou') || (pagestate.curpage <= 0 && this.node.dataset.whFormBacklink)));\n    this.node.classList.toggle(\"wh-form--allownext\", morepages && nextpagerole !== 'thankyou');\n    this.node.classList.toggle(\"wh-form--allowsubmit\", curpagerole === 'thankyou'\n      ? pagestate.pages[pagestate.curpage].dataset.whFormExitButton !== undefined\n      : (!morepages || nextpagerole === 'thankyou'));\n  }\n\n  _navigateToThankYou(richvalues?: RichValues) {\n    const state = this._getPageState();\n\n    if (state.curpage >= 0) {\n      const nextpage = this._getDestinationPage(state, +1);\n      if (nextpage !== -1 && state.pages[nextpage] && state.pages[nextpage].dataset.whFormPagerole === 'thankyou') {\n        const rawNavigateTo = state.pages[nextpage].dataset.whFormNavigateTo;\n        const exitButton = state.pages[nextpage].dataset.whFormExitButton;\n        const parsedNavTo = rawNavigateTo ? JSON.parse(rawNavigateTo) : null;\n        if (parsedNavTo)\n          this.exitButtonNavigateTo = parsedNavTo;\n\n        const redirectdelay = parseInt(state.pages[nextpage].dataset.whFormPageredirectDelay ?? \"\");\n\n        if (exitButton) {\n          const submitButton = this.node.querySelector<HTMLElement>(\".wh-form__button--submit\");\n          const submitButtonLabel = submitButton?.querySelector<HTMLElement>(\".wh-form__buttonlabel\");\n          if (submitButton && submitButtonLabel) {\n            submitButton.dataset.whFormAction = \"exit\";\n            submitButtonLabel.textContent = exitButton;\n          } else {\n            console.error(`Unable to find the submit button '.wh-form__button--submit .wh-form__buttonlabel' - I need to replace its label with '${exitButton}'!`);\n          }\n        }\n\n        if (parsedNavTo && !(redirectdelay >= 0) && !exitButton) {\n          navigateTo(parsedNavTo);\n          return;\n        }\n\n        this.updateRichValues(state.pages[nextpage], richvalues);\n        this.gotoPage(nextpage, { __isSubmit: true });\n        if (parsedNavTo && redirectdelay >= 0) {\n          // If redirectdelay==0 (redirect immediately, while showing the thank you page), redirect after a small delay to\n          // give the browser time to hide the busy layer\n          // Might be caused by this: https://stackoverflow.com/a/60439478\n          setTimeout(() => navigateTo(parsedNavTo), redirectdelay * 1000 || 100);\n        }\n      }\n    }\n  }\n  updateRichValues(page: HTMLElement, richvalues?: RichValues) {\n    if (richvalues) {\n      for (const { field, value } of richvalues) {\n        const node = page.querySelector(`.wh-form__fieldgroup--richtext[data-wh-form-group-for=\"${CSS.escape(field)}\"] .wh-form__richtext`);\n        if (node) {\n          node.innerHTML = value;\n          dompack.registerMissed(node);\n        }\n      }\n    }\n  }\n\n  private ensureLegacyWarning(field: HTMLElement) {\n    if (!this.didLegacyWarning && !isLive)\n      console.warn(`[form] ${getFieldDisplayName(field)} is using wh:form-getvalue/wh:form-setvalue events. It should switch to JSFormElement`);\n\n    this.didLegacyWarning = true;\n  }\n\n  /* Override this to overwrite the processing of individual fields. Note that\n     radio and checkboxes are not passed through getFieldValue, and that\n     getFieldValue may return undefined or a promise. */\n  async getFieldValue(field: HTMLElement) {\n    if (field[rfSymbol])\n      return field[rfSymbol].getValue();\n\n    if (field.hasAttribute('data-wh-form-name') || field.whUseFormGetValue) {\n      //create a deferred promise for the field to fulfill\n      const deferred = Promise.withResolvers<unknown>();\n      //if cancelled, we'll assume the promise is taken over\n      if (!dompack.dispatchCustomEvent(field, 'wh:form-getvalue', { bubbles: true, cancelable: true, detail: { deferred } })) {\n        this.ensureLegacyWarning(field);\n        return deferred.promise;\n      }\n    }\n    if (!isFormFieldLike(field)) {\n      /* Can't fail on these, weird embeddings do weird things. Eg google's recaptcha v2 triggers this because it assigns a random name=\n         to the iframe it injects and then we pick that up.. (may need to move this error behind a debugflag if that's the only likely cause) */\n      if (debugFlags.fhv)\n        console.log(`[fhv] Cannot get value on non-FormControl`, field);\n      return undefined; //TODO throw? but wasn't currently fatal\n    }\n\n    if (field.matches('input[type=file]')) //We don't care for multiple yet, as our form RPC APIs don't support that either\n      return [...(field as HTMLInputElement).files || []].map(file => ({ fileName: file.name, file: file, link: null })) satisfies FormFileValue[];\n\n    return field.value;\n  }\n\n  /* Override this to overwrite the setting of individual fields. In contrast\n     to getFieldValue, this function will also be invoked for radio and checkboxes */\n  setFieldValue(fieldnode: HTMLElement, value: unknown) {\n    if (fieldnode[rfSymbol])\n      return fieldnode[rfSymbol].setValue(value);\n\n    if (fieldnode.hasAttribute('data-wh-form-name')) {\n      if (!dompack.dispatchCustomEvent(fieldnode, 'wh:form-setvalue', { bubbles: true, cancelable: true, detail: { value } })) {\n        this.ensureLegacyWarning(fieldnode);\n        return;\n      }\n      // Event is not cancelled, set node value directly\n    }\n\n    if (!isFormFieldLike(fieldnode)) {\n      console.error(`Cannot set value on non-FormControl`, fieldnode, value);\n      return; //TODO throw? but wasn't currently fatal\n    }\n\n    //NOTE this blocks a lot of 'new sets' being done through setFieldValue, eg resetting an array by setting it to []. which is fine for me, just use the data proxy..\n    if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n      console.error(`Setting value of type ${typeof value} on a FormControl`, fieldnode, value);\n      return; //TODO throw? but wasn't currently fatal\n    }\n\n    const saveInteractive = this.isInteractive;\n    try {\n      this.isInteractive = false;\n      if (isFormControl(fieldnode))\n        dompack.changeValue(fieldnode, value);\n      else\n        fieldnode.value = value;\n    } finally {\n      this.isInteractive = saveInteractive;\n    }\n  }\n\n  _isPartOfForm(el: HTMLElement) {\n    //In HTML terms, an input must either have *no* form attribute or explicitly point to us. eg <input form> is *outside* a form\n    //However nodes may live in fragments (eg arrayedits) that are not in the DOM and not attached anywhere, so we also consider anything outside the DOM to be in our form...\n    return !(\"form\" in el) || el.form === this.node || !document.contains(el)\n      || (!this.node && !el.hasAttribute(\"form\")); //FIXME remove this workaround needed now to work around form init race where arrayfields try to use _queryAllFields\n  }\n\n  _queryAllFields(options?: {\n    skiparraymembers?: boolean;\n    skipfield?: HTMLElement;\n    onlysettable?: boolean;\n    startnode?: HTMLElement;\n  }): FormControlDescription[] {\n    const foundfields = new Array<FormControlDescription>;\n    const skiparraymembers = options && options.skiparraymembers;\n\n    for (const field of this._getFieldsToValidate(options?.startnode)) {\n      if (options && field === options.skipfield) //arrayfield.es needs it\n        continue;\n      if (!this._isPartOfForm(field))\n        continue;\n      if (options && options.onlysettable && !this._isNowSettable(field))\n        continue;\n      if (skiparraymembers && field.closest(\".wh-form__arrayrow\"))\n        continue;\n\n      const name = getFieldName(field);\n      if (!name)\n        continue;\n\n      let addto = foundfields.find(_ => _.name === name);\n      if (isRadioOrCheckbox(field)) { //expect multiple inputs with this name?\n        if (!addto) {\n          addto = { name: name, multi: true, nodes: [] };\n          foundfields.push(addto);\n        } else if (!addto.multi) {\n          console.error(`[fhv] Encountered duplicate field '${name}'`, field);\n          continue;\n        }\n        addto.nodes.push(field);\n      } else {\n        if (addto) {\n          console.error(`[fhv] Encountered duplicate field '${name}'`, field);\n          continue;\n        }\n\n        foundfields.push({ name: name, multi: false, node: field });\n      }\n    }\n\n    return foundfields;\n  }\n\n  /** Return the names of all form elements */\n  getFormElementNames() {\n    return this._queryAllFields().map(_ => _.name);\n  }\n\n  /** getValue from a field as returned by _queryAllFields (supporting both multilevel and plain fields)\n      @returns promise */\n  _getQueryiedFieldValue(field: FormControlDescription) {\n    if (!field.multi)\n      return this.getFieldValue(field.node);\n\n    return field.nodes.filter(node => node.checked).map(node => node.value);\n  }\n\n  /** Return a promise resolving to the submittable form value */\n  async getFormValue(): Promise<FormResultValue> {\n    const outdata: FormResultValue = {};\n    const fieldpromises = new Array<Promise<void>>;\n\n    for (const field of this._queryAllFields({ onlysettable: true, skiparraymembers: true }))\n      this._processFieldValue(outdata, fieldpromises, field.name, this._getQueryiedFieldValue(field));\n\n    await Promise.all(fieldpromises);\n    return outdata;\n  }\n\n  _isNowSettable(node: HTMLElement) {\n    // If the node is disabled, it's not settable\n    if (\"disabled\" in node && node.disabled)\n      return false;\n\n    // If the node's field group is disabled or hidden, it's not settable\n    const formgroup = node.closest(\".wh-form__fieldgroup\");\n    if (formgroup) {\n      if (formgroup.classList.contains(\"wh-form__fieldgroup--disabled\"))\n        return false;\n      if (formgroup.classList.contains(\"wh-form__fieldgroup--hidden\"))\n        return false;\n    }\n\n    // If the node's form page is hidden dynamically, it's not settable\n    const formpage = node.closest<HTMLElement>(\".wh-form__page\");\n    if (formpage) {\n      if (formpage.propWhFormCurrentVisible === false)\n        return false;\n    }\n    // The node is settable\n    return true;\n  }\n\n  _processFieldValue(outdata: FormResultValue, fieldpromises: Array<Promise<void>>, fieldname: string, receivedvalue: unknown) {\n    if (receivedvalue === undefined)\n      return;\n    if (isPromise(receivedvalue)) {\n      fieldpromises.push(new Promise<void>((resolve, reject) => {\n        receivedvalue.then(result => {\n          if (result !== undefined)\n            outdata[fieldname] = result;\n\n          resolve();\n        }).catch(e => reject(e as Error));\n      }));\n    } else {\n      outdata[fieldname] = receivedvalue;\n    }\n  }\n\n  //get the option lines associated with a specific radio/checkbox group\n  getOptions(name: string) {\n    const nodes = this.getElementByName(name);\n    if (!(nodes instanceof RadioNodeList))\n      return [];\n\n    return [...nodes].map(node => ({\n      inputnode: node,\n      fieldline: node.closest<HTMLElement>('.wh-form__fieldline'),\n      value: node.value\n    }));\n  }\n\n  /** gets the selected option associated with a radio/checkbox group as an array\n      */\n  getSelectedOptions(name: string) {\n    let opts = this.getOptions(name);\n    opts = opts.filter(node => node.inputnode.checked);\n    return opts;\n  }\n\n  /** get the selected option associated with a radio/checkbox group. returns an object that's either null or the first selected option\n      */\n  getSelectedOption(name: string) {\n    const opts = this.getSelectedOptions(name);\n    return opts.length ? opts[0] : null;\n  }\n\n  /** get the fieldgroup for an element */\n  getFieldGroup(name: string): HTMLElement | null {\n    let node = this.getElementByName(name);\n    if (node instanceof RadioNodeList)\n      node = node[0];\n\n    return node ? node.closest<HTMLElement>('.wh-form__fieldgroup') : null;\n  }\n\n  /** get the values of the currently selected radio/checkbox group */\n  private getValues(name: string) {\n    return this.getSelectedOptions(name).map(node => node.value);\n  }\n  /** get the value of the first currently selected radio/checkbox group */\n  private getValue(name: string) {\n    const vals = this.getValues(name);\n    return vals.length ? vals[0] : null;\n  }\n\n  /** @deprecated Just import setupValidator from \\@mod-publisher/js/forms */\n  static setupValidator(node: HTMLElement, checker: (node: HTMLElement) => Promise<string> | string) {\n    setupValidator(node, checker);\n  }\n\n  /** @deprecated Just import setFieldError from \\@mod-publisher/js/forms */\n  static setFieldError(field: HTMLElement, error: string, options?: Partial<FieldErrorOptions>) {\n    setFieldError(field, error, options);\n  }\n\n  setFieldError(field: HTMLElement, error: string, options?: Partial<FieldErrorOptions>) {\n    setFieldError(field, error, options);\n  }\n\n  async validateSingleFormField(field: HTMLElement): Promise<boolean> {\n    return true;\n  }\n\n  async _validateSingleFieldOurselves(field: HTMLElement): Promise<boolean> {\n    const state = getValidationState(field);\n\n    if (!state.explicit && isFieldNativeErrored(field)) {\n      //browser checks go first, any additional checks are always additive (just disable browserchecks you don't want to apply)\n      updateFieldError(field);\n      return this._reportFieldValidity(field);\n    }\n\n    //TODO we probably *shouldn't* be bothering running our validations if state.explicit is set, but then setFieldError needs to rerun the checks once the explicit error is dropped\n    state.dynamicError = null;\n    await this.validateSingleFormField(field);\n\n    if (!state.dynamicError)\n      for (const validator of state.validators) {\n        state.dynamicError = await validator(field) || null;\n        if (state.dynamicError)\n          break; //one is enough\n      }\n\n    if (!state.dynamicError && field.whFormsApiChecker)\n      await field.whFormsApiChecker();\n\n    return this._reportFieldValidity(field);\n  }\n\n  /** validate the form\n      @param limitset - A single element, nodelist or array of elements to validate (or their children)\n      @returns a promise that will fulfill when the form is validated\n       */\n  async validate(limitset?: LimitSet, options?: ValidationOptions): Promise<FormValidationResult> {\n    if (debugFlags.fdv) {\n      console.warn(`[fdv] Validation of form was skipped`);\n      return { valid: true, failed: [], firstfailed: null };\n    }\n\n    //Overlapping validations are dangerous, because we can't evaluate 'hasEverFailed' too early... if an earlier validation is still running it may still decide to mark fields as failed.\n    const defer = Promise.withResolvers<FormValidationResult>();\n    this.validationqueue.push({ defer, limitset, options });\n    if (this.validationqueue.length === 1)\n      this._executeNextValidation(); //we're first on the queue so process it\n\n    return defer.promise;\n  }\n\n  async _executeNextValidation() {\n    while (this.validationqueue.length) {\n      const item = this.validationqueue[0];\n      try {\n        const result = await this._executeQueuedValidation(item.limitset, item.options);\n        item.defer.resolve(result);\n      } catch (error) {\n        item.defer.reject(error as Error);\n      }\n      this.validationqueue.shift(); //remove the top item\n    }\n  }\n\n  async _executeQueuedValidation(limitset?: LimitSet, options?: ValidationOptions): Promise<FormValidationResult> {\n    const original = limitset;\n    if (!limitset)  //validate entire form if unspecified what to validate\n      limitset = this._getFieldsToValidate();\n\n    const tovalidate = new Set<HTMLElement>;\n    for (const node of Array.isArray(limitset) ? limitset : [limitset]) {\n      /* If you're explicitly validating a radio/checkbox, we need to validate its group (but not recurse down) as that's where radiogroup.es and checkboxgroup.es attach their validations\n         If you're targeting a group, we'll end up validating both the radio/checkbox (directly attached here) and any eg. embedded textedits  */\n      if (node.matches(`input[type=radio],input[type=checkbox]`)) {\n        const group = node.closest<HTMLElement>(\".wh-form__fieldgroup\");\n        if (group)\n          tovalidate.add(group);\n        continue;\n      }\n\n      if (this._shouldValidateField(node))\n        tovalidate.add(node);\n      for (const subnode of this._getFieldsToValidate(node)) //TODO this is overly recursive esp. if limitset is empty...\n        tovalidate.add(subnode);\n    }\n\n    /* This was:\n    tovalidate = Array.from(tovalidate); //we need an array now for further processing\n       but that breaks on some old mootools integrations, see https://gitlab.webhare.com/webharebv/codekloppers/-/issues/677#note_146801\n       wokaround: */\n    let tovalidatelist = [...tovalidate]; //we need an array now for further processing\n\n    if (options && options.iffailedbefore)\n      tovalidatelist = tovalidatelist.filter(node => hasEverFailed(node));\n\n    if (debugFlags.fhv)\n      console.log(\"[fhv] Validation of %o expanded to %d elements: %o\", original, tovalidatelist.length, [...tovalidatelist]);\n\n    const lock = dompack.flagUIBusy();\n    try {\n      if (!tovalidatelist.length)\n        return { valid: true, failed: [], firstfailed: null };\n\n      const validationresults = await Promise.all(tovalidatelist.map(fld => this._validateSingleFieldOurselves(fld)));\n      //remove the elements from validate for which the promise failed\n      const failed = tovalidatelist.filter((fld, idx) => !validationresults[idx]);\n      const result: FormValidationResult = {\n        valid: failed.length === 0,\n        failed: failed,\n        firstfailed: null\n      };\n\n      result.firstfailed = result.failed.length ? result.failed[0] : null;\n      if (result.firstfailed && (!options || options.focusfailed)) {\n        //FIXME shouldn't getFocusableComponents also return startnode if focusable?\n        const tofocus = domfocus.canFocusTo(result.firstfailed) ? result.firstfailed : domfocus.getFocusableComponents(result.firstfailed)[0];\n        if (tofocus)\n          dompack.focus(tofocus, { preventScroll: true });\n\n        this.scrollIntoView(result.firstfailed);\n      }\n\n      if (debugFlags.fhv)\n        console.log(`[fhv] Validation of ${tovalidatelist.length} fields done, ${result.failed.length} failed`, result);\n\n      return result;\n    } finally {\n      lock.release();\n    }\n  }\n\n  reset() {\n    this.node.reset();\n    this.gotoPage(0);\n  }\n}\n","export function getActiveElement(doc: Document | null): HTMLElement | null {\n  return doc?.activeElement as HTMLElement || null;\n}\n\nexport function getToplevelWindow() {\n  let toplevelwindow: Window = window;\n  while (toplevelwindow.frameElement)\n    toplevelwindow = toplevelwindow.parent;\n  return toplevelwindow;\n}\n\nexport function asIframe(node: Element | null): HTMLIFrameElement | null {\n  return node && (node as HTMLElement)?.matches?.('iframe') ? node as HTMLIFrameElement : null;\n}\n\n/**\n     Find the currently focused element\n *\n    @param limitdoc - If set, only return compontents in the specified document (prevents editable iframes from returning subframes)\n    @returns The element or null\n */\nexport function getCurrentlyFocusedElement(limitdoc?: Document): HTMLElement | null {\n  try {\n    let focused = getActiveElement(getToplevelWindow().document);\n    for (; ;) {\n      const frame = asIframe(focused);\n      if (frame && (!limitdoc || frame.ownerDocument !== limitdoc))\n        focused = getActiveElement(frame.contentDocument);\n      else\n        break;\n    }\n    if (focused && limitdoc && focused.ownerDocument !== limitdoc)\n      return null;\n    return focused;\n  } catch (e) {\n    return null;\n  }\n}\n\n/** Return whether the node is reachable for focus by keyboard navigation\n   (because tabIndex === -1 will be seen a non(keyboard)focusable by this function)\n\n    @param node - Node to test\n    @param ignoreInert - Ignore the inert attribute\n*/\nexport function canFocusTo(node: Element, { ignoreInertAttribute = false } = {}): node is HTMLElement { //returns if a -visible- node is focusable (this function does not check for visibility itself)\n  if (!node.closest) //callers are not necessarily calling us with HTMLElement, eg getClosestValidFocusTarget might supply a document\n    return false;\n  if (!ignoreInertAttribute && node.closest('[inert]'))\n    return false;\n\n  if ((node as HTMLElement).contentEditable === \"true\")\n    return true;\n  if (node.shadowRoot?.delegatesFocus)\n    return true;\n\n  return (node as HTMLElement).tabIndex >= 0 && !(node as HTMLInputElement).disabled && !(node.tagName === 'A' && !(node as HTMLAnchorElement).href);\n}\n\nexport function getFocusableComponents(startnode: Element | null, options?: boolean | { recurseFrames?: boolean; ignoreInertAttribute?: boolean }): HTMLElement[] {\n  if (typeof options !== \"object\") {\n    options = { recurseFrames: options };\n  }\n  let focusable: HTMLElement[] = [];\n  if (!startnode)\n    return focusable;\n  for (const currentnode of startnode.children) {\n    // Get current style (avoid mootools due to cross-frame issues)\n    const currentstyle = getComputedStyle(currentnode);\n    if (!currentstyle || currentstyle.display === \"none\" || currentstyle.visibility === \"hidden\") {\n      //if(currentnode.getStyle) console.log(\"getFocusableComponents skipping\",currentnode, $(currentnode).getStyle(\"display\"), currentnode.getStyle(\"visibility\"))\n      continue;\n    }\n\n    let iframe;\n    if (options?.recurseFrames && (iframe = asIframe(currentnode))) { //might contain more things to focus\n      try {\n        const subnodes = getFocusableComponents(iframe.contentDocument!.documentElement, options);\n        if (subnodes.length)\n          focusable = focusable.concat(subnodes);\n      } catch {\n        //assume permission error\n      }\n    } else if (canFocusTo(currentnode, options)) {\n      focusable.push(currentnode);\n    }\n\n    if ((currentnode as HTMLElement).isContentEditable)\n      continue; //don't look for further focusable nodes inside, the whole RTE counts as an editable component\n\n    const subnodes = getFocusableComponents(currentnode, options);\n    if (subnodes.length)\n      focusable = focusable.concat(subnodes);\n  }\n  return focusable;\n}\n\nexport function getAllFocusableComponents() {\n  return getFocusableComponents(getToplevelWindow().document.documentElement, true);\n}\n","export const rfSymbol = Symbol('RegisteredField');\n\ndeclare global {\n  interface HTMLElement {\n    [rfSymbol]?: FormFieldAPI;\n  }\n}\n\nexport interface FormFieldAPI {\n  getValue(): unknown;\n  setValue(newvalue: unknown): void;\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport { getTid } from \"@webhare/gettid\";\nimport \"./arrayfield.css\";\nimport { throwError } from \"@webhare/std\";\nimport { addDocEventListener, qS, qSA, type DocEvent, registerMissed, stop } from \"@webhare/dompack\";\nimport { getFieldName, getFormElementCandidates, getFormHandler, parseCondition, setFieldName } from \"@webhare/forms/src/domsupport\";\nimport type { FormCondition } from \"@webhare/forms/src/types\";\nimport { RecordFieldHandler, type FormParent } from \"@webhare/forms/src/fieldmap\";\nimport type FormBase from \"../formbase\";\nimport { setup } from \"../internal/webharefields\";\n\n\nfunction fixupConditionRecursive(node: HTMLElement, condition: FormCondition, mapping: Map<string, string>): boolean {\n  switch (condition.matchtype) {\n    case \"AND\":\n    case \"OR\":\n      {\n        let anychanges = false;\n        for (const subcondition of condition.conditions)\n          anychanges = fixupConditionRecursive(node, subcondition, mapping) || anychanges;\n        return anychanges;\n      }\n    case \"NOT\":\n      {\n        return fixupConditionRecursive(node, condition.condition, mapping);\n      }\n    default:\n      {\n        const newName = mapping.get(condition.field);\n        if (newName && node.querySelector(`[name=\"${newName}\"]`)) {\n          condition.field = newName;\n          return true;\n        }\n      }\n  }\n  return false;\n}\n\ntype NewType = FormParent;\n\nexport default class ArrayField {\n  valueNode: HTMLInputElement;\n  nextrowid = 0;\n  template;\n  insertPoint: HTMLElement;\n  arrayBaseName;\n  handler: NewType;\n  node: HTMLElement;\n  name: string;\n\n  constructor(handler: NewType, node: HTMLElement, items: HTMLElement[], name: string) {\n    this.handler = handler;\n    this.node = node;\n    this.name = name;\n    this.arrayBaseName = node.dataset.whFormGroupFor || throwError(\"Missing array base name\");\n\n    // The template for new rows. If we have arrays-in-array, it will still be the first <template>\n    this.template = qS<HTMLTemplateElement>(node, \"template\") || throwError(\"Missing array template\");\n    // The node before which to add new rows\n    this.insertPoint = this.template.parentNode!.lastElementChild! as HTMLElement;\n    if (!this.insertPoint.matches(\".wh-form__arrayadd\"))\n      throw new Error(\"Missing array insert point\");\n\n    // Event handler for add/delete button clicks\n    this.insertPoint.addEventListener(\"click\", event => this.onAddRow(event));\n    addDocEventListener(node, \"click\", event => this._onClick(event));\n\n    // Proxy node for getting/setting properties and receiving events\n    this.valueNode = qS<HTMLInputElement>(node, \"input.wh-form__arrayinput\") ?? throwError(\"Missing array input\");\n    this.valueNode.whUseFormGetValue = true;\n    this.valueNode.addEventListener(\"wh:form-getvalue\", event => this._onGetValue(event));\n    //@ts-expect-error wh:form-setvalue isn't defined - but it'll go away anyway\n    this.valueNode.addEventListener(\"wh:form-setvalue\", event => this._onSetValue(event));\n\n    // Initialize initial value rows\n    for (const rownode of qSA(this.node, \".wh-form__arrayrow\"))\n      this._fixupRowNode(rownode);\n\n    this._checkValidity();\n  }\n\n  get form(): FormBase {\n    const form = getFormHandler(this.node.closest(\"form\") ?? throwError(\"Could not find <form>\")) ?? throwError(\"Could not find form for arrayfield\");\n    if (!form._getFieldsToValidate) //avoid calling into formbase from our constructor, it may not be there yet...\n      throw new Error(\"The <form> is not ready yet\");\n    return form;\n  }\n\n  addRow(): HTMLElement {\n    // Instatiate a new row\n    const newrow = this.template.content.cloneNode(true) as HTMLElement;\n    (newrow.firstElementChild! as HTMLElement).dataset.whFormRowid = String(this.nextrowid++);\n\n    // Insert the new row\n    this.insertPoint.parentNode!.insertBefore(newrow, this.insertPoint);\n    const addedrow = this.insertPoint.previousElementSibling! as HTMLElement;\n\n    /* If the form is relying on legacy dompack.register to go through ImgEditField and do the actual\n       customElements.define call.... then the 'name' attributes won't actually work on the 'new' elements.\n       therefore dompack.registerMissed must run before _fixupRowNode */\n    registerMissed(addedrow);\n    setup(addedrow);\n\n    this._fixupRowNode(addedrow as HTMLElement);\n    this._checkValidity();\n    this.form.__scheduleUpdateConditions();\n    return this.insertPoint.previousSibling as HTMLElement;\n  }\n\n  /* seems a unused API ?.  .. if we need to provide this, just let people pass us a row node instead of understanding IDs\n    removeRow(id)\n    {\n      // Remove a row by id\n      let node = this.node.querySelector(`.wh-form__arrayrow[data-row-id=${id}]`);\n      if (node)\n        this._removeRowNode(node);\n    }\n  */\n\n  private onAddRow(event: Event) {\n    stop(event);\n    this.addRow();\n  }\n  _onClick(event: DocEvent<MouseEvent>) {\n    // Check if a delete button was clicked\n    const delNode = event.target.closest(\".wh-form__arraydelete\");\n    if (delNode) {\n      event.preventDefault();\n      this._removeRowNode(delNode.closest(\".wh-form__arrayrow\")!);\n    }\n  }\n\n  getRowHandler(row: HTMLElement): RecordFieldHandler {\n    const rowBaseName = this.valueNode.name + \".\" + row.dataset.whFormRowid;\n    const rowFields = getFormElementCandidates(row, rowBaseName).filter(_ => _.dataset.whFormCellname !== \"row_uid\"); //row_uid points back to us, so requesting that triggers a loop\n    return new RecordFieldHandler(this.handler, rowBaseName, rowFields);\n  }\n\n  getValue() {\n    const rows = [];\n    for (const row of qSA(this.node, \".wh-form__arrayrow\").filter(n => n.parentNode === this.template.parentNode)) {\n      const handler = this.getRowHandler(row);\n      const rowval = handler.getValue();\n      rows.push(rowval);\n    }\n    return rows;\n  }\n\n  _onGetValue(event: CustomEvent<{ deferred: PromiseWithResolvers<unknown> }>) {\n    // We're using the deferred promise to return our value\n    event.preventDefault();\n    event.stopPropagation();\n\n    // Create a promise for each row that resolves with the combined value of all fields in the row\n    const valuePromises = [];\n    for (const row of qSA(this.node, \".wh-form__arrayrow\").filter(n => n.parentNode === this.template.parentNode)) {\n      const rowFields = this._queryAllFields(row);\n      // Create a promise for each of the row's subfields to get its value\n      const rowPromises = rowFields.map(field => (this.form as FormBase)._getQueryiedFieldValue(field)); //FIXME get rid of 'as FormBase' to support array-in-array\n      // Add an all promise for the value promises and add it to the list of row promises\n      valuePromises.push(Promise.all(rowPromises).then(values => {\n        // Combine the values into a value object for this row\n        const rowValue: Record<string, unknown> = { formrowid: row.dataset.whFormRowid };\n        values.forEach((value, idx) => {\n          // The values are returned in the order that the promises were added to the list of value promises, so we can use\n          // the index of the value to get the original field\n          const rowField = rowFields[idx];\n          const firstnode = rowField.multi ? rowField.nodes[0] : rowField.node;\n          rowValue[firstnode.dataset.whFormCellname!] = value;\n        });\n        return rowValue;\n      }));\n    }\n    // Wait for all the row promises (which resolves with a list of promise resolution values, which will be the final value\n    // of the array field)\n    Promise.all(valuePromises).then(valueRows => event.detail.deferred.resolve(valueRows));\n  }\n\n  setValue(newvalue: unknown[]) {\n    if (!Array.isArray(newvalue))\n      throw new Error(`Invalid value for array field '${this.name}': ${JSON.stringify(newvalue)}`);\n\n    // Remove all current rows (TODO optimize)\n    while (this.insertPoint.previousElementSibling?.classList.contains(\"wh-form__arrayrow\"))\n      this._removeRowNode(this.insertPoint.previousElementSibling);\n\n    // Check if we have an array value\n    for (const value of newvalue) {\n      // Add a row\n      const row = this.addRow();\n      const handler = this.getRowHandler(row);\n      handler.setValue(value);\n    }\n    this._checkValidity();\n  }\n\n  _onSetValue(event: CustomEvent<{ value: unknown }>) {\n    event.preventDefault();\n    event.stopPropagation();\n\n    // Remove all current rows\n    while (this.insertPoint.previousElementSibling?.classList.contains(\"wh-form__arrayrow\"))\n      this._removeRowNode(this.insertPoint.previousElementSibling);\n\n    // Check if we have an array value\n    if (Array.isArray(event.detail.value)) {\n      for (const value of event.detail.value) {\n        // Add a row\n        const row = this.addRow();\n        // Initialize the row's fields\n        for (const field of this._queryAllFields(row)) {\n          for (const fieldnode of (field.multi ? field.nodes : [field.node])) {\n            if (fieldnode.dataset.whFormCellname && fieldnode.dataset.whFormCellname in value) {\n              (this.form as FormBase).setFieldValue(fieldnode, value[fieldnode.dataset.whFormCellname]); //FIXME get rid of 'as FormBase' to support array-in-array\n            }\n          }\n        }\n      }\n    }\n    this._checkValidity();\n  }\n\n  _fixupRowNode(node: HTMLElement) {\n    const rowid = node.dataset.whFormRowid;\n\n    // Rename all fields to avoid duplicate field names\n    const mapping = new Map<string, string>;\n    for (const fieldnode of getFormElementCandidates(node, this.arrayBaseName)) {\n\n      // Leave embedded arrayfields alone! Except if this is specifically the wh-form__arrayinput one level down\n      const nodeArray = fieldnode.closest(\".wh-form__fieldgroup--array\");\n      if (nodeArray && nodeArray !== this.node && !(fieldnode.matches(\".wh-form__arrayinput\") && (nodeArray.parentNode! as HTMLElement).closest(\".wh-form__fieldgroup--array\") === this.node)) {\n        // console.log(\"Skipping\", fieldnode, \"as it's not in our array\");\n        continue;\n      }\n\n      // Rename fields\n      const fieldname = getFieldName(fieldnode);\n      // When rendering, the fields simply have their arrayname prefixed in their name=, see InstantiateField in array.whlib (TODO seems dangerous, eg preset radio buttons interfering with each other?\n      // So we'll just take the part after the first dot as the cellname\n      fieldnode.dataset.whFormCellname ||= fieldname.substring(this.arrayBaseName.length + 1);\n\n      const cellname: string = fieldnode.dataset.whFormCellname;\n      const subname = this.valueNode.name + \".\" + rowid + \".\" + cellname;\n      // console.log(\"for\", this.name, \"rename\", fieldname, \"to\", subname, fieldnode);\n      setFieldName(fieldnode, subname);\n      mapping.set(fieldname, subname);\n\n      // Rename id's to make them unique; update the labels within the field's fieldgroup to point to the new id\n      if (fieldnode.id) {\n        const labelnodes = qSA<HTMLLabelElement>(node, `label[for=\"${fieldnode.id}\"]`);\n        fieldnode.id += \"-\" + rowid;\n        for (const labelnode of labelnodes)\n          labelnode.htmlFor = fieldnode.id;\n      }\n\n      // Rewrite conditions after all fields have been renamed\n      for (const type of [\"visible\", \"enabled\", \"required\"]) {\n        for (const conditionnode of qSA(node, `[data-wh-form-${type}-if]`)) {\n          const condition = parseCondition(conditionnode.dataset[`whForm${type[0].toUpperCase() + type.slice(1)}If`]!);\n          if (fixupConditionRecursive(node, condition, mapping))\n            conditionnode.dataset[`whForm${type[0].toUpperCase() + type.slice(1)}If`] = JSON.stringify({ c: condition });\n        }\n      }\n    }\n\n    this.getRowHandler(node); //initializes deeper arrays. fieldmap should probably be handling this and build a full mapping top to botom...\n  }\n\n  _removeRowNode(node: Element) {\n    // Remove the row node\n    node.remove();\n    this._checkValidity();\n  }\n\n  _checkValidity() {\n    const minRows = parseInt(this.valueNode.dataset.whMin || \"0\");\n    const maxRows = parseInt(this.valueNode.dataset.whMax || \"0\");\n\n    const numRows = this.node.querySelectorAll(\".wh-form__arrayrow\").length;\n    if (numRows < minRows)\n      this.valueNode.setCustomValidity(getTid(\"publisher:site.forms.commonerrors.minarray\", minRows));\n    else if (maxRows > 0 && numRows > maxRows)\n      this.valueNode.setCustomValidity(getTid(\"publisher:site.forms.commonerrors.maxarray\", maxRows));\n    else\n      this.valueNode.setCustomValidity(\"\");\n\n    // Disable the add button if the maximum number of rows is reached\n    if (maxRows > 0 && numRows >= maxRows)\n      this.node.classList.add(\"wh-form__array--maxrows\");\n    else\n      this.node.classList.remove(\"wh-form__array--maxrows\");\n  }\n\n  _queryAllFields(node: HTMLElement) {\n    return (this.form as FormBase)._queryAllFields({ startnode: node, skipfield: this.valueNode });  //FIXME get rid of 'as FormBase' to support array-in-array\n  }\n}\n","import { getFieldName } from \"./domsupport\";\nimport { rfSymbol, type FormFieldAPI } from \"./registeredfield\";\nimport ArrayField from \"@mod-publisher/js/forms/fields/arrayfield\";\nimport type { AddressValue } from \"@webhare/address\";\nimport { omit, nameToSnakeCase, nameToCamelCase, throwError, isDate } from \"@webhare/std\";\nimport type { RecursivePartial } from \"@webhare/js-api-tools\";\nimport type { FormFieldLike } from \"./jsformelement\";\n\nexport interface FormParent {\n  __scheduleUpdateConditions(): void;\n}\n\n\ninterface FormField {\n  getValue(): unknown;\n\n  /** Set a value\n   * @param newvalue - The new value to set\n   * @param ignoreInvalid - Do not throw if the value is invalid. Used for eg. prefills which can't usefully handle it anyway\n   * @returns True if succesfully set */\n\n  setValue(newvalue: unknown): void;\n}\n\ntype ValueType = \"number\" | \"boolean\" | \"date\";\n\nfunction unmapFieldName(camelCaseName: string) {\n  return camelCaseName.startsWith(\"__formfield\") ? camelCaseName : nameToSnakeCase(camelCaseName);\n\n}\nfunction mapFieldName(htmlName: string) {\n  return htmlName.startsWith(\"__formfield\") ? htmlName : nameToCamelCase(htmlName);\n}\n\nfunction mapValue(type: ValueType, invalue: string) {\n  switch (type) {\n    case \"number\":\n      return parseFloat(invalue);\n    case \"boolean\":\n      return invalue === \"true\";\n    case \"date\":\n      return new Date(invalue);\n  }\n}\n\nfunction unmapValue(type: ValueType | undefined, invalue: unknown, fieldDescr: string) {\n  switch (type) {\n    case null:\n      if (typeof invalue !== \"string\")\n        throw new Error(`Invalid type ${typeof invalue} for string field ${fieldDescr}: ${invalue}`);\n      return invalue;\n\n    case \"number\":\n      if (typeof invalue !== \"number\")\n        throw new Error(`Invalid type ${typeof invalue} for number field ${fieldDescr}: ${invalue}`);\n      return String(invalue);\n\n    case \"boolean\":\n      if (typeof invalue !== \"boolean\")\n        throw new Error(`Invalid type ${typeof invalue} for boolean field ${fieldDescr}: ${invalue}`);\n      return String(invalue);\n\n    case \"date\":\n      if (!isDate(invalue))\n        throw new Error(`Invalid type ${typeof invalue} for date field ${fieldDescr}: ${invalue}`);\n      return invalue.toISOString();\n  }\n}\n\nclass HTMLFormFieldHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly field: FormFieldLike;\n\n  constructor(form: FormParent, field: FormFieldLike) {\n    this.form = form;\n    this.field = field;\n    this.valuetype = field.dataset.whFormValueType as undefined | ValueType;\n    if (!this.valuetype && field.matches('input[type=number]'))\n      this.valuetype = \"number\";\n  }\n\n  getValue(): unknown {\n    if (this.field.matches('input[type=checkbox]'))\n      return (this.field as HTMLInputElement).checked;\n    if (this.field.matches('input[type=date]'))\n      return (this.field as HTMLInputElement).valueAsDate;\n\n    if (this.field.tagName === \"SELECT\") {\n      const selectedrow = (this.field as HTMLSelectElement).selectedOptions[0];\n      if (!selectedrow || selectedrow.dataset.placeholder !== undefined)\n        return null; //didn't select a 'real' option\n\n      return this.valuetype ? mapValue(this.valuetype, selectedrow.value) : selectedrow.value;\n    }\n\n    return this.valuetype ? mapValue(this.valuetype, this.field.value as string) : this.field.value;\n  }\n\n  setValue(newvalue: unknown): void {\n    if (this.field.matches('input[type=checkbox]')) {\n      //For convenience we're interpreting setting a checkbox as 'truthy' instead of explicit true/false\n      const setvalue = Boolean(newvalue);\n      if (setvalue === (this.field as HTMLInputElement).checked)\n        return;\n\n      (this.field as HTMLInputElement).checked = setvalue;\n    } else if (this.field.matches('input[type=date]')) {\n      if ((this.field as HTMLInputElement)?.valueAsDate?.getTime() === (newvalue as Date | null)?.getTime())\n        return;\n      (this.field as HTMLInputElement).valueAsDate = newvalue as Date;\n    } else if (this.field.tagName === \"SELECT\" && newvalue === null) { //'null' resets the select to 'no value', so figure out if there's a placeholder row\n      const setvalue = (this.field as HTMLSelectElement).options[0]?.dataset.placeholder !== undefined ? 0 : -1;\n      if ((this.field as HTMLSelectElement).selectedIndex === setvalue)\n        return;\n      (this.field as HTMLSelectElement).selectedIndex = setvalue;\n    } else {\n      const setvalue = this.valuetype ? unmapValue(this.valuetype, newvalue, this.field.name) : newvalue;\n      if (this.field.value === setvalue)\n        return;\n      this.field.value = setvalue;\n    }\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\nclass RadioFormFieldHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly name: string;\n  private readonly rnodes: HTMLInputElement[];\n\n  constructor(form: FormParent, name: string, rnodes: HTMLInputElement[]) {\n    this.form = form;\n    this.name = name;\n    this.rnodes = rnodes;\n    const group = rnodes[0].closest<HTMLElement>(\".wh-form__fieldgroup\");\n    if (!group) { //value metadata is stored at the fieldgroup level, so reject these\n      console.error(\"Missing group for radiofield \", group);\n      console.error('if a radio field does not want to participate in the form, it should set attribute form=\"\"');\n    } else {\n      this.valuetype = group.dataset.whFormValueType as undefined | ValueType;\n    }\n  }\n  getValue(): unknown {\n    const node = this.rnodes.find(_ => _.checked);\n    return (node ? this.valuetype ? mapValue(this.valuetype, node.value) : node.value : null);\n  }\n  setValue(newvalue: unknown): void {\n    if (newvalue === null) {\n      for (const node of this.rnodes)\n        node.checked = false;\n\n      this.form.__scheduleUpdateConditions();\n      return;\n    }\n\n    const myname = `radio group ${this.name}`;\n    const setvalue = unmapValue(this.valuetype, newvalue, myname);\n\n    const node = this.rnodes.find(_ => _.value === setvalue);\n    if (!node)\n      throw new Error(`No such value '${setvalue}' in radio group '${this.name}`);\n\n    node.checked = true;\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\nclass CheckboxGroupHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly name: string;\n  private readonly cboxes: HTMLInputElement[];\n\n  constructor(form: FormParent, name: string, cboxes: HTMLInputElement[]) {\n    this.form = form;\n    this.name = name;\n    this.cboxes = cboxes;\n    this.valuetype = (cboxes[0].closest<HTMLElement>(\".wh-form__fieldgroup\") ?? throwError(\"RadioFormFieldHandler: Missing group\")).dataset.whFormValueType as undefined | ValueType;\n  }\n  getValue(): unknown {\n    return this.cboxes.filter(_ => _.checked).map(_ => this.valuetype ? mapValue(this.valuetype, _.value) : _.value);\n  }\n  setValue(newvalue: unknown): void {\n    const myname = `checkbox group '${this.name}'`;\n    if (!Array.isArray(newvalue))\n      throw new Error(`Value for ${myname} should be an array, got '${JSON.stringify(newvalue)}'`);\n\n    const toset = newvalue.map(_ => unmapValue(this.valuetype, _, myname));\n\n    this.cboxes.forEach(_ => _.checked = toset.includes(_.value));\n    this.form.__scheduleUpdateConditions();\n\n    //in case the error is caught and ignored (eg prefill), we'll update what we can\n    const missing = toset.filter(_ => !this.cboxes.some(cbox => cbox.value === _));\n    if (missing.length)\n      throw new Error(`Invalid value(s) for ${myname}: ${missing.join(', ')}`);\n  }\n}\n\nclass RegisteredFieldHandler implements FormField {\n  protected form: FormParent;\n  private readonly field: FormFieldAPI;\n\n  constructor(form: FormParent, field: FormFieldAPI) {\n    this.form = form;\n    this.field = field;\n  }\n\n  getValue(): unknown {\n    return this.field.getValue();\n  }\n  setValue(newvalue: unknown): void {\n    this.field.setValue(newvalue);\n  }\n}\n\nexport class ArrayFieldHandler extends RegisteredFieldHandler implements FormField {\n  private node: HTMLElement;\n\n  constructor(form: FormParent, node: HTMLElement, items: HTMLElement[]) {\n    node[rfSymbol] ||= new ArrayField(form, node, items, getFieldName(items[0]));\n    super(form, node[rfSymbol]);\n    this.node = node;\n  }\n\n  __scheduleUpdateConditions() {\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\n/** The FormFieldMap exposes a multi-level (ie unflattened) view of the form values. Internally it works with the\n   original names because generated fields names, eg __formfieldbbbwVsWih_0DrJOc0beS7Q_, cannot be assumed to be snake_case and convertable */\nexport abstract class FormFieldMap<DataShape> {\n  /** Field mapping. Uses original names */\n  protected fieldmap = new Map<string, FormField>();\n  protected fieldName: string;\n\n  constructor(fieldName: string, nodes: HTMLElement[]) {\n    this.fieldName = fieldName;\n    const subpos = fieldName ? fieldName.length + 1 : 0;\n    const groups = Map.groupBy(nodes, _ => getFieldName(_).substring(subpos).split('.')[0]);\n\n    for (const [name, items] of groups) {\n      const fullName = (fieldName ? fieldName + '.' : '') + name;\n      if (!name) {\n        console.error(`There are fields without a name:`, items);\n        continue;\n      }\n\n      if (items[0].matches('input[type=radio]')) {\n        this.fieldmap.set(name, new RadioFormFieldHandler(this, fullName, items as HTMLInputElement[]));\n        continue;\n      }\n\n      if (items[0].matches('.wh-form__arrayinput')) {\n        const arraygroup = items[0].closest<HTMLElement>('.wh-form__fieldgroup--array');\n        if (arraygroup) {\n          this.fieldmap.set(name, new ArrayFieldHandler(this, arraygroup, items));\n          continue;\n        }\n      }\n\n      const hasGroupLeader = getFieldName(items[0]) === fullName; //ie name has no followup '.xx'\n      if (hasGroupLeader) { //if no subname, it's the group leader ?\n        if (items[0].matches('input[type=checkbox]')) {//is it a checkbox group?\n          const cboxgroup = items[0].closest(\".wh-form__fieldgroup--checkboxgroup\");\n          if (cboxgroup) {\n            this.fieldmap.set(name, new CheckboxGroupHandler(this, fullName, items as HTMLInputElement[]));\n            continue;\n          }\n        }\n\n        this.fieldmap.set(name, new HTMLFormFieldHandler(this, items[0] as FormFieldLike));\n        continue;\n      }\n\n      //We're an implicit record (even if with just one member)\n      if (items[0].matches('select[name$=\".country\"][data-orderingdata]')) //looks like address.whlib\n        this.fieldmap.set(name, new AddressFieldHandler(this, fullName, items));\n      else\n        this.fieldmap.set(name, new RecordFieldHandler(this, fullName, items));\n    }\n  }\n\n  abstract __scheduleUpdateConditions(): void;\n\n  /** Get a field handler by name */\n  getField(name: string, options: { allowMissing: true }): FormField | null;\n  getField(name: string, options?: { allowMissing?: boolean }): FormField;\n\n  getField(name: string, options?: { allowMissing?: boolean }): FormField | null {\n    const mapName = unmapFieldName(name);\n    const match = this.fieldmap.get(mapName);\n    if (match)\n      return match;\n    if (options?.allowMissing)\n      return null;\n\n    throw new Error(`Field '${name}' not found in this form`); //TODO report the fukll anme\n  }\n\n  getFieldNames(): string[] {\n    return [...this.fieldmap.keys()].map(mapFieldName);\n  }\n\n  /** Set a value for multiple fields\n   * @param data - The data to set\n   * @param ignoreUnknownFields - Do not throw if a field is not found in the form. This is the default\n   */\n  assign(data: RecursivePartial<DataShape>, { ignoreUnknownFields = true } = {}) {\n    for (const [key, value] of Object.entries(data as object)) {\n      const field = this.getField(key, { allowMissing: ignoreUnknownFields });\n      if (field)\n        field.setValue(value);\n    }\n  }\n}\n\nexport class RecordFieldHandler extends FormFieldMap<object> implements FormField {\n  private form: FormParent;\n\n  constructor(form: FormParent, baseName: string, nodes: HTMLElement[]) {\n    super(baseName, nodes);\n    this.form = form;\n  }\n\n  getValue(): unknown {\n    const retval: Record<string, unknown> = {};\n    for (const [name, field] of this.fieldmap) {\n      const val = field.getValue();\n      if (val !== undefined) //Suppress undefined values (where we cannot safely re-set them, eg images in Object.keys\n        retval[mapFieldName(name)] = val;\n    }\n\n    return retval;\n  }\n\n  setValue(newvalue: unknown): void {\n    if (typeof newvalue !== 'object' || newvalue === null)\n      throw new Error(`Invalid value for record field '${this.fieldName}': ${newvalue}`);\n\n    for (const [name, field] of this.fieldmap) {\n      const prettyName = mapFieldName(name);\n      if (prettyName in newvalue)\n        field.setValue((newvalue as Record<string, unknown>)[prettyName]);\n    }\n  }\n\n  __scheduleUpdateConditions() {\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\n/* TODO cleanup... this is a workaround to translate nr_detail to houseNumber. ideally the server would just send house_number as field\n        name but that transition will take time. also we need a nice way to 'take over' addressifelds rather than fieldmapper special casing\n        its detection\n*/\ntype OldAddressValue = Omit<AddressValue, \"houseNumber\"> & { nrDetail?: string };\n\nclass AddressFieldHandler extends RecordFieldHandler {\n  constructor(form: FormParent, baseName: string, nodes: HTMLElement[]) {\n    super(form, baseName, nodes);\n  }\n\n  getValue(): unknown {\n    const val = super.getValue() as OldAddressValue;\n    if (!val?.country)\n      return null;\n\n    return val?.nrDetail !== undefined ? { ...omit(val, [\"nrDetail\"]), houseNumber: val.nrDetail } : val;\n  }\n\n  setValue(val: unknown) {\n    if (val === null) {\n      super.setValue({ country: null, city: \"\", street: \"\", zip: \"\", nrDetail: \"\", state: \"\" });\n      return;\n    }\n\n    ///@ts-expect-error ugly hack, not really worth overwriting with as\n    super.setValue(val?.houseNumber !== undefined ? { ...omit(val, [\"houseNumber\"]), nrDetail: val.houseNumber } : val);\n  }\n}\n\nexport class FieldMapDataProxy implements ProxyHandler<object> {\n  private readonly form: FormFieldMap<object>;\n\n  constructor(form: FormFieldMap<object>) {\n    this.form = form;\n  }\n  get(target: object, p: string | symbol) {\n    //Don't attempt to validate getters... it will break various introspection calls (eg requesting constructor, checking for 'then'...)\n    const field = typeof p === \"string\" ? this.form.getField(p, { allowMissing: true }) : null;\n    return field ? field.getValue() : (target as Record<string | symbol, unknown>)[p];\n  }\n  set(target: unknown, p: string, value: unknown): boolean {\n    this.form.getField(p).setValue(value);\n    return true;\n  }\n  ownKeys(target: object): ArrayLike<string | symbol> {\n    return this.form.getFieldNames();\n  }\n  getOwnPropertyDescriptor(target: unknown, prop: string) { // allows ownKeys to actually return to Object.keys\n    return { enumerable: true, configurable: true };\n  }\n}\n","import type { AddressValue } from \"@webhare/address\";\nimport { stringify, emplace, omit } from \"@webhare/std\";\nimport { getFormService, type HareScriptAddressValidationResult, type HareScriptAddressValue } from \"./formservice\";\n\nexport type { HareScriptAddressValue, HareScriptAddressValidationResult } from \"./formservice\";\n\nexport type AddressChecks = \"nl-zip-suggest\" | \"nl-zip-force\";\n\nexport type AddressValidationStatus = \"ok\" | \"unknown\" | \"error\";\n// not_supported\" | \"ok\" | \"not_enough_data\" | \"invalid_city\" | \"invalid_zip\" | \"invalid_nr_detail\" | \"zip_not_found\" | \"address_not_found\" | \"different_citystreet\" | \"incomplete\" | \"lookup_failed\";\n\nexport interface AddressValidationOptions {\n  checks?: AddressChecks[];\n  lang?: string;\n}\n\nexport interface AddressValidationResult {\n  status: AddressValidationStatus;\n  errors: Array<{\n    ///Fields affected by the error\n    fields: string[];\n    ///Error message in the requested language\n    message: string;\n  }>;\n  corrections: Partial<Record<keyof AddressValue, string>> | null;\n}\n\nlet lookupcache: Map<string, Promise<AddressValidationResult>> | undefined;\n\nexport async function verifyHareScriptAddress(address: HareScriptAddressValue, options: AddressValidationOptions = {}): Promise<HareScriptAddressValidationResult> {\n  if (!lookupcache)\n    lookupcache = new Map<string, Promise<AddressValidationResult>>;\n\n  const lookupkey = stringify({ address, options }, { stable: true });\n  const lookup = emplace(lookupcache, lookupkey, {\n    insert: () => getFormService().verifyAddress(location.pathname, address, options)\n  });\n  return await lookup;\n}\n\nexport async function verifyAddress(address: AddressValue, options: AddressValidationOptions = {}): Promise<AddressValidationResult> {\n  if (!lookupcache)\n    lookupcache = new Map<string, Promise<AddressValidationResult>>;\n\n  // convert houseNumber to nr_detail\n  const hsAddress = { ...omit(address, [\"houseNumber\"]), nr_detail: address.houseNumber };\n\n  const hsresult = await verifyHareScriptAddress(hsAddress, options);\n\n  // back-convert nr_detail to houseNumber\n  let corrections: AddressValidationResult[\"corrections\"] = null;\n  if (hsresult.corrections) {\n    corrections = {};\n    for (const [key, value] of Object.entries(hsresult.corrections) as Array<[keyof HareScriptAddressValue, string]>) {\n      corrections[key === \"nr_detail\" ? \"houseNumber\" as const : key] = value;\n    }\n  }\n  return {\n    status: hsresult.status,\n    errors: hsresult.errors.map(error => ({ fields: error.fields.map(f => f === \"houseNumber\" ? \"nr_detail\" : f), message: error.message })),\n    corrections,\n  };\n}\n","import { isValidDate, isValidTime } from '@webhare/std';\n\nexport function formatDate(dateformat: string, year: number, month: number, day: number): string {\n  if (!isValidDate(year, month, day, { minYear: 1 }))\n    return '';\n\n  let output = '';\n\n  for (const c of dateformat.split(\"\")) {\n    switch (c.toUpperCase()) {\n      case \"Y\":\n        output += ('000' + year).slice(-4);\n        break;\n      case \"M\":\n        output += ('0' + month).slice(-2);\n        break;\n      case \"D\":\n        output += ('0' + day).slice(-2);\n        break;\n      default:\n        output += c;\n        break;\n    }\n  }\n  return output;\n}\n\nexport function formatISODate(year: number, month: number, date: number) {\n  return formatDate(\"Y-M-D\", year, month, date);\n}\n\nexport function formatISOTime(hour: number, minute: number, second: number | null, msec: number | null) {\n  if (!isValidTime(hour, minute, second !== null ? second : 0, msec !== null ? msec : 0))\n    return '';\n\n  let time = ('0' + hour).slice(-2) + ':' + ('0' + minute).slice(-2);\n  if (second !== null)\n    time += ':' + ('0' + second).slice(-2);\n  if (msec !== null)\n    time += '.' + ('00' + msec).slice(-3);\n  return time;\n}\n\nexport interface DateParts {\n  day: number;\n  month: number;\n  year: number;\n}\n\nexport function parseDate(format: string, newdate: string, options?: { nofail: boolean }): DateParts | null {\n  if (!newdate) //empty\n    return null;\n\n  //replace . and / with -\n  const setdate = newdate.replace(/[./]/g, '-');\n  const parts = setdate.split('-');\n\n  if (parts.length === 3) { //parseable\n    format = format.toLowerCase();\n    const dayoffset = format.indexOf('d');\n    const monthoffset = format.indexOf('m');\n    const yearoffset = format.indexOf('y');\n\n    const daypos = 0 + (dayoffset > monthoffset ? 1 : 0) + (dayoffset > yearoffset ? 1 : 0);\n    const monthpos = 0 + (monthoffset > dayoffset ? 1 : 0) + (monthoffset > yearoffset ? 1 : 0);\n    const yearpos = 0 + (yearoffset > dayoffset ? 1 : 0) + (yearoffset > monthoffset ? 1 : 0);\n\n    const day = parseInt(parts[daypos], 0);\n    const month = parseInt(parts[monthpos], 0);\n    const year = parseInt(parts[yearpos], 0);\n\n    // The browser will always add 1900 for years 0-99, so handle years < 100\n    // if (year >= 0 && year < 100 && this.options.cutoffyear > 0)\n    // {\n    //   if (year < this.options.cutoffyear)\n    //     year += 2000;\n    //   else\n    //     year += 1900;\n    // }\n    if (isValidDate(year, month, day))\n      return { year, month, day };\n  }\n  if (options && options.nofail)\n    return null;\n\n  throw new Error(`Invalid date value: '${newdate}'`);\n}\n\n//compare two dates. return -1 if lhs<rhs, 0 if lhs==rhs, 1 if lhs>rhs\nexport function compareDate(lhs: DateParts | null, rhs: DateParts | null) {\n  if (!lhs)\n    return rhs ? -1 : 0; //if rhs is set, <null> is before anything. oterhwise equal\n  else if (!rhs)\n    return 1; //lhs must be set, so lhs>rhs\n\n  return lhs.year < rhs.year ? -1\n    : lhs.year > rhs.year ? 1\n      : lhs.month < rhs.month ? -1\n        : lhs.month > rhs.month ? 1\n          : lhs.day < rhs.day ? -1\n            : lhs.day > rhs.day ? 1\n              : 0;\n}\n\nexport function parseISODate(newdate: string, options?: { nofail: boolean }) {\n  return parseDate('y-m-d', newdate, options);\n}\n\nexport function getLocalToday(): DateParts {\n  const today = new Date;\n  return { year: today.getFullYear(), month: 1 + today.getMonth(), day: today.getDate() };\n}\n\nexport function parseISOTime(intime: string, { nofail = false } = {}) {\n  const split = intime.match(/^([0-9]+):([0-9]+)(:([0-9]+))?(\\.([0-9]+))?$/);\n  if (split) {\n    const hour = parseInt(split[1], 10);\n    const minute = parseInt(split[2], 10);\n    const second = parseInt(split[4] || \"0\", 10);\n    const msec = parseInt(split[6] || \"0\", 10);\n    return { hour, minute, second, msec };\n  }\n  if (nofail)\n    return undefined;\n\n  throw new Error(`Invalid time value: '${intime}'`);\n}\n\nexport function getWeekNumber(jsdate: Date) {\n  jsdate = new Date(jsdate); //don't modify the caller's date!\n  jsdate.setHours(0, 0, 0, 0);\n  // Thursday in current week decides the year.\n  jsdate.setDate(jsdate.getDate() + 3 - (jsdate.getDay() + 6) % 7);\n  // January 4 is always in week 1.\n  const week1 = new Date(jsdate.getFullYear(), 0, 4);\n  // Adjust to Thursday in week 1 and count number of weeks from jsdate to week1.\n  return 1 + Math.round(((jsdate.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);\n}\n\nexport function makeJSUTCDate(dateparts: DateParts) {\n  return new Date(Date.UTC(dateparts.year, dateparts.month - 1, dateparts.day));\n}\n\nexport function formatJSUTCISODate(dateobj: Date) {\n  return dateobj.getUTCFullYear() + '-' + ('0' + (dateobj.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + dateobj.getUTCDate()).slice(-2);\n}\n","/* Support APIs to deal with DOM native form elements (eg input, select, textarea) */\n\nimport type FormBase from '@mod-publisher/js/forms/formbase';\nimport { reformatDate } from \"@mod-publisher/js/forms/internal/webharefields\";\nimport { getTid } from \"@webhare/gettid\";\nimport { isFormControl, isHTMLElement, qSA, type FormControlElement } from \"@webhare/dompack\";\nimport type { FormCondition } from \"./types\";\nimport { JSFormElement, type FormFieldLike } from \"./jsformelement\";\nimport { throwError } from '@webhare/std';\n\nexport type ConstrainedRadioNodeList = RadioNodeList & NodeListOf<HTMLInputElement>;\n\n//Query elements that are likely to be formfieldlike. Anything with a [name] but not eg button (and not data-wh-form-name which usually relies on getformvalue events)\nexport const queryFormFieldLike = `[name]:not(button):not(a):not(output)`;\n\nexport function isInputElement(field: Element): field is HTMLInputElement {\n  return isHTMLElement(field) && field.tagName === 'INPUT';\n}\n\n/// Implements required, disabled, ..\nexport function isFormFieldLike(control: HTMLElement): control is FormFieldLike {\n  return isFormControl(control as HTMLElement) || control instanceof JSFormElement;\n}\n\nexport function isRadioOrCheckbox(field: Element): field is HTMLInputElement {\n  return isInputElement(field) && [\"radio\", \"checkbox\"].includes(field.type);\n}\n\n// Constrains the RadioNodeList type to only return HTMLInputElements. reduces number of casts we need\nexport function isRadioNodeList(el: RadioNodeList | Element): el is ConstrainedRadioNodeList {\n  return el instanceof RadioNodeList;\n}\n\nexport function getFieldName(field: HTMLElement): string {\n  return field.dataset.whFormName || (field as HTMLInputElement).name || '';\n}\n\nexport function setFieldName(field: HTMLElement, newname: string) {\n  if (field.dataset.whFormName !== undefined)\n    field.dataset.whFormName = newname;\n  else if ((field as HTMLInputElement).name !== undefined)\n    (field as HTMLInputElement).name = newname;\n  else\n    throw new Error('Cannot set name on field without existing name');\n}\n\nexport function getFieldDisplayName(field: HTMLElement | ConstrainedRadioNodeList): string {\n  if (isRadioNodeList(field))\n    return `radiogroup '${(field.item(0) as HTMLInputElement)?.name || (field.item(0) as HTMLElement)?.id || '<unnamed>'}'`;\n  if (isFormControl(field))\n    return `native field '${field.name || field.id || '<unnamed>'}'`;\n  if (field.dataset.whFormName)\n    return `custom field '${field.dataset.whFormName || field.id || '<unnamed>'}'`;\n  if (field.classList.contains('wh-form__fieldgroup'))\n    return `field group '${field.dataset.whFormGroupFor || field.id || '<unnamed>'}'`;\n  return `${field.tagName} element '${field.id || '<unnamed>'}'`;\n}\n\n/** The WH Form rendering generates wh-fileedit elements. If no handler is detected for them, we downgrade them to input type=file before\n *  the form actually sets up its handler (it's still safe to rewrite top level form elements then)\n*/\nexport function downgradeUploadFields(form: HTMLElement) {\n  for (const uploadfield of qSA(form, \"wh-fileedit\")) {\n    const input = document.createElement(\"input\");\n    input.type = \"file\";\n    for (const attr of uploadfield.attributes)\n      input.setAttribute(attr.name, attr.value);\n\n    uploadfield.replaceWith(input);\n  }\n}\n\nexport function getErrorForValidity(field: FormControlElement): string {\n  const validity = field.validity;\n  if (validity.customError && field.validationMessage)\n    return field.validationMessage;\n\n  if (validity.valueMissing)\n    return getTid(\"publisher:site.forms.commonerrors.required\");\n  if (field instanceof HTMLInputElement) {\n    if (validity.rangeOverflow) {\n      const max = field.type === 'date' ? reformatDate(field.max) : field.max;\n      return getTid(\"publisher:site.forms.commonerrors.max\", max);\n    }\n    if (validity.rangeUnderflow) {\n      const min = field.type === 'date' ? reformatDate(field.min) : field.min;\n      return getTid(\"publisher:site.forms.commonerrors.min\", min);\n    }\n    if (validity.tooShort)\n      return getTid(\"publisher:site.forms.commonerrors.minlength\", field.minLength);\n    if (validity.tooLong)\n      return getTid(\"publisher:site.forms.commonerrors.maxlength\", field.maxLength);\n    if (validity.stepMismatch)\n      if (!field.step || parseInt(field.step) === 1)\n        return getTid(\"publisher:site.forms.commonerrors.step1mismatch\");\n      else\n        return getTid(\"publisher:site.forms.commonerrors.stepmismatch\", field.step);\n  }\n\n  if (validity.badInput)\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n  if (validity.typeMismatch)\n    if ([\"email\", \"url\", \"number\"].includes(field.type))\n      return getTid(\"publisher:site.forms.commonerrors.\" + field.type);\n\n  for (const key of [\"badInput\", \"customError\", \"patternMismatch\", \"rangeOverflow\", \"rangeUnderflow\", \"stepMismatch\", \"typeMismatch\", \"valueMissing\"] as const)\n    if (validity[key])\n      return key;\n\n  return '?';\n}\n\nexport function isFieldNativeErrored(field: HTMLElement): field is FormControlElement {\n  return isFormControl(field) && !field.hasAttribute(\"data-wh-form-skipnativevalidation\") && !field.checkValidity();\n}\n\nexport function getFieldNativeError(field: HTMLElement) {\n  if (isFieldNativeErrored(field))\n    return getErrorForValidity(field);\n\n  return null;\n}\n\n\nexport function parseCondition(conditiontext: string): FormCondition {\n  interface FormConditionWrapper {\n    c: FormCondition;\n  }\n\n  return (JSON.parse(conditiontext) as FormConditionWrapper).c;\n}\n\nexport function getFormElementCandidates(basenode: HTMLElement, namePrefix: string) {\n  const parentForm = basenode.closest('form');\n  if (!parentForm)\n    throw new Error('No form found for element');\n\n  const candidates = qSA<HTMLElement>(basenode, queryFormFieldLike).filter(el => !(\"form\" in el) || el.form === parentForm);\n  if (namePrefix)\n    return candidates.filter(el => getFieldName(el).startsWith(namePrefix + '.'));\n  else\n    return candidates;\n}\n\n/** Get the handler for a form element */\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, options: { allowMissing: true }): FormType | null;\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, options?: { allowMissing?: boolean }): FormType;\n\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, { allowMissing = false } = {}): FormType | null {\n  //FIXME convert to Symbol? but make sure we work cross-realm (ie tests)\n  return (node.propWhFormhandler as FormType) || (allowMissing ? null : throwError('No form handler found for form'));\n}\n\n/** Get the data for a form element. Shorthand for getFormHandler\\<FormBase\\<Shape\\>\\>(xx).data */\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, options: { allowMissing: true }): DataShape | null;\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, options?: { allowMissing?: boolean }): DataShape;\n\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, { allowMissing = false } = {}): DataShape | null {\n  return getFormHandler<FormBase<DataShape>>(node, { allowMissing })?.data;\n}\n","export interface FormFieldLike extends HTMLElement {\n  disabled: boolean;\n  name: string;\n  required: boolean;\n  value: unknown;\n}\n\n/** Base class for customElements that need to act as WebHare (Publisher) form elements */\nexport abstract class JSFormElement<ValueType> extends HTMLElement implements FormFieldLike {\n  static formAssociated = true;\n  static observedAttributes = [\"required\", \"disabled\"];\n\n  // #internals = this.attachInternals();\n\n  constructor() {\n    super();\n  }\n\n  get name() {\n    return this.getAttribute('name') || '';\n  }\n  set name(newname: string) {\n    this.setAttribute('name', newname);\n  }\n  get required(): boolean {\n    return this.hasAttribute('required');\n  }\n  set required(required: boolean) {\n    if (required)\n      this.setAttribute(\"required\", \"\");\n    else\n      this.removeAttribute(\"required\");\n\n    this.refreshState();\n  }\n\n  get disabled(): boolean {\n    return this.hasAttribute('disabled');\n  }\n  set disabled(disable: boolean) {\n    if (disable)\n      this.setAttribute(\"disabled\", \"\");\n    else\n      this.removeAttribute(\"disabled\");\n\n    this.refreshState();\n  }\n\n  abstract value: ValueType;\n\n  /** Invoked whenever disabled/required states change */\n  protected refreshState() {\n  }\n\n  attributeChangedCallback(name: string, oldValue: unknown, newValue: unknown) {\n    if ([\"disabled\", \"required\"].includes(name))\n      this.refreshState();\n  }\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from '@webhare/dompack';\nimport * as focus from 'dompack/browserfix/focus';\nimport * as merge from './internal/merge';\nimport FormBase, { type FormResultValue, type FormSubmitEmbeddedResult, type FormSubmitMessage, type FormSubmitResult } from './formbase';\nimport { getFormService, getTSFormService, type PublisherFormService } from \"@webhare/forms/src/formservice\";\nimport * as emailvalidation from './internal/emailvalidation';\nimport { runMessageBox } from 'dompack/api/dialog';\nimport { debugFlags, isLive, navigateTo, type NavigateInstruction } from \"@webhare/env\";\nimport { isBlob, pick } from '@webhare/std';\nimport { setFieldError } from './internal/customvalidation';\nimport type { RPCFormTarget, RPCFormInvokeBase, RPCFormSubmission } from '@webhare/forms/src/types';\nimport { SingleFileUploader, type UploadResult } from '@webhare/upload';\nimport { createClient } from '@webhare/jsonrpc-client';\nimport { setupCaptchaFieldGroup } from './fields/captchafield';\nimport { getFormConfiguration } from '@webhare/forms/src/registration';\nimport type { CaptchaProvider } from '../captcha/api';\n\nfunction unpackObject(formvalue: FormResultValue): RPCFormInvokeBase[\"vals\"] {\n  return Object.entries(formvalue).map(_ => ({ name: _[0], value: _[1] }));\n}\n\nexport interface FormSubmitDetails<DataShape extends object = Record<string, unknown>> {\n  form: HTMLElement;\n  rpchandler: RPCFormBase<DataShape>;\n  extrasubmitdata?: unknown;\n  submitted: FormResultValue;\n  result: unknown;\n  errors: FormSubmitMessage[];\n}\n\ntype UploadCache = WeakMap<Blob, UploadResult>;\n\nfunction buildTarget(target: string): RPCFormTarget {\n  return { target, url: location.href.split('/').slice(3).join('/') };\n}\n\nclass FormSubmitter {\n  private readonly target;\n  private readonly cache: UploadCache;\n  private readonly offline: boolean;\n\n  constructor(target: string, cache: UploadCache | null, offline: boolean) {\n    this.target = buildTarget(target);\n    this.cache = cache || new WeakMap();\n    this.offline = offline;\n  }\n\n  private async uploadFile(file: Blob) {\n    if (this.offline)\n      throw new Error(\"Cannot upload files in offline mode\"); //TODO convert to dataurl and test it\n\n    //TODO what if the server discarded the token? we should negotiate with the server which files it (still) wants\n    const completed = this.cache.get(file);\n    if (completed)\n      return completed;\n\n    const uploader = new SingleFileUploader(file);\n    //Ask the server if it's okay to upload these files\n    const uploadinstructions = await getTSFormService().requestUpload(this.target, uploader.manifest);\n    //Run the actual upload. Options: onProgress, signal\n    const uploadedfile: UploadResult = await uploader.upload(uploadinstructions);\n    this.cache.set(file, uploadedfile);\n    return uploadedfile;\n  }\n\n  private async convertSubmittable(formvalue: unknown): Promise<unknown> {\n    //TODO combine multiple uploads into one\n    if (Array.isArray(formvalue))\n      return await Promise.all(formvalue.map(file => this.getSubmittable(file)));\n\n    if (formvalue && typeof formvalue === 'object') {\n      if (isBlob(formvalue))\n        return await this.uploadFile(formvalue as Blob);\n\n      const result: Record<string, unknown> = {};\n      for (const [key, value] of Object.entries(formvalue)) {\n        result[key] = await this.getSubmittable(value);\n        //console.log(key, value, result[key]);\n      }\n      return result;\n    }\n    return formvalue;\n  }\n\n  async getSubmittable(formvalue: object): Promise<FormResultValue> {\n    return await this.convertSubmittable(formvalue) as FormResultValue;\n  }\n}\n\n/** Directly submit a RPC form to WebHare\n *  @param target - Formtarget as obtained from\n * @deprecated Switch to \\@webhare/forms submitForm and buildFormSubmission\n */\nexport async function submitForm(target: string, formvalue: FormResultValue, options?: { extrasubmit: unknown }): Promise<FormSubmitResult> {\n  const submitparameters = await buildRPCFormSubmission(target, formvalue, { extraSubmit: options?.extrasubmit || null, });\n  return await submitRPCForm(submitparameters);\n}\n\n/** Return a value safe for RPC submission or typed serialization */\nexport async function buildRPCFormSubmission<DataShape extends object = Record<string, unknown>>(target: string, formValue: DataShape, options?:\n  {\n    extraSubmit?: unknown;\n    offline?: boolean;\n    uploadCache?: WeakMap<Blob, UploadResult>;\n    __setupEvent?: FormSubmitDetails<DataShape>;\n  }): Promise<RPCFormSubmission> {\n  const submitter = new FormSubmitter(target, options?.uploadCache || null, options?.offline || false);\n\n  const vals = await submitter.getSubmittable(formValue);\n\n  if (options?.__setupEvent) {\n    const eventdetail = options.__setupEvent;\n    eventdetail.extrasubmitdata = options.extraSubmit || null;\n    eventdetail.submitted = vals;\n  }\n\n  const submitparameters: RPCFormSubmission = {\n    ...buildTarget(target),\n    vals: unpackObject(vals),\n    extrasubmit: options?.extraSubmit || null\n  };\n  return submitparameters;\n}\n\nexport async function submitRPCForm(submission: RPCFormSubmission): Promise<FormSubmitResult> {\n  // TODO switch over to typed rpc, allow rpc options that make sense to be specified as options to submitRPCForm\n  const client = createClient<PublisherFormService>(\"publisher:forms\");\n  return await client.formSubmit(submission);\n}\n\nexport default class RPCFormBase<DataShape extends object = Record<string, unknown>> extends FormBase<DataShape> {\n  __formhandler = {\n    errors: [],\n    warnings: [],\n    formid: \"\",\n    url: \"\",\n    target: \"\",\n    submitting: false\n  };\n\n  #hadFocus = false;\n  #completedUploads = new WeakMap<Blob, UploadResult>;\n  #settingUpCaptcha = false;\n\n  pendingrpcs = new Array<Promise<unknown>>;\n\n  constructor(formnode: HTMLFormElement) {\n    super(formnode);\n    this.__formhandler.formid = formnode.dataset.whFormId || ''; //needed for 'old' __formwidget: stuff\n    this.__formhandler.url = location.href.split('/').slice(3).join('/');\n    this.__formhandler.target = formnode.dataset.whFormTarget || '';\n    window.addEventListener(\"wh:form-configure\", () => this.checkCaptcha());\n    this.node.addEventListener(\"focusin\", this.#onFirstFocus, true);\n\n    if (!this.__formhandler.target) {\n      if (this.__formhandler.formid) {\n        console.error(\"This page needs to be republished!\");\n      } else {\n        if (!isLive)\n          console.error(\"Missing data-wh-form-target on form, did your witty apply '[form.formattributes]' to the <form> tag ?\", formnode);\n        throw new Error(\"Form does not appear to be a WebHare form\");\n      }\n    }\n\n    this.checkCaptcha();\n  }\n\n  getRPCFormIdentifier(): RPCFormTarget { //submitinfo as required by some RPCs\n    return buildTarget(this.__formhandler.target);\n  }\n\n  async #getSubmitVals(): Promise<FormResultValue> {\n    const formvalue = await this.getFormValue();\n    const submitter = new FormSubmitter(this.__formhandler.target, this.#completedUploads, false);\n    return await submitter.getSubmittable(formvalue);\n  }\n\n  //Invoke a function on the form on the server\n  async _invokeRPC(background: boolean, methodname: string, args: unknown[]) {\n    const waiter = Promise.withResolvers<void>();\n\n    if (!background)\n      this.onRPC(waiter.promise);\n\n    const lock = dompack.flagUIBusy({ modal: !background });\n    try {\n      const rpc = getFormService().formInvoke({\n        ...this.getRPCFormIdentifier(),\n        vals: unpackObject(await this.#getSubmitVals()),\n        methodname,\n        args\n      });\n      this.pendingrpcs.push(rpc);\n      const result = await rpc;\n      this._processMessages(result.messages);\n      return result.result;\n    } finally {\n      lock.release();\n      waiter.resolve();\n    }\n  }\n\n  /* Override this to implement support for incoming field messages */\n  processFieldMessage(field: string, prop: string, value: unknown) {\n    if (field.startsWith(\"#page.\")) {\n      const matchpage = field === \"#page.thankyou\" ? this.node.querySelector<HTMLElement>(`.wh-form__page[data-wh-form-pagerole=thankyou]`) : null;\n      if (!matchpage) { //we currently don't have anything to edit on other pages than thankyou\n        console.warn(\"Message for non-page field: \" + field + \", prop: \" + prop + \", value: \" + String(value));\n        return;\n      }\n\n      if (prop === 'data') {\n        const dataval = value as { redirect: NavigateInstruction | null; exitbutton: string };\n        matchpage.dataset.whFormNavigateTo = dataval.redirect ? JSON.stringify(dataval.redirect) : undefined;\n        matchpage.dataset.whFormExitButton = dataval.exitbutton;\n      }\n    } else {\n      const fieldnode = this.node.querySelector<HTMLElement>(`*[name=\"${CSS.escape(field)}\"], *[data-wh-form-name=\"${CSS.escape(field)}\"]`);\n      if (!fieldnode) {\n        console.warn(\"Message for non-existent field: \" + field + \", prop: \" + prop + \", value: \" + String(value));\n        return;\n      }\n      if (prop === 'value') {\n        this.setFieldValue(fieldnode, value);\n        return;\n      }\n    }\n    console.warn(\"Unknown field message: field: \" + field + \", prop: \" + prop + \", value: \" + String(value));\n  }\n\n  //Override this function to easily submit extra fields\n  getFormExtraSubmitData(): object | Promise<object> {\n    return {};\n  }\n\n  //Invoked when RPC is occuring. Is passed a promise that will resolve on completion\n  //onRPC is DEPRECATED, switching to event based api\n  onRPC(promise: Promise<void>) {\n  }\n\n  /** Invoke a function on the form on the server\n      @param methodname - Name of the function on the form\n      @param args - Arguments for the function\n      @returns Promise that resolves to the result of the rpc call\n  */\n  invokeRPC(methodname: string, ...args: unknown[]) {\n    return this._invokeRPC(false, methodname, args);\n  }\n\n  /** Invoke a function on the form on the server, doesn't call .onRPC or request modality layers\n      @param methodname - Name of the function on the form\n      @param args - Arguments for the function\n      @returns Promise that resolves to the result of the rpc call\n  */\n  invokeBackgroundRPC(methodname: string, ...args: unknown[]) {\n    return this._invokeRPC(true, methodname, args);\n  }\n\n  _processMessages(messages: Array<{ field: string; prop: string; data: unknown }>) {\n    for (const msg of messages) {\n      this.processFieldMessage(msg.field, msg.prop, msg.data);\n    }\n  }\n\n  async _flushPendingRPCs() {\n    while (this.pendingrpcs.length) {\n      try {\n        await this.pendingrpcs.pop();\n      } catch (ignore) {\n        //*we* can't handle those...\n      }\n    }\n  }\n\n  async buildFormSubmission(extradata?: object, options?: { __setupEvent?: FormSubmitDetails<DataShape> }): Promise<RPCFormSubmission> {\n    //Request extrasubmit first, so that if it returns a promise, it can execute in parallel with getFormValue\n    const extraSubmitAwaitable = this.getFormExtraSubmitData();\n    //FIXME we want getFormValue to be sync (and just use 'this.data' here) - who is still sending promises our way? too much to sort out for a backport\n    const formvalue = await this.getFormValue() as DataShape;\n    const extraSubmit = { ...extradata, ...(await extraSubmitAwaitable as Record<string, unknown>) };\n\n    await this._flushPendingRPCs();\n    dompack.dispatchCustomEvent(this.node, \"wh:form-preparesubmit\", {\n      bubbles: true, cancelable: false, detail: {\n        extrasubmit: extraSubmit\n      }\n    });\n\n    const submitparameters = await buildRPCFormSubmission<DataShape>(this.__formhandler.target, formvalue, {\n      extraSubmit,\n      offline: false,\n      uploadCache: this.#completedUploads,\n      //hack because we need to record the 'vars' value before unpackObject flattens it for safe HareScript RPC\n      __setupEvent: options?.__setupEvent\n    });\n\n    return submitparameters;\n  }\n\n  #onFirstFocus = () => {\n    this.#hadFocus = true;\n    this.checkCaptcha();\n  };\n\n  private checkCaptcha() {\n    //Checks whether to show captcha based on configuration. Note that even if *we* think it's not needed, form submission may still require a captcha\n    const config = getFormConfiguration();\n    const shouldShow = config?.captcha === \"onLoad\" || (config?.captcha === \"onActivate\" && this.#hadFocus);\n    if (shouldShow && this.node.dataset.whFormCaptcha !== undefined && !this.#settingUpCaptcha && !this.getElementByName(\"__form_captcha\")) {\n      this.#settingUpCaptcha = true;\n      void getFormService().getCaptchaConfiguration(this.getRPCFormIdentifier()).then(captchaConfig => {\n        if (captchaConfig) {\n          setupCaptchaFieldGroup(this, captchaConfig);\n        }\n      });\n    }\n  }\n\n  async submitForm(parameters: RPCFormSubmission): Promise<FormSubmitResult> {\n    return await submitRPCForm(parameters);\n  }\n\n  async submit(extradata?: object): Promise<{ result?: FormSubmitEmbeddedResult }> {\n    //ADDME timeout and free the form after some time\n    if (this.__formhandler.submitting) //throwing is the safest solution... having the caller register a second resolve is too dangerous\n      throw new Error(\"The form is already being submitted\");\n\n    const waiter = Promise.withResolvers<void>();\n    let insubmitrpc = false;\n    this.onRPC(waiter.promise);\n\n    const eventdetail: FormSubmitDetails<DataShape> = {\n      form: this.node,\n      rpchandler: this,\n      submitted: {},\n      errors: [],\n      result: null\n    };\n\n    try {\n      this.__formhandler.submitting = true;\n\n      const submitparameters = await this.buildFormSubmission(extradata, { __setupEvent: eventdetail });\n\n      if (debugFlags.fhv)\n        console.log('[fhv] start submission', submitparameters);\n\n      insubmitrpc = true; //so we can easily determine exception source\n      const result = await this.submitForm(submitparameters);\n      insubmitrpc = false;\n\n      if (debugFlags.fhv)\n        console.log('[fhv] received response', result);\n\n      this._processMessages(result.messages);\n\n      if (!dompack.dispatchCustomEvent(this.node, \"wh:form-response\", { bubbles: true, cancelable: true, detail: result }))\n        return result;\n\n      eventdetail.result = result.result;\n      eventdetail.errors = result.errors;\n\n      let didfirstfocus = false;\n      const globalerrors = [];\n      for (const error of result.errors) {\n        if (!error.name) {\n          globalerrors.push(error);\n          continue;\n        }\n\n        let failednode = this.node.querySelector('[name=\"' + error.name + '\"], [data-wh-form-name=\"' + error.name + '\"]');\n        if (!failednode) {\n          if (error.name === \"__form_captcha\") { //created on demand\n            const serverMetadata = error.metadata as { provider: CaptchaProvider };\n            failednode = setupCaptchaFieldGroup(this, serverMetadata.provider);\n          } else {\n            console.error(\"[fhv] Unable to find node '\" + error.name + \"' which caused error:\" + error.message);\n            continue;\n          }\n        }\n        if (!didfirstfocus) {\n          dompack.focus(failednode);\n          didfirstfocus = true;\n        }\n        setFieldError(failednode, error.message, { reportimmediately: true, serverside: true, metadata: error.metadata });\n      }\n\n      if (result.success) {\n        this.sendFormEvent({ event: 'submitted' });\n        if (dompack.dispatchCustomEvent(this.node, \"wh:form-submitted\", { bubbles: true, cancelable: true, detail: eventdetail as FormSubmitDetails<Record<string, unknown>> })) {\n          merge.run(this.node, { form: await this.getFormValue() });\n\n          //FIXME why is going to 'thank you' not in the formbase?\n          this._navigateToThankYou(result.result && result.result.richvalues);\n          this.onSubmitSuccess(result.result);\n        }\n      } else {\n        const failedfields = result.errors.map(error => error.name || \"*\").sort().join(\" \");\n        this.sendFormEvent({ event: 'failed', errorfields: failedfields, errorsource: 'server' });\n\n        if (globalerrors.length) {\n          if (dompack.dispatchCustomEvent(this.node, \"wh:form-globalerrors\", { bubbles: true, cancelable: true, detail: { globalerrors } }))\n            this.displayGlobalErrors(globalerrors);\n        }\n\n        if (dompack.dispatchCustomEvent(this.node, \"wh:form-failed\", { bubbles: true, cancelable: true, detail: eventdetail }))\n          this.onSubmitFailed(result.errors, result.result);\n      }\n      return pick(result, [\"result\"]);\n    } catch (e) {\n      this.sendFormEvent({ event: 'exception', exception: String(e), errorsource: insubmitrpc ? 'server' : 'client' });\n\n      if (dompack.dispatchCustomEvent(this.node, \"wh:form-exception\", { bubbles: true, cancelable: true, detail: eventdetail }))\n        this.onSubmitException(e as Error);\n\n      throw e;\n    } finally {\n      waiter.resolve();\n      this.__formhandler.submitting = false;\n    }\n  }\n\n  displayGlobalErrors(globalerrors: FormSubmitMessage[]) {\n    try {\n      const errors = globalerrors.map(error => dompack.create(\"p\", { textContent: error.message }));\n      runMessageBox(errors, [{ title: \"OK\" }]); //TODO: language?\n    } catch (e) {\n      console.error(\"runMessageBox failed\", e);\n      // eslint-disable-next-line no-alert -- alert is our fallback without message boxes\n      alert(globalerrors.map(error => error.message).join(\"\\n\"));\n    }\n  }\n\n  //Get the first group that failed error handling\n  getFirstFailedGroup() {\n    return this.node.querySelector(\".wh-form__fieldgroup-error\");\n  }\n\n  //override this to deal with succesful submissions\n  onSubmitSuccess(result: FormSubmitEmbeddedResult<unknown>) {\n    const formpos = this.node.getBoundingClientRect();\n    if (formpos.top < 0)\n      this.node.scrollIntoView({ block: 'start', behavior: 'smooth' });\n\n    if (result && result.resultsguid)\n      this.node.dataset.whFormResultguid = result.resultsguid;\n\n    if (result && result.submitinstruction)\n      navigateTo(result.submitinstruction);\n  }\n\n  //override this to deal with failed submissions\n  onSubmitFailed(errors: FormSubmitMessage[], result: unknown) {\n  }\n\n  //override this to deal with form exceptions\n  onSubmitException(e: Error) {\n  }\n\n  async validateSingleFormField(field: HTMLElement): Promise<boolean> {\n    if (field instanceof HTMLInputElement && field.type === \"email\") { //TODO perhaps move this to webharefields.es ?\n      if (focus.getCurrentlyFocusedElement() === field) { //TODO clearing suggestion on change should probably be generalized\n        if (field.propWhValidationSuggestion) {\n          field.propWhValidationSuggestion = null;\n        }\n      }\n\n      //Just because it's focused doesn't mean we shouldn't validate it\n      const validation = emailvalidation.validateField(this, field);\n      this.pendingrpcs.push(validation);\n      if (!(await validation))\n        return false;\n    }\n    return true;\n  }\n}\n","import * as dompack from 'dompack';\nimport { getTid, getTidLanguage } from \"@webhare/gettid\";\nimport { getFormService } from \"@webhare/forms/src/formservice\";\nimport { isValidEmail, wrapInTimeout } from '@webhare/std';\nimport { setFieldError } from './customvalidation';\nimport type { EmailValidationResult } from '@webhare/forms/src/types';\nimport type FormBase from '../formbase';\nimport type RPCFormBase from '../rpc';\nimport { debugFlags } from '@webhare/env';\n\nconst cache:\n  {\n    [key: string]: Promise<EmailValidationResult>;\n  } = {};\n\nfunction mayValidateField(field: HTMLInputElement) {\n  if (field.disabled || field.readOnly) //FIXME shouldn't we just decide not to validate at a much higher level if something cannot be changed ?\n    return false;\n\n  if (field.autocomplete && field.autocomplete.split(' ').includes(\"username\")) //Well, we shouldn't *force* usernames as a blacklisted domain might still have been explicitly added as login. but suggestions are still useful?\n    return false;\n  return true;\n}\n\nfunction acceptEmailSuggestion<DataShape extends object = Record<string, unknown>>(evt: Event, form: FormBase<DataShape>, field: HTMLInputElement, suggestion: string) {\n  dompack.stop(evt);\n  field.value = suggestion;\n  field.propWhValidationSuggestion = null;\n  form._reportFieldValidity(field);\n}\n\nexport async function validateField<DataShape extends object = Record<string, unknown>>(form: FormBase<DataShape> | RPCFormBase<DataShape>, field: HTMLInputElement) {\n  if (field.dataset.whFormEmailBlocked) {\n    delete field.dataset.whFormEmailBlocked;\n    setFieldError(field, \"\"); //explicitly clear our earlier setFieldError, but only if we set it. FIXME To really cleanly solve this we need better integration with rpc.ts - we want to be in the setupValidation chain and simply return errors instead of being explictly invoked\n  }\n\n  const checkvalue: string = field.value;\n  if (!checkvalue || !mayValidateField(field)) {\n    return true; //not a problem\n  }\n\n  if (!isValidEmail(checkvalue)) {\n    //TODO why aren't we just returning the error like a validator callback? may also help avoid the whFormEamailBlocked hack..\n    field.dataset.whFormEmailBlocked = \"true\";\n    setFieldError(field, getTid(\"publisher:site.forms.commonerrors.email\"));\n    return false;\n  }\n\n  //user is 'done' with email field apparently. remotely validate it\n  const key = \"e_\" + field.name + \".\" + checkvalue; //e_ prefix protects against funny people using 'constructor' etc. TODO just switch to a Map<> or similar. TODO only include field.name if needed, and also bind to the form then\n  if (cache[key] === undefined) {\n    const rpcCall = \"getRPCFormIdentifier\" in form ?\n      //TODO rendering.whlib should add a data attribute if there are form+field-specific checks, perhaps we can even generalize that for all fields instead of just email whenever they need to do direct validation\n      getFormService().formValidateEmail({ ...form.getRPCFormIdentifier(), field: field.name }, checkvalue)\n      : getFormService().validateEmail(getTidLanguage(), checkvalue);\n\n    //wrap in timeout\n    cache[key] = wrapInTimeout(rpcCall, 3000, \"Timeout\");\n  }\n\n  //TODO should we ever clear the cache? only relevant probably if someone is on the frontend testing emails and doesn't want to refresh\n  let result: EmailValidationResult | undefined;\n\n  try {\n    result = await cache[key];\n  } catch (e) { //timeout or other error, or offline form (PWA?)\n    if (debugFlags.fhv)\n      console.log('[fhv] Email validation error or timeout for value', checkvalue, e);\n  }\n\n  if (checkvalue !== field.value || !mayValidateField(field))\n    return true; //the field already changed, don't report about old errors\n\n  if (result?.blocked) {\n    field.dataset.whFormEmailBlocked = \"true\";\n    setFieldError(field, result.blocked);\n    return false;\n  }\n\n  if (result?.force) {\n    field.value = result.force;\n\n    //we should be able to assume we won't have to revalidate a server-provided suggestion\n    cache[\"e_\" + field.name + \".\" + result.force] = Promise.resolve<EmailValidationResult>({});\n\n    return true;\n  } else if (result?.suggestion) {\n    const suggestion = getTid(\"publisher:site.forms.commonerrors.email_suggestion\", \"___SUGGESTION___\").split(\"___SUGGESTION___\");\n\n    //we should be able to assume we won't have to revalidate a server-provided suggestion\n    cache[\"e_\" + field.name + \".\" + result.suggestion] = Promise.resolve<EmailValidationResult>({});\n\n    field.propWhValidationSuggestion =\n      <span class=\"wh-form__emailcorrection\">\n        {suggestion[0]}\n        <a href=\"#\" class=\"wh-form__emailcorrected\" on={{ click: (evt: Event) => acceptEmailSuggestion(evt, form, field, result.suggestion as string) }}>{result.suggestion}</a>\n        {suggestion[1]}\n      </span>;\n    return true;\n  }\n  return true;\n}\n","/* Dialogapi offers an API to which dialog providers cannot connect. It does\n   not implement the dialogs themselves\n*/\n\nimport * as dompack from 'dompack';\nimport * as domfocus from 'dompack/browserfix/focus';\nimport KeyboardHandler from \"dompack/extra/keyboard\";\n\nexport type DialogOptions =\n  {\n    /**  Allow the dialog to be cancelled by clicking outside the dialog. Defaults to true if no choices are specified */\n    allowcancel?: boolean;\n    /**  Element to focus on closing the dialog */\n    focusonclose?: HTMLElement;\n    /**  An AbortSignal which if set will close the dialog and resolve it with a null response */\n    signal?: EventTarget;\n    /**  Additional class to set on the dialog */\n    messageboxclassbase?: string;\n\n    borrow?: Element | string;\n  };\ntype DialogConstructor = (options?: DialogOptions) => DialogBase;\n\nconst dialogstack: DialogBase[] = [];\nlet keyhandler: KeyboardHandler | null = null;\nlet dialogconstructor: DialogConstructor | null = null;\nlet dialogoptions: DialogOptions | null = null;\n\nfunction onEscape(event: KeyboardEvent) {\n  if (!dialogstack.length)\n    return;\n\n  dompack.stop(event);\n  if (dialogstack[dialogstack.length - 1].options.allowcancel)\n    dialogstack[dialogstack.length - 1].resolve(null);\n}\n\nfunction onTab(event: KeyboardEvent, direction: number) {\n  if (!dialogstack.length)\n    return;\n\n  dompack.stop(event);\n\n  const focusable = domfocus.getFocusableComponents(dialogstack[dialogstack.length - 1].contentnode, true);\n  const el = domfocus.getCurrentlyFocusedElement();\n  const tofocusidx = el ? focusable.indexOf(el) + direction : -1;\n  const tofocus = tofocusidx < 0 ? focusable[focusable.length - 1] : tofocusidx >= focusable.length ? focusable[0] : focusable[tofocusidx];\n  if (tofocus)\n    dompack.focus(tofocus);\n}\n\nexport class DialogBase {\n  options: DialogOptions;\n  private _borrowedfrom: Element | null = null;\n  private _borrowednext: Element | null = null;\n  contentnode: Element | null; //FIXME a successor to DialogBase should not allow these to be | null. have our child inform us through super() about the contentnode and buttonsnode so we can ensure it's set\n  buttonsnode: Element | null = null;\n  private _deferred: PromiseWithResolvers<string | null>;\n  open: boolean;\n  private _previousfocus: Element | null = null;\n\n  constructor(options?: DialogOptions) {\n    this.options = {\n      allowcancel: true,\n      ...options\n    };\n\n    if (this.options.borrow && typeof this.options.borrow === 'string') {\n      const borrow = document.querySelector(this.options.borrow);\n      if (!borrow)\n        throw new Error(\"Invalid 'borrow' selectior: \" + this.options.borrow);\n      this.options.borrow = borrow;\n    }\n    // At this point, if this.options.borrow was a string, it's been resolved to an Element\n\n    if (this.options.borrow) {\n      this._borrowedfrom = (this.options.borrow as Element).parentElement;\n      this._borrowednext = (this.options.borrow as Element).nextElementSibling;\n    }\n\n    if (this.options.signal)\n      this.options.signal.addEventListener(\"abort\", () => { this.resolve(null); });\n\n    this.contentnode = null;\n    this._deferred = Promise.withResolvers();\n    this.open = false;\n  }\n\n  async runModal() {\n    if (this.open)\n      throw new Error(\"Attempting to re-open already opened dialog\");\n\n    if (!keyhandler)\n      keyhandler = new KeyboardHandler(window, {\n        \"Escape\": (evt: KeyboardEvent) => onEscape(evt),\n        \"Tab\": (evt: KeyboardEvent) => onTab(evt, +1),\n        \"Shift+Tab\": (evt: KeyboardEvent) => onTab(evt, -1)\n      }, { captureunsafekeys: true, listenoptions: { capture: true } });\n\n    this._previousfocus = domfocus.getCurrentlyFocusedElement();\n    this._openDialog();\n\n    this.open = true;\n    dialogstack.push(this);\n\n    try {\n      this.afterShow();\n      this._checkFocus();\n      return await this._deferred.promise;\n    } finally {\n      if (this.open)\n        this.closeDialog();\n    }\n  }\n\n  _openDialog() {\n    throw new Error(\"_openDialog not overridden by dialog class\");\n  }\n\n  _checkFocus() {\n    const focusable = domfocus.getFocusableComponents(this.contentnode, true);\n    if (focusable.length !== 0)\n      dompack.focus(focusable[0]);\n    else\n      dompack.focus(document.body);\n  }\n\n  //close the dialog. this may be invoked even when inside runModal to ensure synchronous dialog cleanup\n  closeDialog() {\n    if (!this.open)\n      return;\n\n    const myoffset = dialogstack.indexOf(this);\n    if (myoffset >= 0)\n      dialogstack.splice(myoffset, 1);\n\n    this.open = false;\n    if (this.options.borrow)\n      if (this._borrowedfrom)\n        this._borrowedfrom.insertBefore(this.options.borrow as Element, this._borrowednext);\n      else\n        this._borrowednext?.remove();\n\n    if (this.options.focusonclose)\n      dompack.focus(this.options.focusonclose);\n    else if (this._previousfocus)\n      dompack.focus(this._previousfocus as HTMLElement);\n\n    if (dialogstack.length === 0 && keyhandler) {\n      keyhandler.destroy();\n      keyhandler = null;\n    }\n  }\n\n  /**\n   * resolve the dialog with the specified answer\n   *\n   * @param response - Response (or choice) to return. null if the dialog was simply cancelled\n   */\n  resolve(response: string | null) {\n    if (this.open)\n      this.closeDialog();\n    this._deferred.resolve(response);\n  }\n\n  afterShow() {\n    // supposed to be empty but extenders can override\n  }\n}\n\nexport function setupDialogs(newdialogconstructor: DialogConstructor, options?: DialogOptions) {\n  if (dialogconstructor) {\n    console.error(\"Duplicate setupDialogs call!\");\n    return;\n  }\n\n  dialogconstructor = newdialogconstructor;\n  dialogoptions = { messageboxclassbase: 'dompack-messagebox__', ...options };\n}\n\n/** Verify whether the dialog api is initialized */\nexport function isCreateDialogAvailable(): boolean {\n  return Boolean(dialogconstructor);\n}\n\n/**\n * Create a dialog\n *\n * @param options - dialog settings\n */\nexport function createDialog(options?: DialogOptions) {\n  if (!dialogconstructor)\n    throw new Error(\"Cannot create dialog, no dialog class defined\");\n\n  const dialog = dialogconstructor(options);\n  if (dialog.options.borrow)\n    dialog.contentnode?.appendChild(dialog.options.borrow as Element);\n  return dialog;\n}\n\ntype DialogChoice =\n  {\n    /** Title for the choice */\n    title: string;\n    /** Override result to return if clicked (otherwise you'll just receive the title) */\n    result?: string;\n    className?: string;\n  };\n\n\n/**\n                     @param question - if a string, will be wrapped as textContent into a <p> and presented as the question\n                    - if a html node, will appear as the question (allowing you to insert html)\n                    - if an array of nodes, all these nodes will be inserted\n    @param choices - Buttons (choices) the message box will offer, eg Ok and Cancel\n    @param options - Dialog options\n */\nexport async function runMessageBox(question: string | HTMLElement | HTMLElement[], choices: DialogChoice[], options?: DialogOptions) {\n  choices = choices || [];\n  options = { allowcancel: choices.length === 0, ...options };\n\n  const dialog = createDialog(options);\n  const choicebuttons = choices.map(choice =>\n    dompack.create(\"button\", {\n      type: \"button\",\n      className: dialogoptions ? dialogoptions.messageboxclassbase + \"button \" + (choice.className || \"\") : \"\",\n      textContent: choice.title,\n      on: { click: () => dialog.resolve(choice.result || choice.title) },\n      dataset: { messageboxResult: choice.result || choice.title }\n    }));\n\n  if (typeof question === 'string')\n    question = dompack.create(\"p\", { textContent: question });\n\n  if (Array.isArray(question))\n    dialog.contentnode?.append(...question);\n  else\n    dialog.contentnode?.append(question);\n\n  if (dialog.buttonsnode) //this dialog has a separte node for the button area\n    dialog.buttonsnode.append(...choicebuttons);\n  else\n    dialog.contentnode?.append(dompack.create(\"div\", {\n      className: dialogoptions ? dialogoptions.messageboxclassbase + \"buttongroup\" : \"\",\n      childNodes: choicebuttons\n    }));\n\n  return dialog.runModal();\n}\n","import * as dompack from '@webhare/dompack';\nimport { initializeCaptcha, type CaptchaProvider } from \"@mod-publisher/js/captcha/api\";\nimport { setFieldError, type SetFieldErrorData } from '../internal/customvalidation';\n\nimport \"../../captcha/__captcha.lang.json\"; //TODO or have forms send this tid (so it can also be overridden there)\nimport { JSFormElement } from '@webhare/forms';\nimport { getTid } from '@webhare/gettid';\nimport type RPCFormBase from '../rpc';\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"wh-captcha\": CaptchaField;\n  }\n}\n\nexport default class CaptchaField extends JSFormElement<string> {\n  value = '';\n  provider: CaptchaProvider | null = null;\n\n  constructor() {\n    super();\n    this.addEventListener('wh:form-setfielderror', evt => void this._setFieldError(evt));\n    this.whFormsApiChecker = () => this.check();\n\n    const form = this.closest('form');\n    if (form)\n      form.addEventListener('reset', () => this.onReset());\n  }\n\n  check(): void {\n    if (!this.value)\n      setFieldError(this, getTid(\"publisher:site.forms.commonerrors.required\"), { reportimmediately: false });\n    else\n      setFieldError(this, \"\", { reportimmediately: false });\n  }\n\n  setup(provider: CaptchaProvider) {\n    if (this.provider)\n      throw new Error(\"CaptchaField is already setup\");\n\n    this.provider = provider;\n    this.initialize();\n  }\n\n  private initialize() {\n    this.value = '';\n    this.replaceChildren();\n    void initializeCaptcha(this.provider!, this, {\n      onResponse: (result: string) => { this.value = result; }\n    });\n  }\n\n  private onReset() {\n    void this.initialize();\n  }\n\n  async _setFieldError(evt: CustomEvent<SetFieldErrorData>) {\n    dompack.stop(evt);\n    if (!evt.detail.error) //error cleared\n      return;\n\n    if (this.value) { //we were already sending a response!\n      console.log(\"Captcha response was rejected, resetting\");\n      this.onReset(); //better restart the control, timeout or duplicate submission\n    }\n  }\n}\n\nexport function setupCaptchaFieldGroup(form: RPCFormBase<object>, provider: CaptchaProvider): CaptchaField {\n  /* Setup a page-less holder for the captcha field\n\n    <div class=\"wh-form__page wh-form__page--visible\">\n      <div class=\"wh-form__fieldgroup\" data-wh-form-group-for=\"__form_captcha\">\n        ...\n    */\n\n  const captchaControl = dompack.create(\"wh-captcha\", { class: \"wh-form__captcha\", dataset: { whFormName: \"__form_captcha\", whFormRequired: \"true\" } });\n\n  const virtualCaptchaPage = dompack.create(\"div\", { class: \"wh-form__captchapage\" }, [\n    dompack.create(\"div\", { class: \"wh-form__fieldgroup\", dataset: { whFormGroupFor: \"__form_captcha\" } }, [\n      dompack.create(\"label\", { class: \"wh-form__label\" }, [getTid(\"publisher:site.captcha.title\")]),\n      dompack.create(\"div\", { class: \"wh-form__fields\" },\n        [dompack.create(\"div\", { class: \"wh-form__fieldline\" }, [captchaControl])]\n      )\n    ])\n  ]);\n\n  //Position it before the navbuttons, but if they are missing for whatever reason, just add to the end of the form\n  const buttonarea = dompack.qS(form.node, \".wh-form__navbuttons\");\n  if (buttonarea)\n    buttonarea.before(virtualCaptchaPage);\n  else\n    form.node.appendChild(virtualCaptchaPage);\n\n  void captchaControl.setup(provider);\n\n  return captchaControl;\n}\n\n\ncustomElements.define(\"wh-captcha\", CaptchaField);\n","import { getTid } from \"@webhare/gettid\";\nimport \"./__captcha.lang.json\";\n\nexport interface CaptchaProvider {\n  name: string;\n  apikey: string;\n}\n\nexport interface CaptchaSettings {\n  title: string;\n  onResponse: (response: string) => void;\n}\n\nexport interface CaptchaProviderRegistration {\n  initialize: (provider: CaptchaProvider, injectInto: HTMLElement, settings: CaptchaSettings) => Promise<void>;\n}\n\nexport const captcharegistry: Record<string, CaptchaProviderRegistration> = {};\n\n\nexport async function initializeCaptcha(provider: CaptchaProvider, injectInto: HTMLElement, settings?: Partial<CaptchaSettings>): Promise<void> {\n  if (!captcharegistry[provider.name])\n    throw new Error(`Captcha provider '${provider.name}' not registered`);\n  if (!settings?.onResponse)\n    throw new Error(\"onResponse callback is required\");\n\n  const finalsettings: CaptchaSettings = {\n    title: settings?.title ?? getTid(\"publisher:site.captcha.title\"),\n    onResponse: settings?.onResponse ?? (() => { }),\n  };\n\n  await captcharegistry[provider.name].initialize(provider, injectInto, finalsettings);\n}\n","// Auto-generated language file from /opt/wh/whtree/modules/publisher/js/captcha/__captcha.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"publisher\",\"nl\",{\"site\":{\"captcha\":{\"explain\":\"Vink het vakje hieronder aan\",\"title\":\"Verificatie\"}}});\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/nl.xml\n","import * as dompack from 'dompack';\nimport { getTid } from \"@webhare/gettid\";\nimport { FileEditElement as FileEditElementBase } from './fileeditbase';\nimport './upload.css';\nimport { isFile } from '@webhare/std';\n\n\n\n//FIXME nicer class name? eg add form or field to these (and imgedit) class names?\nexport class FileUploadFormElement extends FileEditElementBase {\n  constructor() {\n    super();\n    this.refresh();\n  }\n\n  #constructFileHolder() {\n    const fileholder = document.createElement(\"div\");\n    fileholder.classList.add('file');\n    return fileholder;\n  }\n\n  refresh() {\n    const nodes = [];\n\n    for (const [idx, file] of this.currentFiles.entries()) {\n      const fileholder = this.#constructFileHolder();\n\n      // const label = getLabelText(this.node);\n      // aria-label={label}\n      const filename = isFile(file) ? file.name : file.fileName;\n      /* for ease of 'form like' presentation, we're currently using an <input>. but quite hacky, eg. we need readonly to have it not interfere with clicks. */\n      const filenamefield =\n        <input part=\"filename\" class=\"file__name\" type=\"text\" value={filename} readonly />;\n\n      const deletebutton = <button part=\"button deletebutton\" class=\"deletebutton file__deletebutton\" />;\n      this.setupDeleteButton(deletebutton, idx);\n\n      fileholder.append(filenamefield, deletebutton);\n      nodes.push(fileholder);\n    }\n\n    if (this.currentFiles.length < this.maxFiles) {\n      const fileholder = this.#constructFileHolder();\n      fileholder.classList.add('file--placeholder');\n\n      const filenamefield =\n        <input part=\"filename\" class=\"file__name\" type=\"text\" value=\"\" placeholder={getTid(\"publisher:site.forms.upload-emptytext\")} disabled readonly />;\n\n      const uploadbutton = <button part=\"button selectbutton\" type=\"button\" class=\"wh-form__uploadfieldselect wh-form__button\"><span class=\"wh-form__buttonlabel\">{getTid(\"publisher:site.forms.selectfile\")}</span></button>;\n      this.setupUploadButton(fileholder);\n      fileholder.append(filenamefield, uploadbutton);\n      nodes.push(fileholder);\n    }\n\n    this.maindiv.replaceChildren(...nodes);\n  }\n}\n\n//////// Legacy version. We expect existing users to migrate to the version above\n\nexport default class UploadField {\n  constructor(node: HTMLElement) {\n    if (!customElements.get(\"wh-fileedit\"))\n      customElements.define(\"wh-fileedit\", FileUploadFormElement);\n  }\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from 'dompack';\nimport { requestFile } from \"@webhare/upload\";\n\nimport { getTid } from \"@webhare/gettid\";\nimport { setFieldError } from '@mod-publisher/js/forms/internal/customvalidation';\nimport { getFieldDisplayName } from '@webhare/forms/src/domsupport';\nimport { JSFormElement } from '@webhare/forms/src/jsformelement';\nimport type { FormFileValue } from '@webhare/forms/src/types';\nimport \"@mod-publisher/js/forms/internal/form.lang.json\"; //we need eg publisher:site.forms.selectfile\n\nfunction isAcceptableType(fileType: string, masks: string[]) {\n  if (masks.includes(fileType))\n    return true;\n\n  const basetype = fileType.split('/')[0];\n  if (['image', 'video', 'audio'].includes(basetype) && masks.includes(basetype + '/*'))\n    return true;\n\n  return false;\n}\n\n\nexport abstract class FileEditElement extends JSFormElement<FormFileValue[]> {\n  root;\n  maindiv;\n  readonly group: HTMLElement | null;\n\n  /** The current uploaded files */\n  protected currentFiles = new Array<FormFileValue>;\n  /** Maximum number of files */\n  protected maxFiles;\n\n  constructor() {\n    super();\n    this.root = this.attachShadow({ mode: 'open', delegatesFocus: true });\n    this.maindiv = document.createElement(\"div\");\n    this.maindiv.inert = this.disabled;\n\n    const csslink = document.createElement(\"link\");\n    csslink.rel = \"stylesheet\";\n    csslink.href = \"/.wh/ea/p/forms/controls.css\";\n    this.root.append(csslink, this.maindiv);\n\n    this.group = this.closest<HTMLElement>(\".wh-form__fieldgroup\");\n    this.whFormsApiChecker = async () => { await this._check(); };\n    this.maxFiles = parseInt(this.getAttribute(\"max-files\")!) || 1;\n    if (this.getAttribute(\"value\"))\n      this.#setValue(JSON.parse(this.getAttribute(\"value\")!));\n\n    if (this.group) {\n      this.group.addEventListener(\"dragover\", evt => evt.preventDefault());\n      this.group.addEventListener(\"dragenter\", evt => evt.preventDefault());\n      this.group.addEventListener(\"drop\", evt => this.doDrop(evt));\n    }\n  }\n  abstract refresh(): void;\n  isSet(): boolean {\n    return this.currentFiles.length > 0;\n  }\n  async _check() {\n    const error = this.required && !this.isSet();\n    if (error)\n      setFieldError(this, getTid(\"publisher:site.forms.commonerrors.required\"), { reportimmediately: false });\n    else\n      setFieldError(this, \"\", { reportimmediately: false });\n    return error;\n  }\n\n  protected refreshState() {\n    this.maindiv.inert = this.disabled;\n  }\n\n  get value(): FormFileValue[] {\n    return this.currentFiles;\n  }\n\n  set value(value: FormFileValue[]) {\n    this.#setValue(value);\n    this.refresh();\n  }\n\n  #setValue(value: Array<Partial<FormFileValue>>) { //taking a partial so we can do a better job at fixing missing fields from incorrect callers\n    //updates the value but does not fire events/refresh()\n    const toset: FormFileValue[] = [];\n\n    for (const row of value) {\n      if (row?.file) {\n        if (!this._isAcceptableType(row.file.type))\n          throw new Error(`File type ${row.file.type} is not acceptable for ${getFieldDisplayName(this)}`);\n        toset.push({ fileName: row.fileName || row.file.name, file: row.file, link: null });\n      } else if (row?.link) {\n        toset.push({ fileName: row.fileName || \"\", file: null, link: row.link });\n      } else {\n        throw new Error(`Incorrect value type received for ${getFieldDisplayName(this)} - expect 'file' or 'link' to be set`);\n      }\n\n      if (toset.length >= this.maxFiles)\n        break;\n    }\n    this.currentFiles = toset;\n  }\n\n  _isAcceptableType(mimetype: string) {\n    const accept = this.getAttribute(\"accept\")?.split(',').map(mask => mask.trim()) ?? [];\n    return !accept.length || isAcceptableType(mimetype, accept);\n  }\n\n  private doDrop(evt: DragEvent) {\n    //FIXME check 'accept' - or can the drag handlers do that?\n    evt.preventDefault();\n\n    const files = evt.dataTransfer?.files;\n    if (files)\n      this.processUpload(files[0]);\n  }\n\n  async uploadFile(evt: Event) {\n    evt.preventDefault();\n\n    if (this.disabled || this.currentFiles.length >= this.maxFiles)\n      return; //should not even have been offered?\n\n    const accept = this.getAttribute(\"accept\")?.split(',') ?? [];\n    using lock = dompack.flagUIBusy();\n    void (lock);\n\n    const file = await requestFile({ accept });\n    if (!file)\n      return;\n\n    await this.processUpload(file);\n  }\n\n  private async processUpload(file: File) {\n    if (this.disabled || this.currentFiles.length >= this.maxFiles)\n      return; //should not even have been offered?\n\n    if (!this._isAcceptableType(file.type)) {\n      //TODO tell server it can destroy the file immediately (should have told uploadsession at the start?\n      const msg = this.dataset.whAccepterror || getTid(\"publisher:site.forms.commonerrors.badfiletype\");\n      setFieldError(this, msg, { reportimmediately: true });\n      return;\n    }\n\n    this.currentFiles.push({ fileName: file.name, file: file, link: null });\n    this.refresh();\n    dompack.dispatchCustomEvent(this, 'change', { bubbles: true, cancelable: false });\n  }\n\n  protected deleteFile(evt: Event, idx: number) {\n    if (evt)\n      dompack.stop(evt);\n\n    this.currentFiles.splice(idx, 1);\n    this.refresh();\n    dompack.dispatchCustomEvent(this, 'change', { bubbles: true, cancelable: false });\n  }\n\n  protected setupUploadButton(button: HTMLElement) {\n    button.addEventListener(\"click\", evt => void this.uploadFile(evt));\n  }\n\n  protected setupDeleteButton(button: HTMLElement, idx: number) {\n    button.addEventListener(\"click\", evt => this.deleteFile(evt, idx));\n    button.ariaLabel = getTid(\"publisher:site.forms.imgedit-remove\");\n  }\n}\n","// Auto-generated language file from /opt/wh/whtree/modules/publisher/js/forms/internal/form.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"publisher\",\"nl\",{\"site\":{\"forms\":{\"imgedit-explain-upload\":\"Sleep bestanden hier of klik om te uploaden\",\"imgedit-groupelement-replace\":[1,\", Vervang afbeelding\"],\"imgedit-groupelement-upload\":[1,\", Upload afbeelding\"],\"imgedit-remove\":\"Verwijder afbeelding\",\"nextpage\":\"Volgende\",\"previouspage\":\"Vorige\",\"selectfile\":\"Selecteer bestand\",\"splitdatetime-day-arialabel\":\"dag\",\"splitdatetime-hours-arialabel\":\"uur\",\"splitdatetime-minutes-arialabel\":\"minuut\",\"splitdatetime-month-arialabel\":\"maand\",\"splitdatetime-seconds-arialabel\":\"seconde\",\"splitdatetime-year-arialabel\":\"jaar\",\"starsrequired\":\"* betekent dat een veld verplicht is\",\"submit\":\"Versturen\",\"upload-emptytext\":\"Geen bestand geselecteerd\",\"upload-filename\":[\"Geselecteerde bestand is \",1],\"upload-remove\":\"Verwijder bestand\",\"addressfield\":{\"address_not_found\":\"Het adres kon niet worden gevonden.\",\"invalid_nr_detail\":\"Ongeldig huisnummer.\",\"invalid_zip\":\"Ongeldige postcode.\",\"zip_not_found\":\"Combinatie van postcode en huisnummer komt niet voor.\"},\"commonerrors\":{\"alphanum\":\"De waarde moet alfanumeriek zijn.\",\"badfiletype\":\"Dit bestandstype is niet toegestaan\",\"check\":[\"Kies minimaal \",1,\" en maximaal \",2,\" items.\"],\"date\":\"Dit is geen geldige datum.\",\"default\":\"Deze waarde is onjuist.\",\"digits\":\"De waarde moet numeriek zijn.\",\"email\":\"Dit is geen geldig e-mailadres.\",\"email_baddomain\":[\"Vanwege problemen met het e-mailen naar \",1,\" e-mailadressen, willen we je vragen om een alternatief e-mailadres te gebruiken.\"],\"email_suggestion\":[\"Bedoel je \",1,\"?\"],\"equalto\":\"De waardes moeten identiek zijn.\",\"formunavailable\":\"Dit formulier is momenteel niet beschikbaar\",\"integer\":\"De waarde moet een nummer zijn.\",\"length\":[\"De waarde moet tussen \",1,\" en \",2,\" karakters lang zijn.\"],\"max\":[\"De waarde mag niet groter zijn dan \",1,\".\"],\"maxarray\":[\"U kunt maximaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 onderdeel\"],\"subselse\":[1,\" onderdelen\"]},\" toevoegen.\"],\"maxcheck\":[\"Kies maximaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 item\"],\"subselse\":[1,\" items\"]},\".\"],\"maxheight\":[\"De afbeelding is te groot. Deze mag maximaal \",2,\" pixels hoog zijn.\"],\"maxlength\":[\"De waarde is te lang. Deze mag maximaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 karakter\"],\"subselse\":[1,\" karakters\"]},\" lang zijn.\"],\"maxwidth\":[\"De afbeelding is te groot. Deze mag maximaal \",2,\" pixels breed zijn.\"],\"min\":[\"De waarde mag niet lager zijn dan \",1,\".\"],\"minarray\":[\"U moet minimaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 onderdeel\"],\"subselse\":[1,\" onderdelen\"]},\" toevoegen.\"],\"mincheck\":[\"Kies minimaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 item\"],\"subselse\":[1,\" items\"]},\".\"],\"minheight\":[\"De afbeelding is te klein. Deze moet minimaal \",2,\" pixels hoog zijn.\"],\"minlength\":[\"De tekst is te kort. Deze moet uit minimaal \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 karakter\"],\"subselse\":[1,\" karakters\"]},\" bestaan.\"],\"minwidth\":[\"De afbeelding is te klein. Deze moet minimaal \",2,\" pixels breed zijn.\"],\"notblank\":\"De waarde mag niet leeg zijn.\",\"number\":\"De waarde moet een nummer zijn.\",\"pattern\":\"De waarde is onjuist.\",\"range\":[\"De waarde moet tussen \",1,\" en \",2,\" liggen.\"],\"required\":\"Dit veld is verplicht.\",\"step1mismatch\":\"De waarde moet een geheel getal zijn\",\"stepmismatch\":[\"De waarde moet een meervoud zijn van \",1,\".\"],\"time\":\"Dit is geen geldige tijd.\",\"unacceptableemail\":\"Dit e-mailadres is hier niet toegestaan\",\"upload_cannotcheck\":\"Dit bestand kan niet geüpload worden omdat we het momenteel niet kunnen verifiëren\",\"upload_suspicious\":\"Dit bestand ziet er verdacht uit en kan helaas niet geüpload worden\",\"url\":\"Dit is geen geldige URL.\"}}}});\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/nl.xml\n","/* import ImgEditField from '@mod-publisher/js/forms/fields/imgedit';\n*/\nimport * as dompack from '@webhare/dompack';\nimport { FileEditElement } from './fileeditbase';\nimport { emplace } from '@webhare/std';\nimport { getTid } from '@webhare/gettid';\nimport { getFileAsDataURL } from '@webhare/upload';\nimport { setFieldError } from '@mod-publisher/js/forms/internal/customvalidation';\n\nlet revoker: FinalizationRegistry<string> | undefined;\nconst cachedURLs = new WeakMap<File, string>();\n\nfunction createFileURL(file: File): string {\n  return emplace(cachedURLs, file, {\n    insert: () => {\n      const newurl = URL.createObjectURL(file);\n      //setup a finalizer to revoke object urls\n      revoker ||= new FinalizationRegistry<string>((oldurl) => URL.revokeObjectURL(oldurl));\n      //as soon as file is lost to us\n      revoker.register(file, newurl);\n      return newurl;\n    }\n  });\n}\n\nasync function getImageDimensions(file: File): Promise<{ width: number; height: number }> {\n  const img = await dompack.loadImage(await getFileAsDataURL(file));\n  return { width: img.naturalWidth, height: img.naturalHeight };\n}\n\ninterface ImgEditTexts {\n  explainUpload?: string;\n}\n\nexport class ImgEditElement extends FileEditElement {\n  static observedAttributes = [\"min-width\", \"max-width\", \"min-height\", \"max-height\"];\n\n  private static texts: ImgEditTexts | null = null;\n\n  minWidth: number;\n  maxWidth: number;\n  minHeight: number;\n  maxHeight: number;\n\n  constructor() {\n    super();\n    // this.addEventListener(\"keypress\", evt => this.checkForUploadOrClear(evt)); // handle space+enter to active\n\n    this.maindiv.classList.add(\"images\");\n\n    this.minWidth = parseInt(this.getAttribute(\"min-width\") || \"0\") || 0;\n    this.maxWidth = parseInt(this.getAttribute(\"max-width\") || \"0\") || 0;\n    this.minHeight = parseInt(this.getAttribute(\"min-height\") || \"0\") || 0;\n    this.maxHeight = parseInt(this.getAttribute(\"max-height\") || \"0\") || 0;\n\n    this.refresh();\n  }\n\n  attributeChangedCallback(name: string, _oldValue: string, newValue: string) {\n    const value = parseInt(newValue);\n    if (isNaN(value))\n      return;\n    switch (name) {\n      case \"min-width\": {\n        this.minWidth = value;\n        break;\n      }\n      case \"max-width\": {\n        this.maxWidth = value;\n        break;\n      }\n      case \"min-height\": {\n        this.minHeight = value;\n        break;\n      }\n      case \"max-height\": {\n        this.maxHeight = value;\n        break;\n      }\n    }\n  }\n\n  static setTexts(textupdate: ImgEditTexts) {\n    if (!ImgEditElement.texts)\n      ImgEditElement.texts = {};\n\n    Object.assign(ImgEditElement.texts, textupdate);\n    dompack.qSA<ImgEditElement>(\"wh-imgedit\").forEach(node => node.refresh()); //update any existing nodes\n  }\n\n  async _check() {\n    const error = await super._check();\n    if (!error && this.isSet() && (this.minWidth || this.maxWidth || this.minHeight || this.maxHeight)) {\n      for (const file of this.currentFiles) {\n        if (file.file) {\n          const size = await getImageDimensions(file.file);\n          if (this.minWidth && size.width < this.minWidth)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.minwidth\", size.width, this.minWidth), { reportimmediately: false });\n          else if (this.maxWidth && size.width > this.maxWidth)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.maxwidth\", size.width, this.maxWidth), { reportimmediately: false });\n          else if (this.minHeight && size.height < this.minHeight)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.minheight\", size.height, this.minHeight), { reportimmediately: false });\n          else if (this.maxHeight && size.height > this.maxHeight)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.maxheight\", size.height, this.maxHeight), { reportimmediately: false });\n        }\n      }\n    }\n    return error;\n  }\n\n  refresh() {\n    const nodes = [];\n    for (const [idx, file] of this.currentFiles.entries()) {\n      const imgholder = dompack.create(\"div\", { class: \"image\", part: \"image\" });\n      const img = dompack.create(\"img\", { class: 'image__img', src: file.link ?? createFileURL(file.file) });\n\n      const deletebutton = dompack.create(\"button\", { part: \"button deletebutton\", class: \"deletebutton image__deletebutton\" });\n      this.setupDeleteButton(deletebutton, idx);\n\n      imgholder.append(img, deletebutton);\n      nodes.push(imgholder);\n    }\n\n    if (this.currentFiles.length < this.maxFiles) {\n      //add an extra 'image' which is the placeholder for additional uploads\n      const imgholder = dompack.create(\"div\", { class: \"image image--placeholder\", part: \"image placeholder\" });\n      const contentwrapper = dompack.create(\"div\", { class: \"image__content\" });\n      const uploadicon = dompack.create(\"div\", { class: \"image__uploadicon\", part: \"uploadicon\" });\n      const explain = dompack.create(\"div\", {\n        class: \"image__explain\",\n        textContent: ImgEditElement.texts?.explainUpload || getTid(\"publisher:site.forms.imgedit-explain-upload\")\n      });\n      imgholder.append(contentwrapper);\n      contentwrapper.append(uploadicon, explain);\n      imgholder.tabIndex = 0;\n      this.setupUploadButton(imgholder);\n      nodes.push(imgholder);\n    }\n\n    /* FIXME aria label, currently set at group level, should be per image?\n\n          // Set the aria-label to a combined label of the field together with the action which activating it through click/enter/space will perform\n          this.node.setAttribute(\"aria-label\", getTid(\"publisher:site.forms.imgedit-groupelement-upload\", this.node.dataset.arialabel));\n\n                    // Set the aria-label to a combined label of the field together with the action which activating it through click/enter/space will perform\n          this.node.setAttribute(\"aria-label\", getTid(\"publisher:site.forms.imgedit-groupelement-replace\", this.node.dataset.arialabel));\n*/\n\n    this.maindiv.replaceChildren(...nodes);\n  }\n}\n\n//////// Legacy version. We expect existing users to migrate to the version above\n\nexport default class ImgEditField {\n  constructor(node: HTMLElement) {\n    if (!customElements.get(\"wh-imgedit\"))\n      customElements.define(\"wh-imgedit\", ImgEditElement);\n  }\n}\n","import FormBase from '@mod-publisher/js/forms/rpc';\nimport type { FormConfiguration, FormHandlerFactory } from \"@webhare/forms\";\nimport { dispatchCustomEvent, flagUIBusy, qSA, register } from \"@webhare/dompack\";\nimport { emplace, sleep } from \"@webhare/std\";\nimport { downgradeUploadFields } from \"./domsupport\";\n\nlet formConfiguration: FormConfiguration | undefined;\nlet handlers: Map<string, FormHandlerFactory | PromiseWithResolvers<FormHandlerFactory>> | undefined;\nlet configuredRegistrations: true | undefined;\nconst firstWarningMs = 150, warningIntervalMs = 5000;\n\nasync function scheduleFormSetup(form: HTMLFormElement, factory: FormHandlerFactory) {\n  using lock = flagUIBusy();\n  void (lock);\n\n  //Ensure any custom elements in the form are actually registered or our communication with these elements may fail\n  const customEls = [...new Set(qSA(form, \"[name]\").map(_ => _.tagName.toLowerCase()))].filter(_ => _.includes(\"-\"));\n  if (customEls.length) {\n    const initPromise = Promise.all(customEls.map(_ => customElements.whenDefined(_))).then(() => ({ timeout: false }));\n\n    let nextWarning = Date.now() + firstWarningMs;\n    for (; ;) {\n      const timeoutPromise = sleep(new Date(nextWarning)).then(() => ({ timeout: true }));\n      const result = await Promise.race([initPromise, timeoutPromise]);\n      if (!result.timeout)\n        break;\n\n      const missing = customEls.filter(tag => !customElements.get(tag)).join(\", \");\n      if (missing === 'wh-fileedit') {\n        console.warn(`Developers: we recommend explicitly registering a component for \".wh-form__upload\"`);\n        downgradeUploadFields(form);\n        break;\n      }\n      console.warn(`Still waiting for the following custom elements to be defined in form ${form.id ?? form.dataset.whFormId}:`, missing);\n      nextWarning = Date.now() + warningIntervalMs;\n    }\n  }\n  factory(form);\n}\n\nexport function configureForms(setup: FormConfiguration) {\n  if (!Object.keys(setup).length)\n    return;\n\n  formConfiguration = { ...formConfiguration, ...setup };\n  dispatchCustomEvent(window, \"wh:form-configure\", { bubbles: true, cancelable: false, detail: formConfiguration });\n}\n\nexport function registerHandlers(addHandlers: Record<string, FormHandlerFactory>) {\n  if (!handlers) { //register initial handlers (now that form support is activated)\n    //we want to stop distinguishing between these, not worth the effort/complexity seperating  them\n    const defaultHandler = (form: HTMLFormElement) => new FormBase(form);\n    addHandlers = {\n      \"publisher:form\": defaultHandler,\n      \"publisher:rpc\": defaultHandler,\n      ...addHandlers\n    };\n    handlers = new Map;\n  }\n\n  //Configure the handlers. If there's a resolvable promise waiting for us, resolve it, otherwise directly insert the handler\n  for (const [handlername, handler] of Object.entries(addHandlers))\n    emplace(handlers, handlername, {\n      insert: () => handler,\n      update: current => {\n        if (\"promise\" in current) {\n          current.resolve(handler);\n          return current;\n        } else\n          throw new Error(`Handler '${handlername}' is already registered`);\n      }\n    });\n\n  //Set up a registration for form elements, but ensure they only go through one scheduleFormSetup ever\n  if (!configuredRegistrations) { //register for forms that have yet to appear\n    register<HTMLFormElement>(\"form[data-wh-form-handler]\", form => {\n      //Get the current handler or set up a promise that will receive the handler\n      const handler = emplace(handlers!, form.dataset.whFormHandler!, { insert: () => Promise.withResolvers<FormHandlerFactory>() });\n      if (\"promise\" in handler)\n        void handler.promise.then(factory => scheduleFormSetup(form, factory));\n      else\n        void scheduleFormSetup(form, handler);\n\n    });\n    configuredRegistrations = true;\n  }\n}\n\nexport function registerHandler(handlername: string, handler: FormHandlerFactory) {\n  registerHandlers({ [handlername]: handler });\n}\n\nexport function getFormConfiguration(): FormConfiguration | undefined {\n  return formConfiguration;\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/forms\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/forms\" {\n}\n\nimport FormBase from '@mod-publisher/js/forms/rpc';\nimport { default as LocalFormBase } from \"@mod-publisher/js/forms/formbase\"; //'FormBase', the RPC-ing one, is the one you want 99% of the time. LocalFormBase is for pure local handling (eg a PWA Config screen)\nimport { verifyAddress, type AddressValidationResult, type AddressChecks } from './address';\nimport { FileUploadFormElement as FileEditElement } from \"@mod-publisher/js/forms/fields/upload\";\nimport { ImgEditElement } from \"@mod-publisher/js/forms/fields/imgedit\";\nimport { JSFormElement } from './jsformelement';\nimport type { FormFileValue, FormAnalyticsEvent } from './types';\nimport { getFormHandler, getFormData } from './domsupport';\nimport { configureForms, registerHandlers } from './registration';\n\n/* TODO / NOTES\n  - we cannot move this file into jssdk namespace, the lang.json compiler doesn't accept paths that cannot be translated to a WH resource\n  - lang.json isn't really TS compatible, a nicer followup TS interface would allow something like\n    import myModuleTexts from \"wh:tid/mymodle\";\n    and offer intellisense (after solving the problems like \"what if a module wants to export multiple sets, how to implement HTMLTid and variables, etc\")\n  - so for now we'll hardcode importing form.lang.json so external users don't have to do this, take the treeshaking hit, and plan to move builtin texts\n    to some sort of /.wh/generated/builtin-language-texts system where we load the common builtin texts per language on demand\n*/\nimport \"@mod-publisher/js/forms/internal/form.lang.json\";\nimport { omit } from '@webhare/std';\n\nexport { FormBase, verifyAddress, ImgEditElement, FileEditElement, JSFormElement, getFormHandler, getFormData };\nexport type { FormSubmitResult } from \"@mod-publisher/js/forms/formbase\";\nexport { buildRPCFormSubmission as buildFormSubmission, submitRPCForm as submitForm } from \"@mod-publisher/js/forms/rpc\";\nexport type { RPCFormSubmission as FormSubmission } from \"./types\";\nexport type { AddressValidationResult, AddressChecks, FormFileValue, FormAnalyticsEvent };\nexport { DateField, TimeField } from \"@mod-publisher/js/forms/fields/datetime\";\nexport { registerHandler } from \"./registration\";\nexport { setupGoogleRecaptcha } from \"@mod-publisher/js/captcha/google-recaptcha\";\nexport { setupFriendlyCaptcha } from \"./friendly-captcha\";\nexport { setupValidator } from \"@mod-publisher/js/forms/internal/customvalidation\";\nexport { LocalFormBase };\n\nexport type FormHandlerFactory = (form: HTMLFormElement) => LocalFormBase;\n\nexport type FormConfiguration = {\n  captcha?: \"onLoad\" | \"onActivate\";\n};\n\nexport type FormSetupOptions = FormConfiguration & {\n  handlers: Record<string, FormHandlerFactory>;\n};\n\n/// Initialize all forms we already have the handler for\nexport function setupForms(options?: Partial<FormSetupOptions>) {\n  registerHandlers(options?.handlers ?? {});\n  if (options)\n    configureForms(omit(options, [\"handlers\"]));\n}\n","/// @ts-nocheck -- Bulk rename to enable TypeScript validation\n\nimport * as dompack from \"dompack\";\nimport * as datehelpers from \"../internal/datehelpers\";\nimport Keyboard from 'dompack/extra/keyboard';\nimport DatePicker from '@mod-publisher/js/forms/internal/datepicker';\n\nimport { __setUnderlyingValue, setupMyValueProperty } from \"../internal/datetime-valueprops\";\nimport { getTid } from \"@webhare/gettid\";\nimport { getLang } from \"@webhare/dompack\";\nexport { __setUnderlyingValue } from \"../internal/datetime-valueprops\";\n\n/*\nReplaces date/time inputs into separate number type inputs\nField ordering can be set by data attribute data-dateformat\n\nnice to have:\n - placeholder translations\n - Field ordering by localization\n*/\n\ninterface MultiInputSubstitionOptions {\n  baseclass: string;\n}\n\nabstract class MultiInputSubstition {\n  protected _replacednode: HTMLInputElement;\n  protected placeholders: Record<string, string> = {};\n  options: MultiInputSubstitionOptions;\n\n  constructor(inpnode: HTMLInputElement, options: Partial<MultiInputSubstitionOptions>) {\n    this.options = {\n      baseclass: 'datetime',\n      ...options\n    };\n\n    this._baseclass = this.options.baseclass;\n    this._replacednode = inpnode;\n    this._replacednode._split_doupdate = () => this._split_doupdate();\n    this._replacednode.classList.add(this._baseclass + '--replaced');\n    this._replacednode.setAttribute(\"tabindex\", \"-1\"); //disable focus by tabbing replaced field\n    this._replacednode.addEventListener('change', () => this._onOriginalChange());\n\n    if (window.MutationObserver) {\n      const _observer = new MutationObserver(() => this._onObserve());\n      _observer.observe(this._replacednode, { attributes: true, attributeFilter: ['disabled', 'required', 'class'], subtree: false, childList: false });\n    }\n\n    this._nodes = {};\n    setupMyValueProperty(this._replacednode);\n  }\n  _onOriginalChange() { //capture browser initiated changes (they don't go through our value property)\n    if (this._replacednode.value === this._lastsetvalue)\n      return;\n\n    this._lastsetvalue = this._replacednode.value;\n    this._refreshReplacingFields();\n  }\n  _onBlur(field) {\n    if (!isNaN(parseInt(field.value)))\n      field.value = ('000' + parseInt(field.value)).slice(-this._getFieldTextLength(field));\n  }\n  _onReset(evt) {\n    dompack.stop(evt);\n    if (this._replacednode.disabled)\n      return;\n\n    this._replacednode.value = '';\n    dompack.dispatchDomEvent(this._replacednode, 'input');\n    dompack.dispatchDomEvent(this._replacednode, 'change');\n  }\n  _handlePastedValue(inval) {\n    return false;\n  }\n  protected _onInput(field: HTMLInputElement | null) {\n    //now with EARLY focus\n    //FIXME cleanup field first?\n    //FIXME determine whether to use NUMBER of TEL.\n    // if(field && field.input.length === )\n    if (!field)\n      return false;\n\n    if (this._handlePastedValue(field.value)) {\n      this._refreshReplacingFields();\n      return true;\n    }\n\n    const maxlength = this._getFieldTextLength(field);\n    if (field.value.length >= maxlength) {\n      const nextfield = this._getNextField(field);\n      if (nextfield) {\n        dompack.focus(nextfield);\n\n        if (field.value.length > maxlength) { //copy over remaining contents\n          nextfield.value = field.value.substr(maxlength);\n          field.value = field.value.substr(0, maxlength);\n          dompack.dispatchDomEvent(nextfield, 'input');\n          return true; //the next field's _onInput will deal with all the normal validations\n        }\n      }\n    }\n    return false;\n  }\n  protected getLanguageCode() {\n    return getLang(this._replacednode).language;\n  }\n\n  _finalize() {\n    this._refreshAttributes();\n    this._refreshReplacingFields();\n\n    this._controlsnode = <span class={`${this._baseclass}__controls`}></span>;\n    this._inputgroup.appendChild(this._controlsnode);\n    dompack.after(this._replacednode, this._inputgroup);\n\n    this._inputgroup.addEventListener(\"input\", ev => this._onInput(ev.target), true);\n    this._inputgroup.addEventListener(\"focus\", ev => this._onFocus(ev.target), true);\n    this._inputgroup.addEventListener('blur', evt => this._onBlur(evt.target), true);\n\n    new Keyboard(this._inputgroup, {\n      \"ArrowDown\": (evt) => this._trySpin(evt, -1),\n      \"ArrowUp\": (evt) => this._trySpin(evt, +1),\n      \"ArrowLeft\": (evt) => this._arrowHorizontal(evt, -1),\n      \"ArrowRight\": (evt) => this._arrowHorizontal(evt, +1),\n      \"Backspace\": (evt) => this._handleBackspace(evt)\n    }, {\n      captureunsafekeys: true,\n      onkeypress: (evt, key) => this._onKeyPress(evt, key)\n    });\n\n  }\n  _constructPart(partname, options) {\n    return dompack.create(\"input\", {\n      className: `${this._baseclass}__part ${this._baseclass}__${partname}`,\n      pattern: \"[0-9]*\",\n      inputmode: \"numeric\",\n      autocomplete: \"off\",\n      placeholder: this.placeholders[partname],\n      type: \"tel\", //we need 'tel' for fine selection control, we can't control selectionStart/End of a type=number\n      ...options\n    });\n  }\n  _onObserve() {\n    this._refreshAttributes();\n  }\n\n  _split_doupdate() {\n    this._refreshReplacingFields();\n    if (this._currentdatepicker)\n      this._currentdatepicker.readDateNode();\n  }\n\n  _refreshAttributes() {\n    const isdisabled = this._replacednode.disabled;\n    const isrequired = this._replacednode.required;\n\n    dompack.toggleClass(this._inputgroup, this._baseclass + '--disabled', isdisabled);\n    dompack.toggleClass(this._inputgroup, this._baseclass + '--required', isrequired);\n    this._getSubInputs().forEach(node => { node.disabled = isdisabled; node.required = isrequired; });\n  }\n\n  _getSubInputs() {\n    throw new Error(\"Override!\");\n  }\n\n  _setReplacedValue(setvalue) {\n    if (setvalue !== this._lastsetvalue) {\n      __setUnderlyingValue(this._replacednode, setvalue); //direct update to prevent it from rewriting our fields\n      this._lastsetvalue = setvalue;\n\n      //TODO would be more correct to fire 'input' on any value change, but 'change' only on calendar pick OR blur\n      dompack.dispatchDomEvent(this._replacednode, 'input');\n      dompack.dispatchDomEvent(this._replacednode, 'change');\n    }\n  }\n\n  _onFocus(field) {\n    if (this._getSubInputs().indexOf(field) >= 0) //one of our handled fields\n      field.select(); //select contents fully on focus, makes it easier to start typing new values\n  }\n\n  _trySpin(evt, change) {\n    const field = evt.target;\n    const nodeidx = this._getSubInputs().indexOf(field);\n    if (nodeidx < 0) //not one of our inputs\n      return; //not handling!\n\n    dompack.stop(evt);\n    if (this._spinNode(field, nodeidx, change))\n      this._onInput(null);\n    return true;\n  }\n\n  _arrowHorizontal(evt, dir) {\n    const field = evt.target;\n\n    if ((field.selectionStart !== field.selectionEnd) //theres a selection, let the browser deal with that\n      || (dir < 0 && field.selectionStart > 0) //not at the left edge\n      || (dir > 0 && field.selectionEnd < field.value.length)) // not at the right edge\n      return;\n\n    dompack.stop(evt);\n\n    const subinputs = this._getSubInputs();\n    const gotofield = subinputs[subinputs.indexOf(field) + dir];\n    if (gotofield) {\n      dompack.focus(gotofield);\n      gotofield.selectionEnd = gotofield.selectionStart = dir > 0 ? 0 : gotofield.value.length;\n    }\n  }\n\n  _onKeyPress(evt, key) {\n    if ((key >= '0' && key <= '9') || key.length > 1) //digit or special key\n      return true;\n    dompack.stop(evt);\n  }\n\n  _handleBackspace(evt) {\n    const field = evt.target;\n    const nodeidx = this._getSubInputs().indexOf(field);\n    if (nodeidx <= 0) //not one of our fields, or the first (where we can't go back anywhere)\n      return false; //not handling\n\n    if (field.selectionEnd > 0) //selection does not include the left side of the field\n      return false;\n\n    //remove selection, if any (we're a \"backspace\" after all)\n    dompack.stop(evt);\n    field.value = field.value.substr(0, field.selectionStart) + field.value.substr(field.selectionEnd);\n\n    const prevfield = this._getSubInputs()[nodeidx - 1];\n    dompack.focus(prevfield);\n    if (prevfield.value.length > 0) //do a backspace in the previous field as if we were one\n      prevfield.value = prevfield.value.substr(0, prevfield.value.length - 1);\n\n    prevfield.selectionEnd = prevfield.selectionStart = prevfield.value.length;\n    return true;\n  }\n}\n\nexport interface DateFieldOptions extends MultiInputSubstitionOptions {\n  placeholders: {\n    year: string;\n    month: string;\n    day: string;\n  };\n  datepicker: boolean;\n  resetcontrol: boolean;\n  weeknumbers: boolean;\n}\n\nexport class DateField extends MultiInputSubstition {\n  declare options: DateFieldOptions;\n\n  constructor(inpnode: HTMLInputElement, options?: Partial<DateFieldOptions>);\n  /** @deprecated You should ensure the inputnode is a HTMLInputElement */\n  constructor(inpnode: HTMLElement, options?: Partial<DateFieldOptions>);\n\n  constructor(inpnode: HTMLInputElement, options?: Partial<DateFieldOptions>) {\n    options = {\n      datepicker: true,\n      resetcontrol: true,\n      weeknumbers: false,\n      ...options\n    };\n\n    super(inpnode, options);\n    if (!this._replacednode)\n      return;\n\n    this.placeholders = this.options.placeholders ?? (this.getLanguageCode()?.startsWith('nl') ? { year: \"jjjj\", month: \"mm\", day: \"dd\" } : { year: \"yyyy\", month: \"mm\", day: \"dd\" });\n    this.previous = { value: '' };\n\n    const dateformat = inpnode.dataset.format || \"d-m-y\";\n    const parseddate = dateformat.match(/^([dmy])([^dmy]*)([dmy])([^dmy]*)([dmy])$/);\n    if (!parseddate)\n      throw new Error(`Unrecognized date format '${dateformat}'`);\n\n    this._inputgroup = <span class={`${this._baseclass} ${this._baseclass}__date`}>\n      {this._constructDatePart(parseddate[1])}\n      <span class={`${this._baseclass}__sep`}>{parseddate[2]}</span>\n      {this._constructDatePart(parseddate[3])}\n      <span class={`${this._baseclass}__sep`}>{parseddate[4]}</span>\n      {this._constructDatePart(parseddate[5])}\n    </span>;\n\n    this._nodes.day.min = 1;\n    this._nodes.day.max = 31;\n    this._nodes.month.min = 1;\n    this._nodes.month.max = 12;\n\n    if (this._replacednode.min !== \"\") { //Should be iso date\n      const minyear = this._replacednode.min.split(/[^0-9]+/)[0];\n      if (minyear !== \"\")\n        this._nodes.year.min = minyear;\n    }\n\n    if (this._replacednode.max !== \"\") { //Should be iso date\n      const maxyear = this._replacednode.max.split(/[^0-9]+/)[0];\n      if (maxyear !== \"\")\n        this._nodes.year.max = maxyear;\n    }\n\n    this._finalize();\n\n    if (this.options.datepicker) {\n      this._datepickercontrol = <span class={`${this._baseclass}__togglepicker`}></span>;\n      this._datepickercontrol.addEventListener(\"click\", evt => this._onDatePickerClick(evt));\n      this._controlsnode.appendChild(this._datepickercontrol);\n    }\n    if (this.options.resetcontrol) {\n      this._resetcontrol = <span class={`${this._baseclass}__reset`}></span>;\n      this._resetcontrol.addEventListener(\"click\", evt => this._onReset(evt));\n      this._controlsnode.appendChild(this._resetcontrol);\n    }\n  }\n\n  _onDatePickerClick(evt) {\n    dompack.stop(evt);\n\n    if (this._currentdatepicker || this._replacednode.disabled)\n      return;\n    this._currentdatepicker = new DatePicker(this);\n  }\n  __closedDatepicker() {\n    this._currentdatepicker = null;\n\n    //return focus to last replacement input (so if using tab you go to next field)\n    const inplst = this._inputgroup.querySelectorAll(\"input\");\n    if (inplst.length)\n      inplst[inplst.length - 1].focus();\n  }\n\n  _constructDatePart(which) {\n    const partname = { d: \"day\", m: \"month\", y: \"year\" }[which];\n    if (this._nodes[partname])\n      throw new Error(`Duplicate '${partname}' node`);\n\n    this._nodes[partname] = this._constructPart(partname, { maxlength: partname === \"year\" ? 4 : 2 });\n    return this._nodes[partname];\n  }\n\n  _getSubInputs() {\n    return [this._nodes.day, this._nodes.month, this._nodes.year];\n  }\n\n  _setDateByParts(parts) {\n    this._nodes.day.value = ('0' + parts.day).substr(-2);\n    this._nodes.month.value = ('0' + parts.month).substr(-2);\n    this._nodes.year.value = ('000' + parts.year).substr(-4);\n  }\n\n  _refreshReplacingFields() {\n    this._lastsetvalue = this._replacednode.value;\n\n    if (this._replacednode.value) { //Should be iso date\n      this._currentdate = datehelpers.parseISODate(this._replacednode.value, { nofail: true });\n      if (this._currentdate) {\n        this._setDateByParts(this._currentdate);\n        return;\n      }\n    }\n    this._nodes.day.value = \"\";\n    this._nodes.month.value = \"\";\n    this._nodes.year.value = \"\";\n  }\n\n  _getFieldTextLength(field) {\n    return field === this._nodes.year ? 4 : 2;\n  }\n  _getNextField(field) {\n    return field === this._nodes.day ? this._nodes.month\n      : field === this._nodes.month ? this._nodes.year\n        : null;\n\n  }\n\n  _getCurrentAsISODate() {\n    let year = parseInt(this._nodes.year.value, 0);\n    const month = parseInt(this._nodes.month.value, 0);\n    const day = parseInt(this._nodes.day.value, 0);\n\n    if (year >= 0 && year <= 99 && this._replacednode.dataset.shortyearcutoff !== \"\") {\n      const cutoff = parseInt(this._replacednode.dataset.shortyearcutoff);\n      if (year < cutoff) //to do someday.. current century might not be 2000 anymore\n        year += 2000;\n      else\n        year += 1900;\n    }\n\n    return datehelpers.formatISODate(year, month, day);\n  }\n\n  _spinNode(node, nodeidx, change) {\n    const isodate = this._getCurrentAsISODate();\n    if (!isodate)\n      return; //not sure what to do with a corrupt\n\n    let newdate = new Date(isodate);\n    if (node === this._nodes.day) {\n      newdate = new Date(Number(newdate) + (change * 86400000));\n    } else if (node === this._nodes.month) {\n      newdate.setUTCMonth(newdate.getUTCMonth() + change);\n    } else if (node === this._nodes.year) {\n      newdate.setUTCFullYear(newdate.getUTCFullYear() + change);\n    } else {\n      return;\n    }\n\n    this._setReplacedValue(datehelpers.formatJSUTCISODate(newdate));\n    this._split_doupdate();\n    return true;\n  }\n\n  _handlePastedValue(inval) {\n    //if we're spotting a xx-xx-xx or xx/xx/xx pattern, assume a paste\n    const is_dashed = inval.match(/.+-.+-.+/);\n    const is_slashed = inval.match(/.+\\/.+\\/.+/);\n    if (is_dashed || is_slashed) {\n      const parseddate = datehelpers.parseDate('d-m-y', inval, { nofail: true });\n      if (parseddate) {\n        this._setReplacedValue(datehelpers.formatISODate(parseddate.year, parseddate.month, parseddate.day));\n        this._refreshReplacingFields();\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private getInputValues() {\n    return {\n      year: this._nodes.year.value,\n      month: this._nodes.month.value,\n      day: this._nodes.day.value\n    };\n  }\n\n  _onInput(field: HTMLInputElement | null) {\n    if (super._onInput(field))\n      return true;\n\n    const fields = this.getInputValues();\n    if (!fields.year && !fields.month && !fields.day) { //full field clear\n      this._replacednode.setCustomValidity('');\n      this._setReplacedValue(\"\");\n      return;\n    }\n\n    let year = parseInt(fields.year, 0);\n    const month = parseInt(fields.month, 0);\n    const day = parseInt(fields.day, 0);\n\n    if (year >= 0 && year <= 99 && this._replacednode.dataset.shortyearcutoff !== \"\") {\n      const cutoff = parseInt(this._replacednode.dataset.shortyearcutoff);\n      if (year < cutoff) //TODO current century might not be 2000 anymore\n        year += 2000;\n      else\n        year += 1900;\n    }\n\n    const finaldate = datehelpers.formatISODate(year, month, day);\n    this._replacednode.setCustomValidity(finaldate ? \"\" : getTid(\"publisher:site.forms.commonerrors.date\"));\n    this._setReplacedValue(finaldate);\n    return true;\n  }\n\n  _onKeyPress(evt, key) {\n    if (key === '-' || key === '/') {\n      const nextfield = this._getNextField(evt.target);\n      if (nextfield)\n        dompack.focus(nextfield);\n      return false;\n    }\n    return super._onKeyPress(evt, key);\n  }\n\n  /*\n    onKeyUp( ev, node )\n    {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      let prevval = this.previous.value;\n      this.previous.value = node.value;\n\n      if( ev.keyCode === 8 && node.value === \"\" && prevval === \"\" )//backspace\n      {\n        //Try to set focus on previous input\n        let prevnode = node.parentNode.previousSibling;\n        if( prevnode )\n        {\n          let previnp = prevnode.querySelector(\"input\");\n          if( previnp )\n            previnp.focus();\n        }\n\n        return;\n      }\n\n      //First some basic validation\n      let value = node.value.replace(/[^0-9]+/g,'');\n\n      if( value === \"\" || value !== node.value || 1*value < 1*node.min || 1*value > 1*node.max )\n        return;\n\n      //Is field value minimal length\n      if( (node === this.yearnode && value.length < 4) || (node !== this.yearnode && value.length < 2) )\n        return;\n\n      if( prevval === node.value )\n          return;//Only go to next input if value changed\n\n      //Try to set focus on next input\n      let nextnode = node.parentNode.nextSibling;\n      if( !nextnode )\n        return;\n\n      let nextinp = nextnode.querySelector(\"input\");\n      if( nextinp )\n        nextinp.focus();\n    }\n  */\n\n  _onReset(evt) {\n    this.closePicker();\n    super._onReset(evt);\n  }\n\n  //-------- PUBLIC API ---------------\n  closePicker() { //close any open date picker\n    if (this._currentdatepicker)\n      this._currentdatepicker._dismissOverlay();\n  }\n}\n\nexport interface TimeFieldOptions extends MultiInputSubstitionOptions {\n  placeholders: {\n    hour: string;\n    minute: string;\n    second: string;\n    msec: string;\n  };\n  resetcontrol: boolean;\n}\n\nexport class TimeField extends MultiInputSubstition {\n\n  constructor(inpnode: HTMLInputElement, options?: Partial<TimeFieldOptions>);\n  /** @deprecated You should ensure the inputnode is a HTMLInputElement */\n  constructor(inpnode: HTMLElement, options?: Partial<TimeFieldOptions>);\n\n  constructor(inpnode: HTMLInputElement, options?: Partial<TimeFieldOptions>) {\n    options = {\n      resetcontrol: true,\n      ...options\n    };\n\n    super(inpnode, options);\n    if (!this._replacednode)\n      return;\n\n    this.placeholders = this.options.placeholders ?? (this.getLanguageCode() === 'nl' ? { hour: \"uu\", minute: \"mm\", second: \"ss\", msec: \"mmm\" } : { hour: \"hh\", minute: \"mm\", second: \"ss\", msec: \"mmm\" });\n    const step = parseFloat(this._replacednode.getAttribute(\"step\") || '0');\n    this.previous = { value: '' };\n    this._showmsec = step !== Math.floor(step); //fraction\n    this._showsecond = this._showmsec || (step % 60 !== 0); //unable to round to minute... so seconds\n\n    this._inputgroup = <span class={`${this._baseclass} ${this._baseclass}__time`}>\n      {this._constructTimePart(\"hour\")}\n      <span class={`${this._baseclass}__sep`}>:</span>\n      {this._constructTimePart(\"minute\")}\n    </span>;\n\n    this._nodes.hour.max = 23;\n    this._nodes.minute.max = 59;\n\n    if (this._showsecond) {\n      this._inputgroup.appendChild(<span class={`${this._baseclass}__sep`}>:</span>);\n      this._inputgroup.appendChild(this._constructTimePart(\"second\"));\n      this._nodes.second.max = 59;\n    }\n    if (this._showmsec) {\n      this._inputgroup.appendChild(<span class={`${this._baseclass}__sep`}>.</span>);\n      this._inputgroup.appendChild(this._constructTimePart(\"msec\"));\n      this._nodes.msec.max = 999;\n    }\n\n    this._finalize();\n\n    if (this.options.resetcontrol) {\n      this._resetcontrol = <span class={`${this._baseclass}__reset`}></span>;\n      this._resetcontrol.addEventListener(\"click\", evt => this._onReset(evt));\n      this._controlsnode.appendChild(this._resetcontrol);\n    }\n  }\n\n  _spinNode(node, nodeidx, change) {\n    let newval = (parseInt(node.value) || 0) + change;\n    const max = parseInt(node.getAttribute(\"max\"));\n\n    if (newval < 0 || newval > max) {\n      if (nodeidx === 0) //already at top level, no wrapping..\n        return false;\n\n      newval = change < 0 ? max : 0; //wrap it!\n      if (nodeidx > 0) //spin higher node too\n        if (!this._spinNode(this._getSubInputs()[nodeidx - 1], nodeidx - 1, change))\n          return false;\n    }\n\n    //Cannot use dompack.changeValue here as we need to explicitly tell onInput not to move the next field\n    node.value = ('000' + newval).slice(nodeidx === 3 ? -3 : -2);\n    return true;\n  }\n\n  _constructTimePart(partname) {\n    if (this._nodes[partname])\n      throw new Error(`Duplicate '${partname}' node`);\n\n    this._nodes[partname] = this._constructPart(partname, {\n      maxlength: partname === 'msec' ? 3 : 2,\n      min: \"0\"\n    });\n\n    return this._nodes[partname];\n  }\n\n  _refreshReplacingFields() {\n    this._lastsetvalue = this._replacednode.value;\n\n    const time = datehelpers.parseISOTime(this._replacednode.value, { nofail: true });\n    if (time) {\n      this._currenttime = time;\n      this._nodes.hour.value = (\"0\" + this._currenttime.hour).slice(-2);\n      this._nodes.minute.value = (\"0\" + this._currenttime.minute).slice(-2);\n      if (this._nodes.second)\n        this._nodes.second.value = (\"0\" + this._currenttime.second).slice(-2);\n      if (this._nodes.msec)\n        this._nodes.msec.value = (\"00\" + this._currenttime.msec).slice(-3);\n      return;\n    }\n\n    this._nodes.hour.value = \"\";\n    this._nodes.minute.value = \"\";\n    if (this._nodes.second)\n      this._nodes.second.value = \"\";\n    if (this._nodes.msec)\n      this._nodes.msec.value = \"\";\n  }\n\n  _getFieldTextLength(field) {\n    return field === this._nodes.msec ? 3 : 2;\n  }\n  _getSubInputs() {\n    return [\n      this._nodes.hour,\n      this._nodes.minute,\n      ...(this._nodes.second ? [this._nodes.second] : []),\n      ...(this._nodes.msec ? [this._nodes.msec] : [])\n    ];\n  }\n\n  private getInputValues() {\n    return {\n      hour: this._nodes.hour.value,\n      minute: this._nodes.minute.value,\n      second: this._nodes.second?.value ?? \"\",\n      msec: this._nodes.msec?.value ?? \"\"\n    };\n  }\n\n  _onInput(field: HTMLInputElement | null) {\n    if (super._onInput(field))\n      return true;\n\n    const fields = this.getInputValues();\n    if (!fields.hour && !fields.minute && !fields.second && !fields.msec) { //full field clear\n      this._replacednode.setCustomValidity('');\n      this._setReplacedValue(\"\");\n      return;\n    }\n\n    const hour = parseInt(fields.hour, 0);\n    const minute = parseInt(fields.minute, 0);\n    const second = parseInt(fields.second, 0);\n    const msec = parseInt(fields.msec, 0);\n\n    const finaltime = datehelpers.formatISOTime(hour, minute, this._showsecond ? second : null, this._showmsec ? msec : null);\n    this._replacednode.setCustomValidity(finaltime ? \"\" : getTid(\"publisher:site.forms.commonerrors.time\"));\n    this._setReplacedValue(finaltime);\n    return true;\n  }\n\n  _onKeyPress(evt, key) {\n    if (key === ':' || key === '.') {\n      const nextfield = this._getNextField(evt.target);\n      if (nextfield)\n        dompack.focus(nextfield);\n      return false;\n    }\n    return super._onKeyPress(evt, key);\n  }\n\n  _getNextField(field) {\n    return field === this._nodes.hour ? this._nodes.minute\n      : field === this._nodes.minute ? this._nodes.second\n        : null;\n\n  }\n\n\n  /*\n    onKeyUp( ev, node )\n    {\n      ev.preventDefault();\n      ev.stopPropagation();\n\n      let prevval = this.previous.value;\n      this.previous.value = node.value;\n\n      if( ev.keyCode === 8 && node.value === \"\" && prevval === \"\" )//backspace\n      {\n        //Try to set focus on previous input\n        let prevnode = node.parentNode.previousSibling;\n        if( prevnode )\n        {\n          let previnp = prevnode.querySelector(\"input\");\n          if( previnp )\n            previnp.focus();\n        }\n\n        return;\n      }\n\n      //First some basic validation\n      let value = node.value.replace(/[^0-9]+/g,'');\n      if( value === \"\" || value !== node.value || 1*value < 1*node.min || 1*value > 1*node.max )\n        return;\n\n      //Is field value minimal length\n      if( value.length < 2 )\n        return;\n\n      if( prevval === node.value )\n          return;//Only go to next input if value changed\n\n      //Try to set focus on next input\n      let nextnode = node.parentNode.nextSibling;\n      if( !nextnode )\n        return;\n\n      let nextinp = nextnode.querySelector(\"input\");\n      if( nextinp )\n        nextinp.focus();\n    }\n  */\n}\n","/* eslint-disable */\n/// @ts-nocheck -- Bulk rename to enable TypeScript validation\n\nimport * as dompack from 'dompack';\nimport KeyboardHandler from \"dompack/extra/keyboard\";\nimport * as datehelpers from \"./datehelpers\";\nimport { getLang } from '@webhare/dompack/src/tree';\n// import \"./datestrings.lang.json\";\n//import { getTid } from \"@webhare/gettid\";\n\n// FIXME work with backend\nconst langcodes =\n{\n  \"nl\": \"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  \"de\": \"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  \"en\": \"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\n//Load any needed localizations yourself: frameworks.mootools.more.locale.nl-nl.date, frameworks.mootools.more.locale.es-es.date, frameworks.mootools.more.locale.de-de.date, frameworks.mootools.more.locale.fr-fr.date\n\n/*\n\nConverting calendar.js code to calendar2.js\n\n    Changed classes\n      - .-wh-calendar-popup   ->   .wh-datepicker > .value\n      - .-wh-calendar-icon    ->   .wh-datepicker > .arrow\n\n    Changed <input> attributes:\n      - data-formatting -> data-format\n      - data-empty -> placeholder\n\n    Load:\n      LOAD: wh.ui.calendar2\n      LOAD: wh.locale.common.de-de.date\n      LOAD: wh.locale.common.en-us.date\n      LOAD: wh.locale.common.nl-nl.date\n\n    Taal instellen:\n      Locale.use(\"de-DE\");\n      Locale.use(\"en-US\");\n      Locale.use(\"nl-NL\");\n*/\n\n\n/////////////////////\n//\n//\n\n//NOTE preparing to sync this with dompack selectlist.es\n\nclass ComponentOverlay {\n  constructor() {\n    this._boundGlobalEvents = null;\n  }\n  _startOverlayDismissCapture() {\n    //set up capturing handlers to kill our pulldowns asap when something else is clicked\n    if (!this._boundGlobalEvents)\n      this._boundGlobalEvents = evt => this._globalEvents(evt);\n\n    if (!dompack.debugflags.meo) {\n      window.addEventListener(\"keyup\", this._boundGlobalEvents, true);\n      window.addEventListener(\"mousedown\", this._boundGlobalEvents, true);\n      window.addEventListener(\"touchstart\", this._boundGlobalEvents, true);\n    }\n  }\n  _endOverlayDismissCapture() {\n    window.removeEventListener(\"keyup\", this._boundGlobalEvents, true);\n    window.removeEventListener(\"mousedown\", this._boundGlobalEvents, true);\n    window.removeEventListener(\"touchstart\", this._boundGlobalEvents, true);\n  }\n  _globalEvents(evt) {\n    if (evt && evt.type === \"keyup\") {\n      if (evt.keyCode === 27)\n        this._dismissOverlay();\n      return;\n    }\n\n    if (!dompack.contains(this._anchornode, evt.target) && !dompack.contains(this._items, evt.target))\n      this._dismissOverlay();\n  }\n}\n\n\n\n//\n//\n////////////////////\n\n\n\n/*\n * $wh.CalendarTable\n * Builds a plain calendar table based on mootools locale settings\n *\n */\n\nclass CalendarTable extends ComponentOverlay {\n  constructor() {\n    super();\n    this.options = {\n      weeknumbers: false,\n      header_weeknr: '', //weeknr.\n      min: null, //minimal date\n      max: null //maximal date (out of range gets disabled class\n    };\n    this.cdate = null;\n    this.showdate = null;\n  }\n\n  _onDayClick(evt) {\n    const clickedday = evt.target.closest(`.${this.options.baseclass}__day--selectable`);\n    // console.error(clickedday, clickedday.dataset.whDatepickerDate);\n    if (!clickedday)\n      return;\n\n    dompack.stop(evt);\n    this._dismissOverlay();\n\n    dompack.changeValue(this._datenode, clickedday.dataset.whDatepickerDate);\n  }\n\n  getTable(showdate, options) {\n    this.options = { ...this.options, options };\n\n    const caltable = dompack.create('table', {\n      className: this.options.baseclass + '__days',\n      on: { click: evt => this._onDayClick(evt) }\n    });\n    const calbody = dompack.create('tbody');\n    caltable.appendChild(calbody);\n\n    //Build week rows\n    const rownode = <tr class={this.options.baseclass + '__weekdays'}></tr>;\n    if (this.options.weeknumbers)\n      rownode.appendChild(<td></td>); //placeholder for upperleft corner\n\n    for (let w = 0; w < 7; ++w) {\n      rownode.appendChild(<th scope=\"column\" class={this.options.baseclass + '__weekday'}><span>{this._languagetexts[w + 33]}</span></th>);\n    }\n    calbody.appendChild(rownode);\n\n    const mindate = this.options.min ? {\n      day: this.options.min.getUTCDay(),\n      month: this.options.min.getUTCMonth(),\n      year: this.options.min.getUTCFullYear()\n    } : null;\n\n    const maxdate = this.options.max ? {\n      day: this.options.max.getUTCDay(),\n      month: this.options.max.getUTCMonth(),\n      year: this.options.max.getUTCFullYear()\n    } : null;\n\n    //What is the weekday for the first day of the selected month ?\n    const startofmonth = datehelpers.makeJSUTCDate({ ...showdate, day: 1 });\n    const showmonth = startofmonth.getUTCMonth();\n    const showyear = startofmonth.getUTCFullYear();\n\n    //    console.log(startofmonth);\n    const startofmonth_weekday = startofmonth.getUTCDay(); //0-6 where 0=Sunday\n\n    //Work backwards to a monday (start of the week)\n    const backwardsdays = startofmonth_weekday === 0 ? 6 : startofmonth_weekday - 1;\n    let currentgriddate = startofmonth.getTime() - (backwardsdays * 86400 * 1000);\n\n    //Build the grid!\n    for (let week = 0; week < 6; ++week) {\n      const rownode = dompack.create('tr', { className: this.options.baseclass + '__week' });\n\n      for (let day = 0; day < 7; ++day) {\n        const date = new Date(currentgriddate);\n        if (this.options.weeknumbers && day === 0)\n          rownode.appendChild(<th class={this.options.baseclass + '__weeknr'} scope=\"row\"><span>{datehelpers.getWeekNumber(date)}</span></th>);\n\n        const dateY = date.getUTCFullYear();\n        const dateM = date.getUTCMonth();\n        const dateD = date.getUTCDate();\n\n        const celldate = { year: dateY, month: dateM + 1, day: dateD };\n\n        const dayclass = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'][day];\n        const daynode = dompack.create('td', {\n          className: `${this.options.baseclass}__day ${this.options.baseclass}__day--${dayclass}`,\n          childNodes: [dompack.create(\"span\", { textContent: date.getUTCDate() })],\n          dataset: { whDatepickerDate: datehelpers.formatJSUTCISODate(date) }\n        });\n\n        if (dateM !== showmonth || dateY !== showyear)\n          daynode.classList.add(this.options.baseclass + '__day--othermonth');\n\n        if ((mindate && dateY < mindate.year && dateM < mindate.month && dateD < mindate.day)\n          || (maxdate && dateY > maxdate.year && dateM > maxdate.month && dateD > maxdate.day)) {\n          daynode.classList.add(this.options.baseclass + '__day--disabled');\n        } else {\n          daynode.setAttribute(\"tabindex\", \"0\");\n          daynode.classList.add(this.options.baseclass + '__day--selectable');\n        }\n\n        if (datehelpers.compareDate(this.today, celldate) === 0)\n          daynode.classList.add(this.options.baseclass + '__day--today');\n\n        if (this.date && datehelpers.compareDate(this.date, celldate) === 0)\n          daynode.classList.add(this.options.baseclass + '__day--selected');\n\n        rownode.appendChild(daynode);\n        currentgriddate += 86400 * 1000;\n      }\n      calbody.appendChild(rownode);\n    }\n\n    return caltable;\n  }\n}\n\nclass Calendar2 extends CalendarTable {\n  constructor(options) {\n    super();\n    this.options = {\n      weeknumbers: false,\n      date: null,   // initial value\n      min: null,\n      max: null,\n      ...options\n    };\n    this.node = null;\n    this.tablenode = null;\n    this.yearspinner = null;\n    this.monthselectnode = null;\n    this.date = null; //selected date\n    this.keys = null;\n    this.focusednode = null;\n  }\n\n  _onYearMonthChange(evt) {\n    this.options.date = {\n      year: this.yearspinner.value,\n      month: this.monthselectnode.value,\n      day: this._currentdate ? this._currentdate.day : 1\n    };\n\n    this._currentdate.month = parseInt(this.monthselectnode.value);\n    this._currentdate.year = parseInt(this.yearspinner.value);\n\n    this.setMonthTable(this.options.date);\n  }\n\n  readDateNode() {\n    this.mindate = datehelpers.parseISODate(this._datenode.min, { nofail: true });\n    this.maxdate = datehelpers.parseISODate(this._datenode.max, { nofail: true });\n    this.date = datehelpers.parseISODate(this._datenode.value, { nofail: true });\n    const suggestion = datehelpers.parseISODate(this._datenode.dataset.suggestion, { nofail: true });\n    const max = datehelpers.parseISODate(this._datenode.max);\n    this.today = datehelpers.getLocalToday();\n\n    this.yearspinner.min = this.mindate ? this.mindate.year : 1901;\n    this.yearspinner.max = this.maxdate ? this.maxdate.year : 2099;\n\n    let showdate = this.date ?? suggestion ?? this.today;\n    if (this.mindate && datehelpers.makeJSUTCDate(showdate) < datehelpers.makeJSUTCDate(this.mindate))\n      showdate = this.mindate;\n    if (this.maxdate && datehelpers.makeJSUTCDate(showdate) > datehelpers.makeJSUTCDate(this.maxdate))\n      showdate = this.maxdate;\n\n    if (!this._currentdate)\n      this._currentdate = showdate;\n\n    this.setMonthTable(showdate);\n  }\n\n  _addMeToNode(container) {\n    this.node = container;\n\n    this.yearspinner = <input type=\"number\" class={`${this.options.baseclass}__yearselect`} step=\"1\" on={{ change: evt => this._onYearMonthChange(evt) }} />;\n    this.monthselectnode = <select class={`${this.options.baseclass}__monthselect`} on={{ change: evt => this._onYearMonthChange(evt) }} />;\n\n    this.readDateNode();\n\n    //build calendar interface:\n    const headernode = <div class={this.options.baseclass + \"__header\"}>\n      <div class={this.options.baseclass + \"__previous\"} onClick={evt => this.changeMonth(evt, -1)} />\n      {this.monthselectnode}\n      {this.yearspinner}\n      <div class={this.options.baseclass + \"__next\"} onClick={evt => this.changeMonth(evt, +1)} />\n    </div>;\n\n    //month pulldown\n    const selectedmonth = this._currentdate.month;\n    for (let m = 0; m < 12; ++m)\n      this.monthselectnode.appendChild(<option value={m + 1} selected={m === selectedmonth - 1}>{this._languagetexts[m + 2]}</option>);\n\n    this.node.append(headernode, this.tablenode);//, btnbarnode);\n\n    //looks like we're visible ! install a capturing\n    new KeyboardHandler(this.node, {\n      \"Enter\": ev => this.onKeyEnter(ev)\n    }\n      , { captureunsafekeys: true }\n    );\n\n    // Locale.addEvent(\"change\", this.onLanguageChange.bind(this));\n    this._startOverlayDismissCapture();\n    this._onYearMonthChange();\n  }\n\n  setMonthTable(showdate) {\n    this.yearspinner.value = showdate.year;\n    this.monthselectnode.value = showdate.month;\n\n    const newtable = this.getTable(showdate);\n\n    if (this.tablenode)\n      this.tablenode.replaceWith(newtable);\n    this.tablenode = newtable;\n\n    this.setFocus();\n  }\n\n  setFocus() {\n    if (!this.tablenode.clientWidth)\n      return;//Not (yet) visible\n\n    //Set focus on showdate or else first selectable date\n    let fnode;\n    if (this.date)\n      fnode = this.tablenode.querySelector(\"td[data-wh-datepicker-date='\" + datehelpers.formatISODate(this.date.year, this.date.month, this.date.day) + \"']\");\n    if (!fnode) //else pick first selectable day\n      fnode = this.tablenode.querySelector(\".\" + this.options.baseclass + '__day--selectable');\n    if (fnode)\n      fnode.focus();\n  }\n\n  onKeyEnter(ev) {\n    const daynode = ev.target.closest(\".\" + this.options.baseclass + '__day--selectable');\n    if (!daynode)\n      return;\n\n    this._onDayClick(ev);\n  }\n\n  _dismissOverlay() {\n    this.node.remove();\n    this._endOverlayDismissCapture();\n    this._owner.__closedDatepicker();\n  }\n\n  changeMonth(evt, direction) {\n    dompack.stop(evt);\n\n    let newyear = parseInt(this.yearspinner.value);\n    let newmonth = parseInt(this.monthselectnode.value) + direction;\n\n    if (newmonth > 12 || newmonth < 1) //wrap it\n    {\n      newyear += direction;\n      newmonth = direction > 0 ? 1 : 12;\n    }\n    this.setMonthTable({ year: newyear, month: newmonth });\n  }\n}\n\nclass DatePicker extends Calendar2 {\n  /** options.baseclass Base class to use for the elements in the date picker. Defaults to 'datepicker' */\n  constructor(owner) {\n    super({ ...owner.options, baseclass: owner._baseclass + '__picker' });\n    this._owner = owner;\n    this._datenode = owner._replacednode;\n    this.options = {\n      ...this.options,\n      language: null\n    };\n    //TODO limit by supportedlanguages and use gettid(\"~locale.datetimestrings\")\n    if (!this.options.language)\n      this.options.language = getLang().language;\n\n    this._languagetexts = (langcodes[this.options.language] || langcodes.en).split(';');\n\n    //we use the node to store our result, so verify it\n    //FIXME maybe this should be optional and you be allowed to create a datepicker without a corresponding node if you just manage getvalue/setvalue yourself, or maybe this glue code belongs outside us\n    //     if(node.nodeName !== 'INPUT' || node.getAttribute('type') !== 'date')\n    //       throw new Error(\"The DatePicker expects to be associated with a input[type=date]\");\n\n    //     this._node = node;\n    //     this._class = (options ? options.baseclass : '') || 'datepicker';\n    //     this._node.classList.add(this._class + \"--attached\");\n    // //\n    // this._node.addEventListener(\"wh:datepicker-request\");\n\n    this._anchornode = this._datenode.nextSibling;\n\n    this._calendarnode = dompack.create('div', { className: this.options.baseclass }); //tabindex:0 ?\n    this._addMeToNode(this._calendarnode);\n\n    this._items = this._calendarnode; //TODO bit ugly but keeps us compatible with selectlist.es\n\n    this._calendarnode.addEventListener(\"change\", ev => {\n      console.log(ev);\n    });\n\n    //Allow users to hook into the datepicker\n    dompack.dispatchCustomEvent(this._datenode, \"wh:datepicker-built\", { bubbles: true, cancelable: false, detail: { input: this._datenode, datepicker: this._calendarnode } });\n\n    //ADDME can we borrow positioning code from the dompack pulldown?\n    //for now, attach to bottom\n    document.body.appendChild(this._calendarnode);\n    const calendarnodesize = this._calendarnode.getBoundingClientRect();\n    const anchornode = this._anchornode.getBoundingClientRect();\n\n    //fits left aligned?\n    if (anchornode.left + calendarnodesize.width > window.innerWidth) { //doesn't fit left aligned, we must right align\n      this._calendarnode.style.right = '0px';\n    } else //left align\n    {\n      this._calendarnode.style.left = Math.ceil(anchornode.left) + 'px';\n    }\n\n    //fits top aligned?\n    if (anchornode.top + calendarnodesize.height > window.innerHeight) { //doesn't fit below, send above\n      let y = (window.innerHeight - anchornode.top);\n      if ((window.innerHeight - y) - calendarnodesize.height < 0) //Prevent calendar hiding behind top of window\n        y = window.innerHeight - calendarnodesize.height;\n      this._calendarnode.style.bottom = y + 'px';\n    } else //left align\n    {\n      this._calendarnode.style.top = Math.ceil(anchornode.bottom) + 'px';\n    }\n\n    this.setFocus();\n  }\n}\n\nexport default DatePicker;\n","import * as dompack from '@webhare/dompack';\nimport { type CaptchaProvider, type CaptchaSettings, captcharegistry } from \"@mod-publisher/js/captcha/api\";\n\n//recaptcha API: https://developers.google.com/recaptcha/docs/display\nlet recaptchaload: PromiseWithResolvers<void> | undefined;\n\ntype RecaptchaOptions = { language?: string };\nlet recaptchaOptions: RecaptchaOptions | undefined;\n\ndeclare global {\n  interface Window {\n    $wh__ongooglerecaptchaloaded: () => void;\n    grecaptcha: {\n      render: (node: HTMLElement, options: { sitekey: string; callback: () => void }) => string;\n      getResponse: (id: string) => string;\n    };\n  }\n}\n\nwindow.$wh__ongooglerecaptchaloaded = function () {\n  recaptchaload!.resolve();\n};\n\nfunction makeRecaptchaLoadPromise() {\n  recaptchaload = Promise.withResolvers<void>();\n  document.querySelector<HTMLElement>(\"head,body\")!.append(<script src=\"https://www.google.com/recaptcha/api.js?onload=$wh__ongooglerecaptchaloaded&amp;render=explicit\" />);\n  return recaptchaload.promise;\n}\n\nexport async function runRecaptcha(provider: CaptchaProvider, injectInto: HTMLElement, settings: CaptchaSettings) {\n  const lock = dompack.flagUIBusy({ modal: true });\n  try {\n    await (recaptchaload ? recaptchaload.promise : makeRecaptchaLoadPromise());\n\n    const captchanode = <div class=\"wh-captcha__googlerecaptchaholder\"></div>;\n    injectInto.append(captchanode);\n\n    if (provider.apikey === 'mock') {\n      captchanode.appendChild(<label class=\"wh-captcha__mock\"><input type=\"checkbox\" on={{ click: () => settings.onResponse('mock') }} />I am a human, beep-bop</label>);\n    } else {\n      const recaptchaid = window.grecaptcha.render(captchanode, {\n        sitekey: provider.apikey,\n        ...recaptchaOptions?.language ? { hl: recaptchaOptions.language } : {},\n        callback: () => {\n          const response = window.grecaptcha ? window.grecaptcha.getResponse(recaptchaid) : '';\n          settings.onResponse(response);\n        }\n      });\n    }\n  } finally {\n    lock.release();\n  }\n}\n\n\n/** Setup Google reCAPTCHA rendering\n * @param options Optional settings, currently supports:\n *  - language: The language code to use for the reCAPTCHA widget. See https://developers.google.com/recaptcha/docs/language for supported language codes\n */\nexport function setupGoogleRecaptcha(options?: RecaptchaOptions) {\n  if (captcharegistry[\"google-recaptcha\"])\n    throw new Error(\"Duplicate google recaptcha initialization\");\n\n  recaptchaOptions = { ...recaptchaOptions, ...options };\n  captcharegistry[\"google-recaptcha\"] = { initialize: runRecaptcha };\n}\n","import * as dompack from '@webhare/dompack';\nimport { type CaptchaProvider, type CaptchaSettings, captcharegistry } from \"@mod-publisher/js/captcha/api\";\n\n//friendly captcha API: https://developer.friendlycaptcha.com/docs/v2/sdk/configuration\nlet script = \"https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.1.31/site.min.js\";\nlet endpoint: string | undefined;\nlet isLoaded = false;\n\nexport async function runFriendlyCaptcha(provider: CaptchaProvider, injectInto: HTMLElement, settings: CaptchaSettings): Promise<void> {\n  const captcha = document.createElement('div');\n  captcha.className = \"frc-captcha\";\n  captcha.dataset.sitekey = provider.apikey;\n  if (endpoint === \"eu\")\n    captcha.dataset.apiEndpoint = \"eu\"; //https://developer.friendlycaptcha.com/docs/v2/sdk/configuration#data-api-endpoint\n  captcha.addEventListener(\"frc:widget.complete\", ((evt: CustomEvent<{ response: string }>) => settings.onResponse(evt.detail.response)) as EventListener);\n\n  injectInto.append(captcha);\n\n  if (isLoaded) {\n    //@ts-expect-error -- undocumented but this seems to properly refresh the unit\n    window.frcaptcha.attach();\n  } else { //Now initialize it\n    using lock = dompack.flagUIBusy();\n    void (lock);\n    //TODO listen for widget.statechange - https://developer.friendlycaptcha.com/docs/v2/sdk/events#frcwidgetstatechange before releasing the lock\n    await dompack.loadScript(script, { module: true });\n    isLoaded = true;\n  }\n}\n\n/** Setup friendlycaptcha integration */\nexport function setupFriendlyCaptcha(options?: { script?: string; endpoint?: \"eu\" }) {\n  if (captcharegistry[\"friendly-captcha\"])\n    throw new Error(\"Duplicate friendly captcha initialization\");\n\n  if (options?.script)\n    script = options.script;\n  if (options?.endpoint)\n    endpoint = options.endpoint;\n\n  captcharegistry[\"friendly-captcha\"] = { initialize: runFriendlyCaptcha };\n}\n","/* PLEASE NOTE - including @mod-publisher/js/forms is considered including the 'legacy form api'. It comes\n   without tree shaking support and autoregisters forms\n\n   @webhare/forms provides a tree-shakable implementation (but requires more setup). To switch please see dev module forms.ts\n  setupForms();\n*/\n\nimport './internal/requiredstyles.css';\nimport * as merge from './internal/merge';\nimport { setFieldError, setupValidator } from './internal/customvalidation';\nimport FormBase, { type FormSubmitEmbeddedResult } from './formbase';\nimport RPCFormBase from './rpc';\nimport { setupForms, registerHandler } from '@webhare/forms';\nimport { isLive } from '@webhare/env';\nimport { setupFormAnalytics } from '@webhare/frontend/src/pxl';\n\nexport { FormBase, RPCFormBase, setFieldError, setupValidator, type FormSubmitEmbeddedResult };\n\nexport const registerMergeFormatter = merge.registerFormatter;\n\ntype LegacyFormHandlerFactory = (form: HTMLFormElement) => FormBase;\n\nfunction legacyRegisterFormHandler(handlername: string, handler: LegacyFormHandlerFactory) {\n  registerHandler(handlername, (form: HTMLFormElement) => {\n    const createdForm = handler(form);\n    if (!isLive && createdForm instanceof FormBase && !(createdForm instanceof RPCFormBase)) {\n      console.warn(`Form handler for '${handlername}' is deriving from @mod-publisher/js/forms#FormBase - it should derive from RPCFormBase (In WH5.7+, the FormBase exported by @webhare/forms will *be* the RPCFormBase)`);\n    }\n    return createdForm as RPCFormBase;\n  });\n}\n\n/** @deprecated setup() is no longer needed */\nexport function setup(options: unknown) {\n}\n\n// We explicitly bind the 'publisher:form' forms to FormBase. The modern version doesn't distinguish between these anymore (and we want to move away from that difference anyawy, RPCBase isn't that much different)\nsetupForms({\n  handlers: { \"publisher:form\": form => new FormBase(form) as RPCFormBase }\n});\n\n// We assume if you're importing @mod-publisher/js/forms you don't know about having to do setupFormAnalytics to keep analytics in WH 5.7+\nsetupFormAnalytics();\n\nexport { legacyRegisterFormHandler as registerHandler };\n","import { getBrowser } from \"@webhare/dompack\";\nimport { generateRandomId } from \"@webhare/std\";\nimport { debugFlags, isLive } from \"@webhare/env\";\n\ninterface PxlEventDetails {\n  event: string;\n  data: PxlEventData;\n  options: PxlOptions;\n  isAlt: boolean;\n}\n\nexport type PxlEvent = CustomEvent<PxlEventDetails>;\n\nexport type PxlEventData = {\n  [K in `ds_${string}` | `db_${string}` | `dn_${string}`]: (K extends `ds_${string}` ? string :\n    (K extends `db_${string}` ? boolean :\n      (K extends `dn_${string}` ? number : never)))\n};\n\nexport interface PxlOptions {\n  /** Override pi (pxlId) to control or anonymize user ids*/\n  pi?: string | undefined;\n  /**  Base url to which to send PXL events. Defaults to \"/.wh/ea/pxl/\". */\n  url: string;\n  /**  Sample rate for the alternative record url as a fraction of the number of events, for example, setting it to 1/100 sends 1 in 100 events to the alternative record url. Defaults to 0 (no sampling). */\n  altSampleRate: number;\n  /**  Alternative record url. Defaults to \"/.wh/ea/pxl/alt/\". */\n  altUrl: string;\n  /** The number of days the user id is valid. Defaults to 30. */\n  sessionExpiration: number; //TODO if we ever camel this, also add 'Days' to the name\n  /** Set to true to omit some browser context fields (\"bu\", \"bs\" and \"bp\"). This option can\n      be used to reduce the length of the pxl url. Defaults to false. */\n  noBrowser: boolean;\n  /** Node responsible for generating this event (if not set, 'window' is assumed). Used for the event handlers */\n  node?: HTMLElement;\n  /** Send pixels as beacons */\n  beacon: boolean;\n  /** Callback to execute once pixel is sent */\n  onComplete?: () => void;\n}\n\n//event names must match isValidModuleScopedName, but we won't do the module name checks here. also isValidModuleScopedName lives in @webhare/services so..\nconst eventname_regex = /^([a-z0-9][-a-z0-9_]*[a-z0-9]):([a-z0-9][-.a-z0-9_]*[a-z0-9])$/;\nconst datakey_regex = /^(ds_[0-9a-z_]+)|(dn_[0-9a-z_]+)|(db_[0-9a-z_]+)$/;\n/*TODO: Not sure yet what the new maximum URL length will be\nconst max_data_length = 600; // The maximum number of bytes stored for the request*/\nconst max_sessionid_age = 30;\n\nlet globalOptions: Partial<PxlOptions> | undefined;\n\nlet pagesession: string | undefined; //current page session id (used to track multiple events from single page)\nlet useAltRecordURL = false; //send events for this page to the altrecordurl\nlet seqnr = 0;\n\nlet pxlUserId: string | undefined, pxlSessionId: string | undefined;\n\nfunction buildOptions(options: Partial<PxlOptions> | undefined): PxlOptions {\n  return {\n    url: \"/.wh/ea/pxl/\",\n    altSampleRate: 0,\n    altUrl: \"/.wh/ea/pxl/alt/\",\n    sessionExpiration: max_sessionid_age,\n    noBrowser: false,\n    beacon: false,\n    ...globalOptions,\n    ...options\n  };\n}\n\n/** Set global pxl options\n    @param options - Option updates\n*/\nexport function setPxlOptions(options: Partial<PxlOptions> | null) {\n  globalOptions = { ...globalOptions, ...options };\n\n  if (globalOptions.altUrl && globalOptions.altSampleRate) {\n    useAltRecordURL = Math.random() < globalOptions.altSampleRate;\n    if (debugFlags.pxl)\n      console.log(`[pxl] using altrecordurl for ${100 * globalOptions.altSampleRate}% of pageloads, this session is sent to the ${useAltRecordURL ? \"alternative\" : \"normal\"} url`);\n  } else\n    useAltRecordURL = false;\n}\n\nfunction pxlFailed(errormessage: string, ...params: unknown[]) {\n  console.error('[pxl] ' + errormessage, ...params);\n  if (!isLive)\n    throw new Error(errormessage); //big errors on test servers\n  return null;\n}\n\nexport function makePxlURL(baseurl: string, eventname: string, data?: PxlEventData | null, options?: Partial<PxlOptions>) {\n  options = { ...globalOptions, ...options };\n\n  if (typeof eventname !== \"string\")\n    return pxlFailed(`Invalid eventname name '${eventname}', expected string, got ${typeof eventname}`);\n  if (!eventname_regex.test(eventname))\n    return pxlFailed(`Invalid eventname name '${eventname}', must be a valid module:event name`);\n  if (data && typeof data !== \"object\")\n    return pxlFailed(`Invalid data, expected object, got ${typeof data}`);\n\n  if (!pagesession)\n    pagesession = generateRandomId();\n\n  //not using URL object, simplifies support of relative URLs\n  const url = typeof document !== \"undefined\" ? new URL(baseurl, document.baseURI) : new URL(baseurl);\n  url.searchParams.set(\"pe\", eventname);\n  url.searchParams.set(\"pp\", pagesession);\n  url.searchParams.set(\"pc\", String(++seqnr));\n  url.searchParams.set(\"ps\", getPxlSessionId());\n  url.searchParams.set(\"pi\", options?.pi ?? getPxlId());\n\n  if (options.altSampleRate)\n    url.searchParams.set(\"pr\", String(options.altSampleRate));\n\n  const browser = getBrowser();\n  url.searchParams.set(\"bt\", browser.triplet);\n  if (browser.device)\n    url.searchParams.set(\"bd\", browser.device);\n\n  if (typeof document !== \"undefined\") {\n    if (document.documentElement.dataset.whOb)\n      url.searchParams.set(\"ob\", document.documentElement.dataset.whOb.substring(0, 20));\n    if (document.location)\n      url.searchParams.set(\"bl\", document.location.href.substring(0, 1000));\n    if (document.referrer)\n      url.searchParams.set(\"br\", document.referrer.substring(0, 1000));\n\n    if (!options.noBrowser) {\n      url.searchParams.set(\"bu\", window.navigator.userAgent.substring(0, 300));\n      if (window.screen.width && window.screen.height)\n        url.searchParams.set(\"bs\", `${window.screen.width}x${window.screen.height}`);\n      if (window.devicePixelRatio)\n        url.searchParams.set(\"bp\", String(window.devicePixelRatio));\n    }\n  }\n\n  if (data) {\n    for (const [name, value] of Object.entries(data)) {\n      const test = datakey_regex.exec(name);\n      if (!test)\n        return pxlFailed(`Invalid data field name '${name}', should be ds_XXX, dn_XXX or db_XXX with X consisting of characters in the range 0 - 9, a - z or an underscore`);\n\n      const type = typeof value;\n\n      if (test[1]) { // String\n        if (value && type !== \"string\")\n          return pxlFailed(`Invalid value type '${type}', expected 'string' for field '${name}'`);\n\n        url.searchParams.set(name, value as string || '');\n      } else if (test[2]) { // Number\n        if (value && type !== \"number\")\n          return pxlFailed(`Invalid value type '${type}', expected 'number' for field '${name}'`);\n\n        url.searchParams.set(name, String(value) || '0');\n      } else if (test[3]) { // Boolean\n        if (value && type !== \"boolean\")\n          return pxlFailed(`Invalid value type '${type}', expected 'boolean' for field '${name}'`);\n\n        url.searchParams.set(name, value ? \"true\" : \"false\");\n      }\n    }\n  }\n  return url;\n}\n\nexport function getPxlId(): string {\n  if (!pxlUserId) {\n    try {\n      const timestampvar = localStorage.getItem(\"_wh.ti\");\n      if (timestampvar && new Date(timestampvar) > new Date) { //not expired yet\n        pxlUserId = localStorage.getItem(\"_wh.pi\") || undefined;\n        if (pxlUserId && debugFlags.pxl)\n          console.log(`[pxl] Using id ${pxlUserId} from localStorage`);\n      }\n      pxlUserId ||= generateRandomId();\n      const sessionExpireDays = (globalOptions?.sessionExpiration ?? max_sessionid_age);\n      const expiration = new Date(Date.now() + sessionExpireDays * 24 * 60 * 60 * 1000);\n      localStorage.setItem(\"_wh.pi\", pxlUserId);\n      localStorage.setItem(\"_wh.ti\", expiration.toISOString());\n    } catch {\n      pxlUserId ||= generateRandomId();\n    }\n  }\n  return pxlUserId;\n}\n\nexport function getPxlSessionId() {\n  if (!pxlSessionId) {\n    try {\n      pxlSessionId = sessionStorage[\"_wh.ps\"];\n      pxlSessionId ||= generateRandomId();\n      sessionStorage[\"_wh.ps\"] = pxlSessionId;\n    } catch { //privacy mode? just (re)try to generate an id\n      pxlSessionId ||= generateRandomId();\n    }\n  }\n  return pxlSessionId;\n}\n\n/** Send a pxl event\n    @param event - Event type, preferably in the format 'module:event'\n    @param data - Event data. A map whose keys must start with either ds_ (string), db_ (boolean) or dn_ (number)\n*/\nexport function sendPxlEvent(event: string, data?: PxlEventData | null, options?: Partial<PxlOptions>) {\n  const finaloptions = buildOptions(options);\n  const baseurl = useAltRecordURL ? finaloptions.altUrl : finaloptions.url;\n\n  if (debugFlags.pxl)\n    console.log(`[pxl] Event '${event}'`, data);\n\n  // Add the pxl event to the url. We wrap it in async() for simpler code but we won't force our callers to await us, they rarely want to\n  (async () => {\n    const url = makePxlURL(baseurl, event, data, finaloptions);\n    if (!url)\n      return;\n\n    if (finaloptions.beacon && typeof navigator !== \"undefined\" && navigator.sendBeacon) {\n      navigator.sendBeacon(url);\n      return; //as beacons don't return anything per definition, we can stop here\n    }\n\n    if (debugFlags.pxl)\n      console.log(`[pxl] Pinging pxl '${url}'`);\n\n    // Load the pxl file using fetch\n    const fetchRes = await fetch(url, { mode: \"no-cors\", method: \"HEAD\", credentials: \"same-origin\", cache: \"no-store\", keepalive: true });\n    if (fetchRes.type === \"opaque\") { //we can't verify cross-server requests\n      if (debugFlags.pxl)\n        console.log(`[pxl] Assuming succesful pxl event '${event}'`);\n      return;\n    }\n    if (!fetchRes.ok) {\n      console.error(`[pxl] Failed to send pxl event '${event}'`, fetchRes);\n      return;\n    }\n\n    if (finaloptions.onComplete) //if we care about completion, we'll explicitly wait for the body to come in\n      await fetchRes.text(); //this will throw if the request failed, so we can skip the next check\n\n    if (debugFlags.pxl)\n      console.log(`[pxl] Successfully sent pxl event '${event}'`);\n  })().catch((error: Error) => {\n    console.error(`[pxl] Error while sending pxl event '${event}'`, error);\n  }).finally(() => {\n    finaloptions.onComplete?.(); //any exception here we'll keep uncaught\n  });\n}\n","/* TODO Move consilio pxl here eventually, but limit how much we actually want to export */\nimport { sendPxlEvent, type PxlEventData, type PxlOptions } from \"@mod-consilio/js/pxl\";\nimport { dtapStage } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { PxlDataTypes } from \"@webhare/frontend\";\nexport { setPxlOptions, getPxlId as getPxlUserId, getPxlSessionId } from \"@mod-consilio/js/pxl\";\n\nexport type PxlData = Record<string, string | number | boolean>;\n\n// Track listener installation. Especially needed during the transition from @mod-publisher/js/forms to @webhare/frontend. After the transition we might not need stack traces anymore\nconst activeListenPrefixes = new Map<string, Error>;\n\n// Combine with `string & {}` to prevent TypeScript from eliminating `keyof PxlDataTypes`\ntype AllowedKeys = keyof PxlDataTypes | (string & {});\n\n// Filters out invalid types from the PXL data type\ntype FilterValidTypes<T extends object | void> = T extends object ? {\n  [K in keyof T]: T[K] extends undefined | string | number | boolean ?\n  T[K] :\n  { __error: \"Invalid property type used in PXL event declaration, allowed: boolean, number, string\"; __type: T[K] };\n} : T;\n\n/// Helper type to allow making the data parameter optional when the datatype is void\ntype ParamTuples<DataType, Key extends AllowedKeys> = Key extends keyof PxlDataTypes ?\n  [data: FilterValidTypes<PxlDataTypes[Key]>, options?: Partial<PxlOptions>] :\n  (DataType extends void ?\n    [data?: void, options?: Partial<PxlOptions>] :\n    [data: DataType, options?: Partial<PxlOptions>]);\n\n// Error type for when an event is not declared in PxlDataTypes and no data type override is provided\ntype NeedTypeParamError = { __error: \"Event not declared in PxlDataTypes and no data type override provided\" } & symbol;\n\nexport function sendPxl<DataType extends (Event extends keyof PxlDataTypes ? NeedTypeParamError : void | PxlData | NeedTypeParamError) = NeedTypeParamError, Event extends AllowedKeys = AllowedKeys>(eventKey: Event, ...params: ParamTuples<NoInfer<DataType>, Event>): void {\n  const [data, options] = params;\n  const pxldata: PxlEventData = {};\n  for (const [k, v] of Object.entries(data ?? {})) {\n    if (v === undefined)\n      continue;\n    if (typeof v === \"string\")\n      pxldata[`ds_${k}`] = v;\n    else if (typeof v === \"number\")\n      pxldata[`dn_${k}`] = v;\n    else if (typeof v === \"boolean\")\n      pxldata[`db_${k}`] = v;\n    else\n      throw new Error(`Invalid type '${typeof v}' for PXL data key '${k}'`);\n  }\n\n  sendPxlEvent(eventKey, pxldata, options);\n}\n\n/** Setup pxl events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalytics(options?: { eventPrefix: string }): void {\n  const prefix = options?.eventPrefix || \"platform:form_\";\n  const registered = activeListenPrefixes.get(prefix);\n  if (registered)\n    if (dtapStage !== \"production\")\n      return console.error(`Duplicate setupFormAnalytics for prefix '${prefix}', earlier registration: `, registered);\n\n  activeListenPrefixes.set(prefix, new Error); //getStackTrace() would have been nicer, but doesn't get sourcemapped in the console\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    const formeventdata: { [K in `formmeta_${string}`]: string | number | boolean } = {};\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        formeventdata[`formmeta_${key}`] = val;\n\n    sendPxl<PxlData>(`${prefix}${e.detail.event}`, formeventdata, e.detail.event === \"abandoned\" ? { beacon: true } : undefined);\n  });\n}\n","/* eslint-disable */\n/// @ts-nocheck -- Bulk rename to enable TypeScript validation\n\nimport * as dompack from \"dompack\";\nimport * as domevents from \"dompack/src/events\";\nimport * as whintegration from \"@mod-system/js/wh/integration\";\nimport { getTid } from \"@webhare/gettid\";\nimport { isLive } from \"@webhare/env\";\nimport { isValidDate } from '@webhare/std';\n\nimport \"./splitdatetime.scss\";\nimport { getLang } from \"@webhare/dompack/src/tree\";\n\n\nif (!isLive)\n  console.warn(\"@mod-publisher/js/forms/splitdatetime has some known issues and is no longer being maintained. Please switch to the @mod-publisher/js/forms/fields/datetime version\");\n\nlet labelcount = 0;\n\n\nfunction formatDate(dateformat, dateparts) {\n  let output = '';\n  if (!dateparts)\n    return '';\n\n  for (const c of dateformat.split(\"\")) {\n    switch (c.toUpperCase()) {\n      case \"Y\":\n        output += dateparts.year;\n        break;\n      case \"M\":\n        output += (dateparts.month >= 10 ? '' : '0') + dateparts.month;\n        break;\n      case \"D\":\n        output += (dateparts.day >= 10 ? '' : '0') + dateparts.day;\n        break;\n      default:\n        output += c;\n        break;\n    }\n  }\n  return output;\n}\n\nfunction formatISODate(dateparts) {\n  return formatDate(\"Y-M-D\", dateparts);\n}\n\nfunction ensureLabelID(inputnode) {\n  const id = inputnode.id;\n  if (id === \"\") {\n    // FIXME: lookup whether we are nested in a label\n    return \"\";\n  }\n\n  const labelnode = document.querySelector(`[for=\"${CSS.escape(id)}\"]`);\n  if (!labelnode) {\n    console.log(\"Failed to find label for\", id);\n    return \"\";\n  }\n\n  // Ensure the label has an unique ID\n  if (labelnode.id === \"\") {\n    labelcount++;\n    labelnode.setAttribute(\"id\", `splitdatetime_lbl_${labelcount}`);\n  }\n\n  return labelnode.id;\n}\n\n\n\n\n/*\ncSplitDateInput replaces date input with 3 separate number type inputs\nfield ordering can be set by data attribute data-dateformat\n\nnice to have:\n - placeholder translations\n - for time input option for seconds/msec??\n*/\n\n///////////////////////////////////////\n//\n// new 'value' property\n//\nfunction mySelectGetValue() {\n  const origgetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), 'value').get;\n  //console.error(\"mySelectGetValue\", origgetter, origgetter.apply(this));\n  return origgetter.apply(this);\n}\nfunction mySelectSetValue(newvalue) {\n  const origsetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), 'value').set;\n  if (origsetter) //this works on chrome, firefox and IE\n  {\n    origsetter.apply(this, [newvalue]);\n  } else {\n    //safari doesnt let us call the original setter. but we _can_ remove the value property and it will be restored\n    delete this.value;\n    this.value = newvalue;\n    setupMyDateValueProperty(this); //reset our custom property\n  }\n  this._split_doupdate();\n}\n\nfunction setupMyDateValueProperty(select) {\n  Object.defineProperty(select, 'value', { configurable: true, get: mySelectGetValue, set: mySelectSetValue });\n}\n\nclass MultiInputSubstition {\n  constructor(inpnode) {\n    if (!window.MutationObserver)\n      return; //best to leave it alone\n\n    this._replacednode = inpnode;\n    this._replacednode._split_doupdate = () => this._split_doupdate();\n\n    if (window.MutationObserver) {\n      this._observer = new MutationObserver(() => this._onObserve());\n      this._observer.observe(this._replacednode, { attributes: true, attributeFilter: ['disabled', 'required', 'class'], subtree: false, childList: false });\n    }\n  }\n  _onObserve() {\n    console.log(\"observed!\");\n    this._refreshAttributes();\n  }\n\n  _split_doupdate() {\n    this._refreshReplacingFields();\n  }\n\n  _refreshAttributes() {\n    const isdisabled = this._replacednode.disabled;\n    const isrequired = this._replacednode.required;\n\n    dompack.toggleClass(this.inputgroup, this._class + '--disabled', isdisabled);\n    dompack.toggleClass(this.inputgroup, this._class + '--required', isrequired);\n    this._getSubInputs().forEach(node => { node.disabled = isdisabled; node.required = isrequired; });\n  }\n}\nexport class SplitDateField extends MultiInputSubstition {\n  constructor(inpnode) {\n    super(inpnode);\n    if (!this._replacednode)\n      return;\n\n    this._class = \"wh-form__dateinputgroup\";\n    setupMyDateValueProperty(this._replacednode);\n\n    __hideInput(inpnode);//hide current input\n\n    this.previous = { value: '' };\n\n    let day_pos = 0;\n    let month_pos = 1;\n    let year_pos = 2;\n\n    if (inpnode.dataset.dateformat) // y-m-d, d-m-y, ...\n    {\n      const ordering = __strToIntegerArray(inpnode.dataset.dateformat);\n      for (let i = 0; i < ordering.length; ++i) {\n        if (ordering[i].indexOf(\"y\") > -1)\n          year_pos = i;\n        else if (ordering[i].indexOf(\"m\") > -1)\n          month_pos = i;\n        else if (ordering[i].indexOf(\"d\") > -1)\n          day_pos = i;\n      }\n    }\n\n    this.placeholder = {\n      year: \"yyyy\",\n      month: \"mm\",\n      day: \"dd\"\n    };\n\n    if (getLang().language === \"nl\")\n      this.placeholder = {\n        year: \"jjjj\",\n        month: \"mm\",\n        day: \"dd\"\n      };\n\n    this.day = null;\n    this.month = null;\n    this.year = null;\n\n    if (this._replacednode.value !== \"\")//Should be iso date\n    {\n      const parts = __strToIntegerArray(this._replacednode.value);\n      if (parts.length > 2) {\n        this.day = parts[2];\n        this.month = parts[1];\n        this.year = parts[0];\n      }\n    }\n\n    const isdisabled = this._replacednode.disabled;\n    const isreadonly = this._replacednode.readonly;\n\n    let year_min = 1900; let year_max = 2999;\n\n    if (this._replacednode.min !== \"\") //Should be iso date\n    {\n      const parts = __strToIntegerArray(this._replacednode.min);\n      if (parts.length)\n        year_min = parts[0];\n    }\n\n    if (this._replacednode.max !== \"\") {\n      const parts = __strToIntegerArray(this._replacednode.max);\n      if (parts.length && parts[0] >= year_min)\n        year_max = parts[0];\n    }\n\n\n    this.inputgroup = <div class=\"wh-form__dateinputgroup\" role=\"group\" />;\n\n\n    // Refer to the label (Because we have role=\"group\" we need a label)\n    const labelid = ensureLabelID(inpnode);\n    if (labelid !== \"\")\n      this.inputgroup.setAttribute(\"aria-labelledby\", labelid);\n\n\n    this.daynode = <input readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"2\" placeholder={this.placeholder.day} min=\"1\" max=\"31\" type=\"number\" aria-label={getTid(\"publisher:site.forms.splitdatetime-day-arialabel\")} />;\n    this.monthnode = <input readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"2\" placeholder={this.placeholder.month} min=\"1\" max=\"12\" type=\"number\" aria-label={getTid(\"publisher:site.forms.splitdatetime-month-arialabel\")} />;\n    this.yearnode = <input readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"4\" placeholder={this.placeholder.year} min={year_min} max={year_max} type=\"number\" aria-label={getTid(\"publisher:site.forms.splitdatetime-year-arialabel\")} />;\n    this._refreshAttributes();\n    this._refreshReplacingFields();\n\n    for (let i = 0; i < 3; ++i) {\n      if (i === day_pos) {\n        this.inputgroup.appendChild(<div class=\"wh-form__dateinputgroup__line wh-form__dateinputgroup__day\">\n          {this.daynode}\n        </div>); //\n      }\n      if (i === month_pos) {\n        this.inputgroup.appendChild(<div class=\"wh-form__dateinputgroup__line wh-form__dateinputgroup__month\">\n          {this.monthnode}\n        </div>); //\n      }\n      if (i === year_pos) {\n        this.inputgroup.appendChild(<div class=\"wh-form__dateinputgroup__line wh-form__dateinputgroup__year\">\n          {this.yearnode}\n        </div>); //\n      }\n    }\n\n\n    // Take the replaced input out of the keyboard navigation.\n    // But it'll retain the ability to get focus. So if code sets the focus it will be forwarded to the first input in the group (the day).\n    this._replacednode.setAttribute(\"tabindex\", \"-1\");\n\n    //If focus on hidden date input, set focus on first field in replacement\n    this._replacednode.addEventListener(\"focus\", ev => {\n      // NOTE: It's important we have set tabindex=\"-1\" on the input, otherwise when we tab backwards from\n      //       the first input in our group we are returned back to the day input. (so we can never escape backwards)\n      const nextnode = this.inputgroup.querySelector(\"input\");\n      if (nextnode)\n        nextnode.focus();\n    });\n\n\n    if (isdisabled)\n      this.inputgroup.classList.add(\"wh-form__dateinputgroup--disabled\");\n    if (isreadonly)\n      this.inputgroup.classList.add(\"wh-form__dateinputgroup--disabled\");\n\n    inpnode.parentNode.appendChild(this.inputgroup);\n\n    // this._replacednode.addEventListener(\"wh:form-enable\", ev =>\n    // {\n    //   dompack.toggleClass(this.inputgroup, \"wh-form__dateinputgroup--disabled\", ev.detail.enabled );\n\n    //   this.daynode.disabled = !ev.detail.enabled;\n    //   this.monthnode.disabled = !ev.detail.enabled;\n    //   this.yearnode.disabled = !ev.detail.enabled;\n\n    //   this.daynode.readonly = !ev.detail.enabled;\n    //   this.monthnode.readonly = !ev.detail.enabled;\n    //   this.yearnode.readonly = !ev.detail.enabled;\n    // });\n\n    for (const node of this.inputgroup.querySelectorAll(\"input\")) {\n      node.addEventListener(\"blur\", () => { this.inputgroup.classList.remove(\"focus\"); });\n      node.addEventListener(\"focus\", () => {\n        this.previous.value = node.value;\n        this.inputgroup.classList.add(\"focus\");\n      });\n\n      node.addEventListener(\"change\", ev => this.onChange(ev, node));\n      node.addEventListener(\"keyup\", ev => this.onKeyUp(ev, node));\n    }\n  }\n\n  _getSubInputs() {\n    return [this.daynode, this.monthnode, this.yearnode];\n  }\n\n  _refreshReplacingFields() {\n    this.day = null;\n    this.month = null;\n    this.year = null;\n\n    if (this._replacednode.value !== \"\")//Should be iso date\n    {\n      const parts = __strToIntegerArray(this._replacednode.value);\n      if (parts.length > 2) {\n        this.day = parts[2];\n        this.month = parts[1];\n        this.year = parts[0];\n      }\n    }\n\n    this.daynode.value = this.day === null ? \"\" : this.day;\n    this.monthnode.value = this.month === null ? \"\" : this.month;\n    this.yearnode.value = this.year === null ? \"\" : this.year;\n  }\n\n  onChange(ev, node) {\n    const prev_day = this.day;\n    const prev_month = this.month;\n    const prev_year = this.year;\n\n    if (node === this.daynode)\n      __validateNumberField(this, \"day\", node);\n    else if (node === this.monthnode)\n      __validateNumberField(this, \"month\", node);\n    else if (node === this.yearnode)\n      __validateNumberField(this, \"year\", node);\n\n    let setvalue = null;\n    if (this.day !== null && this.month !== null && this.year !== null && isValidDate(this.year, this.month, this.day))\n      setvalue = formatISODate(this);\n    else if (this.daynode.value === \"\" && this.monthnode.value === \"\" && this.yearnode.value === \"\")\n      setvalue = \"\";\n\n    //FIXME who needs these classes ?\n    const hasvalue = this.day !== null && this.month !== null && this.year !== null;\n    dompack.toggleClass(this.inputgroup, \"hasvalue\", hasvalue);\n    dompack.toggleClass(this.inputgroup, \"partlyfilled\", !hasvalue && (this.day !== null || this.month !== null || this.year !== null));\n\n    if (setvalue !== null && this._lastsetvalue !== setvalue) {\n      this._replacednode.value = setvalue;\n      this._lastsetvalue = setvalue;\n      domevents.fireHTMLEvent(this._replacednode, 'change');\n    }\n  }\n\n  onKeyUp(ev, node) {\n    ev.preventDefault();\n    ev.stopPropagation();\n\n    const prevval = this.previous.value;\n    this.previous.value = node.value;\n\n    if (ev.keyCode === 8 && node.value === \"\" && prevval === \"\")//backspace\n    {\n      //Try to set focus on previous input\n      const prevnode = node.parentNode.previousSibling;\n      if (prevnode) {\n        const previnp = prevnode.querySelector(\"input\");\n        if (previnp)\n          previnp.focus();\n      }\n\n      return;\n    }\n\n    //First some basic validation\n    const value = node.value.replace(/[^0-9]+/g, '');\n\n    if (value === \"\" || value !== node.value || Number(value) < Number(node.min) || Number(value) > Number(node.max))\n      return;\n\n    //Is field value minimal length\n    if ((node === this.yearnode && value.length < 4) || (node !== this.yearnode && value.length < 2))\n      return;\n\n    if (prevval === node.value)\n      return;//Only go to next input if value changed\n\n    //Try to set focus on next input\n    const nextnode = node.parentNode.nextSibling;\n    if (!nextnode)\n      return;\n\n    const nextinp = nextnode.querySelector(\"input\");\n    if (nextinp)\n      nextinp.focus();\n  }\n}\n\nexport class SplitTimeField extends MultiInputSubstition {\n  constructor(inpnode) {\n    super(inpnode);\n    if (!this._replacednode)\n      return;\n\n    __hideInput(inpnode);//hide current input\n\n    this.previous = { value: '' };\n\n    this.placeholder = {\n      hours: \"hh\",\n      minutes: \"mm\",\n      seconds: \"ss\"\n    };\n\n    if (getLang().language === \"nl\")\n      this.placeholder = {\n        hours: \"uu\",\n        minutes: \"mm\",\n        seconds: \"ss\"\n      };\n\n    this.hours = null;\n    this.minutes = null;\n    this.seconds = null;\n\n    if (this._replacednode.value !== \"\")//Should be iso date\n    {\n      const parts = __strToIntegerArray(this._replacednode.value);\n      if (parts.length > 1) {\n        this.hour = parts[0];\n        this.minute = parts[1];\n\n        if (this._replacednode.dataset.whPrecision === \"seconds\" && parts.length > 2)\n          this.seconds = parts[2];\n      }\n    }\n\n    const isdisabled = this._replacednode.disabled;\n    const isreadonly = this._replacednode.readonly;\n\n    this.hournode = <input disabled={isdisabled} readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"2\" value={this.hours === null ? \"\" : this.hours} min=\"0\" max=\"23\" type=\"number\"\n      placeholder={this.placeholder.hours}\n      aria-label={getTid(\"publisher:site.forms.splitdatetime-hours-arialabel\")}\n    />;\n    this.minutenode = <input disabled={isdisabled} readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"2\" value={this.minutes === null ? \"\" : this.minutes} min=\"0\" max=\"59\" type=\"number\"\n      placeholder={this.placeholder.minutes}\n      aria-label={getTid(\"publisher:site.forms.splitdatetime-minutes-arialabel\")}\n    />;\n\n    this.inputgroup = <div class=\"wh-form__timeinputgroup\" role=\"group\">\n      <div class=\"wh-form__timeinputgroup__line wh-form__timeinputgroup__hour\">\n        {this.hournode}\n      </div>\n      <div class=\"wh-form__timeinputgroup__line wh-form__timeinputgroup__minute\">\n        {this.minutenode}\n      </div>\n    </div>;\n\n    // Refer to the label (Because we have role=\"group\" we need a label)\n    const labelid = ensureLabelID(inpnode);\n    //console.log(\"labelid for time field\", labelid);\n    if (labelid !== \"\")\n      this.inputgroup.setAttribute(\"aria-labelledby\", labelid);\n\n\n    if (this._replacednode.dataset.whPrecision === \"seconds\") {\n      this.secondnode = <input disabled={isdisabled} readonly={isreadonly} pattern=\"[0-9]*\" inputmode=\"numeric\" autocomplete=\"off\" maxlength=\"2\" value={this.seconds === null ? \"\" : this.seconds} min=\"0\" max=\"59\" type=\"number\"\n        placeholder={this.placeholder.seconds}\n        aria-label={getTid(\"publisher:site.forms.splitdatetime-seconds-arialabel\")}\n      />;\n      this.inputgroup.appendChild(<div class=\"wh-form__timeinputgroup__line wh-form__timeinputgroup__second\">\n        {this.secondnode}\n      </div>);\n\n      this.inputgroup.classList.add(\"wh-form__timeinputgroup--3col\");\n    }\n\n\n    // Take the replaced input out of the keyboard navigation.\n    // But it'll retain the ability to get focus. So if code sets the focus it will be forwarded to the first input in the group (the day).\n    this._replacednode.setAttribute(\"tabindex\", \"-1\");\n\n    //If focus on hidden time input, set focus on first field in replacement\n    this._replacednode.addEventListener(\"focus\", ev => {\n      // NOTE: It's important we have set tabindex=\"-1\" on the input, otherwise when we tab backwards from\n      //       the first input in our group we are returned back to the day input. (so we can never escape backwards)\n      const nextnode = this.inputgroup.querySelector(\"input\");\n      if (nextnode)\n        nextnode.focus();\n    });\n\n\n    if (isdisabled)\n      this.inputgroup.classList.add(\"wh-form__timeinputgroup--disabled\");\n    if (isreadonly)\n      this.inputgroup.classList.add(\"wh-form__timeinputgroup--disabled\");\n\n    inpnode.parentNode.appendChild(this.inputgroup);\n\n    this._replacednode.addEventListener(\"wh:form-enable\", ev => {\n      dompack.toggleClass(this.inputgroup, \"wh-form__timeinputgroup--disabled\", ev.detail.enabled);\n\n      this.hournode.disabled = !ev.detail.enabled;\n      this.minutenode.disabled = !ev.detail.enabled;\n      if (this.secondnode)\n        this.secondnode.disabled = !ev.detail.enabled;\n\n      this.hournode.readonly = !ev.detail.enabled;\n      this.minutenode.readonly = !ev.detail.enabled;\n      if (this.secondnode)\n        this.secondnode.readonly = !ev.detail.enabled;\n    });\n\n    for (const node of this.inputgroup.querySelectorAll(\"input\")) {\n      node.addEventListener(\"blur\", () => { this.inputgroup.classList.remove(\"focus\"); });\n      node.addEventListener(\"focus\", () => {\n        this.previous.value = node.value;\n        this.inputgroup.classList.add(\"focus\");\n      });\n\n      node.addEventListener(\"change\", ev => this.onChange(ev, node));\n      node.addEventListener(\"keyup\", ev => this.onKeyUp(ev, node));\n    }\n  }\n\n  _getSubInputs() {\n    return [this.hournode, this.minutenode, ...(this.secondnode ? [this.secondenode] : [])];\n  }\n\n  onChange(ev, node) {\n    const prev_hours = this.hours;\n    const prev_minutes = this.minutes;\n    const prev_seconds = this.seconds;\n\n    if (node === this.hournode)\n      __validateNumberField(this, \"hours\", node);\n    else if (node === this.minutenode) {\n      __validateNumberField(this, \"minutes\", node);\n      if (node.value.length === 1)\n        node.value = \"0\" + node.value;\n    } else if (node === this.secondnode) {\n      __validateNumberField(this, \"seconds\", node);\n      if (node.value.length === 1)\n        node.value = \"0\" + node.value;\n    }\n\n    if (this.hours !== null && this.minutes !== null)\n      this._replacednode.value = (this.hours < 10 ? \"0\" : \"\") + this.hours + (this.minutes < 10 ? \":0\" : \":\") + this.minutes;\n    else\n      this._replacednode.value = \"\";\n\n    let hasvalue = this.hours !== null && this.minutes !== null;\n    if (hasvalue && this.secondnode && this.seconds === null)\n      hasvalue = false;\n    dompack.toggleClass(this.inputgroup, \"hasvalue\", hasvalue);\n    dompack.toggleClass(this.inputgroup, \"partlyfilled\", !hasvalue && (this.hours !== null || this.minutes !== null || (this.secondnode && this.seconds !== null)));\n\n    //Trigger change event on original input\n    if (prev_hours !== this.hours || prev_minutes !== this.minutes || prev_seconds !== this.seconds)\n      domevents.fireHTMLEvent(this._replacednode, 'change');\n  }\n\n  onKeyUp(ev, node) {\n    ev.preventDefault();\n    ev.stopPropagation();\n\n    const prevval = this.previous.value;\n    this.previous.value = node.value;\n\n    if (ev.keyCode === 8 && node.value === \"\" && prevval === \"\")//backspace\n    {\n      //Try to set focus on previous input\n      const prevnode = node.parentNode.previousSibling;\n      if (prevnode) {\n        const previnp = prevnode.querySelector(\"input\");\n        if (previnp)\n          previnp.focus();\n      }\n\n      return;\n    }\n\n    //First some basic validation\n    const value = node.value.replace(/[^0-9]+/g, '');\n    if (value === \"\" || value !== node.value || Number(value) < Number(node.min) || Number(value) > Number(node.max))\n      return;\n\n    //Is field value minimal length\n    if (value.length < 2)\n      return;\n\n    if (prevval === node.value)\n      return;//Only go to next input if value changed\n\n    //Try to set focus on next input\n    const nextnode = node.parentNode.nextSibling;\n    if (!nextnode)\n      return;\n\n    const nextinp = nextnode.querySelector(\"input\");\n    if (nextinp)\n      nextinp.focus();\n  }\n}\n\n\nfunction __strToIntegerArray(str) {\n  const ilist = [];\n  const parts = str.split(/[^0-9]+/);\n  for (let i = 0; i < parts.length; ++i)\n    ilist.push(Number(parts[i]));\n\n  return ilist;\n}\n\n\nfunction __validateNumberField(self, fieldname, node) {\n  const value = node.value.replace(/[^0-9]+/g, '');\n  node.value = value;\n\n  if (value !== \"\")\n    self[fieldname] = Number(value);\n  else\n    self[fieldname] = null;\n}\n\n\nfunction __hideInput(node) {\n  node.style.display = \"block\";\n  node.style.position = \"absolute\";\n  node.style.left = \"-9999px\";\n  node.style.width = \"0px\";\n  node.style.height = \"0px\";\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\n/** Generic support for .wh-form .wh-rtd--forminput */\nimport * as dompack from 'dompack';\n\n//we delay load the RTE, but we still need its styling - we don't have a delayed load for SCSS yet.\nimport '@mod-tollium/web/ui/components/richeditor/styling';\n\nimport type * as RichEditor from '@mod-tollium/web/ui/components/richeditor';\nimport type FreeEditor from '@mod-tollium/web/ui/components/richeditor/internal/free-editor';\nimport type StructuredEditor from '@mod-tollium/web/ui/components/richeditor/internal/structurededitor';\nimport type { ExternalStructureDef } from '@mod-tollium/web/ui/components/richeditor/internal/parsedstructure';\nimport type { EditorBaseOptions } from '@mod-tollium/web/ui/components/richeditor/internal/editorbase';\nimport type RPCFormBase from '../../rpc';\nimport type { RTEWidget } from '@mod-tollium/web/ui/components/richeditor/internal/types';\nimport { JSFormElement } from '@webhare/forms/src/jsformelement';\n\n//FIXME  Are we sure we want to have one control handling both Free and Structured RTD? does the form RPC currently even support Free? might remove 'as' below if we dont eg insertVideo...\n\nexport interface RTDFieldOptions {\n  /** options.onInsertVideo: function (node) - should return a promise resolving to an instance if the insertion is successful, or resolve to null if cancelled. receives the html rteedit node on which we're invoked */\n  onInsertVideo?: (node: HTMLElement) => void;\n  hidebuttons?: string[];\n  rtdoptions?: EditorBaseOptions;\n}\n\nexport class RTDEditElement extends JSFormElement<string> {\n  rte: FreeEditor | StructuredEditor | null = null;\n  // options: RTDFieldOptions;\n  // _fieldgroup: HTMLElement | null;\n  node;\n  onInsertVideo?: (node: HTMLElement) => void;\n\n  constructor() {\n    super();\n    this.node = this;\n    //@ts-expect-error cleanup registration\n    this.node.whRTDField = this;\n  }\n\n  async connectedCallback() {\n    const specifiedopts = JSON.parse(this.node.dataset.whRtdoptions || '{}') as { structure?: ExternalStructureDef };\n    const structure = specifiedopts.structure || null;\n    const hidebuttons = this.node.getAttribute(\"hidebuttons\")?.split(\" \") || [];\n\n    if (structure && !structure.blockstyles.some(style => style.type === \"table\"))\n      hidebuttons.push(\"table\");\n    hidebuttons.push('object-insert');\n    hidebuttons.push('action-showformatting');\n\n    // //We shouldn't be waiting to receive enable/disable until the RTD is there\n    // this._fieldgroup = this.node.closest(\".wh-form__fieldgroup\");\n    // if (this._fieldgroup) {\n    //   this.node.dataset.whFormStateListener = \"true\";\n    //   this.node.addEventListener('wh:form-enable', evt => this._handleEnable(evt));\n    // }\n\n    const rtdoptions: Partial<EditorBaseOptions> =\n    {\n      enabled: true,\n      readonly: false,\n      structure,\n      allowtags: null,//data.allowtags.length ? data.allowtags : null\n      hidebuttons: hidebuttons,\n      editembeddedobjects: false,\n      ...specifiedopts\n    };\n    //FIXME\n    //, onStatechange: this._onRTEStateChange.bind(this)\n    //FIXME\n    //, language: 'en'//parent.app.lang      // FIXME\n    //, log:true\n    //FIXME , structure: data.structure\n    //, csslinks: [data.cssurl]\n    //, cssinstance: data.cssinstance\n    //, breakupnodes: this.isemaileditor ? [ 'blockquote' ] : []\n    //, hidebuttons: hidebuttons\n    //, htmlclass: data.htmlclass\n    //, bodyclass: data.bodyclass\n    //, csscode: data.csscode\n\n    //Mark the UI as busy while we're loading the RTE\n    using lock = dompack.flagUIBusy();\n    void (lock);\n\n    const richeditor = await import('@mod-tollium/web/ui/components/richeditor') as typeof RichEditor;\n\n    this.rte = richeditor.createRTE(this.node, {\n      ...rtdoptions,\n      enabled: !this.disabled //initial enabled state\n    });\n\n    this.node.rte = this.rte;\n    //@ts-expect-error -- remove as soon as wh:richeditor-action is defined\n    this.node.addEventListener('wh:richeditor-action', evt => void this.executeAction(evt));\n    this.node.addEventListener('wh:richeditor-dirty', evt => dompack.dispatchCustomEvent(this.node, 'input', { bubbles: true, cancelable: false }));\n  }\n\n  get value(): string {\n    return this.rte ? this.rte.getValue() : this.node.innerHTML;\n  }\n\n  set value(newvalue: string) {\n    if (typeof newvalue !== 'string')\n      throw new Error(`Invalid value for RTE field: ${typeof newvalue}`);\n\n    if (this.rte)\n      this.rte.setValue(newvalue);\n    else\n      this.node.innerHTML = newvalue;\n  }\n\n  async executeAction(evt: CustomEvent<{ action: string }>) {\n    if (evt.detail.action === 'object-video' && this.onInsertVideo) {\n      evt.stopPropagation();\n      evt.preventDefault();\n      this.onInsertVideo(this.node);\n      return;\n    }\n  }\n\n  async insertVideoByURL(url: string) {\n    const formhandler = this.node.closest('form')?.propWhFormhandler;\n    if (!formhandler)\n      throw new Error(`RTE no longer associated with a form`);\n\n    const result = await (formhandler as RPCFormBase).invokeRPC(this.name + '.insertVideoByUrl', url) as { success: boolean; embeddedobject?: RTEWidget };\n    if (!result.success)\n      return { success: false, message: \"Video URL not understood\" };\n\n    (this.rte!.getEditor() as StructuredEditor).insertEmbeddedObject(result.embeddedobject!);\n    return { success: true };\n  }\n\n  set disabled(disable: boolean) {\n    super.disabled = disable;\n    this._updateEnabledStatus(!disable);\n  }\n  _updateEnabledStatus(nowenabled: boolean) {\n    this.rte?.setEnabled(nowenabled);\n    if (nowenabled)\n      this.node.removeAttribute(\"data-wh-form-disabled\");\n    else\n      this.node.setAttribute(\"data-wh-form-disabled\", \"\");\n  }\n\n  static getForNode(node: HTMLElement): RTDField | null {\n    //@ts-expect-error cleanup registration\n    return (node.whRTDField as RTDField) || null;\n  }\n}\n\nexport default class RTDField {\n  constructor(node: HTMLElement, options?: RTDFieldOptions) {\n    const hidebuttons = options?.hidebuttons || [];\n    if (!options?.onInsertVideo)\n      hidebuttons.push('object-video');\n    if (hidebuttons.length)\n      node.setAttribute(\"hidebuttons\", hidebuttons.join(\" \"));\n\n    customElements.whenDefined(\"wh-rtdedit\").then(() => {\n      if (options?.onInsertVideo) //TODO cleaner, use event handlers? RTD already has some action-eventhandler stuff though..\n        (node as RTDEditElement).onInsertVideo = options.onInsertVideo;\n    });\n\n    if (!customElements.get(\"wh-rtdedit\"))\n      customElements.define(\"wh-rtdedit\", RTDEditElement);\n  }\n}\n","/// @ts-nocheck -- Bulk rename to enable TypeScript validation\n\nimport * as dompack from 'dompack';\nimport { getTid } from \"@webhare/gettid\";\nimport \"./video.css\";\nimport \"../internal/rtd.lang.json\";\nimport * as consenthandler from '@mod-publisher/js/analytics/consenthandler';\n\n\nfunction createMyFrame() {\n  const ifrm = document.createElement(\"iframe\");\n  ifrm.style.width = \"100%\";\n  ifrm.style.height = \"100%\";\n  ifrm.setAttribute(\"frameborder\", 0);\n  ifrm.setAttribute(\"allowfullscreen\", \"\");\n\n  /*\n  Most browsers default to \"strict-origin-when-cross-origin\", but let's explicitly request it.\n  (so video providers can only see from which website you view the video, not which specific page)\n  Note that YouTube won't accept \"no-referrer\", it'll give an \"YouTube Error 153\" message.\n  (this probably was enforced since july 2025, error 153 appeared in the IFrame Player API documentation somewhere between 2 and 9 july 2025)\n\n  Also see:\n  - https://developers.google.com/youtube/iframe_api_reference\n  - https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-player-api-client-identity\n  */\n  ifrm.setAttribute(\"referrerpolicy\", \"strict-origin-when-cross-origin\");\n\n  // delegate autoplay (for Chrome) and fullscreen permission to the video player iframe\n  // see: https://developer.chrome.com/blog/autoplay/#iframe_delegation\n  ifrm.setAttribute(\"allow\", \"autoplay; fullscreen\");\n\n  return ifrm;\n}\n\nfunction initYouTube(node, video, playback) {\n  const ifrm = createMyFrame();\n\n  // List of embed parameters YouTube supports:\n  // https://developers.google.com/youtube/player_parameters\n\n  const youtubeUrl = new URL(`https://www.youtube.com/embed/${encodeURIComponent(video.id)}`);\n\n  if (playback.autoplay)\n    youtubeUrl.searchParams.set(\"autoplay\", \"1\");\n\n  if (video.mute || playback.mute)\n    youtubeUrl.searchParams.set(\"mute\", \"1\");\n\n  if (video.starttime)\n    youtubeUrl.searchParams.set(\"start\", String(Math.floor(video.starttime))); // seconds, whole integer (YouTube also uses t= in the shorturl??)\n\n  if (video.endtime)\n    youtubeUrl.searchParams.set(\"end\", String(Math.floor(video.endtime)));\n\n  if (typeof playback.controls !== \"undefined\" && !playback.controls)\n    youtubeUrl.searchParams.set(\"controls\", \"0\");\n\n  if (video.loop || playback.loop) {\n    /* from the documentation: https://developers.google.com/youtube/player_parameters\n       Note: This parameter has limited support in IFrame embeds. To loop a single video,\n       set the loop parameter value to 1 and set the playlist parameter value to the\n       same video ID already specified in the Player API URL:\n       https://www.youtube.com/embed/VIDEO_ID?playlist=VIDEO_ID&loop=1\n    */\n    youtubeUrl.searchParams.set(\"loop\", \"1\");\n    youtubeUrl.searchParams.set(\"playlist\", video.id);//To enable loop, set same video as playlist\n  }\n\n  youtubeUrl.searchParams.set(\"rel\", \"0\"); // disable 'related video's'\n  youtubeUrl.searchParams.set(\"enablejsapi\", \"1\");\n  youtubeUrl.searchParams.set(\"origin\", location.origin);\n\n  ifrm.src = youtubeUrl.toString();\n  ifrm.title = video.title ? \"YouTube video: \" + video.title : \"YouTube video\";\n  node.appendChild(ifrm);\n}\n\nfunction initVimeo(node, video, playback) {\n  const ifrm = createMyFrame();\n\n  // List of embed parameters Vimeo supports:\n  // https://vimeo.zendesk.com/hc/en-us/articles/360001494447-Player-parameters-overview\n\n  const vimeoUrl = new URL(`https://player.vimeo.com/video/${encodeURIComponent(video.id)}`);\n\n  if (playback.autoplay)\n    vimeoUrl.searchParams.set(\"autoplay\", \"1\");\n\n  if (video.mute || playback.mute)\n    vimeoUrl.searchParams.set(\"muted\", \"1\");\n\n  if (video.endtime)\n    console.warn(\"setting an endtime doesn't work for Vimeo video's\");\n\n  // NOTE: actually disabling controls is possible, but ONLY if the video is hosted by a Plus account or higher\n  if (typeof playback.controls !== \"undefined\" && !playback.controls)\n    console.warn(\"disabling video controls not possible for Vimeo video's\");\n\n  if (video.loop || playback.loop)\n    vimeoUrl.searchParams.set(\"loop\", \"1\");\n\n  if (playback.background)\n    vimeoUrl.searchParams.set(\"background\", \"1\");\n\n  if (playback.api) {\n    vimeoUrl.searchParams.set(\"api\", playback.api);\n\n    // we need a player_id to distinguish from which iframe a message came.\n    // (in cross domain situations we cannot lookup/compare the event source with iframe.contentWindow)\n    if (playback.player_id)\n      vimeoUrl.searchParams.set(\"player_id\", playback.player_id);\n  }\n\n  if (video.starttime) {\n    // #t=3m28s\n    const t = video.starttime;\n    const minutes = Math.floor(t / 60);\n    const seconds = t % 60;\n    vimeoUrl.hash = \"#t=\" + minutes + \"m\" + seconds + \"s\";\n  }\n\n  ifrm.src = vimeoUrl.toString();\n  ifrm.title = video.title ? \"Vimeo video: \" + video.title : \"Vimeo video\";\n  node.appendChild(ifrm);\n}\n\nfunction launchVideo(node, video, opts) {\n  switch (video.network) {\n    case 'youtube':\n      initYouTube(node, video, opts || {});\n      break;\n    case 'vimeo':\n      initVimeo(node, video, opts || {});\n      break;\n  }\n}\n\nfunction initializeVideoElementV1(node) {\n  const video = JSON.parse(node.dataset.video);\n  const opts = node.dataset.videoOptions ? JSON.parse(node.dataset.videoOptions) : {};\n  node.innerHTML = '';\n  launchVideo(node, video, opts);\n}\n\nfunction initializeVideoElementV2(node) {\n  const video = JSON.parse(node.dataset.whVideo);\n\n  const videonodes = dompack.qSA(node, \".wh-video--activate\");\n\n  for (const videonode of videonodes) {\n    videonode.addEventListener(\"click\", function () {\n      activateVideo(videonode, video);\n    });\n\n    const playbutton = videonode.querySelector(\".wh-video__playbutton\");\n    playbutton.setAttribute(\"tabindex\", \"0\");\n    playbutton.setAttribute(\"role\", \"button\");\n    playbutton.setAttribute(\"aria-label\", getTid(\"publisher:site.rtd.embedvideo.playbutton-aria\"));\n\n    playbutton.addEventListener(\"click\", function () {\n      activateVideo(videonode, video, { autoplay: true });\n    });\n\n    // Because we don't use <button> we must implement it's keyboard interaction\n    playbutton.addEventListener(\"keypress\", function (evt) {\n      // we are only interested in enter and space keypressed\n      if (evt.keyCode !== 13 && evt.keyCode !== 32)\n        return;\n\n      // prevent other code getting the event or the space both triggering the video AND scrolling the page\n      evt.preventDefault();\n\n      activateVideo(videonode, video, { autoplay: true });\n    });\n\n    if (video.autoplay) //activate immediately\n      if (node.dataset.whConsentRequired)\n        consenthandler.onConsent(node.dataset.whConsentRequired, () => activateVideo(videonode, { ...video, mute: true }, { autoplay: true }));\n      else\n        activateVideo(videonode, { ...video, mute: true }, { autoplay: true });\n  }\n}\n\nfunction activateVideo(videonode, video, opts) {\n  if (videonode.__initialized)\n    return;\n\n  videonode.querySelector(\".wh-video__innerframe__preview\").hidden = true;\n  videonode.__initialized = true;\n  launchVideo(videonode, video, opts);\n}\n\ndompack.register('.wh-video', node => node.dataset.video ? initializeVideoElementV1(node) : initializeVideoElementV2(node));\n","// Auto-generated language file from /opt/wh/whtree/modules/publisher/js/internal/rtd.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"publisher\",\"nl\",{\"site\":{\"rtd\":{\"embedvideo\":{\"playbutton-aria\":\"Speel video af\",\"unrecognized\":\"De URL is niet herkend als een ondersteunde video URL\",\"videourl\":\"Video URL\"}}}});\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/nl.xml\n","import * as dompack from '@webhare/dompack';\nimport { navigateTo } from '@webhare/env';\nimport { debugFlags } from '@webhare/env/src/envbackend';\n\ndeclare global {\n  interface Window {\n    whResetConsent: () => void;\n  }\n  interface GlobalEventHandlersEventMap {\n    \"wh:consent-changed\": CustomEvent<ConsentSettings>;\n  }\n}\n\nexport interface SetupConsentOptions {\n  /** Domain to which to bind the cookie, can be at most one level higher (eg '.example.net' for 'www.example.net') */\n  cookiedomain?: string;\n  /** Duration to store or extend the consent, in days. Defaults to 365 */\n  cookieduration?: number;\n  /** The consent tags which are active by default (only use this for anonymous tracking and functional cookies) */\n  defaultconsent?: string[];\n}\n\ninterface ConsentStatus {\n  /** Version (2) */\n  v: 2;\n  //** Consent options */\n  c?: string[];\n  /** Last consent change (ISO8601 date) */\n  lc?: string;\n}\n\nlet consentstatus: ConsentStatus | null;\nlet cookiename: string | undefined;\nlet consentoptions: SetupConsentOptions | undefined;\n\nexport type ConsentSettings = {\n  isdefault: true;\n  consent: string[];\n} | {\n  isdefault: false;\n  consent: string[] | undefined; //we've explicitly defined no consent-yet-given as 'undefined' (TODO was this a good idea?)\n};\n\n/** Setup the consent handler\n    @param usecookiename - Name of the cookie. Should be identical for all sites sharing this consent, set to empty string if you store consent externally\n    @param consentrequester - Function to invoke if consent is unknown to eg trigger a cookie bar. This function will be immediately registered for invocation through dompack.onDomReady\n*/\nexport function setup(usecookiename: string, consentrequester?: () => void, options?: SetupConsentOptions) {\n  if (typeof usecookiename !== 'string')\n    throw new Error(\"Cookiename must be of type 'string'\");\n  if (debugFlags.cst)\n    console.log(`[cst] consenthandler initialized. cookiename: '${usecookiename}'`);\n\n  cookiename = usecookiename;\n  consentoptions = {\n    cookieduration: 365,\n    defaultconsent: [],\n    ...options\n  };\n\n  if (consentrequester)\n    try {\n      consentstatus = JSON.parse(dompack.getCookie(cookiename)!);\n      if (debugFlags.cst)\n        console.log(`[cst] initial consent state:`, consentstatus);\n    } catch (ignore) {\n    }\n\n  if (!consentstatus || typeof consentstatus !== \"object\" || consentstatus.v !== 2 || typeof consentstatus.c !== \"object\")\n    consentstatus = { v: 2 };\n\n  if (!(\"c\" in consentstatus)) { //simple consent flag\n    if (consentrequester)\n      dompack.onDomReady(consentrequester); //run the request function, but only on domready! it's a safe assumption it should be delayed...\n  } else {\n    storeConsent(); //renew the status\n  }\n  updateConsent();\n}\n\n//Test for consent\nexport function hasConsent(consentsetting: string) {\n  if (consentsetting === undefined) //generic consent check\n    throw new Error(\"hasConsent required a string argument\");\n\n  const details = getConsentDetail();\n  if (!details // setup() not called yet?\n    || !details.consent) // no consent has been given and no defaults are available consent will be undefined?\n    return undefined;\n\n  return details.consent.includes(consentsetting);\n}\n\n//Set simple consent\nexport function setConsent(newsetting: string[]) {\n  if (cookiename === undefined)\n    throw new Error(\"Invoke consenthandler.setup before modifying consent state!\");\n  if (typeof newsetting !== \"object\" || !Array.isArray(newsetting))\n    throw new Error(\"Expecting an array in call to setConsent\");\n\n  // Check if there are some consents being revoked\n  const details = getConsentDetail(); // get current list of consent tags, including implicit (default) consent\n  let consent_revoked = false;\n  if (details?.consent) { // if no explicit or default consent, the consent field is undefined\n    for (const tag of details.consent) {\n      if (!newsetting.includes(tag))\n        consent_revoked = true;\n    }\n  }\n\n  if (!consentstatus)\n    throw new Error(`Attempting to change consent status before invoking consenthandler.setup`);\n\n  consentstatus.c = newsetting.sort();//ensure stable order\n  consentstatus.lc = (new Date()).toISOString();\n\n  storeConsent();\n\n  // Revoked consent may need a reload to take effect.\n  // This is because it's not worth the effort for most websites to implement on-the-fly disabling\n  // of functionality. It might even be impossible if 3rd party scripts are already loaded.\n  if (consent_revoked) {\n    console.log(\"[cst] Reloading to handle revoked consent\");\n    navigateTo({ type: \"reload\" });\n  }\n\n  updateConsent();\n}\n\n/** Get a list of consents and whether they are defaults (or explicitly set)\n    @returns consent: list all consents\n            isdefault: if true then the consents are implicit/defaults (not consent explicitly given by the user)\n*/\nfunction getConsentDetail(): ConsentSettings | null {\n  if (!consentstatus) // setup() did not run yet\n    return null;\n\n  if (!(\"c\" in consentstatus)) { // consent not set yet\n    if (consentoptions?.defaultconsent && consentoptions?.defaultconsent.length > 0)\n      return { consent: consentoptions!.defaultconsent!, isdefault: true }; // use fallback consent\n    else\n      return { consent: undefined, isdefault: false }; // no consent given yet (expected to return undefined for consent)\n  }\n\n  return {\n    consent: consentstatus.c,\n    isdefault: false\n  };\n}\n\nexport function onConsent(type: string, callback: (cs: ConsentSettings) => void) {\n  window.addEventListener(\"wh:consent-changed\", evt => {\n    if (evt.detail.consent?.includes(type))\n      callback(evt.detail);\n  });\n\n  const details = getConsentDetail();\n\n  if (details && details.consent && details.consent.includes(type)) {//already missed it, so invoke\n    if (debugFlags.cst)\n      console.log(\"[anl] Invoking callback\", details);\n    callback(details);\n  }\n}\n\n//Register callback for content changes\nexport function onConsentChange(callback: (cs: ConsentSettings) => void): void {\n  window.addEventListener(\"wh:consent-changed\", evt => callback(evt.detail));\n\n  const details = getConsentDetail();\n\n  if (details) { //already missed it, so invoke\n    if (debugFlags.cst)\n      console.log(\"[cst] Invoking callback\", details);\n    callback(details);\n  }\n}\n\nfunction updateConsentOverlays() {\n  const overlays = dompack.qSA(\".wh-requireconsent__overlay\");\n  const consent = getConsentDetail()!.consent; //we are only scheduled when details are set (but we reread them as they may change)\n\n  if (debugFlags.cst)\n    console.log(`[cst] update ${overlays.length} consent overlay(s). ${consent ? `consent: ${consent.length ? consent.join(', ') : \"<none>\"}` : \"<undefined>\"}`);\n\n  overlays.forEach(overlay => {\n    const parent = overlay.closest<HTMLElement>(\".wh-requireconsent\");\n    if (parent && parent.dataset.whConsentRequired)\n      overlay.hidden = consent?.includes(parent.dataset.whConsentRequired) || false;\n  });\n}\n\nfunction updateConsent() { //update in DOM, GTM, etc\n  const details = getConsentDetail();\n\n  if (!details // setup() not called yet?\n    || !details.consent) { // no consent has been given and no defaults are available consent will be undefined?\n    document.documentElement.dataset.whConsent = \"unknown\"; // unknown - no explicit or explicit (options.defaultconsent) consent\n    return;\n  }\n\n  document.documentElement.dataset.whConsent = details.consent.length ? details.consent.join(\" \") : \"denied\";\n\n  if (debugFlags.cst)\n    console.log(\"[cst] Firing wh:consent-changed with\", details);\n\n  dompack.dispatchCustomEvent(window, \"wh:consent-changed\", { bubbles: false, cancelable: false, detail: details });\n  dompack.onDomReady(updateConsentOverlays);\n}\n\nfunction storeConsent() {\n  if (cookiename)\n    dompack.setCookie(cookiename, JSON.stringify(consentstatus), { duration: consentoptions!.cookieduration, domain: consentoptions!.cookiedomain });\n}\n\nwindow.whResetConsent = function () {\n  if (cookiename === undefined)\n    throw new Error(\"Consent handler not setup\");\n  else if (!cookiename)\n    throw new Error(\"Consent handler is not handling storage\");\n\n  dompack.deleteCookie(cookiename);\n  console.log(\"Reloading for whResetConsent\");\n  navigateTo({ type: \"reload\" });\n};\n","import './home.scss';\n\nimport * as dompack from 'dompack';\n\ndompack.onDomReady(() => {\n  if (!document.documentElement.classList.contains('page-home'))\n    return;\n\n  console.info('page: home');\n});\n","import './about.scss';\n\nimport * as dompack from 'dompack';\n\ndompack.onDomReady(() => {\n  if (!document.documentElement.classList.contains('page-about'))\n    return;\n\n  dompack.qS('html').classList.add('show');\n});\n","import \"@mod-system/js/wh/integration\";\nimport \"dompack/browserfix/reset.css\";\nimport { openLinksInNewWindow } from \"@mod-publisher/js/linkhandler\";\n\nimport './shared/forms/forms';\nimport './shared/rtd/rtd';\n\nimport './alsikindehemelcom.scss';\n\nimport './widgets/widgets';\n\nimport './pages/home/home';\nimport './pages/about/about';\n\nopenLinksInNewWindow(/*openLinksInNewWindow: true*/);\n","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/alsikindehemelcom.20261004T145047.664Z/webdesigns/alsikindehemelcom/alsikindehemelcom.es\";const aps = globalThis.whAssetPacks ||= {}; aps[\"alsikindehemelcom:alsikindehemelcom\"]=\"2026-10-04T14:50:50.982Z\";"],"mappings":"woBAIAA,KCFO,SAASC,GAAqBC,EAA2B,CAC9D,IAAMC,EAAQ,CAAC,EACTC,EAAc,IAAI,IAAI,SAAS,IAAI,EAAE,aAAa,IAAIF,CAAO,EAKnE,GAJIE,GACFD,EAAM,KAAK,GAAGC,EAAY,MAAM,GAAG,CAAC,EAGlC,OAAO,SAAa,IAAa,CACnC,IAAMC,EAAc,SAAS,OAAO,MAAM,cAAcH,CAAO,UAAU,EACzE,GAAIG,EAAa,CACf,IAAMC,EAAmB,mBAAmBD,EAAY,CAAC,CAAC,EACtDC,GACFH,EAAM,KAAK,GAAKG,EAAiB,MAAM,GAAG,EAAE,OAAOC,GAAQ,CAACA,EAAK,WAAW,MAAM,CAAC,CAAE,CACzF,CACF,CAEA,GAAI,OAAO,eAAmB,IAAa,CACzC,IAAMC,EAAe,eAAe,QAAQN,CAAO,EAC/CM,GACFL,EAAM,KAAK,GAAGK,EAAa,MAAM,GAAG,CAAC,CACzC,CAEA,OAAOL,CACT,CDnBAM,KAEAC,IA6CA,IAAIC,GACAC,GACAC,GAAuB,aAGrBC,GAAa,OAAO,SAAa,IAAc,SAAS,cAAc,kBAAkB,EAAI,KAClG,GAAIA,IAAY,YAAa,CAC3B,IAAMC,EAAoF,KAAK,MAAMD,GAAW,WAAW,EAC3HH,GAASK,EAAKD,EAAc,CAAC,WAAY,YAAa,QAAQ,CAAC,EAG/DH,GAAWG,EAAa,UAAYA,EAAa,SACjDF,GAAYE,EAAa,WAAaA,EAAa,SACrD,CAEAE,GAA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AG,CAAE,SAAU,EAAK,CAAC,CAAC,EAErIe,GAAcD,EAAW,CAAE,GAAGd,EAAO,KAAM,EAAK,EAAG,CAAE,SAAU,EAAK,CAAC,EAC3E,CACF,CAEA,SAASe,GAAcD,EAAWd,EAAOS,EAAM,CACzCK,EAAU,gBAGdA,EAAU,cAAc,gCAAgC,EAAE,OAAS,GACnEA,EAAU,cAAgB,GAC1BN,GAAYM,EAAWd,EAAOS,CAAI,EACpC,CAEQW,EAAS,YAAarB,GAAQA,EAAK,QAAQ,MAAQW,GAAyBX,CAAI,EAAIY,GAAyBZ,CAAI,CAAC,EG/L1HsB,IAEQC,GAAW,IAAM,CAClB,SAAS,gBAAgB,UAAU,SAAS,WAAW,GAG5D,QAAQ,KAAK,YAAY,CAC3B,CAAC,ECPDC,IAEQC,GAAW,IAAM,CAClB,SAAS,gBAAgB,UAAU,SAAS,YAAY,GAGrDC,EAAG,MAAM,EAAE,UAAU,IAAI,MAAM,CACzC,CAAC,ECKDC,GAAmD,ECb4E,IAAMC,GAAM,WAAW,eAAiB,CAAC,EAAGA,GAAI,qCAAqC,EAAE","names":["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","init_polyfills","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_dompack","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","e","init_dompack","init_env","linkopenoptions","isattached","onLinkClick","event","link","url","destdomain","ext","match","setupLinksInNewWindow","options","ourdomain","init_dompack","formatters","updaters","mergeNode","node","set","data","parts","isNodeFunc","func","exprpath","callparts","funcrest","value","exprpathparts","i","prop","run","mergenode","filter","nodes","sets","init_dompack","init_env","init_dompack","getISOLocalDate","date","init_dompack","init_dompack","getActiveElement","doc","getToplevelWindow","toplevelwindow","asIframe","node","getCurrentlyFocusedElement","limitdoc","focused","frame","canFocusTo","ignoreInertAttribute","getFocusableComponents","startnode","options","focusable","currentnode","currentstyle","iframe","subnodes","init_std","init_env","rfSymbol","init_gettid","init_std","init_dompack","fixupConditionRecursive","node","condition","mapping","anychanges","subcondition","newName","ArrayField","handler","items","name","throwError","qS","event","addDocEventListener","rownode","qSA","form","getFormHandler","newrow","addedrow","registerMissed","setup","stop","delNode","row","rowBaseName","rowFields","getFormElementCandidates","_","RecordFieldHandler","rows","n","rowval","valuePromises","rowPromises","field","values","rowValue","value","idx","rowField","firstnode","valueRows","newvalue","fieldnode","rowid","nodeArray","fieldname","getFieldName","cellname","subname","setFieldName","labelnodes","labelnode","type","conditionnode","parseCondition","minRows","maxRows","numRows","getTid","init_std","unmapFieldName","camelCaseName","nameToSnakeCase","mapFieldName","htmlName","nameToCamelCase","mapValue","type","invalue","unmapValue","fieldDescr","isDate","HTMLFormFieldHandler","form","field","selectedrow","newvalue","setvalue","RadioFormFieldHandler","name","rnodes","group","node","_","myname","CheckboxGroupHandler","cboxes","throwError","toset","missing","cbox","RegisteredFieldHandler","ArrayFieldHandler","items","rfSymbol","ArrayField","getFieldName","FormFieldMap","fieldName","nodes","subpos","groups","fullName","arraygroup","AddressFieldHandler","RecordFieldHandler","options","mapName","match","data","ignoreUnknownFields","key","value","baseName","retval","val","prettyName","omit","FieldMapDataProxy","target","p","prop","init_browser","delayvalidation","validationpendingfor","didGlobalHandlers","lineFeedsToBreaks","text","frag","part","getPageIdx","state","page","idx","getErrorFields","validationresult","field","getFieldName","value","index","self","hasEverFailed","doValidation","iffailedbefore","releasePendingValidations","debugFlags","form","doDelayValidation","tovalidate","lastfocusout","handleFocusOutEvent","event","handleFocusInEvent","handleValidateAfterEvent","FormBase","FormFieldMap","generateRandomId","#lastFocused","FieldMapDataProxy","node","getFormElementCandidates","setup","addDocEventListener","evt","#recordLastFocus","pagestate","name","#onUnload","now","eventdata","dispatchCustomEvent","control","qSA","element","target","ourcondition","parseCondition","searchparams","allvalues","shouldbechecked","tocheck","_","type","getError","fieldgroup","field_with_message","error","potentialgroupnode","contextnode","messageid","messagenode","suggestionholder","create","describedby","describedby_fields","failedfield","getValidationState","stop","extradata","submitter","submitselector","tempbutton","beforeResult","isPromise","el","queryFormFieldLike","startingpoint","lock","flagUIBusy","result","containingpage","pagenum","actionnode","pages","curpage","pagelist","currentpage","scrollto","origscrollto","__isSubmit","pageidx","goingforward","run","direction","pagenode","action","navigateTo","validationstatus","isinit","hiddenPages","mergeNodes","anychanges","formpage","visible","hiddengroups","enabledgroups","requiredgroups","formgroup","groupPage","enabled","required","formline","inputtargets","node_enabled","isFormFieldLike","node_required","isFormControl","option","option_enabled","option_hidden","selectnode","wrapSerialized","nodes","formvalue","mergeNode","conditiontext","fieldname","options","matchfield","isRadioNodeList","currentvalue","conditionfield","fields","attrname","selectedvalue","val","selected","qS","extrafields","condition","subcondition","birthdate","age","matchcase","compareagainst","currentValArray","nextpage","morepages","curpagerole","nextpagerole","richvalues","rawNavigateTo","exitButton","parsedNavTo","redirectdelay","submitButton","submitButtonLabel","registerMissed","isLive","getFieldDisplayName","rfSymbol","deferred","file","fieldnode","saveInteractive","changeValue","foundfields","skiparraymembers","addto","isRadioOrCheckbox","outdata","fieldpromises","receivedvalue","resolve","reject","e","opts","vals","checker","setupValidator","setFieldError","isFieldNativeErrored","updateFieldError","validator","limitset","defer","item","original","group","subnode","tovalidatelist","validationresults","fld","failed","tofocus","canFocusTo","getFocusableComponents","focus","init_env","init_std","init_formservice","lookupcache","verifyHareScriptAddress","address","options","lookupkey","stringify","emplace","getFormService","init_std","SubField","node","pos","throwError","AddressField","qR","prefixLength","fieldpos","field","qSA","event","fieldname","data","firstfield","key","country","ordering","e","prevgroup","idx","item","fieldgroup","setFieldError","value","visiblefields","anyset","allrequiredset","form","FormBase","curstate","result","lock","flagUIBusy","el","verifyHareScriptAddress","debugFlags","err","anychanges","newvalue","changeValue","init_gettid","init_std","formatDate","dateformat","year","month","day","isValidDate","output","c","parseDate","format","newdate","options","parts","dayoffset","monthoffset","yearoffset","daypos","monthpos","yearpos","day","month","year","isValidDate","parseISODate","newdate","options","parseDate","init_std","validateCheckboxGroup","groupnode","nodes","qSA","min","max","anyenabled","node","numChecked","getTid","validateRadioGroup","reformatDate","datestr","parsed","parseISODate","formatDate","validateDate","date","dateparts","year","month","day","isValidDate","normalizeddate","validateTime","time","timeparts","hours","minutes","seconds","setup","form","datecontrol","field","datematch","propname","thedate","getISOLocalDate","setupValidator","timecontrol","propvalue","checkboxgroup","radiogroup","addresscontrol","AddressField","init_gettid","init_dompack","JSFormElement","newname","required","disable","name","oldValue","newValue","init_std","queryFormFieldLike","isInputElement","field","isHTMLElement","isFormFieldLike","control","isFormControl","JSFormElement","isRadioOrCheckbox","isRadioNodeList","el","getFieldName","setFieldName","newname","getFieldDisplayName","downgradeUploadFields","form","uploadfield","qSA","input","attr","getErrorForValidity","validity","getTid","max","reformatDate","min","key","isFieldNativeErrored","getFieldNativeError","parseCondition","conditiontext","getFormElementCandidates","basenode","namePrefix","parentForm","candidates","getFormHandler","node","allowMissing","throwError","setupServerErrorClear","field","group","setFieldError","ComponentValidationState","el","err","getFieldNativeError","validations","getValidationState","state","newstate","error","options","isHTMLElement","debugFlags","getFieldDisplayName","updateFieldError","dispatchCustomEvent","setupValidator","node","checker","init_dompack","init_formservice","init_dompack","init_gettid","init_formservice","init_std","init_env","cache","mayValidateField","field","acceptEmailSuggestion","evt","form","suggestion","stop","validateField","setFieldError","checkvalue","isValidEmail","getTid","key","rpcCall","getFormService","getTidLanguage","wrapInTimeout","result","e","debugFlags","jsxcreate","init_dompack","init_keyboard","dialogconstructor","dialogoptions","createDialog","options","dialogconstructor","dialog","runMessageBox","question","choices","choicebuttons","choice","create","dialogoptions","init_env","init_std","init_upload","init_jsonrpc_client","init_dompack","init_gettid","registerTexts","captcharegistry","initializeCaptcha","provider","injectInto","settings","finalsettings","getTid","init_dompack","init_gettid","init_dompack","init_upload","init_gettid","registerTexts","isAcceptableType","fileType","masks","basetype","FileEditElement","JSFormElement","csslink","#setValue","evt","error","setFieldError","getTid","value","toset","row","getFieldDisplayName","mimetype","accept","mask","files","_stack","lock","__using","flagUIBusy","file","requestFile","_","_error","_hasError","__callDispose","msg","dispatchCustomEvent","idx","stop","button","init_std","FileUploadFormElement","FileEditElement","#constructFileHolder","fileholder","nodes","idx","file","filename","isFile","filenamefield","jsxcreate","deletebutton","getTid","uploadbutton","UploadField","node","init_dompack","init_std","init_gettid","init_upload","revoker","cachedURLs","createFileURL","file","emplace","newurl","oldurl","getImageDimensions","img","loadImage","getFileAsDataURL","ImgEditElement","_ImgEditElement","FileEditElement","name","_oldValue","newValue","value","textupdate","qSA","node","error","size","setFieldError","getTid","nodes","idx","imgholder","create","deletebutton","contentwrapper","uploadicon","explain","ImgEditField","init_dompack","init_std","formConfiguration","handlers","configuredRegistrations","firstWarningMs","warningIntervalMs","scheduleFormSetup","form","factory","_stack","lock","__using","flagUIBusy","customEls","qSA","_","initPromise","nextWarning","timeoutPromise","sleep","missing","tag","downgradeUploadFields","_error","_hasError","__callDispose","configureForms","setup","dispatchCustomEvent","registerHandlers","addHandlers","defaultHandler","RPCFormBase","handlername","handler","emplace","current","register","getFormConfiguration","formConfiguration","init_std","init_dompack","init_keyboard","init_dompack","init_keyboard","init_tree","init_gettid","init_dompack","init_dompack","recaptchaload","recaptchaload","init_dompack","setupForms","options","registerHandlers","configureForms","omit","init_gettid","CaptchaField","JSFormElement","evt","form","setFieldError","getTid","provider","initializeCaptcha","result","stop","setupCaptchaFieldGroup","captchaControl","create","virtualCaptchaPage","buttonarea","qS","unpackObject","formvalue","_","buildTarget","target","FormSubmitter","cache","offline","file","completed","uploader","SingleFileUploader","uploadinstructions","getTSFormService","uploadedfile","isBlob","result","key","value","buildRPCFormSubmission","target","formValue","options","vals","FormSubmitter","eventdetail","buildTarget","unpackObject","submitRPCForm","submission","createClient","RPCFormBase","FormBase","#hadFocus","#completedUploads","#settingUpCaptcha","formnode","#onFirstFocus","isLive","#getSubmitVals","formvalue","background","methodname","args","waiter","lock","flagUIBusy","rpc","getFormService","result","field","prop","value","matchpage","dataval","fieldnode","promise","messages","msg","extradata","extraSubmitAwaitable","extraSubmit","dispatchCustomEvent","config","getFormConfiguration","captchaConfig","setupCaptchaFieldGroup","parameters","insubmitrpc","submitparameters","debugFlags","didfirstfocus","globalerrors","error","failednode","serverMetadata","focus","setFieldError","run","failedfields","pick","e","errors","create","runMessageBox","navigateTo","getCurrentlyFocusedElement","validation","validateField","init_env","init_dompack","init_std","init_env","eventname_regex","datakey_regex","max_sessionid_age","globalOptions","pagesession","useAltRecordURL","seqnr","pxlUserId","pxlSessionId","buildOptions","options","pxlFailed","errormessage","params","isLive","makePxlURL","baseurl","eventname","data","options","globalOptions","eventname_regex","pagesession","generateRandomId","url","seqnr","getPxlSessionId","getPxlId","browser","getBrowser","name","value","test","datakey_regex","type","pxlUserId","timestampvar","debugFlags","sessionExpireDays","max_sessionid_age","expiration","pxlSessionId","sendPxlEvent","event","finaloptions","buildOptions","useAltRecordURL","fetchRes","error","init_env","activeListenPrefixes","sendPxl","eventKey","params","data","options","pxldata","k","v","sendPxlEvent","setupFormAnalytics","prefix","registered","dtapStage","e","formeventdata","key","val","setupForms","form","FormBase","setupFormAnalytics","init_dompack","init_events","init_gettid","init_env","init_std","init_tree","isLive","labelcount","formatDate","dateformat","dateparts","output","c","formatISODate","ensureLabelID","inputnode","id","labelnode","mySelectGetValue","mySelectSetValue","newvalue","origsetter","setupMyDateValueProperty","select","MultiInputSubstition","inpnode","isdisabled","isrequired","toggleClass","node","SplitDateField","__hideInput","day_pos","month_pos","year_pos","ordering","__strToIntegerArray","i","getLang","parts","isreadonly","year_min","year_max","jsxcreate","labelid","getTid","ev","nextnode","prev_day","prev_month","prev_year","__validateNumberField","setvalue","isValidDate","hasvalue","fireHTMLEvent","prevval","prevnode","previnp","value","nextinp","SplitTimeField","prev_hours","prev_minutes","prev_seconds","str","ilist","self","fieldname","init_dompack","RTDEditElement","JSFormElement","_stack","specifiedopts","structure","hidebuttons","style","rtdoptions","lock","__using","flagUIBusy","richeditor","evt","dispatchCustomEvent","_","_error","_hasError","__callDispose","newvalue","url","formhandler","result","disable","nowenabled","node","RTDField","options","register","node","UploadField","SplitDateField","SplitTimeField","ImgEditField","RTDField","init_dompack","init_gettid","registerTexts","init_dompack","init_env","init_envbackend","consentstatus","cookiename","consentoptions","getConsentDetail","consentstatus","consentoptions","onConsent","type","callback","evt","details","debugFlags","cookiename","deleteCookie","navigateTo","createMyFrame","ifrm","initYouTube","node","video","playback","youtubeUrl","initVimeo","vimeoUrl","t","minutes","seconds","launchVideo","opts","initializeVideoElementV1","initializeVideoElementV2","videonodes","qSA","videonode","activateVideo","playbutton","getTid","evt","onConsent","register","init_dompack","onDomReady","init_dompack","onDomReady","qS","setupLinksInNewWindow","aps"]}