UNPKG

pdfjs-dist

Version:

Generic build of Mozilla's PDF.js library.

211 lines • 121 kB
/**
 * @licstart The following is the entire license notice for the
 * JavaScript code in this page
 *
 * Copyright 2024 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * @licend The above is the entire license notice for the
 * JavaScript code in this page
 */

/**
 * pdfjsVersion = 6.5.438
 * pdfjsBuild = 0a4153349
 */

;// ./src/pdf.sandbox.external.js
class SandboxSupportBase {
  constructor(win) {
    this.win = win;
    this.timeoutIds = new Map();
    this.commFun = null;
  }
  destroy() {
    this.commFun = null;
    for (const id of this.timeoutIds.values()) {
      this.win.clearTimeout(id);
    }
    this.timeoutIds = null;
  }
  exportValueToSandbox(val) {
    throw new Error("Not implemented");
  }
  importValueFromSandbox(val) {
    throw new Error("Not implemented");
  }
  createErrorForSandbox(errorMessage) {
    throw new Error("Not implemented");
  }
  callSandboxFunction(name, args) {
    if (!this.commFun) {
      return;
    }
    try {
      args = this.exportValueToSandbox(args);
      this.commFun(name, args);
    } catch (e) {
      this.win.console.error(e);
    }
  }
  createSandboxExternals() {
    const externals = {
      setTimeout: (callbackId, nMilliseconds) => {
        if (typeof callbackId !== "number" || typeof nMilliseconds !== "number") {
          return;
        }
        if (callbackId === 0) {
          this.win.clearTimeout(this.timeoutIds.get(callbackId));
        }
        const id = this.win.setTimeout(() => {
          this.timeoutIds.delete(callbackId);
          this.callSandboxFunction("timeoutCb", {
            callbackId,
            interval: false
          });
        }, nMilliseconds);
        this.timeoutIds.set(callbackId, id);
      },
      clearTimeout: callbackId => {
        this.win.clearTimeout(this.timeoutIds.get(callbackId));
        this.timeoutIds.delete(callbackId);
      },
      setInterval: (callbackId, nMilliseconds) => {
        if (typeof callbackId !== "number" || typeof nMilliseconds !== "number") {
          return;
        }
        const id = this.win.setInterval(() => {
          this.callSandboxFunction("timeoutCb", {
            callbackId,
            interval: true
          });
        }, nMilliseconds);
        this.timeoutIds.set(callbackId, id);
      },
      clearInterval: callbackId => {
        this.win.clearInterval(this.timeoutIds.get(callbackId));
        this.timeoutIds.delete(callbackId);
      },
      alert: cMsg => {
        if (typeof cMsg !== "string") {
          return;
        }
        this.win.alert(cMsg);
      },
      confirm: cMsg => typeof cMsg !== "string" ? false : this.win.confirm(cMsg),
      prompt: (cQuestion, cDefault) => typeof cQuestion !== "string" || typeof cDefault !== "string" ? null : this.win.prompt(cQuestion, cDefault),
      parseURL: cUrl => {
        const url = new this.win.URL(cUrl);
        const props = ["hash", "host", "hostname", "href", "origin", "password", "pathname", "port", "protocol", "search", "searchParams", "username"];
        return Object.fromEntries(props.map(name => [name, url[name].toString()]));
      },
      send: data => {
        if (!data) {
          return;
        }
        const event = new this.win.CustomEvent("updatefromsandbox", {
          detail: this.importValueFromSandbox(data)
        });
        this.win.dispatchEvent(event);
      }
    };
    Object.setPrototypeOf(externals, null);
    return (name, args) => {
      try {
        const result = externals[name](...args);
        return this.exportValueToSandbox(result);
      } catch (error) {
        throw this.createErrorForSandbox(error?.toString() ?? "");
      }
    };
  }
}
;// ./src/pdf.sandbox.js

class SandboxSupport extends SandboxSupportBase {
  exportValueToSandbox(val) {
    return JSON.stringify(val, (k, v) => v instanceof Map ? Object.fromEntries(v) : v);
  }
  importValueFromSandbox(val) {
    return val;
  }
  createErrorForSandbox(errorMessage) {
    return new Error(errorMessage);
  }
}
class Sandbox {
  constructor(win, module) {
    this.support = new SandboxSupport(win, this);
    module.externalCall = this.support.createSandboxExternals();
    this._module = module;
    this._alertOnError = 0;
  }
  create(data) {
    const code = ["/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n\n;// ./src/scripting_api/app_utils.js\nconst VIEWER_TYPE = \"PDF.js\";\nconst VIEWER_VARIATION = \"Full\";\nconst VIEWER_VERSION = 21.00720099;\nconst FORMS_VERSION = 21.00720099;\nconst USERACTIVATION_CALLBACKID = 0;\nconst USERACTIVATION_MAXTIME_VALIDITY = 5000;\nconst {\n  apply\n} = Reflect;\nfunction uncurryThis(fn) {\n  return (thisArg, ...args) => apply(fn, thisArg, args);\n}\nfunction serializeError(error, prefix = \"\") {\n  let message;\n  try {\n    message = String(error);\n  } catch {\n    message = \"Unknown error\";\n  }\n  let stack;\n  try {\n    stack = error?.stack;\n  } catch {}\n  const value = typeof stack === \"string\" ? `${message}\\n${stack}` : message;\n  return {\n    command: \"error\",\n    value: `${prefix}${value}`\n  };\n}\nconst makeArr = () => [];\nconst makeMap = () => new Map();\nconst publicPrototypes = new Map();\nconst publicFunctions = new WeakSet();\nfunction addPublicFunctions(...fns) {\n  for (const fn of fns) {\n    if (typeof fn === \"function\") {\n      publicFunctions.add(fn);\n    }\n  }\n}\nfunction exposeObject(object, bindMethods = false) {\n  const prototype = Object.getPrototypeOf(object);\n  let publicPrototype = !bindMethods && publicPrototypes.get(prototype);\n  if (!publicPrototype) {\n    const descriptors = Object.getOwnPropertyDescriptors(prototype);\n    delete descriptors.constructor;\n    for (const descriptor of Object.values(descriptors)) {\n      const {\n        value,\n        get,\n        set\n      } = descriptor;\n      addPublicFunctions(value, get, set);\n      if (bindMethods && typeof value === \"function\") {\n        descriptor.value = value.bind(object);\n      }\n    }\n    publicPrototype = Object.create(Object.prototype, descriptors);\n    if (!bindMethods) {\n      publicPrototypes.set(prototype, publicPrototype);\n    }\n  }\n  return Object.setPrototypeOf(object, publicPrototype);\n}\nfunction useNativeToStringForPublicFunctions() {\n  const nativeToString = Function.prototype.toString;\n  const isPublic = uncurryThis(WeakSet.prototype.has);\n  const [prefix, suffix] = apply(nativeToString, nativeToString, []).split(\"toString\");\n  const {\n    toString\n  } = {\n    toString() {\n      return isPublic(publicFunctions, this) ? `${prefix}${this.name}${suffix}` : apply(nativeToString, this, []);\n    }\n  };\n  publicFunctions.add(toString);\n  Object.defineProperty(Function.prototype, \"toString\", {\n    value: toString,\n    writable: true,\n    configurable: true\n  });\n}\n\n;// ./src/scripting_api/constants.js\nconst Border = Object.freeze({\n  s: \"solid\",\n  d: \"dashed\",\n  b: \"beveled\",\n  i: \"inset\",\n  u: \"underline\"\n});\nconst Cursor = Object.freeze({\n  visible: 0,\n  hidden: 1,\n  delay: 2\n});\nconst Display = Object.freeze({\n  visible: 0,\n  hidden: 1,\n  noPrint: 2,\n  noView: 3\n});\nconst Font = Object.freeze({\n  Times: \"Times-Roman\",\n  TimesB: \"Times-Bold\",\n  TimesI: \"Times-Italic\",\n  TimesBI: \"Times-BoldItalic\",\n  Helv: \"Helvetica\",\n  HelvB: \"Helvetica-Bold\",\n  HelvI: \"Helvetica-Oblique\",\n  HelvBI: \"Helvetica-BoldOblique\",\n  Cour: \"Courier\",\n  CourB: \"Courier-Bold\",\n  CourI: \"Courier-Oblique\",\n  CourBI: \"Courier-BoldOblique\",\n  Symbol: \"Symbol\",\n  ZapfD: \"ZapfDingbats\",\n  KaGo: \"HeiseiKakuGo-W5-UniJIS-UCS2-H\",\n  KaMi: \"HeiseiMin-W3-UniJIS-UCS2-H\"\n});\nconst Highlight = Object.freeze({\n  n: \"none\",\n  i: \"invert\",\n  p: \"push\",\n  o: \"outline\"\n});\nconst Position = Object.freeze({\n  textOnly: 0,\n  iconOnly: 1,\n  iconTextV: 2,\n  textIconV: 3,\n  iconTextH: 4,\n  textIconH: 5,\n  overlay: 6\n});\nconst ScaleHow = Object.freeze({\n  proportional: 0,\n  anamorphic: 1\n});\nconst ScaleWhen = Object.freeze({\n  always: 0,\n  never: 1,\n  tooBig: 2,\n  tooSmall: 3\n});\nconst Style = Object.freeze({\n  ch: \"check\",\n  cr: \"cross\",\n  di: \"diamond\",\n  ci: \"circle\",\n  st: \"star\",\n  sq: \"square\"\n});\nconst Trans = Object.freeze({\n  blindsH: \"BlindsHorizontal\",\n  blindsV: \"BlindsVertical\",\n  boxI: \"BoxIn\",\n  boxO: \"BoxOut\",\n  dissolve: \"Dissolve\",\n  glitterD: \"GlitterDown\",\n  glitterR: \"GlitterRight\",\n  glitterRD: \"GlitterRightDown\",\n  random: \"Random\",\n  replace: \"Replace\",\n  splitHI: \"SplitHorizontalIn\",\n  splitHO: \"SplitHorizontalOut\",\n  splitVI: \"SplitVerticalIn\",\n  splitVO: \"SplitVerticalOut\",\n  wipeD: \"WipeDown\",\n  wipeL: \"WipeLeft\",\n  wipeR: \"WipeRight\",\n  wipeU: \"WipeUp\"\n});\nconst ZoomType = Object.freeze({\n  none: \"NoVary\",\n  fitP: \"FitPage\",\n  fitW: \"FitWidth\",\n  fitH: \"FitHeight\",\n  fitV: \"FitVisibleWidth\",\n  pref: \"Preferred\",\n  refW: \"ReflowWidth\"\n});\nconst GlobalConstants = Object.freeze({\n  IDS_GREATER_THAN: \"Invalid value: must be greater than or equal to % s.\",\n  IDS_GT_AND_LT: \"Invalid value: must be greater than or equal to % s \" + \"and less than or equal to % s.\",\n  IDS_LESS_THAN: \"Invalid value: must be less than or equal to % s.\",\n  IDS_INVALID_MONTH: \"** Invalid **\",\n  IDS_INVALID_DATE: \"Invalid date / time: please ensure that the date / time exists. Field\",\n  IDS_INVALID_DATE2: \" should match format \",\n  IDS_INVALID_VALUE: \"The value entered does not match the format of the field\",\n  IDS_AM: \"am\",\n  IDS_PM: \"pm\",\n  IDS_MONTH_INFO: \"January[1] February[2] March[3] April[4] May[5] \" + \"June[6] July[7] August[8] September[9] October[10] \" + \"November[11] December[12] Sept[9] Jan[1] Feb[2] Mar[3] \" + \"Apr[4] Jun[6] Jul[7] Aug[8] Sep[9] Oct[10] Nov[11] Dec[12]\",\n  IDS_STARTUP_CONSOLE_MSG: \"** ^ _ ^ **\",\n  RE_NUMBER_ENTRY_DOT_SEP: [\"[+-]?\\\\d*\\\\.?\\\\d*\"],\n  RE_NUMBER_COMMIT_DOT_SEP: [\"[+-]?\\\\d+(\\\\.\\\\d+)?\", \"[+-]?\\\\.\\\\d+\", \"[+-]?\\\\d+\\\\.\"],\n  RE_NUMBER_ENTRY_COMMA_SEP: [\"[+-]?\\\\d*,?\\\\d*\"],\n  RE_NUMBER_COMMIT_COMMA_SEP: [\"[+-]?\\\\d+([.,]\\\\d+)?\", \"[+-]?[.,]\\\\d+\", \"[+-]?\\\\d+[.,]\"],\n  RE_ZIP_ENTRY: [\"\\\\d{0,5}\"],\n  RE_ZIP_COMMIT: [\"\\\\d{5}\"],\n  RE_ZIP4_ENTRY: [\"\\\\d{0,5}(\\\\.|[- ])?\\\\d{0,4}\"],\n  RE_ZIP4_COMMIT: [\"\\\\d{5}(\\\\.|[- ])?\\\\d{4}\"],\n  RE_PHONE_ENTRY: [\"\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,4}\", \"\\\\(\\\\d{0,3}\", \"\\\\(\\\\d{0,3}\\\\)(\\\\.|[- ])?\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,4}\", \"\\\\(\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,4}\", \"\\\\d{0,3}\\\\)(\\\\.|[- ])?\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,4}\", \"011(\\\\.|[- \\\\d])*\"],\n  RE_PHONE_COMMIT: [\"\\\\d{3}(\\\\.|[- ])?\\\\d{4}\", \"\\\\d{3}(\\\\.|[- ])?\\\\d{3}(\\\\.|[- ])?\\\\d{4}\", \"\\\\(\\\\d{3}\\\\)(\\\\.|[- ])?\\\\d{3}(\\\\.|[- ])?\\\\d{4}\", \"011(\\\\.|[- \\\\d])*\"],\n  RE_SSN_ENTRY: [\"\\\\d{0,3}(\\\\.|[- ])?\\\\d{0,2}(\\\\.|[- ])?\\\\d{0,4}\"],\n  RE_SSN_COMMIT: [\"\\\\d{3}(\\\\.|[- ])?\\\\d{2}(\\\\.|[- ])?\\\\d{4}\"]\n});\n\n;// ./src/scripting_api/fullscreen.js\n\nclass FullScreen {\n  #backgroundColor = [];\n  #clickAdvances = true;\n  #cursor = Cursor.hidden;\n  #defaultTransition = \"\";\n  #escapeExits = true;\n  #isFullScreen = true;\n  #loop = false;\n  #timeDelay = 3600;\n  #usePageTiming = false;\n  #useTimer = false;\n  get backgroundColor() {\n    return this.#backgroundColor;\n  }\n  set backgroundColor(_) {}\n  get clickAdvances() {\n    return this.#clickAdvances;\n  }\n  set clickAdvances(_) {}\n  get cursor() {\n    return this.#cursor;\n  }\n  set cursor(_) {}\n  get defaultTransition() {\n    return this.#defaultTransition;\n  }\n  set defaultTransition(_) {}\n  get escapeExits() {\n    return this.#escapeExits;\n  }\n  set escapeExits(_) {}\n  get isFullScreen() {\n    return this.#isFullScreen;\n  }\n  set isFullScreen(_) {}\n  get loop() {\n    return this.#loop;\n  }\n  set loop(_) {}\n  get timeDelay() {\n    return this.#timeDelay;\n  }\n  set timeDelay(_) {}\n  get transitions() {\n    return [\"Replace\", \"WipeRight\", \"WipeLeft\", \"WipeDown\", \"WipeUp\", \"SplitHorizontalIn\", \"SplitHorizontalOut\", \"SplitVerticalIn\", \"SplitVerticalOut\", \"BlindsHorizontal\", \"BlindsVertical\", \"BoxIn\", \"BoxOut\", \"GlitterRight\", \"GlitterDown\", \"GlitterRightDown\", \"Dissolve\", \"Random\"];\n  }\n  set transitions(_) {\n    throw new Error(\"fullscreen.transitions is read-only\");\n  }\n  get usePageTiming() {\n    return this.#usePageTiming;\n  }\n  set usePageTiming(_) {}\n  get useTimer() {\n    return this.#useTimer;\n  }\n  set useTimer(_) {}\n}\n\n;// ./src/shared/math_clamp.js\nfunction MathClamp(v, min, max) {\n  return Math.min(Math.max(v, min), max);\n}\n\n;// ./src/shared/scripting_utils.js\n\nfunction makeColorComp(n) {\n  return Math.floor(MathClamp(n, 0, 1) * 255).toString(16).padStart(2, \"0\");\n}\nfunction scaleAndClamp(x) {\n  return MathClamp(x, 0, 1) * 255;\n}\nclass ColorConverters {\n  static CMYK_G([c, y, m, k]) {\n    return [\"G\", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];\n  }\n  static G_CMYK([g]) {\n    return [\"CMYK\", 0, 0, 0, 1 - g];\n  }\n  static G_RGB([g]) {\n    return [\"RGB\", g, g, g];\n  }\n  static G_rgb([g]) {\n    g = scaleAndClamp(g);\n    return [g, g, g];\n  }\n  static G_HTML([g]) {\n    const G = makeColorComp(g);\n    return `#${G}${G}${G}`;\n  }\n  static RGB_G([r, g, b]) {\n    return [\"G\", 0.3 * r + 0.59 * g + 0.11 * b];\n  }\n  static RGB_rgb(color) {\n    return color.map(scaleAndClamp);\n  }\n  static RGB_HTML(color) {\n    return `#${color.map(makeColorComp).join(\"\")}`;\n  }\n  static T_HTML() {\n    return \"#00000000\";\n  }\n  static T_rgb() {\n    return [null];\n  }\n  static CMYK_RGB([c, y, m, k]) {\n    return [\"RGB\", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];\n  }\n  static CMYK_rgb([c, y, m, k]) {\n    return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];\n  }\n  static CMYK_HTML(components) {\n    const rgb = this.CMYK_RGB(components).slice(1);\n    return this.RGB_HTML(rgb);\n  }\n  static RGB_CMYK([r, g, b]) {\n    const c = 1 - r;\n    const m = 1 - g;\n    const y = 1 - b;\n    const k = Math.min(c, m, y);\n    return [\"CMYK\", c, m, y, k];\n  }\n}\nconst DateFormats = [\"m/d\", \"m/d/yy\", \"mm/dd/yy\", \"mm/yy\", \"d-mmm\", \"d-mmm-yy\", \"dd-mmm-yy\", \"yy-mm-dd\", \"mmm-yy\", \"mmmm-yy\", \"mmm d, yyyy\", \"mmmm d, yyyy\", \"m/d/yy h:MM tt\", \"m/d/yy HH:MM\"];\nconst TimeFormats = [\"HH:MM\", \"h:MM tt\", \"HH:MM:ss\", \"h:MM:ss tt\"];\n\n;// ./src/scripting_api/color.js\n\nfunction isValidSpace(cColorSpace) {\n  return typeof cColorSpace === \"string\" && (cColorSpace === \"T\" || cColorSpace === \"G\" || cColorSpace === \"RGB\" || cColorSpace === \"CMYK\");\n}\nfunction isValidColor(colorArray) {\n  if (!Array.isArray(colorArray) || colorArray.length === 0) {\n    return false;\n  }\n  const space = colorArray[0];\n  if (!isValidSpace(space)) {\n    return false;\n  }\n  const expectedLength = {\n    T: 1,\n    G: 2,\n    RGB: 4,\n    CMYK: 5\n  }[space];\n  return colorArray.length === expectedLength && colorArray.slice(1).every(c => typeof c === \"number\" && c >= 0 && c <= 1);\n}\nfunction getCorrectColor(colorArray) {\n  return isValidColor(colorArray) ? colorArray : [\"G\", 0];\n}\nclass Color {\n  transparent = [\"T\"];\n  black = [\"G\", 0];\n  white = [\"G\", 1];\n  red = [\"RGB\", 1, 0, 0];\n  green = [\"RGB\", 0, 1, 0];\n  blue = [\"RGB\", 0, 0, 1];\n  cyan = [\"CMYK\", 1, 0, 0, 0];\n  magenta = [\"CMYK\", 0, 1, 0, 0];\n  yellow = [\"CMYK\", 0, 0, 1, 0];\n  dkGray = [\"G\", 0.25];\n  gray = [\"G\", 0.5];\n  ltGray = [\"G\", 0.75];\n  convert(colorArray, cColorSpace) {\n    if (!isValidSpace(cColorSpace)) {\n      return this.black;\n    }\n    if (cColorSpace === \"T\") {\n      return [\"T\"];\n    }\n    colorArray = getCorrectColor(colorArray);\n    if (colorArray[0] === cColorSpace) {\n      return colorArray;\n    }\n    if (colorArray[0] === \"T\") {\n      return this.convert(this.black, cColorSpace);\n    }\n    return ColorConverters[`${colorArray[0]}_${cColorSpace}`](colorArray.slice(1));\n  }\n  equal(colorArray1, colorArray2) {\n    colorArray1 = getCorrectColor(colorArray1);\n    colorArray2 = getCorrectColor(colorArray2);\n    if (colorArray1[0] === \"T\" || colorArray2[0] === \"T\") {\n      return colorArray1[0] === \"T\" && colorArray2[0] === \"T\";\n    }\n    if (colorArray1[0] !== colorArray2[0]) {\n      colorArray2 = this.convert(colorArray2, colorArray1[0]);\n    }\n    return colorArray1.slice(1).every((c, i) => c === colorArray2[i + 1]);\n  }\n}\n\n;// ./src/scripting_api/thermometer.js\nclass Thermometer {\n  #cancelled = false;\n  #duration = 100;\n  #text = \"\";\n  #value = 0;\n  get cancelled() {\n    return this.#cancelled;\n  }\n  set cancelled(_) {\n    throw new Error(\"thermometer.cancelled is read-only\");\n  }\n  get duration() {\n    return this.#duration;\n  }\n  set duration(val) {\n    this.#duration = val;\n  }\n  get text() {\n    return this.#text;\n  }\n  set text(val) {\n    this.#text = val;\n  }\n  get value() {\n    return this.#value;\n  }\n  set value(val) {\n    this.#value = val;\n  }\n  begin() {}\n  end() {}\n}\n\n;// ./src/scripting_api/app.js\n\n\n\n\nconst mapDelete = uncurryThis(Map.prototype.delete);\nconst mapGet = uncurryThis(Map.prototype.get);\nconst mapSet = uncurryThis(Map.prototype.set);\nconst weakMapDelete = uncurryThis(WeakMap.prototype.delete);\nconst weakMapGet = uncurryThis(WeakMap.prototype.get);\nconst weakMapSet = uncurryThis(WeakMap.prototype.set);\nconst registerFinalizer = uncurryThis(FinalizationRegistry.prototype.register);\nconst unregisterFinalizer = uncurryThis(FinalizationRegistry.prototype.unregister);\nconst AppInternals = Object.create(null);\nclass App {\n  #constants = null;\n  #focusRect = true;\n  #fs = exposeObject(new FullScreen(), true);\n  #language;\n  #openInPlace = false;\n  #platform;\n  #runtimeHighlight = false;\n  #runtimeHighlightColor = [\"T\"];\n  #thermometer = exposeObject(new Thermometer(), true);\n  #toolbar = false;\n  #doc;\n  #timeoutIds = new WeakMap();\n  #timeoutIdsRegistry = new FinalizationRegistry(this.#cleanTimeout.bind(this));\n  #timeoutCallbackIds = new Map();\n  #timeoutCallbackId = (/* inlined export .USERACTIVATION_CALLBACKID */0) + 1;\n  #globalEval;\n  #externalCall;\n  #send;\n  #userActivationData;\n  constructor(data) {\n    this.#send = data.send;\n    this.#userActivationData = data.userActivationData;\n    this.#language = App.#getLanguage(data.language);\n    this.#platform = App.#getPlatform(data.platform);\n    this.#doc = data.doc;\n    this.#globalEval = data.globalEval;\n    this.#externalCall = data.externalCall;\n  }\n  static {\n    Object.assign(AppInternals, {\n      evalCallback: (app, data) => app.#evalCallback(data)\n    });\n  }\n  #registerTimeoutCallback(cExpr) {\n    const id = this.#timeoutCallbackId++;\n    mapSet(this.#timeoutCallbackIds, id, cExpr);\n    return id;\n  }\n  #unregisterTimeoutCallback(id) {\n    mapDelete(this.#timeoutCallbackIds, id);\n  }\n  #evalCallback({\n    callbackId,\n    interval\n  }) {\n    if (callbackId === (/* inlined export .USERACTIVATION_CALLBACKID */0)) {\n      this.#userActivationData.userActivation = false;\n      return;\n    }\n    const expr = mapGet(this.#timeoutCallbackIds, callbackId);\n    if (!interval) {\n      this.#unregisterTimeoutCallback(callbackId);\n    }\n    if (expr) {\n      const saveUserActivation = this.#userActivationData.userActivation;\n      this.#userActivationData.userActivation = false;\n      this.#globalEval(expr);\n      this.#userActivationData.userActivation = saveUserActivation;\n    }\n  }\n  #registerTimeout(callbackId, interval) {\n    const timeout = Object.create(null);\n    const id = {\n      callbackId,\n      interval\n    };\n    weakMapSet(this.#timeoutIds, timeout, id);\n    registerFinalizer(this.#timeoutIdsRegistry, timeout, id, timeout);\n    return timeout;\n  }\n  #unregisterTimeout(timeout) {\n    const data = weakMapGet(this.#timeoutIds, timeout);\n    if (!data) {\n      return;\n    }\n    weakMapDelete(this.#timeoutIds, timeout);\n    unregisterFinalizer(this.#timeoutIdsRegistry, timeout);\n    this.#cleanTimeout(data);\n  }\n  #cleanTimeout({\n    callbackId,\n    interval\n  }) {\n    this.#unregisterTimeoutCallback(callbackId);\n    if (interval) {\n      this.#externalCall(\"clearInterval\", [callbackId]);\n    } else {\n      this.#externalCall(\"clearTimeout\", [callbackId]);\n    }\n  }\n  static #getPlatform(platform) {\n    if (typeof platform === \"string\") {\n      platform = platform.toLowerCase();\n      if (platform.includes(\"win\")) {\n        return \"WIN\";\n      } else if (platform.includes(\"mac\")) {\n        return \"MAC\";\n      }\n    }\n    return \"UNIX\";\n  }\n  static #getLanguage(language) {\n    const [main, sub] = language.toLowerCase().split(/[-_]/, 2);\n    switch (main) {\n      case \"zh\":\n        return sub === \"cn\" || sub === \"sg\" ? \"CHS\" : \"CHT\";\n      case \"da\":\n        return \"DAN\";\n      case \"de\":\n        return \"DEU\";\n      case \"es\":\n        return \"ESP\";\n      case \"fr\":\n        return \"FRA\";\n      case \"it\":\n        return \"ITA\";\n      case \"ko\":\n        return \"KOR\";\n      case \"ja\":\n        return \"JPN\";\n      case \"nl\":\n        return \"NLD\";\n      case \"no\":\n        return \"NOR\";\n      case \"pt\":\n        return sub === \"br\" ? \"PTB\" : \"ENU\";\n      case \"fi\":\n        return \"SUO\";\n      case \"SV\":\n        return \"SVE\";\n      default:\n        return \"ENU\";\n    }\n  }\n  get activeDocs() {\n    return [globalThis];\n  }\n  set activeDocs(_) {\n    throw new Error(\"app.activeDocs is read-only\");\n  }\n  get calculate() {\n    return this.#doc.calculate;\n  }\n  set calculate(calculate) {\n    this.#doc.calculate = calculate;\n  }\n  get constants() {\n    return this.#constants ??= Object.freeze({\n      align: Object.freeze({\n        left: 0,\n        center: 1,\n        right: 2,\n        top: 3,\n        bottom: 4\n      })\n    });\n  }\n  set constants(_) {\n    throw new Error(\"app.constants is read-only\");\n  }\n  get focusRect() {\n    return this.#focusRect;\n  }\n  set focusRect(val) {\n    this.#focusRect = val;\n  }\n  get formsVersion() {\n    return FORMS_VERSION;\n  }\n  set formsVersion(_) {\n    throw new Error(\"app.formsVersion is read-only\");\n  }\n  get fromPDFConverters() {\n    return [];\n  }\n  set fromPDFConverters(_) {\n    throw new Error(\"app.fromPDFConverters is read-only\");\n  }\n  get fs() {\n    return this.#fs;\n  }\n  set fs(_) {\n    throw new Error(\"app.fs is read-only\");\n  }\n  get language() {\n    return this.#language;\n  }\n  set language(_) {\n    throw new Error(\"app.language is read-only\");\n  }\n  get media() {\n    return undefined;\n  }\n  set media(_) {\n    throw new Error(\"app.media is read-only\");\n  }\n  get monitors() {\n    return [];\n  }\n  set monitors(_) {\n    throw new Error(\"app.monitors is read-only\");\n  }\n  get numPlugins() {\n    return 0;\n  }\n  set numPlugins(_) {\n    throw new Error(\"app.numPlugins is read-only\");\n  }\n  get openInPlace() {\n    return this.#openInPlace;\n  }\n  set openInPlace(val) {\n    this.#openInPlace = val;\n  }\n  get platform() {\n    return this.#platform;\n  }\n  set platform(_) {\n    throw new Error(\"app.platform is read-only\");\n  }\n  get plugins() {\n    return [];\n  }\n  set plugins(_) {\n    throw new Error(\"app.plugins is read-only\");\n  }\n  get printColorProfiles() {\n    return [];\n  }\n  set printColorProfiles(_) {\n    throw new Error(\"app.printColorProfiles is read-only\");\n  }\n  get printerNames() {\n    return [];\n  }\n  set printerNames(_) {\n    throw new Error(\"app.printerNames is read-only\");\n  }\n  get runtimeHighlight() {\n    return this.#runtimeHighlight;\n  }\n  set runtimeHighlight(val) {\n    this.#runtimeHighlight = val;\n  }\n  get runtimeHighlightColor() {\n    return this.#runtimeHighlightColor;\n  }\n  set runtimeHighlightColor(val) {\n    if (isValidColor(val)) {\n      this.#runtimeHighlightColor = val;\n    }\n  }\n  get thermometer() {\n    return this.#thermometer;\n  }\n  set thermometer(_) {\n    throw new Error(\"app.thermometer is read-only\");\n  }\n  get toolbar() {\n    return this.#toolbar;\n  }\n  set toolbar(val) {\n    this.#toolbar = val;\n  }\n  get toolbarHorizontal() {\n    return this.toolbar;\n  }\n  set toolbarHorizontal(value) {\n    this.toolbar = value;\n  }\n  get toolbarVertical() {\n    return this.toolbar;\n  }\n  set toolbarVertical(value) {\n    this.toolbar = value;\n  }\n  get viewerType() {\n    return (/* inlined export .VIEWER_TYPE */\"PDF.js\");\n  }\n  set viewerType(_) {\n    throw new Error(\"app.viewerType is read-only\");\n  }\n  get viewerVariation() {\n    return (/* inlined export .VIEWER_VARIATION */\"Full\");\n  }\n  set viewerVariation(_) {\n    throw new Error(\"app.viewerVariation is read-only\");\n  }\n  get viewerVersion() {\n    return VIEWER_VERSION;\n  }\n  set viewerVersion(_) {\n    throw new Error(\"app.viewerVersion is read-only\");\n  }\n  addMenuItem() {}\n  addSubMenu() {}\n  addToolButton() {}\n  alert(cMsg, nIcon = 0, nType = 0, cTitle = \"PDF.js\", oDoc = null, oCheckbox = null) {\n    if (!this.#userActivationData.userActivation) {\n      return 0;\n    }\n    this.#userActivationData.userActivation = false;\n    if (cMsg && typeof cMsg === \"object\") {\n      nType = cMsg.nType;\n      cMsg = cMsg.cMsg;\n    }\n    cMsg = (cMsg || \"\").toString();\n    if (!cMsg) {\n      return 0;\n    }\n    nType = typeof nType !== \"number\" || isNaN(nType) || nType < 0 || nType > 3 ? 0 : nType;\n    if (nType >= 2) {\n      return this.#externalCall(\"confirm\", [cMsg]) ? 4 : 3;\n    }\n    this.#externalCall(\"alert\", [cMsg]);\n    return 1;\n  }\n  beep() {}\n  beginPriv() {}\n  browseForDoc() {}\n  clearInterval(oInterval) {\n    this.#unregisterTimeout(oInterval);\n  }\n  clearTimeOut(oTime) {\n    this.#unregisterTimeout(oTime);\n  }\n  endPriv() {}\n  execDialog() {}\n  execMenuItem(item) {\n    if (!this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    switch (item) {\n      case \"SaveAs\":\n        if (this.#userActivationData.disableSaving) {\n          return;\n        }\n        this.#send({\n          command: item\n        });\n        break;\n      case \"FirstPage\":\n      case \"LastPage\":\n      case \"NextPage\":\n      case \"PrevPage\":\n      case \"ZoomViewIn\":\n      case \"ZoomViewOut\":\n        this.#send({\n          command: item\n        });\n        break;\n      case \"FitPage\":\n        this.#send({\n          command: \"zoom\",\n          value: \"page-fit\"\n        });\n        break;\n      case \"Print\":\n        if (this.#userActivationData.disablePrinting) {\n          return;\n        }\n        this.#send({\n          command: \"print\"\n        });\n        break;\n    }\n  }\n  getNthPlugInName() {}\n  getPath() {}\n  goBack() {}\n  goForward() {}\n  hideMenuItem() {}\n  hideToolbarButton() {}\n  launchURL() {}\n  listMenuItems() {}\n  listToolbarButtons() {}\n  loadPolicyFile() {}\n  mailGetAddrs() {}\n  mailMsg() {}\n  newDoc() {}\n  newCollection() {}\n  newFDF() {}\n  openDoc() {}\n  openFDF() {}\n  popUpMenu() {}\n  popUpMenuEx() {}\n  removeToolButton() {}\n  response(cQuestion, cTitle = \"\", cDefault = \"\", bPassword = \"\", cLabel = \"\") {\n    if (!this.#userActivationData.userActivation) {\n      return null;\n    }\n    this.#userActivationData.userActivation = false;\n    if (cQuestion && typeof cQuestion === \"object\") {\n      cDefault = cQuestion.cDefault;\n      cQuestion = cQuestion.cQuestion;\n    }\n    cQuestion = (cQuestion || \"\").toString();\n    cDefault = (cDefault || \"\").toString();\n    return this.#externalCall(\"prompt\", [cQuestion, cDefault || \"\"]);\n  }\n  setInterval(cExpr, nMilliseconds = 0) {\n    if (cExpr && typeof cExpr === \"object\") {\n      nMilliseconds = cExpr.nMilliseconds || 0;\n      cExpr = cExpr.cExpr;\n    }\n    if (typeof cExpr !== \"string\") {\n      throw new TypeError(\"First argument of app.setInterval must be a string\");\n    }\n    if (typeof nMilliseconds !== \"number\") {\n      throw new TypeError(\"Second argument of app.setInterval must be a number\");\n    }\n    const callbackId = this.#registerTimeoutCallback(cExpr);\n    this.#externalCall(\"setInterval\", [callbackId, nMilliseconds]);\n    return this.#registerTimeout(callbackId, true);\n  }\n  setTimeOut(cExpr, nMilliseconds = 0) {\n    if (cExpr && typeof cExpr === \"object\") {\n      nMilliseconds = cExpr.nMilliseconds || 0;\n      cExpr = cExpr.cExpr;\n    }\n    if (typeof cExpr !== \"string\") {\n      throw new TypeError(\"First argument of app.setTimeOut must be a string\");\n    }\n    if (typeof nMilliseconds !== \"number\") {\n      throw new TypeError(\"Second argument of app.setTimeOut must be a number\");\n    }\n    const callbackId = this.#registerTimeoutCallback(cExpr);\n    this.#externalCall(\"setTimeout\", [callbackId, nMilliseconds]);\n    return this.#registerTimeout(callbackId, false);\n  }\n  trustedFunction() {}\n  trustPropagatorFunction() {}\n}\n\n;// ./src/scripting_api/common.js\nconst FieldType = {\n  none: 0,\n  number: 1,\n  percent: 2,\n  date: 3,\n  time: 4\n};\nfunction createMap(val) {\n  return val instanceof Map ? val : new Map(val ? Object.entries(val) : null);\n}\nfunction getFieldType(actions) {\n  let format = actions.get(\"Format\");\n  if (!format) {\n    return FieldType.none;\n  }\n  format = format[0].trim();\n  if (format.startsWith(\"AFNumber_\")) {\n    return FieldType.number;\n  }\n  if (format.startsWith(\"AFPercent_\")) {\n    return FieldType.percent;\n  }\n  if (format.startsWith(\"AFDate_\")) {\n    return FieldType.date;\n  }\n  return format.startsWith(\"AFTime_\") ? FieldType.time : FieldType.none;\n}\n\n;// ./src/scripting_api/field.js\n\n\n\nconst FieldInternals = Object.create(null);\nlet containerDescriptors = null;\nconst VIEW_PROPERTIES = [\"display\", \"editable\", \"hidden\", \"multipleSelection\", \"print\", \"readonly\", \"required\", \"userName\"];\nclass Field {\n  #actions;\n  #appObjects;\n  #browseForFileToSubmit;\n  #buttonCaption = null;\n  #buttonIcon = null;\n  #charLimit;\n  #children = null;\n  #containerProps = null;\n  #currentValueIndices;\n  #datetimeFormat;\n  #fieldPath;\n  #fieldType;\n  #fillColor;\n  #getTerminalChildren;\n  #globalEval;\n  #hasDateOrTime;\n  #hasValue;\n  #id;\n  #isCheckbox = false;\n  #isChoice;\n  #items;\n  #kidIds;\n  #originalValue;\n  #otherWidgetIds = null;\n  #page;\n  #radioActions = null;\n  #radioIds = null;\n  #radioPages = null;\n  #rotation;\n  #send;\n  #sendError;\n  #strokeColor;\n  #textColor;\n  #util;\n  #value = null;\n  #viewProps;\n  constructor(data, otherWidgets = []) {\n    this.alignment = data.alignment || \"left\";\n    this.borderStyle = data.borderStyle || \"\";\n    this.buttonAlignX = data.buttonAlignX || 50;\n    this.buttonAlignY = data.buttonAlignY || 50;\n    this.buttonFitBounds = data.buttonFitBounds;\n    this.buttonPosition = data.buttonPosition;\n    this.buttonScaleHow = data.buttonScaleHow;\n    this.ButtonScaleWhen = data.buttonScaleWhen;\n    this.calcOrderIndex = data.calcOrderIndex;\n    this.comb = data.comb;\n    this.commitOnSelChange = data.commitOnSelChange;\n    this.defaultStyle = data.defaultStyle;\n    this.defaultValue = data.defaultValue;\n    this.doNotScroll = data.doNotScroll;\n    this.doNotSpellCheck = data.doNotSpellCheck;\n    this.delay = data.delay;\n    this.doc = globalThis;\n    this.exportValues = data.exportValues;\n    this.fileSelect = data.fileSelect;\n    this.highlight = data.highlight;\n    this.lineWidth = data.lineWidth;\n    this.multiline = data.multiline;\n    this.name = data.name;\n    this.password = data.password;\n    this.radiosInUnison = data.radiosInUnison;\n    this.rect = data.rect;\n    this.richText = data.richText;\n    this.richValue = data.richValue;\n    this.style = data.style;\n    this.submitName = data.submitName;\n    this.textFont = data.textFont;\n    this.textSize = data.textSize;\n    this.type = data.type;\n    this.#actions = createMap(data.actions);\n    this.#appObjects = data.appObjects;\n    this.#browseForFileToSubmit = data.browseForFileToSubmit || null;\n    this.#charLimit = data.charLimit;\n    this.#currentValueIndices = data.currentValueIndices || 0;\n    this.#datetimeFormat = data.datetimeFormat || null;\n    this.#fieldPath = data.fieldPath;\n    this.#fieldType = getFieldType(this.#actions);\n    this.#fillColor = data.fillColor || [\"T\"];\n    this.#getTerminalChildren = data.getTerminalChildren;\n    this.#globalEval = data.globalEval;\n    this.#hasDateOrTime = !!data.hasDatetimeHTML;\n    this.#hasValue = Object.hasOwn(data, \"value\");\n    this.#id = data.id;\n    this.#isChoice = Array.isArray(data.items);\n    this.#items = data.items || [];\n    this.#kidIds = data.kidIds || null;\n    this.#page = data.page || 0;\n    this.#rotation = data.rotation || 0;\n    this.#send = data.send || (() => {});\n    this.#sendError = data.sendError;\n    this.#strokeColor = data.strokeColor || [\"G\", 0];\n    this.#textColor = data.textColor || [\"G\", 0];\n    this.#util = data.util;\n    this.#viewProps = Object.fromEntries(VIEW_PROPERTIES.map(name => [name, data[name]]));\n    this.#viewProps.multipleSelection = !!data.multipleSelection;\n    if (data.type === \"radiobutton\" || data.type === \"checkbox\") {\n      this.#isCheckbox = data.type === \"checkbox\";\n      this.exportValues = [this.exportValues];\n      this.#radioIds = [this.#id];\n      this.#radioActions = [this.#actions];\n      this.#radioPages = [this.#page];\n      for (const widget of otherWidgets) {\n        this.exportValues.push(widget.exportValues);\n        this.#radioIds.push(widget.id);\n        this.#radioActions.push(createMap(widget.actions));\n        this.#radioPages.push(widget.page || 0);\n        if (data.value === widget.exportValues) {\n          this.#id = widget.id;\n        }\n      }\n      this.#value = data.value || \"\";\n    } else {\n      if (otherWidgets.length > 0) {\n        this.#otherWidgetIds = otherWidgets.map(widget => widget.id);\n      }\n      this.#setValue(data.value || \"\");\n    }\n    if (this.#kidIds) {\n      this.#containerProps = {\n        ...this\n      };\n      containerDescriptors ??= Field.#getContainerDescriptors(Object.keys(this));\n      Object.defineProperties(this, containerDescriptors);\n    }\n  }\n  static #getContainerDescriptors(names) {\n    const descriptors = Object.create(null);\n    for (const name of names) {\n      const descriptor = {\n        get() {\n          return this.#containerProps[name];\n        },\n        set(value) {\n          this.#containerProps[name] = value;\n          this.#setOnKids(name, value);\n        },\n        enumerable: true,\n        configurable: true\n      };\n      addPublicFunctions(descriptor.get, descriptor.set);\n      descriptors[name] = descriptor;\n    }\n    return descriptors;\n  }\n  static {\n    Object.assign(FieldInternals, {\n      getComputedValue: f => f.#originalValue ?? f.#value,\n      getHasValue: f => f.#hasValue,\n      getInitialValue: f => f.#hasDateOrTime && f.#originalValue || null,\n      getIsChoice: f => f.#isChoice,\n      getKidIds: f => f.#kidIds,\n      getPageActions: f => f.#getPageActions(),\n      getValue: f => f.#value,\n      setValue: (f, value) => f.#setValue(value),\n      prepareEvent(f, id, event) {\n        if (f.#radioIds) {\n          f.#id = id;\n          event.value = f.#isCheckbox && !event.value ? \"Off\" : f.exportValues[f.#checkedIndex];\n          if (event.name === \"Action\") {\n            f.#value = event.value;\n          }\n        }\n      },\n      runActions: (f, event) => f.#runActions(event),\n      send: (f, data) => f.#sendToView(data)\n    });\n    for (const name of VIEW_PROPERTIES) {\n      Object.defineProperty(Field.prototype, name, {\n        get() {\n          return this.#viewProps[name];\n        },\n        set(value) {\n          this.#viewProps[name] = value;\n          this.#update(name, value);\n        },\n        configurable: true\n      });\n    }\n    for (const [name, {\n      value\n    }] of Object.entries(Object.getOwnPropertyDescriptors(Field.prototype))) {\n      if (name !== \"constructor\" && typeof value === \"function\") {\n        Object.defineProperty(Field.prototype, name, {\n          writable: false\n        });\n      }\n    }\n  }\n  get #siblings() {\n    return this.#radioIds?.filter(id => id !== this.#id) ?? this.#otherWidgetIds;\n  }\n  #getPageActions() {\n    const actions = this.#radioActions ?? [this.#actions];\n    const pages = this.#radioPages ?? [this.#page];\n    const pageActions = [];\n    for (let i = 0, ii = actions.length; i < ii; i++) {\n      for (const eventName of [\"PageOpen\", \"PageClose\"]) {\n        const scripts = actions[i].get(eventName);\n        if (scripts) {\n          pageActions.push([pages[i], eventName, scripts]);\n        }\n      }\n    }\n    return pageActions;\n  }\n  #setOnKids(name, value) {\n    if (this.#kidIds) {\n      for (const id of this.#kidIds) {\n        const kid = this.#appObjects[id];\n        if (kid) {\n          kid[name] = value;\n        }\n      }\n    }\n  }\n  #sendToView(data) {\n    const siblings = this.#siblings;\n    this.#send(siblings ? {\n      id: this.#id,\n      siblings,\n      ...data\n    } : {\n      id: this.#id,\n      ...data\n    });\n  }\n  #update(name, value, sentValue = value) {\n    this.#setOnKids(name, value);\n    this.#sendToView({\n      [name]: sentValue\n    });\n  }\n  get currentValueIndices() {\n    return !this.#isChoice ? 0 : this.#currentValueIndices;\n  }\n  set currentValueIndices(indices) {\n    this.#setOnKids(\"currentValueIndices\", indices);\n    if (!this.#isChoice) {\n      return;\n    }\n    if (!Array.isArray(indices)) {\n      indices = [indices];\n    }\n    if (!indices.every(i => Number.isInteger(i) && i >= 0 && i < this.numItems)) {\n      return;\n    }\n    indices.sort((a, b) => a - b);\n    if (this.#viewProps.multipleSelection) {\n      this.#currentValueIndices = indices;\n      this.#value = indices.map(i => this.#items[i].exportValue);\n    } else if (indices.length > 0) {\n      indices = [indices[0]];\n      this.#currentValueIndices = indices[0];\n      this.#value = this.#items[indices[0]].exportValue;\n    }\n    this.#send({\n      id: this.#id,\n      indices\n    });\n  }\n  get fillColor() {\n    return this.#fillColor;\n  }\n  set fillColor(color) {\n    if (isValidColor(color)) {\n      this.#fillColor = color;\n      this.#update(\"fillColor\", color);\n    }\n  }\n  get bgColor() {\n    return this.fillColor;\n  }\n  set bgColor(color) {\n    this.fillColor = color;\n  }\n  get charLimit() {\n    return this.#charLimit;\n  }\n  set charLimit(limit) {\n    if (typeof limit !== \"number\") {\n      throw new Error(\"Invalid argument value\");\n    }\n    this.#charLimit = Math.max(0, Math.floor(limit));\n    this.#update(\"charLimit\", this.#charLimit);\n  }\n  get numItems() {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    return this.#items.length;\n  }\n  set numItems(_) {\n    throw new Error(\"field.numItems is read-only\");\n  }\n  get strokeColor() {\n    return this.#strokeColor;\n  }\n  set strokeColor(color) {\n    if (isValidColor(color)) {\n      this.#strokeColor = color;\n      this.#update(\"strokeColor\", color);\n    }\n  }\n  get borderColor() {\n    return this.strokeColor;\n  }\n  set borderColor(color) {\n    this.strokeColor = color;\n  }\n  get page() {\n    return this.#page;\n  }\n  set page(_) {\n    throw new Error(\"field.page is read-only\");\n  }\n  get rotation() {\n    return this.#rotation;\n  }\n  set rotation(angle) {\n    angle = Math.floor(angle);\n    if (angle % 90 !== 0) {\n      throw new Error(\"Invalid rotation: must be a multiple of 90\");\n    }\n    angle %= 360;\n    if (angle < 0) {\n      angle += 360;\n    }\n    this.#rotation = angle;\n    this.#update(\"rotation\", angle);\n  }\n  get textColor() {\n    return this.#textColor;\n  }\n  set textColor(color) {\n    if (isValidColor(color)) {\n      this.#textColor = color;\n      this.#update(\"textColor\", color);\n    }\n  }\n  get fgColor() {\n    return this.textColor;\n  }\n  set fgColor(color) {\n    this.textColor = color;\n  }\n  get value() {\n    return this.#value;\n  }\n  set value(value) {\n    if (this.#setValue(value)) {\n      this.#update(\"value\", value, this.#originalValue ?? this.#value);\n    }\n  }\n  #setValue(value) {\n    if (this.#radioIds) {\n      return this.#setRadioValue(value);\n    }\n    if (this.#isChoice) {\n      this.#setChoiceValue(value);\n      return true;\n    }\n    if (this.#hasDateOrTime && value) {\n      const date = this.#util.scand(this.#datetimeFormat, value);\n      if (date) {\n        this.#originalValue = date.valueOf();\n        value = this.#util.printd(this.#datetimeFormat, date);\n        this.#value = !isNaN(value) ? parseFloat(value) : value;\n        return true;\n      }\n    }\n    if (value === \"\" || typeof value !== \"string\" || this.#fieldType >= FieldType.date) {\n      this.#originalValue = undefined;\n      this.#value = value;\n      return true;\n    }\n    this.#originalValue = value;\n    const _value = value.trim().replace(\",\", \".\");\n    this.#value = !isNaN(_value) ? parseFloat(_value) : value;\n    return true;\n  }\n  get #checkedIndex() {\n    return this.#radioIds.indexOf(this.#id);\n  }\n  #getWidgetIndex(nWidget) {\n    if (!this.#radioIds) {\n      return -1;\n    }\n    const index = Number(nWidget);\n    return Number.isInteger(index) && index >= 0 && index < this.#radioIds.length && `${index}` === `${nWidget}` ? index : -1;\n  }\n  #check(index, value) {\n    this.#id = this.#radioIds[index];\n    this.#value = value;\n  }\n  #setRadioValue(value) {\n    if (this.#isCheckbox && (!value || value === \"Off\" || !this.exportValues.includes(value))) {\n      this.#value = \"Off\";\n      return true;\n    }\n    if (value === null || value === undefined) {\n      this.#value = \"\";\n      return true;\n    }\n    const i = this.exportValues.indexOf(value);\n    if (i !== -1) {\n      this.#check(i, value);\n      return true;\n    }\n    if (value === \"Off\" && this.#radioIds.length === 2) {\n      const nextI = (1 + this.#checkedIndex) % 2;\n      this.#check(nextI, this.exportValues[nextI]);\n      return true;\n    }\n    return false;\n  }\n  #setChoiceValue(value) {\n    if (this.#viewProps.multipleSelection) {\n      if (!Array.isArray(value)) {\n        value = [value];\n      }\n      const values = new Set(value);\n      if (Array.isArray(this.#currentValueIndices)) {\n        this.#currentValueIndices.length = 0;\n        this.#value.length = 0;\n      } else {\n        this.#currentValueIndices = [];\n        this.#value = [];\n      }\n      this.#items.forEach((item, i) => {\n        if (values.has(item.exportValue)) {\n          this.#currentValueIndices.push(i);\n          this.#value.push(item.exportValue);\n        }\n      });\n    } else {\n      if (Array.isArray(value)) {\n        value = value[0];\n      }\n      const index = this.#items.findIndex(({\n        exportValue\n      }) => value === exportValue);\n      if (index !== -1) {\n        this.#currentValueIndices = index;\n        this.#value = this.#items[index].exportValue;\n      }\n    }\n  }\n  get valueAsString() {\n    return (this.#value ?? \"\").toString();\n  }\n  set valueAsString(_) {}\n  browseForFileToSubmit() {\n    if (this.#browseForFileToSubmit) {\n      this.#browseForFileToSubmit();\n    }\n  }\n  buttonGetCaption(nFace = 0) {\n    return this.#buttonCaption ? this.#buttonCaption[nFace] : \"\";\n  }\n  buttonGetIcon(nFace = 0) {\n    return this.#buttonIcon ? this.#buttonIcon[nFace] : null;\n  }\n  buttonImportIcon(cPath = null, nPave = 0) {}\n  buttonSetCaption(cCaption, nFace = 0) {\n    this.#buttonCaption ??= [\"\", \"\", \"\"];\n    this.#buttonCaption[nFace] = cCaption;\n  }\n  buttonSetIcon(oIcon, nFace = 0) {\n    this.#buttonIcon ??= [null, null, null];\n    this.#buttonIcon[nFace] = oIcon;\n  }\n  checkThisBox(nWidget, bCheckIt = true) {\n    const index = this.#getWidgetIndex(nWidget);\n    if (index === -1 || !bCheckIt && !this.#isCheckbox) {\n      return;\n    }\n    const value = bCheckIt ? this.exportValues[index] : \"Off\";\n    this.#check(index, value);\n    this.#send({\n      id: this.#id,\n      value\n    });\n  }\n  clearItems() {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    this.#items = [];\n    this.#send({\n      id: this.#id,\n      clear: null\n    });\n  }\n  deleteItemAt(nIdx = null) {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    if (!this.numItems) {\n      return;\n    }\n    if (nIdx === null) {\n      nIdx = Array.isArray(this.#currentValueIndices) ? this.#currentValueIndices[0] : this.#currentValueIndices;\n      nIdx ||= 0;\n    }\n    if (nIdx < 0 || nIdx >= this.numItems) {\n      nIdx = this.numItems - 1;\n    }\n    this.#items.splice(nIdx, 1);\n    if (Array.isArray(this.#currentValueIndices)) {\n      let index = this.#currentValueIndices.findIndex(i => i >= nIdx);\n      if (index !== -1) {\n        if (this.#currentValueIndices[index] === nIdx) {\n          this.#currentValueIndices.splice(index, 1);\n        }\n        for (const ii = this.#currentValueIndices.length; index < ii; index++) {\n          --this.#currentValueIndices[index];\n        }\n      }\n    } else if (this.#currentValueIndices === nIdx) {\n      this.#currentValueIndices = this.numItems > 0 ? 0 : -1;\n    } else if (this.#currentValueIndices > nIdx) {\n      --this.#currentValueIndices;\n    }\n    this.#send({\n      id: this.#id,\n      remove: nIdx\n    });\n  }\n  getItemAt(nIdx = -1, bExportValue = false) {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    if (nIdx < 0 || nIdx >= this.numItems) {\n      nIdx = this.numItems - 1;\n    }\n    const item = this.#items[nIdx];\n    return bExportValue ? item.exportValue : item.displayValue;\n  }\n  getArray() {\n    if (this.#kidIds) {\n      const array = [];\n      const fillArrayWithKids = kidIds => {\n        for (const id of kidIds) {\n          const obj = this.#appObjects[id];\n          if (!obj) {\n            continue;\n          }\n          if (obj.#hasValue) {\n            array.push(obj);\n          }\n          if (obj.#kidIds) {\n            fillArrayWithKids(obj.#kidIds);\n          }\n        }\n      };\n      fillArrayWithKids(this.#kidIds);\n      return array;\n    }\n    return this.#children ??= this.#getTerminalChildren(this.#fieldPath);\n  }\n  getLock() {\n    return undefined;\n  }\n  isBoxChecked(nWidget) {\n    const index = this.#getWidgetIndex(nWidget);\n    return index !== -1 && this.#id === this.#radioIds[index] && this.#value === this.exportValues[index];\n  }\n  isDefaultChecked(nWidget) {\n    const index = this.#getWidgetIndex(nWidget);\n    return index !== -1 && this.defaultValue === this.exportValues[index];\n  }\n  insertItemAt(cName, cExport = undefined, nIdx = 0) {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    if (!cName) {\n      return;\n    }\n    if (nIdx < 0 || nIdx > this.numItems) {\n      nIdx = this.numItems;\n    }\n    if (this.#items.some(({\n      displayValue\n    }) => displayValue === cName)) {\n      return;\n    }\n    if (cExport === undefined) {\n      cExport = cName;\n    }\n    const data = {\n      displayValue: cName,\n      exportValue: cExport\n    };\n    this.#items.splice(nIdx, 0, data);\n    if (Array.isArray(this.#currentValueIndices)) {\n      let index = this.#currentValueIndices.findIndex(i => i >= nIdx);\n      if (index !== -1) {\n        for (const ii = this.#currentValueIndices.length; index < ii; index++) {\n          ++this.#currentValueIndices[index];\n        }\n      }\n    } else if (this.#currentValueIndices >= nIdx) {\n      ++this.#currentValueIndices;\n    }\n    this.#send({\n      id: this.#id,\n      insert: {\n        index: nIdx,\n        ...data\n      }\n    });\n  }\n  setAction(cTrigger, cScript) {\n    if (typeof cTrigger !== \"string\" || typeof cScript !== \"string\") {\n      return;\n    }\n    this.#actions.getOrInsertComputed(cTrigger, makeArr).push(cScript);\n  }\n  setFocus() {\n    this.#send({\n      id: this.#id,\n      focus: true\n    });\n  }\n  setItems(oArray) {\n    if (!this.#isChoice) {\n      throw new Error(\"Not a choice widget\");\n    }\n    this.#items.length = 0;\n    for (const element of oArray) {\n      let displayValue, exportValue;\n      if (Array.isArray(element)) {\n        displayValue = element[0]?.toString() || \"\";\n        exportValue = element[1]?.toString() || \"\";\n      } else {\n        displayValue = exportValue = element?.toString() || \"\";\n      }\n      this.#items.push({\n        displayValue,\n        exportValue\n      });\n    }\n    this.#currentValueIndices = 0;\n    this.#send({\n      id: this.#id,\n      items: this.#items\n    });\n  }\n  setLock() {}\n  signatureGetModifications() {}\n  signatureGetSeedValue() {}\n  signatureInfo() {}\n  signatureSetSeedValue() {}\n  signatureSign() {}\n  signatureValidate() {}\n  #runActions(event) {\n    if (this.#radioIds) {\n      this.#actions = this.#radioActions[this.#checkedIndex];\n    }\n    const eventName = event.name;\n    const actions = this.#actions.get(eventName);\n    if (!actions) {\n      return false;\n    }\n    for (const action of actions) {\n      try {\n        this.#globalEval(action);\n      } catch (error) {\n        this.#sendError(serializeError(error, `Error when executing \"${eventName}\" for field \"${this.#id}\"\\n`));\n      }\n    }\n    return true;\n  }\n}\n\n;// ./src/scripting_api/print_params.js\nclass PrintParams {\n  binaryOk = true;\n  bitmapDPI = 150;\n  booklet = {\n    binding: 0,\n    duplexMode: 0,\n    subsetFrom: 0,\n    subsetTo: -1\n  };\n  colorOverride = 0;\n  colorProfile = \"\";\n  constants = Object.freeze({\n    bookletBindings: Object.freeze({\n      Left: 0,\n      Right: 1,\n      LeftTall: 2,\n      RightTall: 3\n    }),\n    bookletDuplexMode: Object.freeze({\n      BothSides: 0,\n      FrontSideOnly: 1,\n      BasicSideOnly: 2\n    }),\n    colorOverrides: Object.freeze({\n      auto: 0,\n      gray: 1,\n      mono: 2\n    }),\n    fontPolicies: Object.freeze({\n      everyPage: 0,\n      jobStart: 1,\n      pageRange: 2\n    }),\n    handling: Object.freeze({\n      none: 0,\n      fit: 1,\n      shrink: 2,\n      tileAll: 3,\n      tileLarge: 4,\n      nUp: 5,\n      booklet: 6\n    }),\n    interactionLevel: Object.freeze({\n      automatic: 0,\n      full: 1,\n      silent: 2\n    }),\n    nUpPageOrders: Object.freeze({\n      Horizontal: 0,\n      HorizontalReversed: 1,\n      Vertical: 2\n    }),\n    printContents: Object.freeze({\n      doc: 0,\n      docAndComments: 1,\n      formFieldsOnly: 2\n    }),\n    flagValues: Object.freeze({\n      applyOverPrint: 1,\n      applySoftProofSettings: 1 << 1,\n      applyWorkingColorSpaces: 1 << 2,\n      emitHalftones: 1 << 3,\n      emitPostScriptXObjects: 1 << 4,\n      emitFormsAsPSForms: 1 << 5,\n      maxJP2KRes: 1 << 6,\n      setPageSize: 1 << 7,\n      suppressBG: 1 << 8,\n      suppressCenter: 1 << 9,\n      suppressCJKFontSubst: 1 << 10,\n      suppressCropClip: 1 << 11,\n      suppressRotate: 1 << 12,\n      suppressTransfer: 1 << 13,\n      suppressUCR: 1 << 14,\n      useTrapAnnots: 1 << 15,\n      usePrintersMarks: 1 << 16\n    }),\n    rasterFlagValues: Object.freeze({\n      textToOutline: 1,\n      strokesToOutline: 1 << 1,\n      allowComplexClip: 1 << 2,\n      preserveOverprint: 1 << 3\n    }),\n    subsets: Object.freeze({\n      all: 0,\n      even: 1,\n      odd: 2\n    }),\n    tileMarks: Object.freeze({\n      none: 0,\n      west: 1,\n      east: 2\n    }),\n    usages: Object.freeze({\n      auto: 0,\n      use: 1,\n      noUse: 2\n    })\n  });\n  downloadFarEastFonts = false;\n  fileName = \"\";\n  firstPage = 0;\n  flags = 0;\n  fontPolicy = 0;\n  gradientDPI = 150;\n  interactive = 1;\n  npUpAutoRotate = false;\n  npUpNumPagesH = 2;\n  npUpNumPagesV = 2;\n  npUpPageBorder = false;\n  npUpPageOrder = 0;\n  pageHandling = 0;\n  pageSubset = 0;\n  printAsImage = false;\n  printContent = 0;\n  printerName = \"\";\n  psLevel = 0;\n  rasterFlags = 0;\n  reversePages = false;\n  tileLabel = false;\n  tileMark = 0;\n  tileOverlap = 0;\n  tileScale = 1.0;\n  transparencyLevel = 75;\n  usePrinterCRD = 0;\n  useT1Conversion = 0;\n  constructor(data) {\n    this.lastPage = data.lastPage;\n  }\n}\n\n;// ./src/scripting_api/doc.js\n\n\n\n\n\nconst DOC_EXTERNAL = false;\nclass InfoProxyHandler {\n  static get(obj, prop) {\n    return obj[prop.toLowerCase()];\n  }\n  static set(obj, prop, value) {\n    throw new Error(`doc.info.${prop} is read-only`);\n  }\n}\nconst DocInternals = Object.create(null);\nclass Doc {\n  #pageActions = null;\n  #otherPageActions = null;\n  #baseURL;\n  #calculate = true;\n  #delay = false;\n  #dirty = false;\n  #disclosed = false;\n  #media;\n  #metadata;\n  #noautocomplete;\n  #nocache;\n  #spellDictionaryOrder = [];\n  #spellLanguageOrder = [];\n  #printParams;\n  #fields = new Map();\n  #fieldNames = [];\n  #author;\n  #creator;\n  #creationDate;\n  #docID;\n  #documentFileName;\n  #filesize;\n  #keywords;\n  #layout;\n  #modDate;\n  #numPages;\n  #pageNum;\n  #producer;\n  #securityHandler;\n  #subject;\n  #title;\n  #URL;\n  #info;\n  #zoomType = ZoomType.none;\n  #zoom;\n  #actions;\n  #appObjects;\n  #globalEval;\n  #send;\n  #userActivationData;\n  #calculateNow;\n  constructor(data) {\n    this.#baseURL = data.baseURL || \"\";\n    this.#metadata = data.metadata || \"\";\n    this.#author = data.Author || \"\";\n    this.#creator = data.Creator || \"\";\n    this.#creationDate = this.#getDate(data.CreationDate) || null;\n    this.#docID = data.docID || [\"\", \"\"];\n    this.#documentFileName = data.filename || \"\";\n    this.#filesize = data.filesize || 0;\n    this.#keywords = data.Keywords || \"\";\n    this.#layout = data.layout || \"\";\n    this.#modDate = this.#getDate(data.ModDate) || null;\n    this.#numPages = data.numPages || 1;\n    this.#pageNum = data.pageNum || 0;\n    this.#producer = data.Producer || \"\";\n    this.#securityHandler = data.EncryptFilterName || null;\n    this.#subject = data.Subject || \"\";\n    this.#title = data.Title || \"\";\n    this.#URL = data.URL || \"\";\n    this.#info = new Proxy(Object.assign(Object.create(null), {\n      title: this.#title,\n      author: this.#author,\n      authors: data.authors || [this.#author],\n      subject: this.#subject,\n      keywords: this.#keywords,\n      creator: this.#creator,\n      producer: this.#producer,\n      creationdate: this.#creationDate,\n      moddate: this.#modDate,\n      trapped: data.Trapped || \"Unknown\"\n    }), InfoProxyHandler);\n    this.#zoom = data.zoom || 100;\n    this.#actions = createMap(data.actions);\n    this.#appObjects = data.appObjects;\n    this.#calculateNow = data.calculateNow;\n    this.#globalEval = data.globalEval;\n    this.#send = data.send;\n    this.#userActivationData = data.userActivationData;\n    this.#printParams = exposeObject(new PrintParams({\n      lastPage: this.#numPages - 1\n    }), true);\n  }\n  static {\n    Object.assign(DocInternals, {\n      addField: (doc, name, field) => doc.#addField(name, field),\n      dispatchDocEvent: (doc, name) => doc.#dispatchDocEvent(name),\n      dispatchPageEvent: (doc, name, actions, pageNumber) => doc.#dispatchPageEvent(name, actions, pageNumber),\n      getTerminalChildren: (doc, fieldName) => doc.#getTerminalChildren(fieldName),\n      initActions: doc => doc.#initActions()\n    });\n  }\n  #initActions() {\n    for (const field of this.#fields.values()) {\n      const initialValue = FieldInternals.getInitialValue(field);\n      if (initialValue) {\n        FieldInternals.send(field, {\n          value: initialValue,\n          formattedValue: FieldInternals.getValue(field).toString()\n        });\n      }\n    }\n    const dontRun = new Set([\"WillClose\", \"WillSave\", \"DidSave\", \"WillPrint\", \"DidPrint\", \"OpenAction\"]);\n    this.#userActivationData.disableSaving = true;\n    for (const actionName of this.#actions.keys()) {\n      if (!dontRun.has(actionName)) {\n        this.#runActions(actionName);\n      }\n    }\n    this.#userActivationData.disableSaving = false;\n  }\n  #dispatchDocEvent(name) {\n    switch (name) {\n      case \"Open\":\n        this.#userActivationData.disableSaving = true;\n        this.#runActions(\"OpenAction\");\n        this.#userActivationData.disableSaving = false;\n        break;\n      case \"WillPrint\":\n        this.#userActivationData.disablePrinting = true;\n        try {\n          this.#runActions(name);\n        } catch (error) {\n          this.#send(serializeError(error));\n        }\n        this.#send({\n          command: \"WillPrintFinished\"\n        });\n        this.#userActivationData.disablePrinting = false;\n        break;\n      case \"WillSave\":\n        this.#userActivationData.disableSaving = true;\n        try {\n          this.#runActions(name);\n        } catch (error) {\n          this.#send(serializeError(error));\n        }\n        this.#send({\n          command: \"WillSaveFinished\"\n        });\n        this.#userActivationData.disableSaving = false;\n        break;\n      default:\n        this.#runActions(name);\n    }\n  }\n  #dispatchPageEvent(name, actions, pageNumber) {\n    if (name === \"PageOpen\") {\n      this.#pageActions ??= new Map();\n      this.#pageActions.getOrInsertComputed(pageNumber, () => createMap(actions));\n      this.#pageNum = pageNumber - 1;\n    }\n    for (const acts of [this.#pageActions, this.#otherPageActions]) {\n      actions = acts?.get(pageNumber)?.get(name);\n      if (actions) {\n        for (const action of actions) {\n          this.#globalEval(action);\n        }\n      }\n    }\n  }\n  #runActions(name) {\n    const actions = this.#actions.get(name);\n    if (!actions) {\n      return;\n    }\n    for (const action of actions) {\n      try {\n        this.#globalEval(action);\n      } catch (error) {\n        this.#send(serializeError(error, `Error when executing \"${name}\" for document\\n`));\n      }\n    }\n  }\n  #addField(name, field) {\n    this.#fields.set(name, field);\n    this.#fieldNames.push(name);\n    for (const [page, eventName, scripts] of FieldInternals.getPageActions(field)) {\n      this.#otherPageActions ??= new Map();\n      this.#otherPageActions.getOrInsertComputed(page + 1, makeMap).getOrInsertComputed(eventName, makeArr).push(...scripts);\n    }\n  }\n  #getDate(date) {\n    if (!date || date.length < 15 || !date.startsWith(\"D:\")) {\n      return date;\n    }\n    date = date.substring(2);\n    const year = date.substring(0, 4);\n    const month = date.substring(4, 6);\n    const day = date.substring(6, 8);\n    const hour = date.substring(8, 10);\n    const minute = date.substring(10, 12);\n    const o = date.charAt(12);\n    let second, offsetPos;\n    if (o === \"Z\" || o === \"+\" || o === \"-\") {\n      second = \"00\";\n      offsetPos = 12;\n    } else {\n      second = date.substring(12, 14);\n      offsetPos = 14;\n    }\n    const offset = date.substring(offsetPos).replaceAll(\"'\", \"\");\n    return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${offset}`);\n  }\n  get author() {\n    return this.#author;\n  }\n  set author(_) {\n    throw new Error(\"doc.author is read-only\");\n  }\n  get baseURL() {\n    return this.#baseURL;\n  }\n  set baseURL(baseURL) {\n    this.#baseURL = baseURL;\n  }\n  get bookmarkRoot() {\n    return undefined;\n  }\n  set bookmarkRoot(_) {\n    throw new Error(\"doc.bookmarkRoot is read-only\");\n  }\n  get calculate() {\n    return this.#calculate;\n  }\n  set calculate(calculate) {\n    this.#calculate = calculate;\n  }\n  get creator() {\n    return this.#creator;\n  }\n  set creator(_) {\n    throw new Error(\"doc.creator is read-only\");\n  }\n  get dataObjects() {\n    return [];\n  }\n  set dataObjects(_) {\n    throw new Error(\"doc.dataObjects is read-only\");\n  }\n  get delay() {\n    return this.#delay;\n  }\n  set delay(delay) {\n    this.#delay = delay;\n  }\n  get dirty() {\n    return this.#dirty;\n  }\n  set dirty(dirty) {\n    this.#dirty = dirty;\n  }\n  get disclosed() {\n    return this.#disclosed;\n  }\n  set disclosed(disclosed) {\n    this.#disclosed = disclosed;\n  }\n  get docID() {\n    return this.#docID;\n  }\n  set docID(_) {\n    throw new Error(\"doc.docID is read-only\");\n  }\n  get documentFileName() {\n    return this.#documentFileName;\n  }\n  set documentFileName(_) {\n    throw new Error(\"doc.documentFileName is read-only\");\n  }\n  get dynamicXFAForm() {\n    return false;\n  }\n  set dynamicXFAForm(_) {\n    throw new Error(\"doc.dynamicXFAForm is read-only\");\n  }\n  get external() {\n    return DOC_EXTERNAL;\n  }\n  set external(_) {\n    throw new Error(\"doc.external is read-only\");\n  }\n  get filesize() {\n    return this.#filesize;\n  }\n  set filesize(_) {\n    throw new Error(\"doc.filesize is read-only\");\n  }\n  get hidden() {\n    return false;\n  }\n  set hidden(_) {\n    throw new Error(\"doc.hidden is read-only\");\n  }\n  get hostContainer() {\n    return undefined;\n  }\n  set hostContainer(_) {\n    throw new Error(\"doc.hostContainer is read-only\");\n  }\n  get icons() {\n    return undefined;\n  }\n  set icons(_) {\n    throw new Error(\"doc.icons is read-only\");\n  }\n  get info() {\n    return this.#info;\n  }\n  set info(_) {\n    throw new Error(\"doc.info is read-only\");\n  }\n  get innerAppWindowRect() {\n    return [0, 0, 0, 0];\n  }\n  set innerAppWindowRect(_) {\n    throw new Error(\"doc.innerAppWindowRect is read-only\");\n  }\n  get innerDocWindowRect() {\n    return [0, 0, 0, 0];\n  }\n  set innerDocWindowRect(_) {\n    throw new Error(\"doc.innerDocWindowRect is read-only\");\n  }\n  get isModal() {\n    return false;\n  }\n  set isModal(_) {\n    throw new Error(\"doc.isModal is read-only\");\n  }\n  get keywords() {\n    return this.#keywords;\n  }\n  set keywords(_) {\n    throw new Error(\"doc.keywords is read-only\");\n  }\n  get layout() {\n    return this.#layout;\n  }\n  set layout(value) {\n    if (!this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    if (typeof value !== \"string\") {\n      return;\n    }\n    if (value !== \"SinglePage\" && value !== \"OneColumn\" && value !== \"TwoColumnLeft\" && value !== \"TwoPageLeft\" && value !== \"TwoColumnRight\" && value !== \"TwoPageRight\") {\n      value = \"SinglePage\";\n    }\n    this.#send({\n      command: \"layout\",\n      value\n    });\n    this.#layout = value;\n  }\n  get media() {\n    return this.#media;\n  }\n  set media(media) {\n    this.#media = media;\n  }\n  get metadata() {\n    return this.#metadata;\n  }\n  set metadata(metadata) {\n    this.#metadata = metadata;\n  }\n  get modDate() {\n    return this.#modDate;\n  }\n  set modDate(_) {\n    throw new Error(\"doc.modDate is read-only\");\n  }\n  get mouseX() {\n    return 0;\n  }\n  set mouseX(_) {\n    throw new Error(\"doc.mouseX is read-only\");\n  }\n  get mouseY() {\n    return 0;\n  }\n  set mouseY(_) {\n    throw new Error(\"doc.mouseY is read-only\");\n  }\n  get noautocomplete() {\n    return this.#noautocomplete;\n  }\n  set noautocomplete(noautocomplete) {\n    this.#noautocomplete = noautocomplete;\n  }\n  get nocache() {\n    return this.#nocache;\n  }\n  set nocache(nocache) {\n    this.#nocache = nocache;\n  }\n  get numFields() {\n    return this.#fieldNames.length;\n  }\n  set numFields(_) {\n    throw new Error(\"doc.numFields is read-only\");\n  }\n  get numPages() {\n    return this.#numPages;\n  }\n  set numPages(_) {\n    throw new Error(\"doc.numPages is read-only\");\n  }\n  get numTemplates() {\n    return 0;\n  }\n  set numTemplates(_) {\n    throw new Error(\"doc.numTemplates is read-only\");\n  }\n  get outerAppWindowRect() {\n    return [0, 0, 0, 0];\n  }\n  set outerAppWindowRect(_) {\n    throw new Error(\"doc.outerAppWindowRect is read-only\");\n  }\n  get outerDocWindowRect() {\n    return [0, 0, 0, 0];\n  }\n  set outerDocWindowRect(_) {\n    throw new Error(\"doc.outerDocWindowRect is read-only\");\n  }\n  get pageNum() {\n    return this.#pageNum;\n  }\n  set pageNum(value) {\n    if (!this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    if (typeof value !== \"number\" || value < 0 || value >= this.#numPages) {\n      return;\n    }\n    this.#send({\n      command: \"page-num\",\n      value\n    });\n    this.#pageNum = value;\n  }\n  get pageWindowRect() {\n    return [0, 0, 0, 0];\n  }\n  set pageWindowRect(_) {\n    throw new Error(\"doc.pageWindowRect is read-only\");\n  }\n  get path() {\n    return \"\";\n  }\n  set path(_) {\n    throw new Error(\"doc.path is read-only\");\n  }\n  get permStatusReady() {\n    return true;\n  }\n  set permStatusReady(_) {\n    throw new Error(\"doc.permStatusReady is read-only\");\n  }\n  get producer() {\n    return this.#producer;\n  }\n  set producer(_) {\n    throw new Error(\"doc.producer is read-only\");\n  }\n  get requiresFullSave() {\n    return false;\n  }\n  set requiresFullSave(_) {\n    throw new Error(\"doc.requiresFullSave is read-only\");\n  }\n  get securityHandler() {\n    return this.#securityHandler;\n  }\n  set securityHandler(_) {\n    throw new Error(\"doc.securityHandler is read-only\");\n  }\n  get selectedAnnots() {\n    return [];\n  }\n  set selectedAnnots(_) {\n    throw new Error(\"doc.selectedAnnots is read-only\");\n  }\n  get sounds() {\n    return [];\n  }\n  set sounds(_) {\n    throw new Error(\"doc.sounds is read-only\");\n  }\n  get spellDictionaryOrder() {\n    return this.#spellDictionaryOrder;\n  }\n  set spellDictionaryOrder(spellDictionaryOrder) {\n    this.#spellDictionaryOrder = spellDictionaryOrder;\n  }\n  get spellLanguageOrder() {\n    return this.#spellLanguageOrder;\n  }\n  set spellLanguageOrder(spellLanguageOrder) {\n    this.#spellLanguageOrder = spellLanguageOrder;\n  }\n  get subject() {\n    return this.#subject;\n  }\n  set subject(_) {\n    throw new Error(\"doc.subject is read-only\");\n  }\n  get templates() {\n    return [];\n  }\n  set templates(_) {\n    throw new Error(\"doc.templates is read-only\");\n  }\n  get title() {\n    return this.#title;\n  }\n  set title(_) {\n    throw new Error(\"doc.title is read-only\");\n  }\n  get URL() {\n    return this.#URL;\n  }\n  set URL(_) {\n    throw new Error(\"doc.URL is read-only\");\n  }\n  get viewState() {\n    return undefined;\n  }\n  set viewState(_) {\n    throw new Error(\"doc.viewState is read-only\");\n  }\n  get xfa() {\n    return undefined;\n  }\n  set xfa(_) {\n    throw new Error(\"doc.xfa is read-only\");\n  }\n  get XFAForeground() {\n    return false;\n  }\n  set XFAForeground(_) {\n    throw new Error(\"doc.XFAForeground is read-only\");\n  }\n  get zoomType() {\n    return this.#zoomType;\n  }\n  set zoomType(type) {\n    if (!this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    if (typeof type !== \"string\") {\n      return;\n    }\n    switch (type) {\n      case ZoomType.none:\n        this.#send({\n          command: \"zoom\",\n          value: 1\n        });\n        break;\n      case ZoomType.fitP:\n        this.#send({\n          command: \"zoom\",\n          value: \"page-fit\"\n        });\n        break;\n      case ZoomType.fitW:\n        this.#send({\n          command: \"zoom\",\n          value: \"page-width\"\n        });\n        break;\n      case ZoomType.fitH:\n        this.#send({\n          command: \"zoom\",\n          value: \"page-height\"\n        });\n        break;\n      case ZoomType.fitV:\n        this.#send({\n          command: \"zoom\",\n          value: \"auto\"\n        });\n        break;\n      case ZoomType.pref:\n      case ZoomType.refW:\n        break;\n      default:\n        return;\n    }\n    this.#zoomType = type;\n  }\n  get zoom() {\n    return this.#zoom;\n  }\n  set zoom(value) {\n    if (!this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    if (typeof value !== \"number\" || value < 8.33 || value > 6400) {\n      return;\n    }\n    this.#send({\n      command: \"zoom\",\n      value: value / 100\n    });\n  }\n  addAnnot() {}\n  addField() {}\n  addIcon() {}\n  addLink() {}\n  addRecipientListCryptFilter() {}\n  addRequirement() {}\n  addScript() {}\n  addThumbnails() {}\n  addWatermarkFromFile() {}\n  addWatermarkFromText() {}\n  addWeblinks() {}\n  bringToFront() {}\n  calculateNow() {\n    this.#calculateNow();\n  }\n  closeDoc() {}\n  colorConvertPage() {}\n  createDataObject() {}\n  createTemplate() {}\n  deletePages() {}\n  deleteSound() {}\n  embedDocAsDataObject() {}\n  embedOutputIntent() {}\n  encryptForRecipients() {}\n  encryptUsingPolicy() {}\n  exportAsFDF() {}\n  exportAsFDFStr() {}\n  exportAsText() {}\n  exportAsXFDF() {}\n  exportAsXFDFStr() {}\n  exportDataObject() {}\n  exportXFAData() {}\n  extractPages() {}\n  flattenPages() {}\n  getAnnot() {}\n  getAnnots() {}\n  getAnnot3D() {}\n  getAnnots3D() {}\n  getColorConvertAction() {}\n  getDataObject() {}\n  getDataObjectContents() {}\n  getField(cName) {\n    if (cName && typeof cName === \"object\") {\n      cName = cName.cName;\n    }\n    if (typeof cName !== \"string\") {\n      throw new TypeError(\"Invalid field name: must be a string\");\n    }\n    const searchedField = this.#fields.get(cName);\n    if (searchedField) {\n      return searchedField;\n    }\n    const parts = cName.split(\"#\");\n    let childIndex = NaN;\n    if (parts.length === 2) {\n      childIndex = Math.floor(parseFloat(parts[1]));\n      cName = parts[0];\n    }\n    for (const [name, field] of this.#fields) {\n      if (name.endsWith(cName)) {\n        if (!isNaN(childIndex)) {\n          const children = this.#getChildren(name);\n          if (childIndex < 0 || childIndex >= children.length) {\n            childIndex = 0;\n          }\n          if (childIndex < children.length) {\n            this.#fields.set(cName, children[childIndex]);\n            return children[childIndex];\n          }\n        }\n        this.#fields.set(cName, field);\n        return field;\n      }\n    }\n    return null;\n  }\n  #getChildren(fieldName) {\n    const len = fieldName.length;\n    const children = [];\n    const pattern = /^\\.[^.]+$/;\n    for (const [name, field] of this.#fields) {\n      if (name.startsWith(fieldName)) {\n        const finalPart = name.slice(len);\n        if (pattern.test(finalPart)) {\n          children.push(field);\n        }\n      }\n    }\n    return children;\n  }\n  #getTerminalChildren(fieldName) {\n    const children = [];\n    const len = fieldName.length;\n    for (const [name, field] of this.#fields) {\n      if (name.startsWith(fieldName)) {\n        const finalPart = name.slice(len);\n        if (FieldInternals.getHasValue(field) && (finalPart === \"\" || finalPart.startsWith(\".\"))) {\n          children.push(field);\n        }\n      }\n    }\n    return children;\n  }\n  getIcon() {}\n  getLegalWarnings() {}\n  getLinks() {}\n  getNthFieldName(nIndex) {\n    if (nIndex && typeof nIndex === \"object\") {\n      nIndex = nIndex.nIndex;\n    }\n    if (typeof nIndex !== \"number\") {\n      throw new TypeError(\"Invalid field index: must be a number\");\n    }\n    return nIndex >= 0 && nIndex < this.numFields ? this.#fieldNames[Math.trunc(nIndex)] : null;\n  }\n  getNthTemplate() {\n    return null;\n  }\n  getOCGs() {}\n  getOCGOrder() {}\n  getPageBox() {}\n  getPageLabel() {}\n  getPageNthWord() {}\n  getPageNthWordQuads() {}\n  getPageNumWords() {}\n  getPageRotation() {}\n  getPageTransition() {}\n  getPrintParams() {\n    return this.#printParams;\n  }\n  getSound() {}\n  getTemplate() {}\n  getURL() {}\n  gotoNamedDest() {}\n  importAnFDF() {}\n  importAnXFDF() {}\n  importDataObject() {}\n  importIcon() {}\n  importSound() {}\n  importTextData() {}\n  importXFAData() {}\n  insertPages() {}\n  mailDoc() {}\n  mailForm() {}\n  movePage() {}\n  newPage() {}\n  openDataObject() {}\n  print(bUI = true, nStart = 0, nEnd = -1, bSilent = false, bShrinkToFit = false, bPrintAsImage = false, bReverse = false, bAnnotations = true, printParams = null) {\n    if (this.#userActivationData.disablePrinting || !this.#userActivationData.userActivation) {\n      return;\n    }\n    this.#userActivationData.userActivation = false;\n    if (bUI && typeof bUI === \"object\") {\n      nStart = bUI.nStart;\n      nEnd = bUI.nEnd;\n      bSilent = bUI.bSilent;\n      bShrinkToFit = bUI.bShrinkToFit;\n      bPrintAsImage = bUI.bPrintAsImage;\n      bReverse = bUI.bReverse;\n      bAnnotations = bUI.bAnnotations;\n      printParams = bUI.printParams;\n      bUI = bUI.bUI;\n    }\n    if (printParams) {\n      nStart = printParams.firstPage;\n      nEnd = printParams.lastPage;\n    }\n    nStart = typeof nStart === \"number\" ? Math.max(0, Math.trunc(nStart)) : 0;\n    nEnd = typeof nEnd === \"number\" ? Math.max(0, Math.trunc(nEnd)) : -1;\n    this.#send({\n      command: \"print\",\n      start: nStart,\n      end: nEnd\n    });\n  }\n  removeDataObject() {}\n  removeField() {}\n  removeIcon() {}\n  removeLinks() {}\n  removeRequirement() {}\n  removeScript() {}\n  removeTemplate() {}\n  removeThumbnails() {}\n  removeWeblinks() {}\n  replacePages() {}\n  resetForm(aFields = null) {\n    if (aFields && typeof aFields === \"object\" && !Array.isArray(aFields)) {\n      aFields = aFields.aFields;\n    }\n    if (aFields && !Array.isArray(aFields)) {\n      aFields = [aFields];\n    }\n    let mustCalculate = false;\n    let fieldsToReset;\n    if (aFields) {\n      fieldsToReset = new Set();\n      for (const fieldName of aFields) {\n        if (!fieldName) {\n          continue;\n        }\n        if (typeof fieldName !== \"string\") {\n          fieldsToReset = null;\n          break;\n        }\n        const field = this.getField(fieldName);\n        if (!field) {\n          continue;\n        }\n        fieldsToReset.add(field);\n        mustCalculate = true;\n      }\n    }\n    if (fieldsToReset) {\n      for (const field of fieldsToReset) {\n        for (const id of FieldInternals.getKidIds(field) || []) {\n          const kid = this.#appObjects[id];\n          if (kid) {\n            fieldsToReset.add(kid);\n          }\n        }\n      }\n    } else {\n      fieldsToReset = this.#fields.values();\n      mustCalculate = this.#fields.size !== 0;\n    }\n    for (const field of fieldsToReset) {\n      FieldInternals.setValue(field, field.defaultValue);\n      FieldInternals.send(field, {\n        value: field.defaultValue,\n        formattedValue: null,\n        selRange: [0, 0]\n      });\n    }\n    if (mustCalculate) {\n      this.calculateNow();\n    }\n  }\n  saveAs() {}\n  scroll() {}\n  selectPageNthWord() {}\n  setAction() {}\n  setDataObjectContents() {}\n  setOCGOrder() {}\n  setPageAction() {}\n  setPageBoxes() {}\n  setPageLabels() {}\n  setPageRotations() {}\n  setPageTabOrder() {}\n  setPageTransitions() {}\n  spawnPageFromTemplate() {}\n  submitForm() {}\n  syncAnnotScan() {}\n}\n\n;// ./src/scripting_api/event.js\n\n\n\nconst {\n  values\n} = Object;\nconst EVENT_PROTOTYPE = Object.create(Object.prototype, {\n  [Symbol.toStringTag]: {\n    value: \"Event\"\n  }\n});\nfunction createEvent(data) {\n  return {\n    __proto__: EVENT_PROTOTYPE,\n    change: data.change || \"\",\n    changeEx: data.changeEx || null,\n    commitKey: data.commitKey || 0,\n    fieldFull: data.fieldFull || false,\n    keyDown: data.keyDown || false,\n    modifier: data.modifier || false,\n    name: data.name,\n    rc: true,\n    richChange: data.richChange || [],\n    richChangeEx: data.richChangeEx || [],\n    richValue: data.richValue || [],\n    selEnd: data.selEnd ?? -1,\n    selStart: data.selStart ?? -1,\n    shift: data.shift || false,\n    source: data.source || null,\n    target: data.target || null,\n    targetName: \"\",\n    type: \"Field\",\n    value: data.value || \"\",\n    willCommit: data.willCommit || false\n  };\n}\nfunction mergeChange(event) {\n  let value = event.value;\n  if (Array.isArray(value)) {\n    return value;\n  }\n  if (typeof value !== \"string\") {\n    value = value.toString();\n  }\n  const prefix = event.selStart >= 0 ? value.substring(0, event.selStart) : \"\";\n  const postfix = event.selEnd >= 0 && event.selEnd <= value.length ? value.substring(event.selEnd) : \"\";\n  return `${prefix}${event.change}${postfix}`;\n}\nclass EventDispatcher {\n  #calculationOrder;\n  #doc;\n  #externalCall;\n  #isCalculating = false;\n  #objects;\n  #userActivationData;\n  constructor(doc, calculationOrder, objects, externalCall, userActivationData) {\n    this.#doc = doc;\n    this.#calculationOrder = calculationOrder;\n    this.#objects = objects;\n    this.#externalCall = externalCall;\n    this.#userActivationData = userActivationData;\n  }\n  #userActivation() {\n    this.#userActivationData.userActivation = true;\n    this.#externalCall(\"setTimeout\", [(/* inlined export .USERACTIVATION_CALLBACKID */0), (/* inlined export .USERACTIVATION_MAXTIME_VALIDITY */5000)]);\n  }\n  dispatch(baseEvent) {\n    const id = baseEvent.id;\n    if (!(id in this.#objects)) {\n      let event;\n      if (id === \"doc\" || id === \"page\") {\n        event = globalThis.event = createEvent(baseEvent);\n        event.source = event.target = globalThis;\n      }\n      if (id === \"doc\") {\n        const eventName = event.name;\n        if (eventName === \"Open\") {\n          this.#userActivation();\n          DocInternals.initActions(this.#doc);\n          this.#formatAll();\n        }\n        if (![\"DidPrint\", \"DidSave\", \"WillPrint\", \"WillSave\"].includes(eventName)) {\n          this.#userActivation();\n        }\n        DocInternals.dispatchDocEvent(this.#doc, event.name);\n      } else if (id === \"page\") {\n        this.#userActivation();\n        DocInternals.dispatchPageEvent(this.#doc, event.name, baseEvent.actions, baseEvent.pageNumber);\n      } else if (id === \"app\" && baseEvent.name === \"ResetForm\") {\n        this.#userActivation();\n        for (const fieldId of baseEvent.ids) {\n          const field = this.#objects[fieldId];\n          if (field) {\n            FieldInternals.setValue(field, field.defaultValue);\n          }\n        }\n      }\n      return;\n    }\n    const name = baseEvent.name;\n    const source = this.#objects[id];\n    const event = globalThis.event = createEvent(baseEvent);\n    let savedChange;\n    this.#userActivation();\n    FieldInternals.prepareEvent(source, id, event);\n    switch (name) {\n      case \"Keystroke\":\n        savedChange = {\n          value: event.value,\n          changeEx: event.changeEx,\n          change: event.change,\n          selStart: event.selStart,\n          selEnd: event.selEnd\n        };\n        break;\n      case \"Blur\":\n      case \"Focus\":\n        Object.defineProperty(event, \"value\", {\n          configurable: false,\n          writable: false,\n          enumerable: true,\n          value: event.value\n        });\n        break;\n      case \"Validate\":\n        this.#runValidation(source, event);\n        return;\n      case \"Action\":\n        this.#runActions(source, source, event, name);\n        this.#runCalculate(source, event);\n        return;\n    }\n    this.#runActions(source, source, event, name);\n    if (name !== \"Keystroke\") {\n      return;\n    }\n    if (event.rc) {\n      if (event.willCommit) {\n        this.#runValidation(source, event);\n      } else {\n        if (FieldInternals.getIsChoice(source)) {\n          FieldInternals.setValue(source, savedChange.changeEx);\n          FieldInternals.send(source, {\n            value: FieldInternals.getValue(source)\n          });\n          return;\n        }\n        const value = mergeChange(event);\n        FieldInternals.setValue(source, value);\n        let selStart, selEnd;\n        if (event.selStart !== savedChange.selStart || event.selEnd !== savedChange.selEnd) {\n          selStart = event.selStart;\n          selEnd = event.selEnd;\n        } else {\n          selEnd = selStart = savedChange.selStart + event.change.length;\n        }\n        FieldInternals.send(source, {\n          value,\n          selRange: [selStart, selEnd]\n        });\n      }\n    } else if (!event.willCommit) {\n      FieldInternals.send(source, {\n        value: savedChange.value,\n        selRange: [savedChange.selStart, savedChange.selEnd]\n      });\n    } else {\n      FieldInternals.send(source, {\n        value: \"\",\n        formattedValue: null,\n        selRange: [0, 0]\n      });\n    }\n  }\n  #formatAll() {\n    const event = globalThis.event = createEvent({});\n    for (const source of values(this.#objects)) {\n      event.value = FieldInternals.getComputedValue(source);\n      this.#runActions(source, source, event, \"Format\");\n    }\n  }\n  #runValidation(source, event) {\n    const didValidateRun = this.#runActions(source, source, event, \"Validate\");\n    if (event.rc) {\n      FieldInternals.setValue(source, event.value);\n      this.#runCalculate(source, event);\n      const savedValue = event.value = FieldInternals.getComputedValue(source);\n      const formattedValue = this.#runActions(source, source, event, \"Format\") ? event.value?.toString?.() : null;\n      FieldInternals.send(source, {\n        value: savedValue,\n        formattedValue\n      });\n      event.value = savedValue;\n    } else if (didValidateRun) {\n      FieldInternals.send(source, {\n        value: \"\",\n        formattedValue: null,\n        selRange: [0, 0],\n        focus: true\n      });\n    }\n  }\n  #runActions(source, target, event, eventName) {\n    event.source = source;\n    event.target = target;\n    event.name = eventName;\n    event.targetName = target.name;\n    event.rc = true;\n    return FieldInternals.runActions(target, event);\n  }\n  calculateNow() {\n    if (!this.#calculationOrder || this.#isCalculating || !this.#doc.calculate) {\n      return;\n    }\n    this.#isCalculating = true;\n    const first = this.#calculationOrder[0];\n    const source = this.#objects[first];\n    globalThis.event = createEvent({});\n    this.#runCalculate(source, globalThis.event);\n    this.#isCalculating = false;\n  }\n  #runCalculate(source, event) {\n    if (!this.#calculationOrder || !this.#doc.calculate) {\n      return;\n    }\n    for (const targetId of this.#calculationOrder) {\n      if (!(targetId in this.#objects)) {\n        continue;\n      }\n      if (!this.#doc.calculate) {\n        break;\n      }\n      event.value = null;\n      const target = this.#objects[targetId];\n      let savedValue = FieldInternals.getComputedValue(target);\n      this.#runActions(source, target, event, \"Calculate\");\n      if (!event.rc) {\n        continue;\n      }\n      if (event.value !== null) {\n        FieldInternals.setValue(target, event.value);\n      } else {\n        event.value = FieldInternals.getComputedValue(target);\n      }\n      this.#runActions(target, target, event, \"Validate\");\n      if (!event.rc) {\n        if (FieldInternals.getComputedValue(target) !== savedValue) {\n          target.value = savedValue;\n        }\n        continue;\n      }\n      if (event.value === null) {\n        event.value = FieldInternals.getComputedValue(target);\n      }\n      savedValue = FieldInternals.getComputedValue(target);\n      const formattedValue = this.#runActions(target, target, event, \"Format\") ? event.value?.toString?.() : null;\n      FieldInternals.send(target, {\n        value: savedValue,\n        formattedValue\n      });\n    }\n  }\n}\n\n;// ./src/scripting_api/aform.js\n\n\n\n\nclass AForm {\n  #document;\n  #app;\n  #util;\n  #color;\n  #emailRegex = new RegExp(\"^[\\\\w.!#$%&'*+/=?^`{|}~-]+\" + \"@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\" + \"(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\");\n  constructor(document, app, util, color) {\n    this.#document = document;\n    this.#app = app;\n    this.#util = util;\n    this.#color = color;\n  }\n  #mkTargetName(event) {\n    return event.target ? `[ ${event.target.name} ]` : \"\";\n  }\n  #parseDate(cFormat, cDate) {\n    let date = null;\n    try {\n      date = this.#util.scand(cFormat, cDate);\n    } catch {}\n    if (date) {\n      return date;\n    }\n    date = Date.parse(cDate);\n    return isNaN(date) ? null : new Date(date);\n  }\n  AFMergeChange(event = globalThis.event) {\n    return event.willCommit ? event.value.toString() : mergeChange(event);\n  }\n  AFParseDateEx(cString, cOrder) {\n    return this.#parseDate(cOrder, cString);\n  }\n  AFExtractNums(str) {\n    if (typeof str === \"number\") {\n      return [str];\n    }\n    if (!str || typeof str !== \"string\") {\n      return null;\n    }\n    const first = str.charAt(0);\n    if (first === \".\" || first === \",\") {\n      str = `0${str}`;\n    }\n    const numbers = str.match(/(\\d+)/g);\n    return numbers.length === 0 ? null : numbers;\n  }\n  AFMakeNumber(str) {\n    if (typeof str === \"number\") {\n      return str;\n    }\n    if (typeof str !== \"string\") {\n      return null;\n    }\n    str = str.trim().replace(\",\", \".\");\n    const number = parseFloat(str);\n    return isNaN(number) || !isFinite(number) ? null : number;\n  }\n  AFMakeArrayFromList(string) {\n    return typeof string === \"string\" ? string.split(/, ?/g) : string;\n  }\n  AFNumber_Format(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) {\n    const event = globalThis.event;\n    let value = this.AFMakeNumber(event.value);\n    if (value === null) {\n      event.value = \"\";\n      return;\n    }\n    const sign = Math.sign(value);\n    const buf = [];\n    let hasParen = false;\n    if (sign === -1 && bCurrencyPrepend && negStyle === 0) {\n      buf.push(\"-\");\n    }\n    if ((negStyle === 2 || negStyle === 3) && sign === -1) {\n      buf.push(\"(\");\n      hasParen = true;\n    }\n    if (bCurrencyPrepend) {\n      buf.push(strCurrency);\n    }\n    sepStyle = MathClamp(Math.floor(sepStyle), 0, 4);\n    buf.push(\"%,\", sepStyle, \".\", nDec.toString(), \"f\");\n    if (!bCurrencyPrepend) {\n      buf.push(strCurrency);\n    }\n    if (hasParen) {\n      buf.push(\")\");\n    }\n    if (negStyle === 1 || negStyle === 3) {\n      event.target.textColor = sign === 1 ? this.#color.black : this.#color.red;\n    }\n    if ((negStyle !== 0 || bCurrencyPrepend) && sign === -1) {\n      value = -value;\n    }\n    const formatStr = buf.join(\"\");\n    event.value = this.#util.printf(formatStr, value);\n  }\n  AFNumber_Keystroke(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) {\n    const event = globalThis.event;\n    let value = this.AFMergeChange(event);\n    if (!value) {\n      return;\n    }\n    value = value.trim();\n    let pattern;\n    if (sepStyle > 1) {\n      pattern = event.willCommit ? /^[+-]?(\\d+(,\\d*)?|,\\d+)$/ : /^[+-]?\\d*(?:,\\d*)?$/;\n    } else {\n      pattern = event.willCommit ? /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/ : /^[+-]?\\d*(?:\\.\\d*)?$/;\n    }\n    if (!pattern.test(value)) {\n      if (event.willCommit) {\n        const err = `${GlobalConstants.IDS_INVALID_VALUE} ${this.#mkTargetName(event)}`;\n        this.#app.alert(err);\n      }\n      event.rc = false;\n    }\n    if (event.willCommit && sepStyle > 1) {\n      event.value = parseFloat(value.replace(\",\", \".\"));\n    }\n  }\n  AFPercent_Format(nDec, sepStyle, percentPrepend = false) {\n    if (typeof nDec !== \"number\" || typeof sepStyle !== \"number\") {\n      return;\n    }\n    if (nDec < 0) {\n      throw new Error(\"Invalid nDec value in AFPercent_Format\");\n    }\n    const event = globalThis.event;\n    if (nDec > 512) {\n      event.value = \"%\";\n      return;\n    }\n    nDec = Math.floor(nDec);\n    sepStyle = MathClamp(Math.floor(sepStyle), 0, 4);\n    let value = this.AFMakeNumber(event.value);\n    if (value === null) {\n      event.value = \"%\";\n      return;\n    }\n    const formatStr = `%,${sepStyle}.${nDec}f`;\n    value = this.#util.printf(formatStr, value * 100);\n    event.value = percentPrepend ? `%${value}` : `${value}%`;\n  }\n  AFPercent_Keystroke(nDec, sepStyle) {\n    this.AFNumber_Keystroke(nDec, sepStyle, 0, 0, \"\", true);\n  }\n  AFDate_FormatEx(cFormat) {\n    const event = globalThis.event;\n    const value = event.value;\n    if (!value) {\n      return;\n    }\n    const date = this.#parseDate(cFormat, value);\n    if (date !== null) {\n      event.value = this.#util.printd(cFormat, date);\n    }\n  }\n  AFDate_Format(pdf) {\n    this.AFDate_FormatEx(DateFormats[pdf] ?? pdf);\n  }\n  AFDate_KeystrokeEx(cFormat) {\n    const event = globalThis.event;\n    if (!event.willCommit) {\n      return;\n    }\n    const value = this.AFMergeChange(event);\n    if (!value) {\n      return;\n    }\n    if (this.#parseDate(cFormat, value) === null) {\n      const invalid = GlobalConstants.IDS_INVALID_DATE;\n      const invalid2 = GlobalConstants.IDS_INVALID_DATE2;\n      const err = `${invalid} ${this.#mkTargetName(event)}${invalid2}${cFormat}`;\n      this.#app.alert(err);\n      event.rc = false;\n    }\n  }\n  AFDate_Keystroke(pdf) {\n    if (pdf >= 0 && pdf < DateFormats.length) {\n      this.AFDate_KeystrokeEx(DateFormats[pdf]);\n    }\n  }\n  AFRange_Validate(bGreaterThan, nGreaterThan, bLessThan, nLessThan) {\n    const event = globalThis.event;\n    if (!event.value) {\n      return;\n    }\n    const value = this.AFMakeNumber(event.value);\n    if (value === null) {\n      return;\n    }\n    bGreaterThan = !!bGreaterThan;\n    bLessThan = !!bLessThan;\n    if (bGreaterThan) {\n      nGreaterThan = this.AFMakeNumber(nGreaterThan);\n      if (nGreaterThan === null) {\n        return;\n      }\n    }\n    if (bLessThan) {\n      nLessThan = this.AFMakeNumber(nLessThan);\n      if (nLessThan === null) {\n        return;\n      }\n    }\n    let err = \"\";\n    if (bGreaterThan && bLessThan) {\n      if (value < nGreaterThan || value > nLessThan) {\n        err = this.#util.printf(GlobalConstants.IDS_GT_AND_LT, nGreaterThan, nLessThan);\n      }\n    } else if (bGreaterThan) {\n      if (value < nGreaterThan) {\n        err = this.#util.printf(GlobalConstants.IDS_GREATER_THAN, nGreaterThan);\n      }\n    } else if (value > nLessThan) {\n      err = this.#util.printf(GlobalConstants.IDS_LESS_THAN, nLessThan);\n    }\n    if (err) {\n      this.#app.alert(err);\n      event.rc = false;\n    }\n  }\n  AFSimple(cFunction, nValue1, nValue2) {\n    const value1 = this.AFMakeNumber(nValue1);\n    if (value1 === null) {\n      throw new Error(\"Invalid nValue1 in AFSimple\");\n    }\n    const value2 = this.AFMakeNumber(nValue2);\n    if (value2 === null) {\n      throw new Error(\"Invalid nValue2 in AFSimple\");\n    }\n    switch (cFunction) {\n      case \"AVG\":\n        return (value1 + value2) / 2;\n      case \"SUM\":\n        return value1 + value2;\n      case \"PRD\":\n        return value1 * value2;\n      case \"MIN\":\n        return Math.min(value1, value2);\n      case \"MAX\":\n        return Math.max(value1, value2);\n    }\n    throw new Error(\"Invalid cFunction in AFSimple\");\n  }\n  AFSimple_Calculate(cFunction, cFields) {\n    const actions = {\n      AVG: args => Math.sumPrecise(args) / args.length,\n      SUM: args => Math.sumPrecise(args),\n      PRD: args => args.reduce((acc, value) => acc * value, 1),\n      MIN: args => Math.min(...args),\n      MAX: args => Math.max(...args)\n    };\n    if (!(cFunction in actions)) {\n      throw new TypeError(\"Invalid function in AFSimple_Calculate\");\n    }\n    const event = globalThis.event;\n    const values = [];\n    cFields = this.AFMakeArrayFromList(cFields);\n    for (const cField of cFields) {\n      const field = this.#document.getField(cField);\n      if (!field) {\n        continue;\n      }\n      for (const child of field.getArray()) {\n        const number = this.AFMakeNumber(child.value);\n        values.push(number ?? 0);\n      }\n    }\n    if (values.length === 0) {\n      event.value = 0;\n      return;\n    }\n    const res = actions[cFunction](values);\n    event.value = Math.round(1e6 * res) / 1e6;\n  }\n  AFSpecial_Format(psf) {\n    const event = globalThis.event;\n    if (!event.value) {\n      return;\n    }\n    psf = this.AFMakeNumber(psf);\n    let formatStr;\n    switch (psf) {\n      case 0:\n        formatStr = \"99999\";\n        break;\n      case 1:\n        formatStr = \"99999-9999\";\n        break;\n      case 2:\n        formatStr = this.#util.printx(\"9999999999\", event.value).length >= 10 ? \"(999) 999-9999\" : \"999-9999\";\n        break;\n      case 3:\n        formatStr = \"999-99-9999\";\n        break;\n      default:\n        throw new Error(\"Invalid psf in AFSpecial_Format\");\n    }\n    event.value = this.#util.printx(formatStr, event.value);\n  }\n  AFSpecial_KeystrokeEx(cMask) {\n    const event = globalThis.event;\n    const simplifiedFormatStr = cMask.replaceAll(/[^9AOX]/g, \"\");\n    this.#AFSpecial_KeystrokeEx_helper(simplifiedFormatStr, null, false);\n    if (event.rc) {\n      return;\n    }\n    event.rc = true;\n    this.#AFSpecial_KeystrokeEx_helper(cMask, null, true);\n  }\n  #AFSpecial_KeystrokeEx_helper(cMask, value, warn) {\n    if (!cMask) {\n      return;\n    }\n    const event = globalThis.event;\n    value ||= this.AFMergeChange(event);\n    if (!value) {\n      return;\n    }\n    const checkers = new Map([[\"9\", char => char >= \"0\" && char <= \"9\"], [\"A\", char => \"a\" <= char && char <= \"z\" || \"A\" <= char && char <= \"Z\"], [\"O\", char => \"a\" <= char && char <= \"z\" || \"A\" <= char && char <= \"Z\" || \"0\" <= char && char <= \"9\"], [\"X\", char => true]]);\n    function _checkValidity(_value, _cMask) {\n      for (let i = 0, ii = _value.length; i < ii; i++) {\n        const mask = _cMask.charAt(i);\n        const char = _value.charAt(i);\n        const checker = checkers.get(mask);\n        if (checker) {\n          if (!checker(char)) {\n            return false;\n          }\n        } else if (mask !== char) {\n          return false;\n        }\n      }\n      return true;\n    }\n    const err = `${GlobalConstants.IDS_INVALID_VALUE} = \"${cMask}\"`;\n    if (value.length > cMask.length) {\n      if (warn) {\n        this.#app.alert(err);\n      }\n      event.rc = false;\n      return;\n    }\n    if (event.willCommit) {\n      if (value.length < cMask.length) {\n        if (warn) {\n          this.#app.alert(err);\n        }\n        event.rc = false;\n        return;\n      }\n      if (!_checkValidity(value, cMask)) {\n        if (warn) {\n          this.#app.alert(err);\n        }\n        event.rc = false;\n        return;\n      }\n      event.value += cMask.substring(value.length);\n      return;\n    }\n    if (value.length < cMask.length) {\n      cMask = cMask.substring(0, value.length);\n    }\n    if (!_checkValidity(value, cMask)) {\n      if (warn) {\n        this.#app.alert(err);\n      }\n      event.rc = false;\n    }\n  }\n  AFSpecial_Keystroke(psf) {\n    const event = globalThis.event;\n    psf = this.AFMakeNumber(psf);\n    let value = this.AFMergeChange(event);\n    let formatStr, secondFormatStr;\n    switch (psf) {\n      case 0:\n        formatStr = \"99999\";\n        break;\n      case 1:\n        formatStr = \"99999-9999\";\n        break;\n      case 2:\n        formatStr = \"999-9999\";\n        secondFormatStr = \"(999) 999-9999\";\n        break;\n      case 3:\n        formatStr = \"999-99-9999\";\n        break;\n      default:\n        throw new Error(\"Invalid psf in AFSpecial_Keystroke\");\n    }\n    const formats = secondFormatStr ? [formatStr, secondFormatStr] : [formatStr];\n    for (const format of formats) {\n      this.#AFSpecial_KeystrokeEx_helper(format, value, false);\n      if (event.rc) {\n        return;\n      }\n      event.rc = true;\n    }\n    const re = /[-()\\s]+/g;\n    value = value.replaceAll(re, \"\");\n    for (const format of formats) {\n      this.#AFSpecial_KeystrokeEx_helper(format.replaceAll(re, \"\"), value, false);\n      if (event.rc) {\n        return;\n      }\n      event.rc = true;\n    }\n    this.AFSpecial_KeystrokeEx((secondFormatStr && value.match(/\\d/g) || []).length > 7 ? secondFormatStr : formatStr);\n  }\n  AFTime_FormatEx(cFormat) {\n    this.AFDate_FormatEx(cFormat);\n  }\n  AFTime_Format(pdf) {\n    this.AFDate_FormatEx(TimeFormats[pdf] ?? pdf);\n  }\n  AFTime_KeystrokeEx(cFormat) {\n    this.AFDate_KeystrokeEx(cFormat);\n  }\n  AFTime_Keystroke(pdf) {\n    if (pdf >= 0 && pdf < TimeFormats.length) {\n      this.AFDate_KeystrokeEx(TimeFormats[pdf]);\n    }\n  }\n  eMailValidate(str) {\n    return this.#emailRegex.test(str);\n  }\n  AFExactMatch(rePatterns, str) {\n    return rePatterns instanceof RegExp ? str.match(rePatterns)?.[0] === str || 0 : rePatterns.findIndex(re => str.match(re)?.[0] === str) + 1;\n  }\n}\n\n;// ./src/scripting_api/console.js\nclass Console {\n  #send;\n  constructor({\n    send\n  }) {\n    this.#send = send;\n  }\n  clear() {\n    this.#send({\n      id: \"clear\"\n    });\n  }\n  hide() {}\n  println(msg) {\n    if (typeof msg !== \"string\") {\n      try {\n        msg = JSON.stringify(msg);\n      } catch {\n        msg = msg.toString?.() || \"[Unserializable object]\";\n      }\n    }\n    this.#send({\n      command: \"println\",\n      value: `PDF.js Console:: ${msg}`\n    });\n  }\n  show() {}\n}\n\n;// ./src/scripting_api/util.js\nclass Util {\n  #createDateActionsBound = this.#createDateActions.bind(this);\n  #createScandDataBound = this.#createScandData.bind(this);\n  #dateActionsCache = null;\n  #scandCache = null;\n  #months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n  #days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n  MILLISECONDS_IN_DAY = 86400000;\n  MILLISECONDS_IN_WEEK = 604800000;\n  printf(...args) {\n    if (args.length === 0) {\n      throw new Error(\"Invalid number of params in printf\");\n    }\n    if (typeof args[0] !== \"string\") {\n      throw new TypeError(\"First argument of printf must be a string\");\n    }\n    const pattern = /%(,[0-4])?([+ 0#]+)?(\\d+)?(\\.\\d+)?(.)/g;\n    const PLUS = 1;\n    const SPACE = 2;\n    const ZERO = 4;\n    const HASH = 8;\n    let i = 0;\n    return args[0].replaceAll(pattern, function (_, nDecSep, cFlags, nWidth, nPrecision, cConvChar) {\n      if (cConvChar !== \"d\" && cConvChar !== \"f\" && cConvChar !== \"s\" && cConvChar !== \"x\") {\n        const buf = [\"%\"];\n        for (const str of [nDecSep, cFlags, nWidth, nPrecision, cConvChar]) {\n          if (str) {\n            buf.push(str);\n          }\n        }\n        return buf.join(\"\");\n      }\n      i++;\n      if (i === args.length) {\n        throw new Error(\"Not enough arguments in printf\");\n      }\n      const arg = args[i];\n      if (cConvChar === \"s\") {\n        return arg.toString();\n      }\n      let flags = 0;\n      if (cFlags) {\n        for (const flag of cFlags) {\n          switch (flag) {\n            case \"+\":\n              flags |= PLUS;\n              break;\n            case \" \":\n              flags |= SPACE;\n              break;\n            case \"0\":\n              flags |= ZERO;\n              break;\n            case \"#\":\n              flags |= HASH;\n              break;\n          }\n        }\n      }\n      cFlags = flags;\n      nWidth &&= parseInt(nWidth);\n      let intPart = Math.trunc(arg);\n      if (cConvChar === \"x\") {\n        let hex = Math.abs(intPart).toString(16).toUpperCase();\n        if (nWidth !== undefined) {\n          hex = hex.padStart(nWidth, cFlags & ZERO ? \"0\" : \" \");\n        }\n        if (cFlags & HASH) {\n          hex = `0x${hex}`;\n        }\n        return hex;\n      }\n      nPrecision &&= parseInt(nPrecision.substring(1));\n      nDecSep = nDecSep ? nDecSep.substring(1) : \"0\";\n      const separators = {\n        0: [\",\", \".\"],\n        1: [\"\", \".\"],\n        2: [\".\", \",\"],\n        3: [\"\", \",\"],\n        4: [\"'\", \".\"]\n      };\n      const [thousandSep, decimalSep] = separators[nDecSep];\n      let decPart = \"\";\n      if (cConvChar === \"f\") {\n        decPart = nPrecision !== undefined ? Math.abs(arg - intPart).toFixed(nPrecision) : Math.abs(arg - intPart).toString();\n        if (decPart.length > 2) {\n          if (/^1\\.0+$/.test(decPart)) {\n            intPart += Math.sign(arg);\n            decPart = `${decimalSep}${decPart.split(\".\")[1]}`;\n          } else {\n            decPart = `${decimalSep}${decPart.substring(2)}`;\n          }\n        } else {\n          if (decPart === \"1\") {\n            intPart += Math.sign(arg);\n          }\n          decPart = cFlags & HASH ? \".\" : \"\";\n        }\n      }\n      let sign = \"\";\n      if (intPart < 0 || cConvChar === \"f\" && arg < 0) {\n        sign = \"-\";\n        intPart = -intPart;\n      } else if (cFlags & PLUS) {\n        sign = \"+\";\n      } else if (cFlags & SPACE) {\n        sign = \" \";\n      }\n      if (thousandSep && intPart >= 1000) {\n        const buf = [];\n        while (true) {\n          buf.push((intPart % 1000).toString().padStart(3, \"0\"));\n          intPart = Math.trunc(intPart / 1000);\n          if (intPart < 1000) {\n            buf.push(intPart.toString());\n            break;\n          }\n        }\n        intPart = buf.reverse().join(thousandSep);\n      } else {\n        intPart = intPart.toString();\n      }\n      let n = `${intPart}${decPart}`;\n      if (nWidth !== undefined) {\n        n = n.padStart(nWidth - sign.length, cFlags & ZERO ? \"0\" : \" \");\n      }\n      return `${sign}${n}`;\n    });\n  }\n  iconStreamFromIcon() {}\n  printd(cFormat, oDate) {\n    switch (cFormat) {\n      case 0:\n        return this.printd(\"D:yyyymmddHHMMss\", oDate);\n      case 1:\n        return this.printd(\"yyyy.mm.dd HH:MM:ss\", oDate);\n      case 2:\n        return this.printd(\"m/d/yy h:MM:ss tt\", oDate);\n    }\n    const handlers = {\n      mmmm: data => this.#months[data.month],\n      mmm: data => this.#months[data.month].substring(0, 3),\n      mm: data => (data.month + 1).toString().padStart(2, \"0\"),\n      m: data => (data.month + 1).toString(),\n      dddd: data => this.#days[data.dayOfWeek],\n      ddd: data => this.#days[data.dayOfWeek].substring(0, 3),\n      dd: data => data.day.toString().padStart(2, \"0\"),\n      d: data => data.day.toString(),\n      yyyy: data => data.year.toString().padStart(4, \"0\"),\n      yy: data => (data.year % 100).toString().padStart(2, \"0\"),\n      HH: data => data.hours.toString().padStart(2, \"0\"),\n      H: data => data.hours.toString(),\n      hh: data => (1 + (data.hours + 11) % 12).toString().padStart(2, \"0\"),\n      h: data => (1 + (data.hours + 11) % 12).toString(),\n      MM: data => data.minutes.toString().padStart(2, \"0\"),\n      M: data => data.minutes.toString(),\n      ss: data => data.seconds.toString().padStart(2, \"0\"),\n      s: data => data.seconds.toString(),\n      tt: data => data.hours < 12 ? \"am\" : \"pm\",\n      t: data => data.hours < 12 ? \"a\" : \"p\"\n    };\n    const data = {\n      year: oDate.getFullYear(),\n      month: oDate.getMonth(),\n      day: oDate.getDate(),\n      dayOfWeek: oDate.getDay(),\n      hours: oDate.getHours(),\n      minutes: oDate.getMinutes(),\n      seconds: oDate.getSeconds()\n    };\n    const patterns = /(mmmm|mmm|mm|m|dddd|ddd|dd|d|yyyy|yy|HH|H|hh|h|MM|M|ss|s|tt|t|\\\\.)/g;\n    return cFormat.replaceAll(patterns, (_, pattern) => pattern in handlers ? handlers[pattern](data) : pattern.charAt(1));\n  }\n  printx(cFormat, cSource) {\n    cSource = (cSource ?? \"\").toString();\n    const handlers = [x => x, x => x.toUpperCase(), x => x.toLowerCase()];\n    const buf = [];\n    let i = 0;\n    const ii = cSource.length;\n    let currCase = handlers[0];\n    let escaped = false;\n    for (const command of cFormat) {\n      if (escaped) {\n        buf.push(command);\n        escaped = false;\n        continue;\n      }\n      if (i >= ii) {\n        break;\n      }\n      switch (command) {\n        case \"?\":\n          buf.push(currCase(cSource.charAt(i++)));\n          break;\n        case \"X\":\n          while (i < ii) {\n            const char = cSource.charAt(i++);\n            if (\"a\" <= char && char <= \"z\" || \"A\" <= char && char <= \"Z\" || \"0\" <= char && char <= \"9\") {\n              buf.push(currCase(char));\n              break;\n            }\n          }\n          break;\n        case \"A\":\n          while (i < ii) {\n            const char = cSource.charAt(i++);\n            if (\"a\" <= char && char <= \"z\" || \"A\" <= char && char <= \"Z\") {\n              buf.push(currCase(char));\n              break;\n            }\n          }\n          break;\n        case \"9\":\n          while (i < ii) {\n            const char = cSource.charAt(i++);\n            if (\"0\" <= char && char <= \"9\") {\n              buf.push(char);\n              break;\n            }\n          }\n          break;\n        case \"*\":\n          while (i < ii) {\n            buf.push(currCase(cSource.charAt(i++)));\n          }\n          break;\n        case \"\\\\\":\n          escaped = true;\n          break;\n        case \">\":\n          currCase = handlers[1];\n          break;\n        case \"<\":\n          currCase = handlers[2];\n          break;\n        case \"=\":\n          currCase = handlers[0];\n          break;\n        default:\n          buf.push(command);\n      }\n    }\n    return buf.join(\"\");\n  }\n  #createDateActions(cFormat) {\n    const actions = [];\n    cFormat.replaceAll(/(d+)|(m+)|(y+)|(H+)|(M+)|(s+)/g, function (_, d, m, y, H, M, s) {\n      if (d) {\n        actions.push((n, data) => {\n          if (n >= 1 && n <= 31) {\n            data.day = n;\n            return true;\n          }\n          return false;\n        });\n      } else if (m) {\n        actions.push((n, data) => {\n          if (n >= 1 && n <= 12) {\n            data.month = n - 1;\n            return true;\n          }\n          return false;\n        });\n      } else if (y) {\n        actions.push((n, data) => {\n          if (n < 50) {\n            n += 2000;\n          } else if (n < 100) {\n            n += 1900;\n          }\n          data.year = n;\n          return true;\n        });\n      } else if (H) {\n        actions.push((n, data) => {\n          if (n >= 0 && n <= 23) {\n            data.hours = n;\n            return true;\n          }\n          return false;\n        });\n      } else if (M) {\n        actions.push((n, data) => {\n          if (n >= 0 && n <= 59) {\n            data.minutes = n;\n            return true;\n          }\n          return false;\n        });\n      } else if (s) {\n        actions.push((n, data) => {\n          if (n >= 0 && n <= 59) {\n            data.seconds = n;\n            return true;\n          }\n          return false;\n        });\n      }\n      return \"\";\n    });\n    return actions;\n  }\n  #tryToGuessDate(cFormat, cDate) {\n    const actions = (this.#dateActionsCache ??= new Map()).getOrInsertComputed(cFormat, this.#createDateActionsBound);\n    const number = /\\d+/g;\n    let i = 0;\n    let array;\n    const data = {\n      year: new Date().getFullYear(),\n      month: 0,\n      day: 1,\n      hours: 12,\n      minutes: 0,\n      seconds: 0\n    };\n    while ((array = number.exec(cDate)) !== null) {\n      if (i < actions.length) {\n        if (!actions[i++](parseInt(array[0]), data)) {\n          return null;\n        }\n      } else {\n        break;\n      }\n    }\n    if (i === 0) {\n      return null;\n    }\n    return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);\n  }\n  #createScandData(cFormat) {\n    const months = this.#months,\n      days = this.#days;\n    const handlers = {\n      mmmm: {\n        pattern: `(${months.join(\"|\")})`,\n        action: (value, data) => {\n          data.month = months.indexOf(value);\n        }\n      },\n      mmm: {\n        pattern: `(${months.map(month => month.substring(0, 3)).join(\"|\")})`,\n        action: (value, data) => {\n          data.month = months.findIndex(month => month.substring(0, 3) === value);\n        }\n      },\n      mm: {\n        pattern: `(\\\\d{2})`,\n        action: (value, data) => {\n          data.month = parseInt(value) - 1;\n        }\n      },\n      m: {\n        pattern: `(\\\\d{1,2})`,\n        action: (value, data) => {\n          data.month = parseInt(value) - 1;\n        }\n      },\n      dddd: {\n        pattern: `(${days.join(\"|\")})`,\n        action: (value, data) => {\n          data.day = days.indexOf(value);\n        }\n      },\n      ddd: {\n        pattern: `(${days.map(day => day.substring(0, 3)).join(\"|\")})`,\n        action: (value, data) => {\n          data.day = days.findIndex(day => day.substring(0, 3) === value);\n        }\n      },\n      dd: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.day = parseInt(value);\n        }\n      },\n      d: {\n        pattern: \"(\\\\d{1,2})\",\n        action: (value, data) => {\n          data.day = parseInt(value);\n        }\n      },\n      yyyy: {\n        pattern: \"(\\\\d{4})\",\n        action: (value, data) => {\n          data.year = parseInt(value);\n        }\n      },\n      yy: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.year = 2000 + parseInt(value);\n        }\n      },\n      HH: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.hours = parseInt(value);\n        }\n      },\n      H: {\n        pattern: \"(\\\\d{1,2})\",\n        action: (value, data) => {\n          data.hours = parseInt(value);\n        }\n      },\n      hh: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.hours = parseInt(value);\n        }\n      },\n      h: {\n        pattern: \"(\\\\d{1,2})\",\n        action: (value, data) => {\n          data.hours = parseInt(value);\n        }\n      },\n      MM: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.minutes = parseInt(value);\n        }\n      },\n      M: {\n        pattern: \"(\\\\d{1,2})\",\n        action: (value, data) => {\n          data.minutes = parseInt(value);\n        }\n      },\n      ss: {\n        pattern: \"(\\\\d{2})\",\n        action: (value, data) => {\n          data.seconds = parseInt(value);\n        }\n      },\n      s: {\n        pattern: \"(\\\\d{1,2})\",\n        action: (value, data) => {\n          data.seconds = parseInt(value);\n        }\n      },\n      tt: {\n        pattern: \"([aApP][mM])\",\n        action: (value, data) => {\n          const char = value.charAt(0);\n          data.am = char === \"a\" || char === \"A\";\n        }\n      },\n      t: {\n        pattern: \"([aApP])\",\n        action: (value, data) => {\n          data.am = value === \"a\" || value === \"A\";\n        }\n      }\n    };\n    const escapedFormat = cFormat.replaceAll(/[.*+\\-?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    const patterns = /(mmmm|mmm|mm|m|dddd|ddd|dd|d|yyyy|yy|HH|H|hh|h|MM|M|ss|s|tt|t)/g;\n    const actions = [];\n    const re = escapedFormat.replaceAll(patterns, function (_, patternElement) {\n      const {\n        pattern,\n        action\n      } = handlers[patternElement];\n      actions.push(action);\n      return pattern.includes(\",\") ? `(?=${pattern})\\\\${actions.length}` : pattern;\n    });\n    return [new RegExp(`^${re}$`), actions];\n  }\n  scand(cFormat, cDate) {\n    if (typeof cDate !== \"string\") {\n      return new Date(cDate);\n    }\n    if (cDate === \"\") {\n      return new Date();\n    }\n    switch (cFormat) {\n      case 0:\n        return this.scand(\"D:yyyymmddHHMMss\", cDate);\n      case 1:\n        return this.scand(\"yyyy.mm.dd HH:MM:ss\", cDate);\n      case 2:\n        return this.scand(\"m/d/yy h:MM:ss tt\", cDate);\n    }\n    const [regex, actions] = (this.#scandCache ??= new Map()).getOrInsertComputed(cFormat, this.#createScandDataBound);\n    const matches = regex.exec(cDate);\n    if (!matches || matches.length !== actions.length + 1) {\n      return this.#tryToGuessDate(cFormat, cDate);\n    }\n    const data = {\n      year: 2000,\n      month: 0,\n      day: 1,\n      hours: 0,\n      minutes: 0,\n      seconds: 0,\n      am: null\n    };\n    actions.forEach((action, i) => action(matches[i + 1], data));\n    if (data.am !== null) {\n      data.hours = data.hours % 12 + (data.am ? 0 : 12);\n    }\n    return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);\n  }\n  spansToXML() {}\n  stringFromStream() {}\n  xmlToSpans() {}\n}\n\n;// ./src/scripting_api/initialization.js\n\n\n\n\n\n\n\n\n\n\n\nfunction initSandbox(params) {\n  delete globalThis.pdfjsScripting;\n  const externalCall = globalThis.callExternalFunction;\n  delete globalThis.callExternalFunction;\n  const globalEval = globalThis.eval.bind(globalThis);\n  const send = data => externalCall(\"send\", [data]);\n  const {\n    data\n  } = params;\n  const appObjects = Object.create(null);\n  const userActivationData = {\n    userActivation: false,\n    disablePrinting: false,\n    disableSaving: false\n  };\n  let eventDispatcher = null;\n  const doc = new Doc({\n    ...data.docInfo,\n    send,\n    globalEval,\n    appObjects,\n    userActivationData,\n    calculateNow: () => eventDispatcher.calculateNow()\n  });\n  eventDispatcher = new EventDispatcher(doc, data.calculationOrder, appObjects, externalCall, userActivationData);\n  const app = new App({\n    ...data.appInfo,\n    send,\n    globalEval,\n    externalCall,\n    doc,\n    userActivationData\n  });\n  const util = new Util();\n  const getTerminalChildren = fieldName => DocInternals.getTerminalChildren(doc, fieldName);\n  for (const [name, objs] of createMap(data.objects)) {\n    const annotations = [];\n    let container = null;\n    for (const obj of objs) {\n      if (obj.type !== \"\") {\n        annotations.push(obj);\n      } else {\n        container = obj;\n      }\n    }\n    let obj = container;\n    if (annotations.length > 0) {\n      obj = annotations[0];\n      obj.send = send;\n    }\n    obj.globalEval = globalEval;\n    obj.sendError = send;\n    obj.fieldPath = name;\n    obj.appObjects = appObjects;\n    obj.util = util;\n    obj.getTerminalChildren = getTerminalChildren;\n    const field = exposeObject(new Field(obj, annotations.slice(1)));\n    DocInternals.addField(doc, name, field);\n    for (const object of objs) {\n      appObjects[object.id] = field;\n    }\n    if (container) {\n      appObjects[container.id] = field;\n    }\n  }\n  const color = exposeObject(new Color(), true);\n  globalThis.event = null;\n  globalThis.global = Object.create(null);\n  globalThis.app = exposeObject(app, true);\n  globalThis.color = color;\n  globalThis.console = exposeObject(new Console({\n    send\n  }), true);\n  globalThis.util = exposeObject(util, true);\n  globalThis.border = Border;\n  globalThis.cursor = Cursor;\n  globalThis.display = Display;\n  globalThis.font = Font;\n  globalThis.highlight = Highlight;\n  globalThis.position = Position;\n  globalThis.scaleHow = ScaleHow;\n  globalThis.scaleWhen = ScaleWhen;\n  globalThis.style = Style;\n  globalThis.trans = Trans;\n  globalThis.zoomtype = ZoomType;\n  globalThis.ADBE = {\n    Reader_Value_Asked: true,\n    Viewer_Value_Asked: true\n  };\n  const aform = new AForm(doc, app, util, color);\n  for (const name of Object.getOwnPropertyNames(AForm.prototype)) {\n    if (name !== \"constructor\") {\n      globalThis[name] = aform[name].bind(aform);\n    }\n  }\n  for (const [name, value] of Object.entries(GlobalConstants)) {\n    Object.defineProperty(globalThis, name, {\n      value,\n      writable: false\n    });\n  }\n  Object.defineProperties(globalThis, {\n    ColorConvert: {\n      value: color.convert.bind(color),\n      writable: true\n    },\n    ColorEqual: {\n      value: color.equal.bind(color),\n      writable: true\n    }\n  });\n  const properties = Object.create(null);\n  for (const name of Object.getOwnPropertyNames(Doc.prototype)) {\n    if (name === \"constructor\") {\n      continue;\n    }\n    const descriptor = Object.getOwnPropertyDescriptor(Doc.prototype, name);\n    if (descriptor.get) {\n      properties[name] = {\n        get: descriptor.get.bind(doc),\n        set: descriptor.set.bind(doc)\n      };\n    } else {\n      properties[name] = {\n        value: Doc.prototype[name].bind(doc)\n      };\n    }\n  }\n  Object.defineProperties(globalThis, properties);\n  useNativeToStringForPublicFunctions();\n  const functions = {\n    dispatchEvent: event => eventDispatcher.dispatch(event),\n    timeoutCb: timeout => AppInternals.evalCallback(app, timeout)\n  };\n  return (name, args) => {\n    try {\n      functions[name](args);\n    } catch (error) {\n      send(serializeError(error));\n    }\n  };\n}\n\n;// ./src/pdf.scripting.js\n\nglobalThis.pdfjsScripting = {\n  initSandbox: initSandbox\n};\n/******/ })()\n;"];
    code.push("delete dump;");
    let success = false;
    let buf = 0;
    try {
      const sandboxData = this.support.exportValueToSandbox(data);
      code.push(`pdfjsScripting.initSandbox({ data: ${sandboxData} })`);
      buf = this._module.stringToNewUTF8(code.join("\n"));
      success = !!this._module.ccall("init", "number", ["number", "number"], [buf, this._alertOnError]);
    } catch (error) {
      console.error(error);
    } finally {
      if (buf) {
        this._module.ccall("free", "number", ["number"], [buf]);
      }
    }
    if (success) {
      this.support.commFun = this._module.cwrap("commFun", null, ["string", "string"]);
    } else {
      this.nukeSandbox();
      throw new Error("Cannot start sandbox");
    }
  }
  dispatchEvent(event) {
    this.support?.callSandboxFunction("dispatchEvent", event);
  }
  dumpMemoryUse() {
    this._module?.ccall("dumpMemoryUse", null, []);
  }
  nukeSandbox() {
    if (this._module !== null) {
      this.support.destroy();
      this.support = null;
      this._module.ccall("nukeSandbox", null, []);
      this._module = null;
    }
  }
  evalForTesting(code, key) {
    throw new Error("Not implemented: evalForTesting");
  }
}
async function QuickJSSandbox(wasmUrl = "../web/wasm/") {
  const {
    default: ModuleLoader
  } = await import(
  /*webpackIgnore: true*/
  /*@vite-ignore*/
  `${wasmUrl}quickjs-eval.js`);
  const module = await ModuleLoader();
  return new Sandbox(window, module);
}
globalThis.pdfjsSandbox = {
  QuickJSSandbox
};

export { QuickJSSandbox };

//# sourceMappingURL=pdf.sandbox.mjs.map